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
ZELLMECHANIK-DRESDEN/dclab
dclab/features/fl_crosstalk.py
get_compensation_matrix
def get_compensation_matrix(ct21, ct31, ct12, ct32, ct13, ct23): """Compute crosstalk inversion matrix The spillover matrix is | | c11 c12 c13 | | | c21 c22 c23 | | | c31 c32 c33 | The diagonal elements are set to 1, i.e. ct11 = c22 = c33 = 1 Parameters ---------- cij: float...
python
def get_compensation_matrix(ct21, ct31, ct12, ct32, ct13, ct23): """Compute crosstalk inversion matrix The spillover matrix is | | c11 c12 c13 | | | c21 c22 c23 | | | c31 c32 c33 | The diagonal elements are set to 1, i.e. ct11 = c22 = c33 = 1 Parameters ---------- cij: float...
[ "def", "get_compensation_matrix", "(", "ct21", ",", "ct31", ",", "ct12", ",", "ct32", ",", "ct13", ",", "ct23", ")", ":", "ct11", "=", "1", "ct22", "=", "1", "ct33", "=", "1", "if", "ct21", "<", "0", ":", "raise", "ValueError", "(", "\"ct21 matrix el...
Compute crosstalk inversion matrix The spillover matrix is | | c11 c12 c13 | | | c21 c22 c23 | | | c31 c32 c33 | The diagonal elements are set to 1, i.e. ct11 = c22 = c33 = 1 Parameters ---------- cij: float Spill from channel i to channel j Returns ------- ...
[ "Compute", "crosstalk", "inversion", "matrix" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/features/fl_crosstalk.py#L9-L58
ZELLMECHANIK-DRESDEN/dclab
dclab/features/fl_crosstalk.py
correct_crosstalk
def correct_crosstalk(fl1, fl2, fl3, fl_channel, ct21=0, ct31=0, ct12=0, ct32=0, ct13=0, ct23=0): """Perform crosstalk correction Parameters ---------- fli: int, float, or np.ndarray Measured fluorescence signals fl_channel: int (1, 2, or 3) The channel number ...
python
def correct_crosstalk(fl1, fl2, fl3, fl_channel, ct21=0, ct31=0, ct12=0, ct32=0, ct13=0, ct23=0): """Perform crosstalk correction Parameters ---------- fli: int, float, or np.ndarray Measured fluorescence signals fl_channel: int (1, 2, or 3) The channel number ...
[ "def", "correct_crosstalk", "(", "fl1", ",", "fl2", ",", "fl3", ",", "fl_channel", ",", "ct21", "=", "0", ",", "ct31", "=", "0", ",", "ct12", "=", "0", ",", "ct32", "=", "0", ",", "ct13", "=", "0", ",", "ct23", "=", "0", ")", ":", "fl_channel",...
Perform crosstalk correction Parameters ---------- fli: int, float, or np.ndarray Measured fluorescence signals fl_channel: int (1, 2, or 3) The channel number for which the crosstalk-corrected signal should be computed cij: float Spill (crosstalk or bleed-through) f...
[ "Perform", "crosstalk", "correction" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/features/fl_crosstalk.py#L61-L98
ZELLMECHANIK-DRESDEN/dclab
dclab/features/inert_ratio.py
cont_moments_cv
def cont_moments_cv(cont, flt_epsilon=1.19209e-07, dbl_epsilon=2.2204460492503131e-16): """Compute the moments of a contour The moments are computed in the same way as they are computed in OpenCV's `contourMoments` in `moments.cpp`. Parameters ---------- ...
python
def cont_moments_cv(cont, flt_epsilon=1.19209e-07, dbl_epsilon=2.2204460492503131e-16): """Compute the moments of a contour The moments are computed in the same way as they are computed in OpenCV's `contourMoments` in `moments.cpp`. Parameters ---------- ...
[ "def", "cont_moments_cv", "(", "cont", ",", "flt_epsilon", "=", "1.19209e-07", ",", "dbl_epsilon", "=", "2.2204460492503131e-16", ")", ":", "# Make sure we have no unsigned integers", "if", "np", ".", "issubdtype", "(", "cont", ".", "dtype", ",", "np", ".", "unsig...
Compute the moments of a contour The moments are computed in the same way as they are computed in OpenCV's `contourMoments` in `moments.cpp`. Parameters ---------- cont: array of shape (N,2) The contour for which to compute the moments. flt_epsilon: float The value of ``FLT_EPS...
[ "Compute", "the", "moments", "of", "a", "contour" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/features/inert_ratio.py#L10-L114
ZELLMECHANIK-DRESDEN/dclab
dclab/features/inert_ratio.py
get_inert_ratio_cvx
def get_inert_ratio_cvx(cont): """Compute the inertia ratio of the convex hull of a contour The inertia ratio is computed from the central second order of moments along x (mu20) and y (mu02) via `sqrt(mu20/mu02)`. Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A...
python
def get_inert_ratio_cvx(cont): """Compute the inertia ratio of the convex hull of a contour The inertia ratio is computed from the central second order of moments along x (mu20) and y (mu02) via `sqrt(mu20/mu02)`. Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A...
[ "def", "get_inert_ratio_cvx", "(", "cont", ")", ":", "if", "isinstance", "(", "cont", ",", "np", ".", "ndarray", ")", ":", "# If cont is an array, it is not a list of contours,", "# because contours can have different lengths.", "cont", "=", "[", "cont", "]", "ret_list"...
Compute the inertia ratio of the convex hull of a contour The inertia ratio is computed from the central second order of moments along x (mu20) and y (mu02) via `sqrt(mu20/mu02)`. Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A 2D array that holds the contour of an...
[ "Compute", "the", "inertia", "ratio", "of", "the", "convex", "hull", "of", "a", "contour" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/features/inert_ratio.py#L117-L178
ZELLMECHANIK-DRESDEN/dclab
dclab/features/inert_ratio.py
get_inert_ratio_prnc
def get_inert_ratio_prnc(cont): """Compute principal inertia ratio of a contour The principal inertia ratio is rotation-invariant, which makes it applicable to reservoir measurements where e.g. cells are not aligned with the channel. Parameters ---------- cont: ndarray or list of ndarrays ...
python
def get_inert_ratio_prnc(cont): """Compute principal inertia ratio of a contour The principal inertia ratio is rotation-invariant, which makes it applicable to reservoir measurements where e.g. cells are not aligned with the channel. Parameters ---------- cont: ndarray or list of ndarrays ...
[ "def", "get_inert_ratio_prnc", "(", "cont", ")", ":", "if", "isinstance", "(", "cont", ",", "np", ".", "ndarray", ")", ":", "# If cont is an array, it is not a list of contours,", "# because contours can have different lengths.", "cont", "=", "[", "cont", "]", "ret_list...
Compute principal inertia ratio of a contour The principal inertia ratio is rotation-invariant, which makes it applicable to reservoir measurements where e.g. cells are not aligned with the channel. Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A 2D array that ...
[ "Compute", "principal", "inertia", "ratio", "of", "a", "contour" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/features/inert_ratio.py#L181-L233
ZELLMECHANIK-DRESDEN/dclab
dclab/features/inert_ratio.py
get_inert_ratio_raw
def get_inert_ratio_raw(cont): """Compute the inertia ratio of a contour The inertia ratio is computed from the central second order of moments along x (mu20) and y (mu02) via `sqrt(mu20/mu02)`. Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A 2D array that hold...
python
def get_inert_ratio_raw(cont): """Compute the inertia ratio of a contour The inertia ratio is computed from the central second order of moments along x (mu20) and y (mu02) via `sqrt(mu20/mu02)`. Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A 2D array that hold...
[ "def", "get_inert_ratio_raw", "(", "cont", ")", ":", "if", "isinstance", "(", "cont", ",", "np", ".", "ndarray", ")", ":", "# If cont is an array, it is not a list of contours,", "# because contours can have different lengths.", "cont", "=", "[", "cont", "]", "ret_list"...
Compute the inertia ratio of a contour The inertia ratio is computed from the central second order of moments along x (mu20) and y (mu02) via `sqrt(mu20/mu02)`. Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A 2D array that holds the contour of an event (in pixels) ...
[ "Compute", "the", "inertia", "ratio", "of", "a", "contour" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/features/inert_ratio.py#L236-L292
ZELLMECHANIK-DRESDEN/dclab
dclab/features/inert_ratio.py
get_tilt
def get_tilt(cont): """Compute tilt of raw contour relative to channel axis Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A 2D array that holds the contour of an event (in pixels) e.g. obtained using `mm.contour` where `mm` is an instance of `RTDCBase`....
python
def get_tilt(cont): """Compute tilt of raw contour relative to channel axis Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A 2D array that holds the contour of an event (in pixels) e.g. obtained using `mm.contour` where `mm` is an instance of `RTDCBase`....
[ "def", "get_tilt", "(", "cont", ")", ":", "if", "isinstance", "(", "cont", ",", "np", ".", "ndarray", ")", ":", "# If cont is an array, it is not a list of contours,", "# because contours can have different lengths.", "cont", "=", "[", "cont", "]", "ret_list", "=", ...
Compute tilt of raw contour relative to channel axis Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A 2D array that holds the contour of an event (in pixels) e.g. obtained using `mm.contour` where `mm` is an instance of `RTDCBase`. The first and second colum...
[ "Compute", "tilt", "of", "raw", "contour", "relative", "to", "channel", "axis" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/features/inert_ratio.py#L295-L344
deep-compute/funcserver
funcserver/funcserver.py
tag
def tag(*tags): ''' Constructs a decorator that tags a function with specified strings (@tags). The tags on the decorated function are available via fn.tags ''' def dfn(fn): _tags = getattr(fn, 'tags', set()) _tags.update(tags) fn.tags = _tags return fn return...
python
def tag(*tags): ''' Constructs a decorator that tags a function with specified strings (@tags). The tags on the decorated function are available via fn.tags ''' def dfn(fn): _tags = getattr(fn, 'tags', set()) _tags.update(tags) fn.tags = _tags return fn return...
[ "def", "tag", "(", "*", "tags", ")", ":", "def", "dfn", "(", "fn", ")", ":", "_tags", "=", "getattr", "(", "fn", ",", "'tags'", ",", "set", "(", ")", ")", "_tags", ".", "update", "(", "tags", ")", "fn", ".", "tags", "=", "_tags", "return", "f...
Constructs a decorator that tags a function with specified strings (@tags). The tags on the decorated function are available via fn.tags
[ "Constructs", "a", "decorator", "that", "tags", "a", "function", "with", "specified", "strings", "(" ]
train
https://github.com/deep-compute/funcserver/blob/ce3418cb4a0cb85f0a3cbf86d12ea9733ca23f23/funcserver/funcserver.py#L42-L53
deep-compute/funcserver
funcserver/funcserver.py
raw
def raw(mime='application/octet-stream'): ''' Constructs a decorator that marks the fn as raw response format ''' def dfn(fn): tags = getattr(fn, 'tags', set()) tags.add('raw') fn.tags = tags fn.mime = getattr(fn, 'mime', mime) return fn return dfn
python
def raw(mime='application/octet-stream'): ''' Constructs a decorator that marks the fn as raw response format ''' def dfn(fn): tags = getattr(fn, 'tags', set()) tags.add('raw') fn.tags = tags fn.mime = getattr(fn, 'mime', mime) return fn return dfn
[ "def", "raw", "(", "mime", "=", "'application/octet-stream'", ")", ":", "def", "dfn", "(", "fn", ")", ":", "tags", "=", "getattr", "(", "fn", ",", "'tags'", ",", "set", "(", ")", ")", "tags", ".", "add", "(", "'raw'", ")", "fn", ".", "tags", "=",...
Constructs a decorator that marks the fn as raw response format
[ "Constructs", "a", "decorator", "that", "marks", "the", "fn", "as", "raw", "response", "format" ]
train
https://github.com/deep-compute/funcserver/blob/ce3418cb4a0cb85f0a3cbf86d12ea9733ca23f23/funcserver/funcserver.py#L69-L80
deep-compute/funcserver
funcserver/funcserver.py
WSConnection.open
def open(self, pysession_id): ''' Called when client opens connection. Initialization is done here. ''' self.id = id(self) self.funcserver = self.application.funcserver self.pysession_id = pysession_id # register this connection with node self.sta...
python
def open(self, pysession_id): ''' Called when client opens connection. Initialization is done here. ''' self.id = id(self) self.funcserver = self.application.funcserver self.pysession_id = pysession_id # register this connection with node self.sta...
[ "def", "open", "(", "self", ",", "pysession_id", ")", ":", "self", ".", "id", "=", "id", "(", "self", ")", "self", ".", "funcserver", "=", "self", ".", "application", ".", "funcserver", "self", ".", "pysession_id", "=", "pysession_id", "# register this con...
Called when client opens connection. Initialization is done here.
[ "Called", "when", "client", "opens", "connection", ".", "Initialization", "is", "done", "here", "." ]
train
https://github.com/deep-compute/funcserver/blob/ce3418cb4a0cb85f0a3cbf86d12ea9733ca23f23/funcserver/funcserver.py#L115-L125
deep-compute/funcserver
funcserver/funcserver.py
WSConnection.on_message
def on_message(self, msg): ''' Called when client sends a message. Supports a python debugging console. This forms the "eval" part of a standard read-eval-print loop. Currently the only implementation of the python console is in the WebUI but the implementation ...
python
def on_message(self, msg): ''' Called when client sends a message. Supports a python debugging console. This forms the "eval" part of a standard read-eval-print loop. Currently the only implementation of the python console is in the WebUI but the implementation ...
[ "def", "on_message", "(", "self", ",", "msg", ")", ":", "msg", "=", "json", ".", "loads", "(", "msg", ")", "psession", "=", "self", ".", "funcserver", ".", "pysessions", ".", "get", "(", "self", ".", "pysession_id", ",", "None", ")", "if", "psession"...
Called when client sends a message. Supports a python debugging console. This forms the "eval" part of a standard read-eval-print loop. Currently the only implementation of the python console is in the WebUI but the implementation of a terminal based console is planned.
[ "Called", "when", "client", "sends", "a", "message", "." ]
train
https://github.com/deep-compute/funcserver/blob/ce3418cb4a0cb85f0a3cbf86d12ea9733ca23f23/funcserver/funcserver.py#L127-L164
deep-compute/funcserver
funcserver/funcserver.py
WSConnection.on_close
def on_close(self): ''' Called when client closes this connection. Cleanup is done here. ''' if self.id in self.funcserver.websocks: self.funcserver.websocks[self.id] = None ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(lambda:...
python
def on_close(self): ''' Called when client closes this connection. Cleanup is done here. ''' if self.id in self.funcserver.websocks: self.funcserver.websocks[self.id] = None ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(lambda:...
[ "def", "on_close", "(", "self", ")", ":", "if", "self", ".", "id", "in", "self", ".", "funcserver", ".", "websocks", ":", "self", ".", "funcserver", ".", "websocks", "[", "self", ".", "id", "]", "=", "None", "ioloop", "=", "tornado", ".", "ioloop", ...
Called when client closes this connection. Cleanup is done here.
[ "Called", "when", "client", "closes", "this", "connection", ".", "Cleanup", "is", "done", "here", "." ]
train
https://github.com/deep-compute/funcserver/blob/ce3418cb4a0cb85f0a3cbf86d12ea9733ca23f23/funcserver/funcserver.py#L166-L181
deep-compute/funcserver
funcserver/funcserver.py
RPCHandler._clean_kwargs
def _clean_kwargs(self, kwargs, fn): ''' Remove unexpected keyword arguments from the set of received keyword arguments. ''' # Do not do the cleaning if server config # doesnt ask to ignore if not self.server.IGNORE_UNEXPECTED_KWARGS: return kwargs ...
python
def _clean_kwargs(self, kwargs, fn): ''' Remove unexpected keyword arguments from the set of received keyword arguments. ''' # Do not do the cleaning if server config # doesnt ask to ignore if not self.server.IGNORE_UNEXPECTED_KWARGS: return kwargs ...
[ "def", "_clean_kwargs", "(", "self", ",", "kwargs", ",", "fn", ")", ":", "# Do not do the cleaning if server config", "# doesnt ask to ignore", "if", "not", "self", ".", "server", ".", "IGNORE_UNEXPECTED_KWARGS", ":", "return", "kwargs", "expected_kwargs", "=", "set",...
Remove unexpected keyword arguments from the set of received keyword arguments.
[ "Remove", "unexpected", "keyword", "arguments", "from", "the", "set", "of", "received", "keyword", "arguments", "." ]
train
https://github.com/deep-compute/funcserver/blob/ce3418cb4a0cb85f0a3cbf86d12ea9733ca23f23/funcserver/funcserver.py#L301-L317
deep-compute/funcserver
funcserver/funcserver.py
Server.dump_stacks
def dump_stacks(self): ''' Dumps the stack of all threads. This function is meant for debugging. Useful when a deadlock happens. borrowed from: http://blog.ziade.org/2012/05/25/zmq-and-gevent-debugging-nightmares/ ''' dump = [] # threads threads = dict(...
python
def dump_stacks(self): ''' Dumps the stack of all threads. This function is meant for debugging. Useful when a deadlock happens. borrowed from: http://blog.ziade.org/2012/05/25/zmq-and-gevent-debugging-nightmares/ ''' dump = [] # threads threads = dict(...
[ "def", "dump_stacks", "(", "self", ")", ":", "dump", "=", "[", "]", "# threads", "threads", "=", "dict", "(", "[", "(", "th", ".", "ident", ",", "th", ".", "name", ")", "for", "th", "in", "threading", ".", "enumerate", "(", ")", "]", ")", "for", ...
Dumps the stack of all threads. This function is meant for debugging. Useful when a deadlock happens. borrowed from: http://blog.ziade.org/2012/05/25/zmq-and-gevent-debugging-nightmares/
[ "Dumps", "the", "stack", "of", "all", "threads", ".", "This", "function", "is", "meant", "for", "debugging", ".", "Useful", "when", "a", "deadlock", "happens", "." ]
train
https://github.com/deep-compute/funcserver/blob/ce3418cb4a0cb85f0a3cbf86d12ea9733ca23f23/funcserver/funcserver.py#L522-L542
deep-compute/funcserver
funcserver/funcserver.py
Server.define_log_pre_format_hooks
def define_log_pre_format_hooks(self): """ adds a hook to send to websocket if the run command was selected """ hooks = super(Server, self).define_log_pre_format_hooks() # NOTE enabling logs only on debug mode if self.args.func == self.run and self.args.debug: ...
python
def define_log_pre_format_hooks(self): """ adds a hook to send to websocket if the run command was selected """ hooks = super(Server, self).define_log_pre_format_hooks() # NOTE enabling logs only on debug mode if self.args.func == self.run and self.args.debug: ...
[ "def", "define_log_pre_format_hooks", "(", "self", ")", ":", "hooks", "=", "super", "(", "Server", ",", "self", ")", ".", "define_log_pre_format_hooks", "(", ")", "# NOTE enabling logs only on debug mode", "if", "self", ".", "args", ".", "func", "==", "self", "....
adds a hook to send to websocket if the run command was selected
[ "adds", "a", "hook", "to", "send", "to", "websocket", "if", "the", "run", "command", "was", "selected" ]
train
https://github.com/deep-compute/funcserver/blob/ce3418cb4a0cb85f0a3cbf86d12ea9733ca23f23/funcserver/funcserver.py#L563-L572
deep-compute/funcserver
funcserver/funcserver.py
Server.run
def run(self): """ prepares the api and starts the tornado funcserver """ self.log_id = 0 # all active websockets and their state self.websocks = {} # all active python interpreter sessions self.pysessions = {} if self.DISABLE_REQUESTS_DEBUG_LOGS: d...
python
def run(self): """ prepares the api and starts the tornado funcserver """ self.log_id = 0 # all active websockets and their state self.websocks = {} # all active python interpreter sessions self.pysessions = {} if self.DISABLE_REQUESTS_DEBUG_LOGS: d...
[ "def", "run", "(", "self", ")", ":", "self", ".", "log_id", "=", "0", "# all active websockets and their state", "self", ".", "websocks", "=", "{", "}", "# all active python interpreter sessions", "self", ".", "pysessions", "=", "{", "}", "if", "self", ".", "D...
prepares the api and starts the tornado funcserver
[ "prepares", "the", "api", "and", "starts", "the", "tornado", "funcserver" ]
train
https://github.com/deep-compute/funcserver/blob/ce3418cb4a0cb85f0a3cbf86d12ea9733ca23f23/funcserver/funcserver.py#L656-L713
openstax/cnx-archive
cnxarchive/scripts/export_epub/db.py
_get_sql
def _get_sql(filename): """Returns the contents of the sql file from the given ``filename``.""" with open(os.path.join(SQL_DIR, filename), 'r') as f: return f.read()
python
def _get_sql(filename): """Returns the contents of the sql file from the given ``filename``.""" with open(os.path.join(SQL_DIR, filename), 'r') as f: return f.read()
[ "def", "_get_sql", "(", "filename", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "SQL_DIR", ",", "filename", ")", ",", "'r'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
Returns the contents of the sql file from the given ``filename``.
[ "Returns", "the", "contents", "of", "the", "sql", "file", "from", "the", "given", "filename", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/export_epub/db.py#L32-L35
openstax/cnx-archive
cnxarchive/scripts/export_epub/db.py
verify_id_n_version
def verify_id_n_version(id, version): """Given an ``id`` and ``version``, verify the identified content exists. """ stmt = _get_sql('verify-id-and-version.sql') args = dict(id=id, version=version) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute(stm...
python
def verify_id_n_version(id, version): """Given an ``id`` and ``version``, verify the identified content exists. """ stmt = _get_sql('verify-id-and-version.sql') args = dict(id=id, version=version) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute(stm...
[ "def", "verify_id_n_version", "(", "id", ",", "version", ")", ":", "stmt", "=", "_get_sql", "(", "'verify-id-and-version.sql'", ")", "args", "=", "dict", "(", "id", "=", "id", ",", "version", "=", "version", ")", "with", "db_connect", "(", ")", "as", "db...
Given an ``id`` and ``version``, verify the identified content exists.
[ "Given", "an", "id", "and", "version", "verify", "the", "identified", "content", "exists", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/export_epub/db.py#L38-L52
openstax/cnx-archive
cnxarchive/scripts/export_epub/db.py
get_id_n_version
def get_id_n_version(ident_hash): """From the given ``ident_hash`` return the id and version.""" try: id, version = split_ident_hash(ident_hash) except IdentHashMissingVersion: # XXX Don't import from views... And don't use httpexceptions from pyramid.httpexceptions import HTTPNotFou...
python
def get_id_n_version(ident_hash): """From the given ``ident_hash`` return the id and version.""" try: id, version = split_ident_hash(ident_hash) except IdentHashMissingVersion: # XXX Don't import from views... And don't use httpexceptions from pyramid.httpexceptions import HTTPNotFou...
[ "def", "get_id_n_version", "(", "ident_hash", ")", ":", "try", ":", "id", ",", "version", "=", "split_ident_hash", "(", "ident_hash", ")", "except", "IdentHashMissingVersion", ":", "# XXX Don't import from views... And don't use httpexceptions", "from", "pyramid", ".", ...
From the given ``ident_hash`` return the id and version.
[ "From", "the", "given", "ident_hash", "return", "the", "id", "and", "version", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/export_epub/db.py#L55-L71
openstax/cnx-archive
cnxarchive/scripts/export_epub/db.py
get_type
def get_type(ident_hash): """Return the database type for the given ``ident_hash`` As of now, this could either be a 'Module' or 'Collection'. """ id, version = get_id_n_version(ident_hash) stmt = _get_sql('get-type.sql') args = dict(id=id, version=version) with db_connect() as db_conn: ...
python
def get_type(ident_hash): """Return the database type for the given ``ident_hash`` As of now, this could either be a 'Module' or 'Collection'. """ id, version = get_id_n_version(ident_hash) stmt = _get_sql('get-type.sql') args = dict(id=id, version=version) with db_connect() as db_conn: ...
[ "def", "get_type", "(", "ident_hash", ")", ":", "id", ",", "version", "=", "get_id_n_version", "(", "ident_hash", ")", "stmt", "=", "_get_sql", "(", "'get-type.sql'", ")", "args", "=", "dict", "(", "id", "=", "id", ",", "version", "=", "version", ")", ...
Return the database type for the given ``ident_hash`` As of now, this could either be a 'Module' or 'Collection'.
[ "Return", "the", "database", "type", "for", "the", "given", "ident_hash", "As", "of", "now", "this", "could", "either", "be", "a", "Module", "or", "Collection", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/export_epub/db.py#L74-L88
openstax/cnx-archive
cnxarchive/scripts/export_epub/db.py
get_metadata
def get_metadata(ident_hash): """Return the dictionary of metadata from the database. This data is keyed using the cnx-epub data structure. """ id, version = get_id_n_version(ident_hash) stmt = _get_sql('get-metadata.sql') args = dict(id=id, version=version) # FIXME The license_url and li...
python
def get_metadata(ident_hash): """Return the dictionary of metadata from the database. This data is keyed using the cnx-epub data structure. """ id, version = get_id_n_version(ident_hash) stmt = _get_sql('get-metadata.sql') args = dict(id=id, version=version) # FIXME The license_url and li...
[ "def", "get_metadata", "(", "ident_hash", ")", ":", "id", ",", "version", "=", "get_id_n_version", "(", "ident_hash", ")", "stmt", "=", "_get_sql", "(", "'get-metadata.sql'", ")", "args", "=", "dict", "(", "id", "=", "id", ",", "version", "=", "version", ...
Return the dictionary of metadata from the database. This data is keyed using the cnx-epub data structure.
[ "Return", "the", "dictionary", "of", "metadata", "from", "the", "database", ".", "This", "data", "is", "keyed", "using", "the", "cnx", "-", "epub", "data", "structure", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/export_epub/db.py#L91-L111
openstax/cnx-archive
cnxarchive/scripts/export_epub/db.py
get_content
def get_content(ident_hash, context=None): """Returns the content for the given ``ident_hash``. ``context`` is optionally ident-hash used to find the content within the context of a Collection ident_hash. """ id, version = get_id_n_version(ident_hash) filename = 'index.cnxml.html' if conte...
python
def get_content(ident_hash, context=None): """Returns the content for the given ``ident_hash``. ``context`` is optionally ident-hash used to find the content within the context of a Collection ident_hash. """ id, version = get_id_n_version(ident_hash) filename = 'index.cnxml.html' if conte...
[ "def", "get_content", "(", "ident_hash", ",", "context", "=", "None", ")", ":", "id", ",", "version", "=", "get_id_n_version", "(", "ident_hash", ")", "filename", "=", "'index.cnxml.html'", "if", "context", "is", "not", "None", ":", "stmt", "=", "_get_sql", ...
Returns the content for the given ``ident_hash``. ``context`` is optionally ident-hash used to find the content within the context of a Collection ident_hash.
[ "Returns", "the", "content", "for", "the", "given", "ident_hash", ".", "context", "is", "optionally", "ident", "-", "hash", "used", "to", "find", "the", "content", "within", "the", "context", "of", "a", "Collection", "ident_hash", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/export_epub/db.py#L114-L137
openstax/cnx-archive
cnxarchive/scripts/export_epub/db.py
get_file_info
def get_file_info(hash, context=None): """Returns information about the file, identified by ``hash``. If the `context` (an ident-hash) is supplied, the information returned will be specific to that context. """ if context is None: stmt = _get_sql('get-file-info.sql') args = dict(has...
python
def get_file_info(hash, context=None): """Returns information about the file, identified by ``hash``. If the `context` (an ident-hash) is supplied, the information returned will be specific to that context. """ if context is None: stmt = _get_sql('get-file-info.sql') args = dict(has...
[ "def", "get_file_info", "(", "hash", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "stmt", "=", "_get_sql", "(", "'get-file-info.sql'", ")", "args", "=", "dict", "(", "hash", "=", "hash", ")", "else", ":", "stmt", "=", "_...
Returns information about the file, identified by ``hash``. If the `context` (an ident-hash) is supplied, the information returned will be specific to that context.
[ "Returns", "information", "about", "the", "file", "identified", "by", "hash", ".", "If", "the", "context", "(", "an", "ident", "-", "hash", ")", "is", "supplied", "the", "information", "returned", "will", "be", "specific", "to", "that", "context", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/export_epub/db.py#L140-L161
openstax/cnx-archive
cnxarchive/scripts/export_epub/db.py
get_file
def get_file(hash): """Return the contents of the file as a ``memoryview``.""" stmt = _get_sql('get-file.sql') args = dict(hash=hash) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute(stmt, args) try: file, _ = cursor.fetchone(...
python
def get_file(hash): """Return the contents of the file as a ``memoryview``.""" stmt = _get_sql('get-file.sql') args = dict(hash=hash) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute(stmt, args) try: file, _ = cursor.fetchone(...
[ "def", "get_file", "(", "hash", ")", ":", "stmt", "=", "_get_sql", "(", "'get-file.sql'", ")", "args", "=", "dict", "(", "hash", "=", "hash", ")", "with", "db_connect", "(", ")", "as", "db_conn", ":", "with", "db_conn", ".", "cursor", "(", ")", "as",...
Return the contents of the file as a ``memoryview``.
[ "Return", "the", "contents", "of", "the", "file", "as", "a", "memoryview", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/export_epub/db.py#L164-L176
openstax/cnx-archive
cnxarchive/scripts/export_epub/db.py
get_registered_files
def get_registered_files(ident_hash): """Returns a list SHA1 hashes for registered file entries identified by the given module ``ident_hash``. Note, it's possible for a module to reference a file without having a registered file entry for it. Note, all files are included, including the raw form of...
python
def get_registered_files(ident_hash): """Returns a list SHA1 hashes for registered file entries identified by the given module ``ident_hash``. Note, it's possible for a module to reference a file without having a registered file entry for it. Note, all files are included, including the raw form of...
[ "def", "get_registered_files", "(", "ident_hash", ")", ":", "id", ",", "version", "=", "get_id_n_version", "(", "ident_hash", ")", "stmt", "=", "_get_sql", "(", "'get-registered-files-info.sql'", ")", "args", "=", "dict", "(", "id", "=", "id", ",", "version", ...
Returns a list SHA1 hashes for registered file entries identified by the given module ``ident_hash``. Note, it's possible for a module to reference a file without having a registered file entry for it. Note, all files are included, including the raw form of the content.
[ "Returns", "a", "list", "SHA1", "hashes", "for", "registered", "file", "entries", "identified", "by", "the", "given", "module", "ident_hash", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/export_epub/db.py#L179-L201
openstax/cnx-archive
cnxarchive/scripts/export_epub/db.py
get_tree
def get_tree(ident_hash, baked=False): """Return a tree structure of the Collection""" id, version = get_id_n_version(ident_hash) stmt = _get_sql('get-tree.sql') args = dict(id=id, version=version, baked=baked) with db_connect() as db_conn: with db_conn.cursor() as cursor: curs...
python
def get_tree(ident_hash, baked=False): """Return a tree structure of the Collection""" id, version = get_id_n_version(ident_hash) stmt = _get_sql('get-tree.sql') args = dict(id=id, version=version, baked=baked) with db_connect() as db_conn: with db_conn.cursor() as cursor: curs...
[ "def", "get_tree", "(", "ident_hash", ",", "baked", "=", "False", ")", ":", "id", ",", "version", "=", "get_id_n_version", "(", "ident_hash", ")", "stmt", "=", "_get_sql", "(", "'get-tree.sql'", ")", "args", "=", "dict", "(", "id", "=", "id", ",", "ver...
Return a tree structure of the Collection
[ "Return", "a", "tree", "structure", "of", "the", "Collection" ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/export_epub/db.py#L204-L221
openstax/cnx-archive
cnxarchive/scripts/inject_resource.py
guess_media_type
def guess_media_type(filepath): """Returns the media-type of the file at the given ``filepath``""" o = subprocess.check_output(['file', '--mime-type', '-Lb', filepath]) o = o.strip() return o
python
def guess_media_type(filepath): """Returns the media-type of the file at the given ``filepath``""" o = subprocess.check_output(['file', '--mime-type', '-Lb', filepath]) o = o.strip() return o
[ "def", "guess_media_type", "(", "filepath", ")", ":", "o", "=", "subprocess", ".", "check_output", "(", "[", "'file'", ",", "'--mime-type'", ",", "'-Lb'", ",", "filepath", "]", ")", "o", "=", "o", ".", "strip", "(", ")", "return", "o" ]
Returns the media-type of the file at the given ``filepath``
[ "Returns", "the", "media", "-", "type", "of", "the", "file", "at", "the", "given", "filepath" ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/inject_resource.py#L29-L33
openstax/cnx-archive
cnxarchive/scripts/inject_resource.py
lookup_module_ident
def lookup_module_ident(id, version): """Return the ``module_ident`` for the given ``id`` & major and minor version as a tuple. """ with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute( "SELECT module_ident FROM modules " "WHE...
python
def lookup_module_ident(id, version): """Return the ``module_ident`` for the given ``id`` & major and minor version as a tuple. """ with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute( "SELECT module_ident FROM modules " "WHE...
[ "def", "lookup_module_ident", "(", "id", ",", "version", ")", ":", "with", "db_connect", "(", ")", "as", "db_conn", ":", "with", "db_conn", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", "\"SELECT module_ident FROM modules \"", ...
Return the ``module_ident`` for the given ``id`` & major and minor version as a tuple.
[ "Return", "the", "module_ident", "for", "the", "given", "id", "&", "major", "and", "minor", "version", "as", "a", "tuple", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/inject_resource.py#L47-L65
openstax/cnx-archive
cnxarchive/scripts/inject_resource.py
insert_file
def insert_file(file, media_type): """Upsert the ``file`` and ``media_type`` into the files table. Returns the ``fileid`` and ``sha1`` of the upserted file. """ resource_hash = get_file_sha1(file) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("SEL...
python
def insert_file(file, media_type): """Upsert the ``file`` and ``media_type`` into the files table. Returns the ``fileid`` and ``sha1`` of the upserted file. """ resource_hash = get_file_sha1(file) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("SEL...
[ "def", "insert_file", "(", "file", ",", "media_type", ")", ":", "resource_hash", "=", "get_file_sha1", "(", "file", ")", "with", "db_connect", "(", ")", "as", "db_conn", ":", "with", "db_conn", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".",...
Upsert the ``file`` and ``media_type`` into the files table. Returns the ``fileid`` and ``sha1`` of the upserted file.
[ "Upsert", "the", "file", "and", "media_type", "into", "the", "files", "table", ".", "Returns", "the", "fileid", "and", "sha1", "of", "the", "upserted", "file", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/inject_resource.py#L68-L86
openstax/cnx-archive
cnxarchive/scripts/inject_resource.py
upsert_module_file
def upsert_module_file(module_ident, fileid, filename): """Upsert a file associated with ``fileid`` with ``filename`` as a module_files entry associated with content at ``module_ident``. """ with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("SELECT true F...
python
def upsert_module_file(module_ident, fileid, filename): """Upsert a file associated with ``fileid`` with ``filename`` as a module_files entry associated with content at ``module_ident``. """ with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("SELECT true F...
[ "def", "upsert_module_file", "(", "module_ident", ",", "fileid", ",", "filename", ")", ":", "with", "db_connect", "(", ")", "as", "db_conn", ":", "with", "db_conn", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", "\"SELECT true...
Upsert a file associated with ``fileid`` with ``filename`` as a module_files entry associated with content at ``module_ident``.
[ "Upsert", "a", "file", "associated", "with", "fileid", "with", "filename", "as", "a", "module_files", "entry", "associated", "with", "content", "at", "module_ident", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/inject_resource.py#L89-L111
openstax/cnx-archive
cnxarchive/scripts/inject_resource.py
inject_resource
def inject_resource(ident_hash, file, filename, media_type): """Injects the contents of ``file`` (a file-like object) into the database as ``filename`` with ``media_type`` in association with the content at ``ident_hash``. """ resource_hash = get_file_sha1(file) with db_connect() as db_conn: ...
python
def inject_resource(ident_hash, file, filename, media_type): """Injects the contents of ``file`` (a file-like object) into the database as ``filename`` with ``media_type`` in association with the content at ``ident_hash``. """ resource_hash = get_file_sha1(file) with db_connect() as db_conn: ...
[ "def", "inject_resource", "(", "ident_hash", ",", "file", ",", "filename", ",", "media_type", ")", ":", "resource_hash", "=", "get_file_sha1", "(", "file", ")", "with", "db_connect", "(", ")", "as", "db_conn", ":", "with", "db_conn", ".", "cursor", "(", ")...
Injects the contents of ``file`` (a file-like object) into the database as ``filename`` with ``media_type`` in association with the content at ``ident_hash``.
[ "Injects", "the", "contents", "of", "file", "(", "a", "file", "-", "like", "object", ")", "into", "the", "database", "as", "filename", "with", "media_type", "in", "association", "with", "the", "content", "at", "ident_hash", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/inject_resource.py#L114-L127
ZELLMECHANIK-DRESDEN/dclab
dclab/features/contour.py
get_contour
def get_contour(mask): """Compute the image contour from a mask The contour is computed in a very inefficient way using scikit-image and a conversion of float coordinates to pixel coordinates. Parameters ---------- mask: binary ndarray of shape (M,N) or (K,M,N) The mask outlining the p...
python
def get_contour(mask): """Compute the image contour from a mask The contour is computed in a very inefficient way using scikit-image and a conversion of float coordinates to pixel coordinates. Parameters ---------- mask: binary ndarray of shape (M,N) or (K,M,N) The mask outlining the p...
[ "def", "get_contour", "(", "mask", ")", ":", "if", "isinstance", "(", "mask", ",", "np", ".", "ndarray", ")", "and", "len", "(", "mask", ".", "shape", ")", "==", "2", ":", "mask", "=", "[", "mask", "]", "ret_list", "=", "False", "else", ":", "ret...
Compute the image contour from a mask The contour is computed in a very inefficient way using scikit-image and a conversion of float coordinates to pixel coordinates. Parameters ---------- mask: binary ndarray of shape (M,N) or (K,M,N) The mask outlining the pixel positions of the event. ...
[ "Compute", "the", "image", "contour", "from", "a", "mask" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/features/contour.py#L13-L54
simse/pymitv
pymitv/discover.py
Discover.scan
def scan(self, stop_on_first=True, base_ip=0): """Scans the local network for TVs.""" tvs = [] # Check if base_ip has been passed if base_ip == 0: # Find IP address of computer pymitv is running on sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ...
python
def scan(self, stop_on_first=True, base_ip=0): """Scans the local network for TVs.""" tvs = [] # Check if base_ip has been passed if base_ip == 0: # Find IP address of computer pymitv is running on sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ...
[ "def", "scan", "(", "self", ",", "stop_on_first", "=", "True", ",", "base_ip", "=", "0", ")", ":", "tvs", "=", "[", "]", "# Check if base_ip has been passed\r", "if", "base_ip", "==", "0", ":", "# Find IP address of computer pymitv is running on\r", "sock", "=", ...
Scans the local network for TVs.
[ "Scans", "the", "local", "network", "for", "TVs", "." ]
train
https://github.com/simse/pymitv/blob/03213f591d70fbf90ba2b6af372e474c9bfb99f6/pymitv/discover.py#L13-L39
simse/pymitv
pymitv/discover.py
Discover.check_ip
def check_ip(ip, log=False): """Attempts a connection to the TV and checks if there really is a TV.""" if log: print('Checking ip: {}...'.format(ip)) request_timeout = 0.1 try: tv_url = 'http://{}:6095/request?action=isalive'.format(ip) requ...
python
def check_ip(ip, log=False): """Attempts a connection to the TV and checks if there really is a TV.""" if log: print('Checking ip: {}...'.format(ip)) request_timeout = 0.1 try: tv_url = 'http://{}:6095/request?action=isalive'.format(ip) requ...
[ "def", "check_ip", "(", "ip", ",", "log", "=", "False", ")", ":", "if", "log", ":", "print", "(", "'Checking ip: {}...'", ".", "format", "(", "ip", ")", ")", "request_timeout", "=", "0.1", "try", ":", "tv_url", "=", "'http://{}:6095/request?action=isalive'",...
Attempts a connection to the TV and checks if there really is a TV.
[ "Attempts", "a", "connection", "to", "the", "TV", "and", "checks", "if", "there", "really", "is", "a", "TV", "." ]
train
https://github.com/simse/pymitv/blob/03213f591d70fbf90ba2b6af372e474c9bfb99f6/pymitv/discover.py#L42-L55
xenon-middleware/pyxenon
xenon/oop.py
get_field_type
def get_field_type(f): """Obtain the type name of a GRPC Message field.""" types = (t[5:] for t in dir(f) if t[:4] == 'TYPE' and getattr(f, t) == f.type) return next(types)
python
def get_field_type(f): """Obtain the type name of a GRPC Message field.""" types = (t[5:] for t in dir(f) if t[:4] == 'TYPE' and getattr(f, t) == f.type) return next(types)
[ "def", "get_field_type", "(", "f", ")", ":", "types", "=", "(", "t", "[", "5", ":", "]", "for", "t", "in", "dir", "(", "f", ")", "if", "t", "[", ":", "4", "]", "==", "'TYPE'", "and", "getattr", "(", "f", ",", "t", ")", "==", "f", ".", "ty...
Obtain the type name of a GRPC Message field.
[ "Obtain", "the", "type", "name", "of", "a", "GRPC", "Message", "field", "." ]
train
https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/oop.py#L48-L52
xenon-middleware/pyxenon
xenon/oop.py
get_field_description
def get_field_description(f): """Get the type description of a GRPC Message field.""" type_name = get_field_type(f) if type_name == 'MESSAGE' and \ {sf.name for sf in f.message_type.fields} == {'key', 'value'}: return 'map<string, string>' elif type_name == 'MESSAGE': return ...
python
def get_field_description(f): """Get the type description of a GRPC Message field.""" type_name = get_field_type(f) if type_name == 'MESSAGE' and \ {sf.name for sf in f.message_type.fields} == {'key', 'value'}: return 'map<string, string>' elif type_name == 'MESSAGE': return ...
[ "def", "get_field_description", "(", "f", ")", ":", "type_name", "=", "get_field_type", "(", "f", ")", "if", "type_name", "==", "'MESSAGE'", "and", "{", "sf", ".", "name", "for", "sf", "in", "f", ".", "message_type", ".", "fields", "}", "==", "{", "'ke...
Get the type description of a GRPC Message field.
[ "Get", "the", "type", "description", "of", "a", "GRPC", "Message", "field", "." ]
train
https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/oop.py#L55-L66
xenon-middleware/pyxenon
xenon/oop.py
make_static_request
def make_static_request(method, *args, **kwargs): """Creates a request from a static method function call.""" if args and not use_signature: raise NotImplementedError("Only keyword arguments allowed in Python2") if use_signature: new_kwargs = {kw: unwrap(value) for kw, value in kwargs.items...
python
def make_static_request(method, *args, **kwargs): """Creates a request from a static method function call.""" if args and not use_signature: raise NotImplementedError("Only keyword arguments allowed in Python2") if use_signature: new_kwargs = {kw: unwrap(value) for kw, value in kwargs.items...
[ "def", "make_static_request", "(", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "and", "not", "use_signature", ":", "raise", "NotImplementedError", "(", "\"Only keyword arguments allowed in Python2\"", ")", "if", "use_signature", ":...
Creates a request from a static method function call.
[ "Creates", "a", "request", "from", "a", "static", "method", "function", "call", "." ]
train
https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/oop.py#L188-L209
xenon-middleware/pyxenon
xenon/oop.py
make_request
def make_request(self, method, *args, **kwargs): """Creates a request from a method function call.""" if args and not use_signature: raise NotImplementedError("Only keyword arguments allowed in Python2") new_kwargs = {kw: unwrap(value) for kw, value in kwargs.items()} if use_signature: ...
python
def make_request(self, method, *args, **kwargs): """Creates a request from a method function call.""" if args and not use_signature: raise NotImplementedError("Only keyword arguments allowed in Python2") new_kwargs = {kw: unwrap(value) for kw, value in kwargs.items()} if use_signature: ...
[ "def", "make_request", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "and", "not", "use_signature", ":", "raise", "NotImplementedError", "(", "\"Only keyword arguments allowed in Python2\"", ")", "new_kwargs", "="...
Creates a request from a method function call.
[ "Creates", "a", "request", "from", "a", "method", "function", "call", "." ]
train
https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/oop.py#L212-L248
xenon-middleware/pyxenon
xenon/oop.py
method_wrapper
def method_wrapper(m): """Generates a method from a `GrpcMethod` definition.""" if m.is_simple: def simple_method(self): """TODO: no docstring!""" return apply_transform( self.__service__, m.output_transform, grpc_call(self.__service__, m, unwrap(...
python
def method_wrapper(m): """Generates a method from a `GrpcMethod` definition.""" if m.is_simple: def simple_method(self): """TODO: no docstring!""" return apply_transform( self.__service__, m.output_transform, grpc_call(self.__service__, m, unwrap(...
[ "def", "method_wrapper", "(", "m", ")", ":", "if", "m", ".", "is_simple", ":", "def", "simple_method", "(", "self", ")", ":", "\"\"\"TODO: no docstring!\"\"\"", "return", "apply_transform", "(", "self", ".", "__service__", ",", "m", ".", "output_transform", ",...
Generates a method from a `GrpcMethod` definition.
[ "Generates", "a", "method", "from", "a", "GrpcMethod", "definition", "." ]
train
https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/oop.py#L276-L316
xenon-middleware/pyxenon
xenon/oop.py
GrpcMethod.request_name
def request_name(self): """Generate the name of the request.""" if self.static and not self.uses_request: return 'Empty' if not self.uses_request: return None if isinstance(self.uses_request, str): return self.uses_request return to_camel_ca...
python
def request_name(self): """Generate the name of the request.""" if self.static and not self.uses_request: return 'Empty' if not self.uses_request: return None if isinstance(self.uses_request, str): return self.uses_request return to_camel_ca...
[ "def", "request_name", "(", "self", ")", ":", "if", "self", ".", "static", "and", "not", "self", ".", "uses_request", ":", "return", "'Empty'", "if", "not", "self", ".", "uses_request", ":", "return", "None", "if", "isinstance", "(", "self", ".", "uses_r...
Generate the name of the request.
[ "Generate", "the", "name", "of", "the", "request", "." ]
train
https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/oop.py#L104-L115
xenon-middleware/pyxenon
xenon/oop.py
GrpcMethod.request_type
def request_type(self): """Retrieve the type of the request, by fetching it from `xenon.proto.xenon_pb2`.""" if self.static and not self.uses_request: return getattr(xenon_pb2, 'Empty') if not self.uses_request: return None return getattr(xenon_pb2, self...
python
def request_type(self): """Retrieve the type of the request, by fetching it from `xenon.proto.xenon_pb2`.""" if self.static and not self.uses_request: return getattr(xenon_pb2, 'Empty') if not self.uses_request: return None return getattr(xenon_pb2, self...
[ "def", "request_type", "(", "self", ")", ":", "if", "self", ".", "static", "and", "not", "self", ".", "uses_request", ":", "return", "getattr", "(", "xenon_pb2", ",", "'Empty'", ")", "if", "not", "self", ".", "uses_request", ":", "return", "None", "retur...
Retrieve the type of the request, by fetching it from `xenon.proto.xenon_pb2`.
[ "Retrieve", "the", "type", "of", "the", "request", "by", "fetching", "it", "from", "xenon", ".", "proto", ".", "xenon_pb2", "." ]
train
https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/oop.py#L118-L127
xenon-middleware/pyxenon
xenon/oop.py
GrpcMethod.signature
def signature(self): """Create a signature for this method, only in Python > 3.4""" if not use_signature: raise NotImplementedError("Python 3 only.") if self.static: parameters = \ (Parameter(name='cls', kind=Parameter.POSITIONA...
python
def signature(self): """Create a signature for this method, only in Python > 3.4""" if not use_signature: raise NotImplementedError("Python 3 only.") if self.static: parameters = \ (Parameter(name='cls', kind=Parameter.POSITIONA...
[ "def", "signature", "(", "self", ")", ":", "if", "not", "use_signature", ":", "raise", "NotImplementedError", "(", "\"Python 3 only.\"", ")", "if", "self", ".", "static", ":", "parameters", "=", "(", "Parameter", "(", "name", "=", "'cls'", ",", "kind", "="...
Create a signature for this method, only in Python > 3.4
[ "Create", "a", "signature", "for", "this", "method", "only", "in", "Python", ">", "3", ".", "4" ]
train
https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/oop.py#L131-L161
xenon-middleware/pyxenon
xenon/oop.py
GrpcMethod.docstring
def docstring(self, servicer): """Generate a doc-string.""" s = getattr(servicer, to_lower_camel_case(self.name)).__doc__ \ or "TODO: no docstring in .proto file" if self.uses_request: s += "\n" for field in get_fields(self.request_type): if f...
python
def docstring(self, servicer): """Generate a doc-string.""" s = getattr(servicer, to_lower_camel_case(self.name)).__doc__ \ or "TODO: no docstring in .proto file" if self.uses_request: s += "\n" for field in get_fields(self.request_type): if f...
[ "def", "docstring", "(", "self", ",", "servicer", ")", ":", "s", "=", "getattr", "(", "servicer", ",", "to_lower_camel_case", "(", "self", ".", "name", ")", ")", ".", "__doc__", "or", "\"TODO: no docstring in .proto file\"", "if", "self", ".", "uses_request", ...
Generate a doc-string.
[ "Generate", "a", "doc", "-", "string", "." ]
train
https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/oop.py#L164-L178
openstax/cnx-archive
cnxarchive/utils/text.py
slugify
def slugify(string): """Return a slug for the unicode_string. (lowercase, only letters and numbers, hyphens replace spaces) """ filtered_string = [] if isinstance(string, str): string = unicode(string, 'utf-8') for i in unicodedata.normalize('NFKC', string): cat = unicodedata.ca...
python
def slugify(string): """Return a slug for the unicode_string. (lowercase, only letters and numbers, hyphens replace spaces) """ filtered_string = [] if isinstance(string, str): string = unicode(string, 'utf-8') for i in unicodedata.normalize('NFKC', string): cat = unicodedata.ca...
[ "def", "slugify", "(", "string", ")", ":", "filtered_string", "=", "[", "]", "if", "isinstance", "(", "string", ",", "str", ")", ":", "string", "=", "unicode", "(", "string", ",", "'utf-8'", ")", "for", "i", "in", "unicodedata", ".", "normalize", "(", ...
Return a slug for the unicode_string. (lowercase, only letters and numbers, hyphens replace spaces)
[ "Return", "a", "slug", "for", "the", "unicode_string", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/utils/text.py#L16-L32
openstax/cnx-archive
cnxarchive/utils/text.py
utf8
def utf8(item): """Change all python2 str/bytes instances to unicode/python3 str.""" if isinstance(item, list): return [utf8(i) for i in item] if isinstance(item, tuple): return tuple([utf8(i) for i in item]) if isinstance(item, dict): return {utf8(k): utf8(v) for k, v in item.it...
python
def utf8(item): """Change all python2 str/bytes instances to unicode/python3 str.""" if isinstance(item, list): return [utf8(i) for i in item] if isinstance(item, tuple): return tuple([utf8(i) for i in item]) if isinstance(item, dict): return {utf8(k): utf8(v) for k, v in item.it...
[ "def", "utf8", "(", "item", ")", ":", "if", "isinstance", "(", "item", ",", "list", ")", ":", "return", "[", "utf8", "(", "i", ")", "for", "i", "in", "item", "]", "if", "isinstance", "(", "item", ",", "tuple", ")", ":", "return", "tuple", "(", ...
Change all python2 str/bytes instances to unicode/python3 str.
[ "Change", "all", "python2", "str", "/", "bytes", "instances", "to", "unicode", "/", "python3", "str", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/utils/text.py#L35-L46
ZELLMECHANIK-DRESDEN/dclab
dclab/rtdc_dataset/filter.py
Filter.update
def update(self, force=[]): """Update the filters according to `self.rtdc_ds.config["filtering"]` Parameters ---------- force : list A list of feature names that must be refiltered with min/max values. """ # These lists may help us become very fa...
python
def update(self, force=[]): """Update the filters according to `self.rtdc_ds.config["filtering"]` Parameters ---------- force : list A list of feature names that must be refiltered with min/max values. """ # These lists may help us become very fa...
[ "def", "update", "(", "self", ",", "force", "=", "[", "]", ")", ":", "# These lists may help us become very fast in the future", "newkeys", "=", "[", "]", "oldvals", "=", "[", "]", "newvals", "=", "[", "]", "cfg_cur", "=", "self", ".", "rtdc_ds", ".", "con...
Update the filters according to `self.rtdc_ds.config["filtering"]` Parameters ---------- force : list A list of feature names that must be refiltered with min/max values.
[ "Update", "the", "filters", "according", "to", "self", ".", "rtdc_ds", ".", "config", "[", "filtering", "]" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/filter.py#L49-L170
ZELLMECHANIK-DRESDEN/dclab
dclab/external/skimage/_find_contours.py
find_contours
def find_contours(array, level, fully_connected='low', positive_orientation='low'): """Find iso-valued contours in a 2D array for a given level value. Uses the "marching squares" method to compute a the iso-valued contours of the input 2D array for a particular level value. Array values a...
python
def find_contours(array, level, fully_connected='low', positive_orientation='low'): """Find iso-valued contours in a 2D array for a given level value. Uses the "marching squares" method to compute a the iso-valued contours of the input 2D array for a particular level value. Array values a...
[ "def", "find_contours", "(", "array", ",", "level", ",", "fully_connected", "=", "'low'", ",", "positive_orientation", "=", "'low'", ")", ":", "array", "=", "np", ".", "asarray", "(", "array", ",", "dtype", "=", "np", ".", "double", ")", "if", "array", ...
Find iso-valued contours in a 2D array for a given level value. Uses the "marching squares" method to compute a the iso-valued contours of the input 2D array for a particular level value. Array values are linearly interpolated to provide better precision for the output contours. Parameters -------...
[ "Find", "iso", "-", "valued", "contours", "in", "a", "2D", "array", "for", "a", "given", "level", "value", "." ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/external/skimage/_find_contours.py#L9-L124
openstax/cnx-archive
cnxarchive/database.py
get_module_ident_from_ident_hash
def get_module_ident_from_ident_hash(ident_hash, cursor): """Return the moduleid for a given ``ident_hash``.""" try: uuid, (mj_ver, mn_ver) = split_ident_hash( ident_hash, split_version=True) except IdentHashMissingVersion as e: uuid, mj_ver, mn_ver = e.id, None, None args = ...
python
def get_module_ident_from_ident_hash(ident_hash, cursor): """Return the moduleid for a given ``ident_hash``.""" try: uuid, (mj_ver, mn_ver) = split_ident_hash( ident_hash, split_version=True) except IdentHashMissingVersion as e: uuid, mj_ver, mn_ver = e.id, None, None args = ...
[ "def", "get_module_ident_from_ident_hash", "(", "ident_hash", ",", "cursor", ")", ":", "try", ":", "uuid", ",", "(", "mj_ver", ",", "mn_ver", ")", "=", "split_ident_hash", "(", "ident_hash", ",", "split_version", "=", "True", ")", "except", "IdentHashMissingVers...
Return the moduleid for a given ``ident_hash``.
[ "Return", "the", "moduleid", "for", "a", "given", "ident_hash", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L98-L123
openstax/cnx-archive
cnxarchive/database.py
get_tree
def get_tree(ident_hash, cursor, as_collated=False): """Return a JSON representation of the binder tree for ``ident_hash``.""" uuid, version = split_ident_hash(ident_hash) cursor.execute(SQL['get-tree-by-uuid-n-version'], (uuid, version, as_collated,)) try: tree = cursor.fetch...
python
def get_tree(ident_hash, cursor, as_collated=False): """Return a JSON representation of the binder tree for ``ident_hash``.""" uuid, version = split_ident_hash(ident_hash) cursor.execute(SQL['get-tree-by-uuid-n-version'], (uuid, version, as_collated,)) try: tree = cursor.fetch...
[ "def", "get_tree", "(", "ident_hash", ",", "cursor", ",", "as_collated", "=", "False", ")", ":", "uuid", ",", "version", "=", "split_ident_hash", "(", "ident_hash", ")", "cursor", ".", "execute", "(", "SQL", "[", "'get-tree-by-uuid-n-version'", "]", ",", "("...
Return a JSON representation of the binder tree for ``ident_hash``.
[ "Return", "a", "JSON", "representation", "of", "the", "binder", "tree", "for", "ident_hash", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L126-L138
openstax/cnx-archive
cnxarchive/database.py
get_collated_content
def get_collated_content(ident_hash, context_ident_hash, cursor): """Return collated content for ``ident_hash``.""" cursor.execute(SQL['get-collated-content'], (ident_hash, context_ident_hash,)) try: return cursor.fetchone()[0] except TypeError: # NoneType return
python
def get_collated_content(ident_hash, context_ident_hash, cursor): """Return collated content for ``ident_hash``.""" cursor.execute(SQL['get-collated-content'], (ident_hash, context_ident_hash,)) try: return cursor.fetchone()[0] except TypeError: # NoneType return
[ "def", "get_collated_content", "(", "ident_hash", ",", "context_ident_hash", ",", "cursor", ")", ":", "cursor", ".", "execute", "(", "SQL", "[", "'get-collated-content'", "]", ",", "(", "ident_hash", ",", "context_ident_hash", ",", ")", ")", "try", ":", "retur...
Return collated content for ``ident_hash``.
[ "Return", "collated", "content", "for", "ident_hash", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L141-L148
openstax/cnx-archive
cnxarchive/database.py
get_module_uuid
def get_module_uuid(plpy, moduleid): """Retrieve page uuid from legacy moduleid.""" plan = plpy.prepare("SELECT uuid FROM modules WHERE moduleid = $1;", ('text',)) result = plpy.execute(plan, (moduleid,), 1) if result: return result[0]['uuid']
python
def get_module_uuid(plpy, moduleid): """Retrieve page uuid from legacy moduleid.""" plan = plpy.prepare("SELECT uuid FROM modules WHERE moduleid = $1;", ('text',)) result = plpy.execute(plan, (moduleid,), 1) if result: return result[0]['uuid']
[ "def", "get_module_uuid", "(", "plpy", ",", "moduleid", ")", ":", "plan", "=", "plpy", ".", "prepare", "(", "\"SELECT uuid FROM modules WHERE moduleid = $1;\"", ",", "(", "'text'", ",", ")", ")", "result", "=", "plpy", ".", "execute", "(", "plan", ",", "(", ...
Retrieve page uuid from legacy moduleid.
[ "Retrieve", "page", "uuid", "from", "legacy", "moduleid", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L151-L157
openstax/cnx-archive
cnxarchive/database.py
get_current_module_ident
def get_current_module_ident(moduleid, plpy): """Retrieve module_ident for a given moduleid. Note that module_ident is used only for internal database relational associations, and is equivalent to a uuid@version for a given document. """ plan = plpy.prepare('''\ SELECT m.module_ident FROM m...
python
def get_current_module_ident(moduleid, plpy): """Retrieve module_ident for a given moduleid. Note that module_ident is used only for internal database relational associations, and is equivalent to a uuid@version for a given document. """ plan = plpy.prepare('''\ SELECT m.module_ident FROM m...
[ "def", "get_current_module_ident", "(", "moduleid", ",", "plpy", ")", ":", "plan", "=", "plpy", ".", "prepare", "(", "'''\\\n SELECT m.module_ident FROM modules m\n WHERE m.moduleid = $1 ORDER BY revised DESC'''", ",", "(", "'text'", ",", ")", ")", "results", ...
Retrieve module_ident for a given moduleid. Note that module_ident is used only for internal database relational associations, and is equivalent to a uuid@version for a given document.
[ "Retrieve", "module_ident", "for", "a", "given", "moduleid", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L160-L171
openstax/cnx-archive
cnxarchive/database.py
get_minor_version
def get_minor_version(module_ident, plpy): """Retrieve minor version only given module_ident.""" # Make sure to always return the max minor version that is already in the # database, in case the given module_ident is not the latest version plan = plpy.prepare('''\ WITH t AS ( SELECT ...
python
def get_minor_version(module_ident, plpy): """Retrieve minor version only given module_ident.""" # Make sure to always return the max minor version that is already in the # database, in case the given module_ident is not the latest version plan = plpy.prepare('''\ WITH t AS ( SELECT ...
[ "def", "get_minor_version", "(", "module_ident", ",", "plpy", ")", ":", "# Make sure to always return the max minor version that is already in the", "# database, in case the given module_ident is not the latest version", "plan", "=", "plpy", ".", "prepare", "(", "'''\\\n WITH ...
Retrieve minor version only given module_ident.
[ "Retrieve", "minor", "version", "only", "given", "module_ident", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L174-L189
openstax/cnx-archive
cnxarchive/database.py
get_collections
def get_collections(module_ident, plpy): """Get all the collections that the module is part of.""" # Make sure to only return one match per collection and only if it is the # latest collection (which may not be the same as what is in # latest_modules) plan = plpy.prepare(''' WITH RECURSIVE t(node, p...
python
def get_collections(module_ident, plpy): """Get all the collections that the module is part of.""" # Make sure to only return one match per collection and only if it is the # latest collection (which may not be the same as what is in # latest_modules) plan = plpy.prepare(''' WITH RECURSIVE t(node, p...
[ "def", "get_collections", "(", "module_ident", ",", "plpy", ")", ":", "# Make sure to only return one match per collection and only if it is the", "# latest collection (which may not be the same as what is in", "# latest_modules)", "plan", "=", "plpy", ".", "prepare", "(", "'''\nWI...
Get all the collections that the module is part of.
[ "Get", "all", "the", "collections", "that", "the", "module", "is", "part", "of", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L201-L228
openstax/cnx-archive
cnxarchive/database.py
get_subcols
def get_subcols(module_ident, plpy): """Get all the sub-collections that the module is part of.""" plan = plpy.prepare(''' WITH RECURSIVE t(node, parent, path, document) AS ( SELECT tr.nodeid, tr.parent_id, ARRAY[tr.nodeid], tr.documentid FROM trees tr WHERE tr.documentid = $1 and tr...
python
def get_subcols(module_ident, plpy): """Get all the sub-collections that the module is part of.""" plan = plpy.prepare(''' WITH RECURSIVE t(node, parent, path, document) AS ( SELECT tr.nodeid, tr.parent_id, ARRAY[tr.nodeid], tr.documentid FROM trees tr WHERE tr.documentid = $1 and tr...
[ "def", "get_subcols", "(", "module_ident", ",", "plpy", ")", ":", "plan", "=", "plpy", ".", "prepare", "(", "'''\n WITH RECURSIVE t(node, parent, path, document) AS (\n SELECT tr.nodeid, tr.parent_id, ARRAY[tr.nodeid], tr.documentid\n FROM trees tr\n WHERE tr.docu...
Get all the sub-collections that the module is part of.
[ "Get", "all", "the", "sub", "-", "collections", "that", "the", "module", "is", "part", "of", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L231-L249
openstax/cnx-archive
cnxarchive/database.py
rebuild_collection_tree
def rebuild_collection_tree(old_collection_ident, new_document_id_map, plpy): """Create a new tree for the collection based on the old tree. This uses new document ids, replacing old ones. """ get_tree = plpy.prepare(''' WITH RECURSIVE t(node, parent, document, title, childorder, latest, path) ...
python
def rebuild_collection_tree(old_collection_ident, new_document_id_map, plpy): """Create a new tree for the collection based on the old tree. This uses new document ids, replacing old ones. """ get_tree = plpy.prepare(''' WITH RECURSIVE t(node, parent, document, title, childorder, latest, path) ...
[ "def", "rebuild_collection_tree", "(", "old_collection_ident", ",", "new_document_id_map", ",", "plpy", ")", ":", "get_tree", "=", "plpy", ".", "prepare", "(", "'''\n WITH RECURSIVE t(node, parent, document, title, childorder, latest, path)\n AS (SELECT tr.nodeid, tr.parent...
Create a new tree for the collection based on the old tree. This uses new document ids, replacing old ones.
[ "Create", "a", "new", "tree", "for", "the", "collection", "based", "on", "the", "old", "tree", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L252-L302
openstax/cnx-archive
cnxarchive/database.py
republish_collection
def republish_collection(submitter, submitlog, next_minor_version, collection_ident, plpy, revised=None): """Insert a new row for collection_ident with a new version. Returns the module_ident of the row inserted. """ sql = ''' INSERT INTO modules (portal_type, moduleid, uui...
python
def republish_collection(submitter, submitlog, next_minor_version, collection_ident, plpy, revised=None): """Insert a new row for collection_ident with a new version. Returns the module_ident of the row inserted. """ sql = ''' INSERT INTO modules (portal_type, moduleid, uui...
[ "def", "republish_collection", "(", "submitter", ",", "submitlog", ",", "next_minor_version", ",", "collection_ident", ",", "plpy", ",", "revised", "=", "None", ")", ":", "sql", "=", "'''\n INSERT INTO modules (portal_type, moduleid, uuid, version, name, created,\n ...
Insert a new row for collection_ident with a new version. Returns the module_ident of the row inserted.
[ "Insert", "a", "new", "row", "for", "collection_ident", "with", "a", "new", "version", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L305-L359
openstax/cnx-archive
cnxarchive/database.py
set_version
def set_version(portal_type, legacy_version, td): """Set the major_version and minor_version if they are not set.""" modified = 'OK' legacy_major, legacy_minor = legacy_version.split('.') if portal_type == 'Collection': # For collections, both major and minor needs to be set modified = ...
python
def set_version(portal_type, legacy_version, td): """Set the major_version and minor_version if they are not set.""" modified = 'OK' legacy_major, legacy_minor = legacy_version.split('.') if portal_type == 'Collection': # For collections, both major and minor needs to be set modified = ...
[ "def", "set_version", "(", "portal_type", ",", "legacy_version", ",", "td", ")", ":", "modified", "=", "'OK'", "legacy_major", ",", "legacy_minor", "=", "legacy_version", ".", "split", "(", "'.'", ")", "if", "portal_type", "==", "'Collection'", ":", "# For col...
Set the major_version and minor_version if they are not set.
[ "Set", "the", "major_version", "and", "minor_version", "if", "they", "are", "not", "set", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L362-L382
openstax/cnx-archive
cnxarchive/database.py
republish_module
def republish_module(td, plpy): """When a module is republished, create new minor versions of collections. All collections (including subcollections) that this module is contained in part of will need to be updated (a minor update). e.g. there is a collection c1 v2.1, which contains a chapter sc1 v2.1...
python
def republish_module(td, plpy): """When a module is republished, create new minor versions of collections. All collections (including subcollections) that this module is contained in part of will need to be updated (a minor update). e.g. there is a collection c1 v2.1, which contains a chapter sc1 v2.1...
[ "def", "republish_module", "(", "td", ",", "plpy", ")", ":", "portal_type", "=", "td", "[", "'new'", "]", "[", "'portal_type'", "]", "modified", "=", "'OK'", "moduleid", "=", "td", "[", "'new'", "]", "[", "'moduleid'", "]", "legacy_version", "=", "td", ...
When a module is republished, create new minor versions of collections. All collections (including subcollections) that this module is contained in part of will need to be updated (a minor update). e.g. there is a collection c1 v2.1, which contains a chapter sc1 v2.1, which contains a module m1 v3. Wh...
[ "When", "a", "module", "is", "republished", "create", "new", "minor", "versions", "of", "collections", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L385-L446
openstax/cnx-archive
cnxarchive/database.py
republish_module_trigger
def republish_module_trigger(plpy, td): """Trigger called from postgres database when republishing a module. When a module is republished, the versions of the collections that it is part of will need to be updated (a minor update). e.g. there is a collection c1 v2.1, which contains module m1 v3 ...
python
def republish_module_trigger(plpy, td): """Trigger called from postgres database when republishing a module. When a module is republished, the versions of the collections that it is part of will need to be updated (a minor update). e.g. there is a collection c1 v2.1, which contains module m1 v3 ...
[ "def", "republish_module_trigger", "(", "plpy", ",", "td", ")", ":", "# Is this an insert from legacy? Legacy always supplies the version.", "is_legacy_publication", "=", "td", "[", "'new'", "]", "[", "'version'", "]", "is", "not", "None", "if", "not", "is_legacy_public...
Trigger called from postgres database when republishing a module. When a module is republished, the versions of the collections that it is part of will need to be updated (a minor update). e.g. there is a collection c1 v2.1, which contains module m1 v3 m1 is updated, we have a new row in the modules...
[ "Trigger", "called", "from", "postgres", "database", "when", "republishing", "a", "module", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L449-L480
openstax/cnx-archive
cnxarchive/database.py
assign_moduleid_default_trigger
def assign_moduleid_default_trigger(plpy, td): """Trigger to fill in legacy ``moduleid`` when publishing. This correctly assigns ``moduleid`` value to cnx-publishing publications. This does NOT include matching the ``moduleid`` to previous revision by way of ``uuid``. This correctly updates the se...
python
def assign_moduleid_default_trigger(plpy, td): """Trigger to fill in legacy ``moduleid`` when publishing. This correctly assigns ``moduleid`` value to cnx-publishing publications. This does NOT include matching the ``moduleid`` to previous revision by way of ``uuid``. This correctly updates the se...
[ "def", "assign_moduleid_default_trigger", "(", "plpy", ",", "td", ")", ":", "modified_state", "=", "\"OK\"", "portal_type", "=", "td", "[", "'new'", "]", "[", "'portal_type'", "]", "uuid", "=", "td", "[", "'new'", "]", "[", "'uuid'", "]", "moduleid", "=", ...
Trigger to fill in legacy ``moduleid`` when publishing. This correctly assigns ``moduleid`` value to cnx-publishing publications. This does NOT include matching the ``moduleid`` to previous revision by way of ``uuid``. This correctly updates the sequence values when a legacy publication specifies ...
[ "Trigger", "to", "fill", "in", "legacy", "moduleid", "when", "publishing", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L483-L541
openstax/cnx-archive
cnxarchive/database.py
assign_version_default_trigger
def assign_version_default_trigger(plpy, td): """Trigger to fill in legacy data fields. A compatibilty trigger to fill in legacy data fields that are not populated when inserting publications from cnx-publishing. If this is not a legacy publication the ``version`` will be set based on the ``major_...
python
def assign_version_default_trigger(plpy, td): """Trigger to fill in legacy data fields. A compatibilty trigger to fill in legacy data fields that are not populated when inserting publications from cnx-publishing. If this is not a legacy publication the ``version`` will be set based on the ``major_...
[ "def", "assign_version_default_trigger", "(", "plpy", ",", "td", ")", ":", "modified_state", "=", "\"OK\"", "portal_type", "=", "td", "[", "'new'", "]", "[", "'portal_type'", "]", "version", "=", "td", "[", "'new'", "]", "[", "'version'", "]", "minor_version...
Trigger to fill in legacy data fields. A compatibilty trigger to fill in legacy data fields that are not populated when inserting publications from cnx-publishing. If this is not a legacy publication the ``version`` will be set based on the ``major_version`` value.
[ "Trigger", "to", "fill", "in", "legacy", "data", "fields", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L544-L572
openstax/cnx-archive
cnxarchive/database.py
assign_document_controls_default_trigger
def assign_document_controls_default_trigger(plpy, td): """Trigger to fill in document_controls when legacy publishes. A compatibilty trigger to fill in ``uuid`` and ``licenseid`` columns of the ``document_controls`` table that are not populated when inserting publications from legacy. This uuid d...
python
def assign_document_controls_default_trigger(plpy, td): """Trigger to fill in document_controls when legacy publishes. A compatibilty trigger to fill in ``uuid`` and ``licenseid`` columns of the ``document_controls`` table that are not populated when inserting publications from legacy. This uuid d...
[ "def", "assign_document_controls_default_trigger", "(", "plpy", ",", "td", ")", ":", "modified_state", "=", "\"OK\"", "uuid", "=", "td", "[", "'new'", "]", "[", "'uuid'", "]", "# Only do the procedure if this is a legacy publication.", "if", "uuid", "is", "None", ":...
Trigger to fill in document_controls when legacy publishes. A compatibilty trigger to fill in ``uuid`` and ``licenseid`` columns of the ``document_controls`` table that are not populated when inserting publications from legacy. This uuid default is not on ``modules.uuid`` column itself, because th...
[ "Trigger", "to", "fill", "in", "document_controls", "when", "legacy", "publishes", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L575-L599
openstax/cnx-archive
cnxarchive/database.py
upsert_document_acl_trigger
def upsert_document_acl_trigger(plpy, td): """Trigger for filling in acls when legacy publishes. A compatibility trigger to upsert authorization control entries (ACEs) for legacy publications. """ modified_state = "OK" uuid_ = td['new']['uuid'] authors = td['new']['authors'] and td['new']['...
python
def upsert_document_acl_trigger(plpy, td): """Trigger for filling in acls when legacy publishes. A compatibility trigger to upsert authorization control entries (ACEs) for legacy publications. """ modified_state = "OK" uuid_ = td['new']['uuid'] authors = td['new']['authors'] and td['new']['...
[ "def", "upsert_document_acl_trigger", "(", "plpy", ",", "td", ")", ":", "modified_state", "=", "\"OK\"", "uuid_", "=", "td", "[", "'new'", "]", "[", "'uuid'", "]", "authors", "=", "td", "[", "'new'", "]", "[", "'authors'", "]", "and", "td", "[", "'new'...
Trigger for filling in acls when legacy publishes. A compatibility trigger to upsert authorization control entries (ACEs) for legacy publications.
[ "Trigger", "for", "filling", "in", "acls", "when", "legacy", "publishes", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L602-L636
openstax/cnx-archive
cnxarchive/database.py
upsert_users_from_legacy_publication_trigger
def upsert_users_from_legacy_publication_trigger(plpy, td): """A compatibility trigger to upsert users from legacy persons table.""" modified_state = "OK" authors = td['new']['authors'] and td['new']['authors'] or [] maintainers = td['new']['maintainers'] and td['new']['maintainers'] or [] licensors...
python
def upsert_users_from_legacy_publication_trigger(plpy, td): """A compatibility trigger to upsert users from legacy persons table.""" modified_state = "OK" authors = td['new']['authors'] and td['new']['authors'] or [] maintainers = td['new']['maintainers'] and td['new']['maintainers'] or [] licensors...
[ "def", "upsert_users_from_legacy_publication_trigger", "(", "plpy", ",", "td", ")", ":", "modified_state", "=", "\"OK\"", "authors", "=", "td", "[", "'new'", "]", "[", "'authors'", "]", "and", "td", "[", "'new'", "]", "[", "'authors'", "]", "or", "[", "]",...
A compatibility trigger to upsert users from legacy persons table.
[ "A", "compatibility", "trigger", "to", "upsert", "users", "from", "legacy", "persons", "table", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L639-L670
openstax/cnx-archive
cnxarchive/database.py
insert_users_for_optional_roles_trigger
def insert_users_for_optional_roles_trigger(plpy, td): """Trigger to update users from optional roles entries. A compatibility trigger to insert users from moduleoptionalroles records. This is primarily for legacy compatibility, but it is not possible to tell whether the entry came from legacy or cnx-p...
python
def insert_users_for_optional_roles_trigger(plpy, td): """Trigger to update users from optional roles entries. A compatibility trigger to insert users from moduleoptionalroles records. This is primarily for legacy compatibility, but it is not possible to tell whether the entry came from legacy or cnx-p...
[ "def", "insert_users_for_optional_roles_trigger", "(", "plpy", ",", "td", ")", ":", "modified_state", "=", "\"OK\"", "users", "=", "td", "[", "'new'", "]", "[", "'personids'", "]", "and", "td", "[", "'new'", "]", "[", "'personids'", "]", "or", "[", "]", ...
Trigger to update users from optional roles entries. A compatibility trigger to insert users from moduleoptionalroles records. This is primarily for legacy compatibility, but it is not possible to tell whether the entry came from legacy or cnx-publishing. Therefore, we only insert into users.
[ "Trigger", "to", "update", "users", "from", "optional", "roles", "entries", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L673-L697
openstax/cnx-archive
cnxarchive/database.py
add_module_file
def add_module_file(plpy, td): """Database trigger for adding a module file. When a legacy ``index.cnxml`` is added, this trigger transforms it into html and stores it as ``index.cnxml.html``. When a cnx-publishing ``index.cnxml.html`` is added, this trigger checks if ``index.html.cnxml`` exists be...
python
def add_module_file(plpy, td): """Database trigger for adding a module file. When a legacy ``index.cnxml`` is added, this trigger transforms it into html and stores it as ``index.cnxml.html``. When a cnx-publishing ``index.cnxml.html`` is added, this trigger checks if ``index.html.cnxml`` exists be...
[ "def", "add_module_file", "(", "plpy", ",", "td", ")", ":", "module_ident", "=", "td", "[", "'new'", "]", "[", "'module_ident'", "]", "filename", "=", "td", "[", "'new'", "]", "[", "'filename'", "]", "msg", "=", "\"produce {}->{} for module_ident = {}\"", "d...
Database trigger for adding a module file. When a legacy ``index.cnxml`` is added, this trigger transforms it into html and stores it as ``index.cnxml.html``. When a cnx-publishing ``index.cnxml.html`` is added, this trigger checks if ``index.html.cnxml`` exists before transforming it into cnxml an...
[ "Database", "trigger", "for", "adding", "a", "module", "file", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L700-L764
openstax/cnx-archive
cnxarchive/database.py
_transform_abstract
def _transform_abstract(plpy, module_ident): """Transform abstract, bi-directionally. Transforms an abstract using one of content columns ('abstract' or 'html') to determine which direction the transform will go (cnxml->html or html->cnxml). A transform is done on either one of them to make the...
python
def _transform_abstract(plpy, module_ident): """Transform abstract, bi-directionally. Transforms an abstract using one of content columns ('abstract' or 'html') to determine which direction the transform will go (cnxml->html or html->cnxml). A transform is done on either one of them to make the...
[ "def", "_transform_abstract", "(", "plpy", ",", "module_ident", ")", ":", "plan", "=", "plpy", ".", "prepare", "(", "\"\"\"\\\nSELECT a.abstractid, a.abstract, a.html\nFROM modules AS m NATURAL JOIN abstracts AS a\nWHERE m.module_ident = $1\"\"\"", ",", "(", "'integer'", ",", "...
Transform abstract, bi-directionally. Transforms an abstract using one of content columns ('abstract' or 'html') to determine which direction the transform will go (cnxml->html or html->cnxml). A transform is done on either one of them to make the other value. If no value is supplied, the trigger r...
[ "Transform", "abstract", "bi", "-", "directionally", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L767-L807
openstax/cnx-archive
cnxarchive/database.py
get_collection_tree
def get_collection_tree(collection_ident, cursor): """Build and retrieve json tree representation of a book.""" cursor.execute(''' WITH RECURSIVE t(node, parent, document, path) AS ( SELECT tr.nodeid, tr.parent_id, tr.documentid, ARRAY[tr.nodeid] FROM trees tr WHERE tr.documentid = %...
python
def get_collection_tree(collection_ident, cursor): """Build and retrieve json tree representation of a book.""" cursor.execute(''' WITH RECURSIVE t(node, parent, document, path) AS ( SELECT tr.nodeid, tr.parent_id, tr.documentid, ARRAY[tr.nodeid] FROM trees tr WHERE tr.documentid = %...
[ "def", "get_collection_tree", "(", "collection_ident", ",", "cursor", ")", ":", "cursor", ".", "execute", "(", "'''\n WITH RECURSIVE t(node, parent, document, path) AS (\n SELECT tr.nodeid, tr.parent_id, tr.documentid, ARRAY[tr.nodeid]\n FROM trees tr\n WHERE tr.docum...
Build and retrieve json tree representation of a book.
[ "Build", "and", "retrieve", "json", "tree", "representation", "of", "a", "book", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L810-L826
openstax/cnx-archive
cnxarchive/database.py
get_module_can_publish
def get_module_can_publish(cursor, id): """Return userids allowed to publish this book.""" cursor.execute(""" SELECT DISTINCT user_id FROM document_acl WHERE uuid = %s AND permission = 'publish'""", (id,)) return [i[0] for i in cursor.fetchall()]
python
def get_module_can_publish(cursor, id): """Return userids allowed to publish this book.""" cursor.execute(""" SELECT DISTINCT user_id FROM document_acl WHERE uuid = %s AND permission = 'publish'""", (id,)) return [i[0] for i in cursor.fetchall()]
[ "def", "get_module_can_publish", "(", "cursor", ",", "id", ")", ":", "cursor", ".", "execute", "(", "\"\"\"\nSELECT DISTINCT user_id\nFROM document_acl\nWHERE uuid = %s AND permission = 'publish'\"\"\"", ",", "(", "id", ",", ")", ")", "return", "[", "i", "[", "0", "]"...
Return userids allowed to publish this book.
[ "Return", "userids", "allowed", "to", "publish", "this", "book", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/database.py#L829-L835
openstax/cnx-archive
cnxarchive/scripts/export_epub/modeling.py
tree_to_nodes
def tree_to_nodes(tree, context=None, metadata=None): """Assembles ``tree`` nodes into object models. If ``context`` is supplied, it will be used to contextualize the contents of the nodes. Metadata will pass non-node identifying values down to child nodes, if not overridden (license, timestamps, etc) ...
python
def tree_to_nodes(tree, context=None, metadata=None): """Assembles ``tree`` nodes into object models. If ``context`` is supplied, it will be used to contextualize the contents of the nodes. Metadata will pass non-node identifying values down to child nodes, if not overridden (license, timestamps, etc) ...
[ "def", "tree_to_nodes", "(", "tree", ",", "context", "=", "None", ",", "metadata", "=", "None", ")", ":", "nodes", "=", "[", "]", "for", "item", "in", "tree", "[", "'contents'", "]", ":", "if", "'contents'", "in", "item", ":", "sub_nodes", "=", "tree...
Assembles ``tree`` nodes into object models. If ``context`` is supplied, it will be used to contextualize the contents of the nodes. Metadata will pass non-node identifying values down to child nodes, if not overridden (license, timestamps, etc)
[ "Assembles", "tree", "nodes", "into", "object", "models", ".", "If", "context", "is", "supplied", "it", "will", "be", "used", "to", "contextualize", "the", "contents", "of", "the", "nodes", ".", "Metadata", "will", "pass", "non", "-", "node", "identifying", ...
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/export_epub/modeling.py#L77-L126
openstax/cnx-archive
cnxarchive/scripts/export_epub/modeling.py
create_epub
def create_epub(ident_hash, file, format='raw'): """Creates an epub from an ``ident_hash``, which is output to the given ``file`` (a file-like object). Returns None, writes to the given ``file``. """ model = factory(ident_hash, baked=(format != 'raw')) if isinstance(model, cnxepub.Document): ...
python
def create_epub(ident_hash, file, format='raw'): """Creates an epub from an ``ident_hash``, which is output to the given ``file`` (a file-like object). Returns None, writes to the given ``file``. """ model = factory(ident_hash, baked=(format != 'raw')) if isinstance(model, cnxepub.Document): ...
[ "def", "create_epub", "(", "ident_hash", ",", "file", ",", "format", "=", "'raw'", ")", ":", "model", "=", "factory", "(", "ident_hash", ",", "baked", "=", "(", "format", "!=", "'raw'", ")", ")", "if", "isinstance", "(", "model", ",", "cnxepub", ".", ...
Creates an epub from an ``ident_hash``, which is output to the given ``file`` (a file-like object). Returns None, writes to the given ``file``.
[ "Creates", "an", "epub", "from", "an", "ident_hash", "which", "is", "output", "to", "the", "given", "file", "(", "a", "file", "-", "like", "object", ")", ".", "Returns", "None", "writes", "to", "the", "given", "file", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/export_epub/modeling.py#L161-L170
openstax/cnx-archive
cnxarchive/views/exports.py
get_export
def get_export(request): """Retrieve an export file.""" settings = get_current_registry().settings exports_dirs = settings['exports-directories'].split() args = request.matchdict ident_hash, type = args['ident_hash'], args['type'] id, version = split_ident_hash(ident_hash) with db_connect()...
python
def get_export(request): """Retrieve an export file.""" settings = get_current_registry().settings exports_dirs = settings['exports-directories'].split() args = request.matchdict ident_hash, type = args['ident_hash'], args['type'] id, version = split_ident_hash(ident_hash) with db_connect()...
[ "def", "get_export", "(", "request", ")", ":", "settings", "=", "get_current_registry", "(", ")", ".", "settings", "exports_dirs", "=", "settings", "[", "'exports-directories'", "]", ".", "split", "(", ")", "args", "=", "request", ".", "matchdict", "ident_hash...
Retrieve an export file.
[ "Retrieve", "an", "export", "file", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/exports.py#L50-L89
openstax/cnx-archive
cnxarchive/views/exports.py
get_export_files
def get_export_files(cursor, id, version, types, exports_dirs, read_file=True): """Retrieve files associated with document.""" request = get_current_request() type_info = dict(request.registry.settings['_type_info']) metadata = get_content_metadata(id, version, cursor) legacy_id = metadata['legacy_i...
python
def get_export_files(cursor, id, version, types, exports_dirs, read_file=True): """Retrieve files associated with document.""" request = get_current_request() type_info = dict(request.registry.settings['_type_info']) metadata = get_content_metadata(id, version, cursor) legacy_id = metadata['legacy_i...
[ "def", "get_export_files", "(", "cursor", ",", "id", ",", "version", ",", "types", ",", "exports_dirs", ",", "read_file", "=", "True", ")", ":", "request", "=", "get_current_request", "(", ")", "type_info", "=", "dict", "(", "request", ".", "registry", "."...
Retrieve files associated with document.
[ "Retrieve", "files", "associated", "with", "document", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/exports.py#L92-L178
openstax/cnx-archive
cnxarchive/views/helpers.py
get_content_metadata
def get_content_metadata(id, version, cursor): """Return metadata related to the content from the database.""" # Do the module lookup args = dict(id=id, version=version) # FIXME We are doing two queries here that can hopefully be # condensed into one. cursor.execute(SQL['get-module-metadat...
python
def get_content_metadata(id, version, cursor): """Return metadata related to the content from the database.""" # Do the module lookup args = dict(id=id, version=version) # FIXME We are doing two queries here that can hopefully be # condensed into one. cursor.execute(SQL['get-module-metadat...
[ "def", "get_content_metadata", "(", "id", ",", "version", ",", "cursor", ")", ":", "# Do the module lookup", "args", "=", "dict", "(", "id", "=", "id", ",", "version", "=", "version", ")", "# FIXME We are doing two queries here that can hopefully be", "# condens...
Return metadata related to the content from the database.
[ "Return", "metadata", "related", "to", "the", "content", "from", "the", "database", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/helpers.py#L61-L83
ZELLMECHANIK-DRESDEN/dclab
dclab/kde_contours.py
find_contours_level
def find_contours_level(density, x, y, level, closed=False): """Find iso-valued density contours for a given level value Parameters ---------- density: 2d ndarray of shape (M, N) Kernel density estimate for which to compute the contours x: 2d ndarray of shape (M, N) or 1d ndarray of size M ...
python
def find_contours_level(density, x, y, level, closed=False): """Find iso-valued density contours for a given level value Parameters ---------- density: 2d ndarray of shape (M, N) Kernel density estimate for which to compute the contours x: 2d ndarray of shape (M, N) or 1d ndarray of size M ...
[ "def", "find_contours_level", "(", "density", ",", "x", ",", "y", ",", "level", ",", "closed", "=", "False", ")", ":", "if", "level", ">=", "1", "or", "level", "<=", "0", ":", "raise", "ValueError", "(", "\"`level` must be in (0,1), got '{}'!\"", ".", "for...
Find iso-valued density contours for a given level value Parameters ---------- density: 2d ndarray of shape (M, N) Kernel density estimate for which to compute the contours x: 2d ndarray of shape (M, N) or 1d ndarray of size M X-values corresponding to `kde` y: 2d ndarray of shape (...
[ "Find", "iso", "-", "valued", "density", "contours", "for", "a", "given", "level", "value" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/kde_contours.py#L12-L67
ZELLMECHANIK-DRESDEN/dclab
dclab/kde_contours.py
get_quantile_levels
def get_quantile_levels(density, x, y, xp, yp, q, normalize=True): """Compute density levels for given quantiles by interpolation For a given 2D density, compute the density levels at which the resulting contours contain the fraction `1-q` of all data points. E.g. for a measurement of 1000 events, all ...
python
def get_quantile_levels(density, x, y, xp, yp, q, normalize=True): """Compute density levels for given quantiles by interpolation For a given 2D density, compute the density levels at which the resulting contours contain the fraction `1-q` of all data points. E.g. for a measurement of 1000 events, all ...
[ "def", "get_quantile_levels", "(", "density", ",", "x", ",", "y", ",", "xp", ",", "yp", ",", "q", ",", "normalize", "=", "True", ")", ":", "# xy coordinates", "if", "len", "(", "x", ".", "shape", ")", "==", "2", ":", "assert", "np", ".", "all", "...
Compute density levels for given quantiles by interpolation For a given 2D density, compute the density levels at which the resulting contours contain the fraction `1-q` of all data points. E.g. for a measurement of 1000 events, all contours at the level corresponding to a quantile of `q=0.95` (95t...
[ "Compute", "density", "levels", "for", "given", "quantiles", "by", "interpolation" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/kde_contours.py#L70-L143
ZELLMECHANIK-DRESDEN/dclab
dclab/kde_contours.py
_find_quantile_level
def _find_quantile_level(density, x, y, xp, yp, quantile, acc=.01, ret_err=False): """Find density level for a given data quantile by iteration Parameters ---------- density: 2d ndarray of shape (M, N) Kernel density estimate for which to compute the contours x: 2d ...
python
def _find_quantile_level(density, x, y, xp, yp, quantile, acc=.01, ret_err=False): """Find density level for a given data quantile by iteration Parameters ---------- density: 2d ndarray of shape (M, N) Kernel density estimate for which to compute the contours x: 2d ...
[ "def", "_find_quantile_level", "(", "density", ",", "x", ",", "y", ",", "xp", ",", "yp", ",", "quantile", ",", "acc", "=", ".01", ",", "ret_err", "=", "False", ")", ":", "if", "quantile", ">=", "1", "or", "quantile", "<=", "0", ":", "raise", "Value...
Find density level for a given data quantile by iteration Parameters ---------- density: 2d ndarray of shape (M, N) Kernel density estimate for which to compute the contours x: 2d ndarray of shape (M, N) or 1d ndarray of size M X-values corresponding to `kde` y: 2d ndarray of shape ...
[ "Find", "density", "level", "for", "a", "given", "data", "quantile", "by", "iteration" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/kde_contours.py#L146-L220
ZELLMECHANIK-DRESDEN/dclab
dclab/rtdc_dataset/write_hdf5.py
write
def write(path_or_h5file, data={}, meta={}, logs={}, mode="reset", compression=None): """Write data to an RT-DC file Parameters ---------- path: path or h5py.File The path or the hdf5 file object to write to. data: dict-like The data to store. Each key of `data` must be a ...
python
def write(path_or_h5file, data={}, meta={}, logs={}, mode="reset", compression=None): """Write data to an RT-DC file Parameters ---------- path: path or h5py.File The path or the hdf5 file object to write to. data: dict-like The data to store. Each key of `data` must be a ...
[ "def", "write", "(", "path_or_h5file", ",", "data", "=", "{", "}", ",", "meta", "=", "{", "}", ",", "logs", "=", "{", "}", ",", "mode", "=", "\"reset\"", ",", "compression", "=", "None", ")", ":", "if", "mode", "not", "in", "[", "\"append\"", ","...
Write data to an RT-DC file Parameters ---------- path: path or h5py.File The path or the hdf5 file object to write to. data: dict-like The data to store. Each key of `data` must be a valid feature name (see `dclab.dfn.feature_names`). The data type must be given accordi...
[ "Write", "data", "to", "an", "RT", "-", "DC", "file" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/write_hdf5.py#L137-L342
openstax/cnx-archive
cnxarchive/search.py
_convert
def _convert(tup, dictlist): """ :param tup: a list of tuples :param di: a dictionary converted from tup :return: dictionary """ di = {} for a, b in tup: di.setdefault(a, []).append(b) for key, val in di.items(): dictlist.append((key, val)) return dictlist
python
def _convert(tup, dictlist): """ :param tup: a list of tuples :param di: a dictionary converted from tup :return: dictionary """ di = {} for a, b in tup: di.setdefault(a, []).append(b) for key, val in di.items(): dictlist.append((key, val)) return dictlist
[ "def", "_convert", "(", "tup", ",", "dictlist", ")", ":", "di", "=", "{", "}", "for", "a", ",", "b", "in", "tup", ":", "di", ".", "setdefault", "(", "a", ",", "[", "]", ")", ".", "append", "(", "b", ")", "for", "key", ",", "val", "in", "di"...
:param tup: a list of tuples :param di: a dictionary converted from tup :return: dictionary
[ ":", "param", "tup", ":", "a", "list", "of", "tuples", ":", "param", "di", ":", "a", "dictionary", "converted", "from", "tup", ":", "return", ":", "dictionary" ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/search.py#L374-L385
openstax/cnx-archive
cnxarchive/search.py
_upper
def _upper(val_list): """ :param val_list: a list of strings :return: a list of upper-cased strings """ res = [] for ele in val_list: res.append(ele.upper()) return res
python
def _upper(val_list): """ :param val_list: a list of strings :return: a list of upper-cased strings """ res = [] for ele in val_list: res.append(ele.upper()) return res
[ "def", "_upper", "(", "val_list", ")", ":", "res", "=", "[", "]", "for", "ele", "in", "val_list", ":", "res", ".", "append", "(", "ele", ".", "upper", "(", ")", ")", "return", "res" ]
:param val_list: a list of strings :return: a list of upper-cased strings
[ ":", "param", "val_list", ":", "a", "list", "of", "strings", ":", "return", ":", "a", "list", "of", "upper", "-", "cased", "strings" ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/search.py#L388-L396
openstax/cnx-archive
cnxarchive/search.py
_build_search
def _build_search(structured_query): """Construct search statment for db execution. Produces the search statement and argument dictionary to be executed by the DBAPI v2 execute method. For example, ``cursor.execute(*_build_search(query, weights))`` :param query: containing terms, filters, and sort...
python
def _build_search(structured_query): """Construct search statment for db execution. Produces the search statement and argument dictionary to be executed by the DBAPI v2 execute method. For example, ``cursor.execute(*_build_search(query, weights))`` :param query: containing terms, filters, and sort...
[ "def", "_build_search", "(", "structured_query", ")", ":", "arguments", "=", "{", "}", "# get text terms and filter out common words", "text_terms", "=", "[", "term", "for", "ttype", ",", "term", "in", "structured_query", ".", "terms", "if", "ttype", "==", "'text'...
Construct search statment for db execution. Produces the search statement and argument dictionary to be executed by the DBAPI v2 execute method. For example, ``cursor.execute(*_build_search(query, weights))`` :param query: containing terms, filters, and sorts. :type query: Query :param weights...
[ "Construct", "search", "statment", "for", "db", "execution", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/search.py#L403-L567
openstax/cnx-archive
cnxarchive/search.py
search
def search(query, query_type=DEFAULT_QUERY_TYPE): """Search database using parsed query. Executes a database search query from the given ``query`` (a ``Query`` object) and optionally accepts a list of search weights. By default, the search results are ordered by weight. :param query: containing te...
python
def search(query, query_type=DEFAULT_QUERY_TYPE): """Search database using parsed query. Executes a database search query from the given ``query`` (a ``Query`` object) and optionally accepts a list of search weights. By default, the search results are ordered by weight. :param query: containing te...
[ "def", "search", "(", "query", ",", "query_type", "=", "DEFAULT_QUERY_TYPE", ")", ":", "# Build the SQL statement.", "statement", ",", "arguments", "=", "_build_search", "(", "query", ")", "# Execute the SQL.", "if", "statement", "is", "None", "and", "arguments", ...
Search database using parsed query. Executes a database search query from the given ``query`` (a ``Query`` object) and optionally accepts a list of search weights. By default, the search results are ordered by weight. :param query: containing terms, filters, and sorts. :type query: Query :retu...
[ "Search", "database", "using", "parsed", "query", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/search.py#L570-L594
openstax/cnx-archive
cnxarchive/search.py
Query.fix_quotes
def fix_quotes(cls, query_string): """Heuristic attempt to fix unbalanced quotes in query_string.""" if query_string.count('"') % 2 == 0: # no unbalanced quotes to fix return query_string fields = [] # contains what's matched by the regexp # e.g. fields = ['sort...
python
def fix_quotes(cls, query_string): """Heuristic attempt to fix unbalanced quotes in query_string.""" if query_string.count('"') % 2 == 0: # no unbalanced quotes to fix return query_string fields = [] # contains what's matched by the regexp # e.g. fields = ['sort...
[ "def", "fix_quotes", "(", "cls", ",", "query_string", ")", ":", "if", "query_string", ".", "count", "(", "'\"'", ")", "%", "2", "==", "0", ":", "# no unbalanced quotes to fix", "return", "query_string", "fields", "=", "[", "]", "# contains what's matched by the ...
Heuristic attempt to fix unbalanced quotes in query_string.
[ "Heuristic", "attempt", "to", "fix", "unbalanced", "quotes", "in", "query_string", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/search.py#L106-L122
openstax/cnx-archive
cnxarchive/search.py
Query.from_raw_query
def from_raw_query(cls, query_string): """Parse raw string to query. Given a raw string (typically typed by the user), parse to a structured format and initialize the class. """ try: node_tree = grammar.parse(query_string) except IncompleteParseError: ...
python
def from_raw_query(cls, query_string): """Parse raw string to query. Given a raw string (typically typed by the user), parse to a structured format and initialize the class. """ try: node_tree = grammar.parse(query_string) except IncompleteParseError: ...
[ "def", "from_raw_query", "(", "cls", ",", "query_string", ")", ":", "try", ":", "node_tree", "=", "grammar", ".", "parse", "(", "query_string", ")", "except", "IncompleteParseError", ":", "query_string", "=", "cls", ".", "fix_quotes", "(", "query_string", ")",...
Parse raw string to query. Given a raw string (typically typed by the user), parse to a structured format and initialize the class.
[ "Parse", "raw", "string", "to", "query", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/search.py#L125-L140
openstax/cnx-archive
cnxarchive/search.py
QueryRecord.highlighted_abstract
def highlighted_abstract(self): """Highlight the found terms in the abstract text.""" abstract_terms = self.fields.get('abstract', []) if abstract_terms: sql = _read_sql_file('highlighted-abstract') else: sql = _read_sql_file('get-abstract') arguments = {'...
python
def highlighted_abstract(self): """Highlight the found terms in the abstract text.""" abstract_terms = self.fields.get('abstract', []) if abstract_terms: sql = _read_sql_file('highlighted-abstract') else: sql = _read_sql_file('get-abstract') arguments = {'...
[ "def", "highlighted_abstract", "(", "self", ")", ":", "abstract_terms", "=", "self", ".", "fields", ".", "get", "(", "'abstract'", ",", "[", "]", ")", "if", "abstract_terms", ":", "sql", "=", "_read_sql_file", "(", "'highlighted-abstract'", ")", "else", ":",...
Highlight the found terms in the abstract text.
[ "Highlight", "the", "found", "terms", "in", "the", "abstract", "text", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/search.py#L177-L192
openstax/cnx-archive
cnxarchive/search.py
QueryRecord.highlighted_fulltext
def highlighted_fulltext(self): """Highlight the found terms in the fulltext.""" terms = self.fields.get('fulltext', []) if not terms: return None arguments = {'id': self['id'], 'query': ' & '.join(terms), } with db_connect() ...
python
def highlighted_fulltext(self): """Highlight the found terms in the fulltext.""" terms = self.fields.get('fulltext', []) if not terms: return None arguments = {'id': self['id'], 'query': ' & '.join(terms), } with db_connect() ...
[ "def", "highlighted_fulltext", "(", "self", ")", ":", "terms", "=", "self", ".", "fields", ".", "get", "(", "'fulltext'", ",", "[", "]", ")", "if", "not", "terms", ":", "return", "None", "arguments", "=", "{", "'id'", ":", "self", "[", "'id'", "]", ...
Highlight the found terms in the fulltext.
[ "Highlight", "the", "found", "terms", "in", "the", "fulltext", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/search.py#L195-L208
ZELLMECHANIK-DRESDEN/dclab
dclab/external/statsmodels/nonparametric/kernel_density.py
KDEMultivariate.pdf
def pdf(self, data_predict=None): r""" Evaluate the probability density function. Parameters ---------- data_predict: array_like, optional Points to evaluate at. If unspecified, the training data is used. Returns ------- pdf_est: array_like ...
python
def pdf(self, data_predict=None): r""" Evaluate the probability density function. Parameters ---------- data_predict: array_like, optional Points to evaluate at. If unspecified, the training data is used. Returns ------- pdf_est: array_like ...
[ "def", "pdf", "(", "self", ",", "data_predict", "=", "None", ")", ":", "if", "data_predict", "is", "None", ":", "data_predict", "=", "self", ".", "data", "else", ":", "data_predict", "=", "_adjust_shape", "(", "data_predict", ",", "self", ".", "k_vars", ...
r""" Evaluate the probability density function. Parameters ---------- data_predict: array_like, optional Points to evaluate at. If unspecified, the training data is used. Returns ------- pdf_est: array_like Probability density function e...
[ "r", "Evaluate", "the", "probability", "density", "function", "." ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/external/statsmodels/nonparametric/kernel_density.py#L126-L160
xenon-middleware/pyxenon
xenon/compat.py
find_xenon_grpc_jar
def find_xenon_grpc_jar(): """Find the Xenon-GRPC jar-file, windows version.""" prefix = Path(sys.prefix) locations = [ prefix / 'lib', prefix / 'local' / 'lib' ] for location in locations: jar_file = location / 'xenon-grpc-{}-all.jar'.format( xenon_grpc_ver...
python
def find_xenon_grpc_jar(): """Find the Xenon-GRPC jar-file, windows version.""" prefix = Path(sys.prefix) locations = [ prefix / 'lib', prefix / 'local' / 'lib' ] for location in locations: jar_file = location / 'xenon-grpc-{}-all.jar'.format( xenon_grpc_ver...
[ "def", "find_xenon_grpc_jar", "(", ")", ":", "prefix", "=", "Path", "(", "sys", ".", "prefix", ")", "locations", "=", "[", "prefix", "/", "'lib'", ",", "prefix", "/", "'local'", "/", "'lib'", "]", "for", "location", "in", "locations", ":", "jar_file", ...
Find the Xenon-GRPC jar-file, windows version.
[ "Find", "the", "Xenon", "-", "GRPC", "jar", "-", "file", "windows", "version", "." ]
train
https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/compat.py#L16-L34
xenon-middleware/pyxenon
xenon/compat.py
kill_process
def kill_process(process): """Kill the process group associated with the given process. (posix)""" logger = logging.getLogger('xenon') logger.info('Terminating Xenon-GRPC server.') os.kill(process.pid, signal.SIGINT) process.wait()
python
def kill_process(process): """Kill the process group associated with the given process. (posix)""" logger = logging.getLogger('xenon') logger.info('Terminating Xenon-GRPC server.') os.kill(process.pid, signal.SIGINT) process.wait()
[ "def", "kill_process", "(", "process", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "'xenon'", ")", "logger", ".", "info", "(", "'Terminating Xenon-GRPC server.'", ")", "os", ".", "kill", "(", "process", ".", "pid", ",", "signal", ".", "SIGIN...
Kill the process group associated with the given process. (posix)
[ "Kill", "the", "process", "group", "associated", "with", "the", "given", "process", ".", "(", "posix", ")" ]
train
https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/compat.py#L37-L42
xenon-middleware/pyxenon
xenon/compat.py
start_xenon_server
def start_xenon_server(port=50051, disable_tls=False): """Start the server.""" jar_file = find_xenon_grpc_jar() if not jar_file: raise RuntimeError("Could not find 'xenon-grpc' jar file.") cmd = ['java', '-jar', jar_file, '-p', str(port)] if not disable_tls: crt_file, key_file = cr...
python
def start_xenon_server(port=50051, disable_tls=False): """Start the server.""" jar_file = find_xenon_grpc_jar() if not jar_file: raise RuntimeError("Could not find 'xenon-grpc' jar file.") cmd = ['java', '-jar', jar_file, '-p', str(port)] if not disable_tls: crt_file, key_file = cr...
[ "def", "start_xenon_server", "(", "port", "=", "50051", ",", "disable_tls", "=", "False", ")", ":", "jar_file", "=", "find_xenon_grpc_jar", "(", ")", "if", "not", "jar_file", ":", "raise", "RuntimeError", "(", "\"Could not find 'xenon-grpc' jar file.\"", ")", "cmd...
Start the server.
[ "Start", "the", "server", "." ]
train
https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/compat.py#L45-L69
simse/pymitv
pymitv/control.py
Control.send_keystrokes
def send_keystrokes(ip, keystrokes, wait=False): """Connects to TV and sends keystroke via HTTP.""" tv_url = 'http://{}:6095/controller?action=keyevent&keycode='.format(ip) for keystroke in keystrokes: if keystroke == 'wait' or wait is True: time.sleep(0.7) ...
python
def send_keystrokes(ip, keystrokes, wait=False): """Connects to TV and sends keystroke via HTTP.""" tv_url = 'http://{}:6095/controller?action=keyevent&keycode='.format(ip) for keystroke in keystrokes: if keystroke == 'wait' or wait is True: time.sleep(0.7) ...
[ "def", "send_keystrokes", "(", "ip", ",", "keystrokes", ",", "wait", "=", "False", ")", ":", "tv_url", "=", "'http://{}:6095/controller?action=keyevent&keycode='", ".", "format", "(", "ip", ")", "for", "keystroke", "in", "keystrokes", ":", "if", "keystroke", "==...
Connects to TV and sends keystroke via HTTP.
[ "Connects", "to", "TV", "and", "sends", "keystroke", "via", "HTTP", "." ]
train
https://github.com/simse/pymitv/blob/03213f591d70fbf90ba2b6af372e474c9bfb99f6/pymitv/control.py#L29-L43
simse/pymitv
pymitv/control.py
Control.mute
def mute(ip): """Polyfill for muting the TV.""" tv_url = 'http://{}:6095/controller?action=keyevent&keycode='.format(ip) count = 0 while count > 30: count = count + 1 request = requests.get(tv_url + 'volumedown') if request.status_code != 20...
python
def mute(ip): """Polyfill for muting the TV.""" tv_url = 'http://{}:6095/controller?action=keyevent&keycode='.format(ip) count = 0 while count > 30: count = count + 1 request = requests.get(tv_url + 'volumedown') if request.status_code != 20...
[ "def", "mute", "(", "ip", ")", ":", "tv_url", "=", "'http://{}:6095/controller?action=keyevent&keycode='", ".", "format", "(", "ip", ")", "count", "=", "0", "while", "count", ">", "30", ":", "count", "=", "count", "+", "1", "request", "=", "requests", ".",...
Polyfill for muting the TV.
[ "Polyfill", "for", "muting", "the", "TV", "." ]
train
https://github.com/simse/pymitv/blob/03213f591d70fbf90ba2b6af372e474c9bfb99f6/pymitv/control.py#L46-L58
openstax/cnx-archive
cnxarchive/views/in_book_search.py
in_book_search
def in_book_search(request): """Full text, in-book search.""" results = {} args = request.matchdict ident_hash = args['ident_hash'] args['search_term'] = request.params.get('q', '') query_type = request.params.get('query_type', '') combiner = '' if query_type: if query_type.low...
python
def in_book_search(request): """Full text, in-book search.""" results = {} args = request.matchdict ident_hash = args['ident_hash'] args['search_term'] = request.params.get('q', '') query_type = request.params.get('query_type', '') combiner = '' if query_type: if query_type.low...
[ "def", "in_book_search", "(", "request", ")", ":", "results", "=", "{", "}", "args", "=", "request", ".", "matchdict", "ident_hash", "=", "args", "[", "'ident_hash'", "]", "args", "[", "'search_term'", "]", "=", "request", ".", "params", ".", "get", "(",...
Full text, in-book search.
[ "Full", "text", "in", "-", "book", "search", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/in_book_search.py#L34-L84
openstax/cnx-archive
cnxarchive/views/in_book_search.py
in_book_search_highlighted_results
def in_book_search_highlighted_results(request): """In-book search - returns a highlighted version of the HTML.""" results = {} args = request.matchdict ident_hash = args['ident_hash'] page_ident_hash = args['page_ident_hash'] try: page_uuid, _ = split_ident_hash(page_ident_hash) e...
python
def in_book_search_highlighted_results(request): """In-book search - returns a highlighted version of the HTML.""" results = {} args = request.matchdict ident_hash = args['ident_hash'] page_ident_hash = args['page_ident_hash'] try: page_uuid, _ = split_ident_hash(page_ident_hash) e...
[ "def", "in_book_search_highlighted_results", "(", "request", ")", ":", "results", "=", "{", "}", "args", "=", "request", ".", "matchdict", "ident_hash", "=", "args", "[", "'ident_hash'", "]", "page_ident_hash", "=", "args", "[", "'page_ident_hash'", "]", "try", ...
In-book search - returns a highlighted version of the HTML.
[ "In", "-", "book", "search", "-", "returns", "a", "highlighted", "version", "of", "the", "HTML", "." ]
train
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/in_book_search.py#L89-L149
ZELLMECHANIK-DRESDEN/dclab
dclab/external/statsmodels/nonparametric/_kernel_base.py
_adjust_shape
def _adjust_shape(dat, k_vars): """ Returns an array of shape (nobs, k_vars) for use with `gpke`.""" dat = np.asarray(dat) if dat.ndim > 2: dat = np.squeeze(dat) if dat.ndim == 1 and k_vars > 1: # one obs many vars nobs = 1 elif dat.ndim == 1 and k_vars == 1: # one obs one var ...
python
def _adjust_shape(dat, k_vars): """ Returns an array of shape (nobs, k_vars) for use with `gpke`.""" dat = np.asarray(dat) if dat.ndim > 2: dat = np.squeeze(dat) if dat.ndim == 1 and k_vars > 1: # one obs many vars nobs = 1 elif dat.ndim == 1 and k_vars == 1: # one obs one var ...
[ "def", "_adjust_shape", "(", "dat", ",", "k_vars", ")", ":", "dat", "=", "np", ".", "asarray", "(", "dat", ")", "if", "dat", ".", "ndim", ">", "2", ":", "dat", "=", "np", ".", "squeeze", "(", "dat", ")", "if", "dat", ".", "ndim", "==", "1", "...
Returns an array of shape (nobs, k_vars) for use with `gpke`.
[ "Returns", "an", "array", "of", "shape", "(", "nobs", "k_vars", ")", "for", "use", "with", "gpke", "." ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/external/statsmodels/nonparametric/_kernel_base.py#L129-L145
ZELLMECHANIK-DRESDEN/dclab
dclab/external/statsmodels/nonparametric/_kernel_base.py
gpke
def gpke(bw, data, data_predict, var_type, ckertype='gaussian', okertype='wangryzin', ukertype='aitchisonaitken', tosum=True): r""" Returns the non-normalized Generalized Product Kernel Estimator Parameters ---------- bw: 1-D ndarray The user-specified bandwidth parameters. dat...
python
def gpke(bw, data, data_predict, var_type, ckertype='gaussian', okertype='wangryzin', ukertype='aitchisonaitken', tosum=True): r""" Returns the non-normalized Generalized Product Kernel Estimator Parameters ---------- bw: 1-D ndarray The user-specified bandwidth parameters. dat...
[ "def", "gpke", "(", "bw", ",", "data", ",", "data_predict", ",", "var_type", ",", "ckertype", "=", "'gaussian'", ",", "okertype", "=", "'wangryzin'", ",", "ukertype", "=", "'aitchisonaitken'", ",", "tosum", "=", "True", ")", ":", "kertypes", "=", "dict", ...
r""" Returns the non-normalized Generalized Product Kernel Estimator Parameters ---------- bw: 1-D ndarray The user-specified bandwidth parameters. data: 1D or 2-D ndarray The training data. data_predict: 1-D ndarray The evaluation points at which the kernel estimation i...
[ "r", "Returns", "the", "non", "-", "normalized", "Generalized", "Product", "Kernel", "Estimator" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/external/statsmodels/nonparametric/_kernel_base.py#L148-L204
ZELLMECHANIK-DRESDEN/dclab
dclab/external/statsmodels/nonparametric/_kernel_base.py
GenericKDE._compute_bw
def _compute_bw(self, bw): """ Computes the bandwidth of the data. Parameters ---------- bw: array_like or str If array_like: user-specified bandwidth. If a string, should be one of: - cv_ml: cross validation maximum likelihood ...
python
def _compute_bw(self, bw): """ Computes the bandwidth of the data. Parameters ---------- bw: array_like or str If array_like: user-specified bandwidth. If a string, should be one of: - cv_ml: cross validation maximum likelihood ...
[ "def", "_compute_bw", "(", "self", ",", "bw", ")", ":", "if", "bw", "is", "None", ":", "bw", "=", "'normal_reference'", "if", "not", "isinstance", "(", "bw", ",", "string_types", ")", ":", "self", ".", "_bw_method", "=", "\"user-specified\"", "res", "=",...
Computes the bandwidth of the data. Parameters ---------- bw: array_like or str If array_like: user-specified bandwidth. If a string, should be one of: - cv_ml: cross validation maximum likelihood - normal_reference: normal reference rule...
[ "Computes", "the", "bandwidth", "of", "the", "data", "." ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/external/statsmodels/nonparametric/_kernel_base.py#L20-L56
ZELLMECHANIK-DRESDEN/dclab
dclab/external/statsmodels/nonparametric/_kernel_base.py
GenericKDE._set_defaults
def _set_defaults(self, defaults): """Sets the default values for the efficient estimation""" self.n_res = defaults.n_res self.n_sub = defaults.n_sub self.randomize = defaults.randomize self.return_median = defaults.return_median self.efficient = defaults.efficient ...
python
def _set_defaults(self, defaults): """Sets the default values for the efficient estimation""" self.n_res = defaults.n_res self.n_sub = defaults.n_sub self.randomize = defaults.randomize self.return_median = defaults.return_median self.efficient = defaults.efficient ...
[ "def", "_set_defaults", "(", "self", ",", "defaults", ")", ":", "self", ".", "n_res", "=", "defaults", ".", "n_res", "self", ".", "n_sub", "=", "defaults", ".", "n_sub", "self", ".", "randomize", "=", "defaults", ".", "randomize", "self", ".", "return_me...
Sets the default values for the efficient estimation
[ "Sets", "the", "default", "values", "for", "the", "efficient", "estimation" ]
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/external/statsmodels/nonparametric/_kernel_base.py#L58-L66
mhostetter/nhl
docs/conf.py
get_version
def get_version(): """Return package version from setup.cfg""" config = RawConfigParser() config.read(os.path.join('..', 'setup.cfg')) return config.get('metadata', 'version')
python
def get_version(): """Return package version from setup.cfg""" config = RawConfigParser() config.read(os.path.join('..', 'setup.cfg')) return config.get('metadata', 'version')
[ "def", "get_version", "(", ")", ":", "config", "=", "RawConfigParser", "(", ")", "config", ".", "read", "(", "os", ".", "path", ".", "join", "(", "'..'", ",", "'setup.cfg'", ")", ")", "return", "config", ".", "get", "(", "'metadata'", ",", "'version'",...
Return package version from setup.cfg
[ "Return", "package", "version", "from", "setup", ".", "cfg" ]
train
https://github.com/mhostetter/nhl/blob/32c91cc392826e9de728563d57ab527421734ee1/docs/conf.py#L27-L31