repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
almarklein/pyelastix
pyelastix.py
_clear_dir
python
def _clear_dir(dirName): # If we got here, clear dir for fname in os.listdir(dirName): try: os.remove( os.path.join(dirName, fname) ) except Exception: pass try: os.rmdir(dirName) except Exception: pass
Remove a directory and it contents. Ignore any failures.
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L174-L186
null
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...
almarklein/pyelastix
pyelastix.py
get_tempdir
python
def get_tempdir(): tempdir = os.path.join(tempfile.gettempdir(), 'pyelastix') # Make sure it exists if not os.path.isdir(tempdir): os.makedirs(tempdir) # Clean up all directories for which the process no longer exists for fname in os.listdir(tempdir): dirName = os.path.join...
Get the temporary directory where pyelastix stores its temporary files. The directory is specific to the current process and the calling thread. Generally, the user does not need this; directories are automatically cleaned up. Though Elastix log files are also written here.
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L189-L222
null
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...
almarklein/pyelastix
pyelastix.py
_clear_temp_dir
python
def _clear_temp_dir(): tempdir = get_tempdir() for fname in os.listdir(tempdir): try: os.remove( os.path.join(tempdir, fname) ) except Exception: pass
Clear the temporary directory.
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L225-L233
null
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...
almarklein/pyelastix
pyelastix.py
_get_image_paths
python
def _get_image_paths(im1, im2): paths = [] for im in [im1, im2]: if im is None: # Groupwise registration: only one image (ndim+1 dimensions) paths.append(paths[0]) continue if isinstance(im, str): # Given a location if os....
If the images are paths to a file, checks whether the file exist and return the paths. If the images are numpy arrays, writes them to disk and returns the paths of the new files.
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L236-L267
null
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...
almarklein/pyelastix
pyelastix.py
_system3
python
def _system3(cmd, verbose=False): # Init flag interrupted = False # Create progress if verbose > 0: progress = Progress() stdout = [] def poll_process(p): while not interrupted: msg = p.stdout.readline().decode() if msg: stdo...
Execute the given command in a subprocess and wait for it to finish. A thread is run that prints output of the process if verbose is True.
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L272-L337
null
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...
almarklein/pyelastix
pyelastix.py
_get_dtype_maps
python
def _get_dtype_maps(): # Define pairs tmp = [ (np.float32, 'MET_FLOAT'), (np.float64, 'MET_DOUBLE'), (np.uint8, 'MET_UCHAR'), (np.int8, 'MET_CHAR'), (np.uint16, 'MET_USHORT'), (np.int16, 'MET_SHORT'), (np.uint32, 'MET_UINT'), (np.int32, 'MET_INT'), (n...
Get dictionaries to map numpy data types to ITK types and the other way around.
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L340-L359
null
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...
almarklein/pyelastix
pyelastix.py
register
python
def register(im1, im2, params, exact_params=False, verbose=1): # Clear dir tempdir = get_tempdir() _clear_temp_dir() # Reference image refIm = im1 if isinstance(im1, (tuple,list)): refIm = im1[0] # Check parameters if not exact_params: params = _compile_par...
register(im1, im2, params, exact_params=False, verbose=1) Perform the registration of `im1` to `im2`, using the given parameters. Returns `(im1_deformed, field)`, where `field` is a tuple with arrays describing the deformation for each dimension (x-y-z order, in world units). Parameters: ...
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L403-L554
[ "def get_elastix_exes():\n \"\"\" Get the executables for elastix and transformix. Raises an error\n if they cannot be found.\n \"\"\"\n if EXES:\n if EXES[0]:\n return EXES\n else:\n raise RuntimeError('No Elastix executable.')\n\n # Find exe\n elastix, ver = _...
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...
almarklein/pyelastix
pyelastix.py
_write_image_data
python
def _write_image_data(im, id): im = im* (1.0/3000) # Create text lines = [ "ObjectType = Image", "NDims = <ndim>", "BinaryData = True", "BinaryDataByteOrderMSB = False", "CompressedData = False", #"TransformMatrix = <transmatr...
Write a numpy array to disk in the form of a .raw and .mhd file. The id is the image sequence number (1 or 2). Returns the path of the mhd file.
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L557-L632
null
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...
almarklein/pyelastix
pyelastix.py
_read_image_data
python
def _read_image_data( mhd_file): tempdir = get_tempdir() # Load description from mhd file fname = tempdir + '/' + mhd_file des = open(fname, 'r').read() # Get data filename and load raw data match = re.findall('ElementDataFile = (.+?)\n', des) fname = tempdir + '/' + match[0] d...
Read the resulting image data and return it as a numpy array.
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L635-L691
null
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...
almarklein/pyelastix
pyelastix.py
_get_fixed_params
python
def _get_fixed_params(im): p = Parameters() if not isinstance(im, np.ndarray): return p # Dimension of the inputs p.FixedImageDimension = im.ndim p.MovingImageDimension = im.ndim # Always write result, so I can verify p.WriteResultImage = True # How to wr...
Parameters that the user has no influence on. Mostly chosen bases on the input images.
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L751-L774
null
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...
almarklein/pyelastix
pyelastix.py
get_advanced_params
python
def get_advanced_params(): p = Parameters() # Internal format used during the registration process p.FixedInternalImagePixelType = "float" p.MovingInternalImagePixelType = "float" # Image direction p.UseDirectionCosines = True # In almost all cases you'd want multi resolu...
Get `Parameters` struct with parameters that most users do not want to think about.
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L777-L820
null
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...
almarklein/pyelastix
pyelastix.py
get_default_params
python
def get_default_params(type='BSPLINE'): # Init p = Parameters() type = type.upper() # ===== Metric to use ===== p.Metric = 'AdvancedMattesMutualInformation' # Number of grey level bins in each resolution level, # for the mutual information. 16 or 32 usually works fine. ...
get_default_params(type='BSPLINE') Get `Parameters` struct with parameters that users may want to tweak. The given `type` specifies the type of allowed transform, and can be 'RIGID', 'AFFINE', 'BSPLINE'. For detail on what parameters are available and how they should be used, we refer to t...
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L823-L938
null
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...
almarklein/pyelastix
pyelastix.py
_compile_params
python
def _compile_params(params, im1): # Compile parameters p = _get_fixed_params(im1) + get_advanced_params() p = p + params params = p.as_dict() # Check parameter dimensions if isinstance(im1, np.ndarray): lt = (list, tuple) for key in [ 'FinalGridSpacingInPhysicalUnits...
Compile the params dictionary: * Combine parameters from different sources * Perform checks to prevent non-compatible parameters * Extend parameters that need a list with one element per dimension
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L941-L967
null
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...
almarklein/pyelastix
pyelastix.py
_write_parameter_file
python
def _write_parameter_file(params): # Get path path = os.path.join(get_tempdir(), 'params.txt') # Define helper function def valToStr(val): if val in [True, False]: return '"%s"' % str(val).lower() elif isinstance(val, int): return str(val) elif i...
Write the parameter file in the format that elaxtix likes.
train
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L970-L1013
null
# Copyright (c) 2010-2016, Almar Klein # This code is subject to the MIT license """ PyElastix - Python wrapper for the Elastix nonrigid registration toolkit This Python module wraps the Elastix registration toolkit. For it to work, the Elastix command line application needs to be installed on your computer. You can ...
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
install
python
def install(application, io_loop=None, **kwargs): if getattr(application, 'amqp', None) is not None: LOGGER.warning('AMQP is already installed') return False kwargs.setdefault('io_loop', io_loop) # Support AMQP_* and RABBITMQ_* variables for prefix in {'AMQP', 'RABBITMQ'}: key...
Call this to install AMQP for the Tornado application. Additional keyword arguments are passed through to the constructor of the AMQP object. :param tornado.web.Application application: The tornado application :param tornado.ioloop.IOLoop io_loop: The current IOLoop. :rtype: bool
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L42-L98
null
"""The PublishingMixin adds RabbitMQ publishing capabilities to a request handler, with methods to speed the development of publishing RabbitMQ messages. Configured using the following environment variables: ``AMQP_URL`` - The AMQP URL to connect to. ``AMQP_TIMEOUT`` - The optional maximum time to wait for a ...
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
PublishingMixin.amqp_publish
python
def amqp_publish(self, exchange, routing_key, body, properties=None): properties = properties or {} if hasattr(self, 'correlation_id') and getattr(self, 'correlation_id'): properties.setdefault('correlation_id', self.correlation_id) return self.application.amqp.publish( e...
Publish a message to RabbitMQ :param str exchange: The exchange to publish the message to :param str routing_key: The routing key to publish the message with :param bytes body: The message body to send :param dict properties: An optional dict of AMQP properties :rtype: tornado.c...
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L108-L126
null
class PublishingMixin(object): """This mixin adds publishing messages to RabbitMQ. It uses a persistent connection and channel opened when the application start up and automatically reopened if closed by RabbitMQ """
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.publish
python
def publish(self, exchange, routing_key, body, properties=None): future = concurrent.Future() properties = properties or {} properties.setdefault('app_id', self.default_app_id) properties.setdefault('message_id', str(uuid.uuid4())) properties.setdefault('timestamp', int(time.tim...
Publish a message to RabbitMQ. If the RabbitMQ connection is not established or is blocked, attempt to wait until sending is possible. :param str exchange: The exchange to publish the message to. :param str routing_key: The routing key to publish the message with. :param bytes body: The...
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L216-L257
null
class Client(object): """This class encompasses all of the AMQP/RabbitMQ specific behaviors. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or soc...
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_delivery_confirmation
python
def on_delivery_confirmation(self, method_frame): confirmation_type = method_frame.method.NAME.split('.')[1].lower() LOGGER.debug('Received %s for delivery tag: %i', confirmation_type, method_frame.method.delivery_tag) if method_frame.method.multiple: confirmed ...
Invoked by pika when RabbitMQ responds to a Basic.Publish RPC command, passing in either a Basic.Ack or Basic.Nack frame with the delivery tag of the message that was published. The delivery tag is an integer counter indicating the message number that was sent on the channel via Basic.Pu...
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L259-L295
null
class Client(object): """This class encompasses all of the AMQP/RabbitMQ specific behaviors. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or soc...
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.connect
python
def connect(self): if not self.idle and not self.closed: raise ConnectionStateError(self.state_description) LOGGER.debug('Connecting to %s', self.url) self.state = self.STATE_CONNECTING self.connection = pika.TornadoConnection( parameters=self.parameters, ...
This method connects to RabbitMQ, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.TornadoConnection
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L371-L388
null
class Client(object): """This class encompasses all of the AMQP/RabbitMQ specific behaviors. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or soc...
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.close
python
def close(self): if not self.closable: LOGGER.warning('Closed called while %s', self.state_description) raise ConnectionStateError(self.state_description) self.state = self.STATE_CLOSING LOGGER.info('Closing RabbitMQ connection') self.connection.close()
Cleanly shutdown the connection to RabbitMQ :raises: sprockets.mixins.amqp.ConnectionStateError
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L390-L401
null
class Client(object): """This class encompasses all of the AMQP/RabbitMQ specific behaviors. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or soc...
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client._reconnect
python
def _reconnect(self): if self.idle or self.closed: LOGGER.debug('Attempting RabbitMQ reconnect in %s seconds', self.reconnect_delay) self.io_loop.call_later(self.reconnect_delay, self.connect) return LOGGER.warning('Reconnect called while %s',...
Schedule the next connection attempt if the class is not currently closing.
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L412-L422
null
class Client(object): """This class encompasses all of the AMQP/RabbitMQ specific behaviors. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or soc...
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_connection_open
python
def on_connection_open(self, connection): LOGGER.debug('Connection opened') connection.add_on_connection_blocked_callback( self.on_connection_blocked) connection.add_on_connection_unblocked_callback( self.on_connection_unblocked) connection.add_backpressure_callba...
This method is called by pika once the connection to RabbitMQ has been established. :type connection: pika.TornadoConnection
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L428-L441
[ "def _open_channel(self):\n \"\"\"Open a new channel with RabbitMQ.\n\n :rtype: pika.channel.Channel\n\n \"\"\"\n LOGGER.debug('Creating a new channel')\n return self.connection.channel(self.on_channel_open)\n" ]
class Client(object): """This class encompasses all of the AMQP/RabbitMQ specific behaviors. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or soc...
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_connection_open_error
python
def on_connection_open_error(self, connection, error): LOGGER.critical('Could not connect to RabbitMQ (%s): %r', connection, error) self.state = self.STATE_CLOSED self._reconnect()
Invoked if the connection to RabbitMQ can not be made. :type connection: pika.TornadoConnection :param Exception error: The exception indicating failure
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L443-L453
[ "def _reconnect(self):\n \"\"\"Schedule the next connection attempt if the class is not currently\n closing.\n\n \"\"\"\n if self.idle or self.closed:\n LOGGER.debug('Attempting RabbitMQ reconnect in %s seconds',\n self.reconnect_delay)\n self.io_loop.call_later(self.re...
class Client(object): """This class encompasses all of the AMQP/RabbitMQ specific behaviors. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or soc...
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_connection_blocked
python
def on_connection_blocked(self, method_frame): LOGGER.warning('Connection blocked: %s', method_frame) self.state = self.STATE_BLOCKED if self.on_unavailable: self.on_unavailable(self)
This method is called by pika if RabbitMQ sends a connection blocked method, to let us know we need to throttle our publishing. :param pika.amqp_object.Method method_frame: The blocked method frame
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L466-L476
null
class Client(object): """This class encompasses all of the AMQP/RabbitMQ specific behaviors. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or soc...
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_connection_unblocked
python
def on_connection_unblocked(self, method_frame): LOGGER.debug('Connection unblocked: %r', method_frame) self.state = self.STATE_READY if self.on_ready: self.on_ready(self)
When RabbitMQ indicates the connection is unblocked, set the state appropriately. :param pika.amqp_object.Method method_frame: Unblocked method frame
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L478-L488
null
class Client(object): """This class encompasses all of the AMQP/RabbitMQ specific behaviors. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or soc...
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_connection_closed
python
def on_connection_closed(self, connection, reply_code, reply_text): start_state = self.state self.state = self.STATE_CLOSED if self.on_unavailable: self.on_unavailable(self) self.connection = None self.channel = None if start_state != self.STATE_CLOSING: ...
This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.TornadoConnection connection: Closed connection :param int reply_code: The server provided reply_code if given ...
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L490-L512
[ "def _reconnect(self):\n \"\"\"Schedule the next connection attempt if the class is not currently\n closing.\n\n \"\"\"\n if self.idle or self.closed:\n LOGGER.debug('Attempting RabbitMQ reconnect in %s seconds',\n self.reconnect_delay)\n self.io_loop.call_later(self.re...
class Client(object): """This class encompasses all of the AMQP/RabbitMQ specific behaviors. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or soc...
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_basic_return
python
def on_basic_return(self, _channel, method, properties, body): if self.on_return: self.on_return(method, properties, body) else: LOGGER.critical( '%s message %s published to %s (CID %s) returned: %s', method.exchange, properties.message_id, ...
Invoke a registered callback or log the returned message. :param _channel: The channel the message was sent on :type _channel: pika.channel.Channel :param pika.spec.Basic.Return method: The method object :param pika.spec.BasicProperties properties: The message properties :param ...
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L518-L535
null
class Client(object): """This class encompasses all of the AMQP/RabbitMQ specific behaviors. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or soc...
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_channel_open
python
def on_channel_open(self, channel): LOGGER.debug('Channel opened') self.channel = channel if self.publisher_confirmations: self.channel.confirm_delivery(self.on_delivery_confirmation) self.channel.add_on_close_callback(self.on_channel_closed) self.channel.add_on_flow_...
This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. :param pika.channel.Channel channel: The channel object
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L541-L557
null
class Client(object): """This class encompasses all of the AMQP/RabbitMQ specific behaviors. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or soc...
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_channel_closed
python
def on_channel_closed(self, channel, reply_code, reply_text): for future in self.messages.values(): future.set_exception(AMQPException(reply_code, reply_text)) self.messages = {} if self.closing: LOGGER.debug('Channel %s was intentionally closed (%s) %s', ...
Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we just want to log the error and create a new channel ...
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L559-L586
[ "def _open_channel(self):\n \"\"\"Open a new channel with RabbitMQ.\n\n :rtype: pika.channel.Channel\n\n \"\"\"\n LOGGER.debug('Creating a new channel')\n return self.connection.channel(self.on_channel_open)\n" ]
class Client(object): """This class encompasses all of the AMQP/RabbitMQ specific behaviors. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or soc...
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_channel_flow
python
def on_channel_flow(self, method): if method.active: LOGGER.info('Channel flow is active (READY)') self.state = self.STATE_READY if self.on_ready: self.on_ready(self) else: LOGGER.warning('Channel flow is inactive (BLOCKED)') se...
When RabbitMQ indicates the connection is unblocked, set the state appropriately. :param pika.spec.Channel.Flow method: The Channel flow frame
train
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L588-L604
null
class Client(object): """This class encompasses all of the AMQP/RabbitMQ specific behaviors. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or soc...
rmorshea/spectate
spectate/mvc/base.py
views
python
def views(model: "Model") -> list: if not isinstance(model, Model): raise TypeError("Expected a Model, not %r." % model) return model._model_views[:]
Return a model's views keyed on what events they respond to. Model views are added by calling :func:`view` on a model.
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/mvc/base.py#L14-L21
null
# See End Of File For Licensing from inspect import signature from functools import wraps from typing import Union, Callable, Optional from spectate.core import Watchable, watched, Data, MethodSpectator from .utils import members __all__ = ["Model", "Control", "view", "unview", "views"] def view(model: "Model", ...
rmorshea/spectate
spectate/mvc/base.py
view
python
def view(model: "Model", *functions: Callable) -> Optional[Callable]: if not isinstance(model, Model): raise TypeError("Expected a Model, not %r." % model) def setup(function: Callable): model._model_views.append(function) return function if functions: for f in functions: ...
A decorator for registering a callback to a model Parameters: model: the model object whose changes the callback should respond to. Examples: .. code-block:: python from spectate import mvc items = mvc.List() @mvc.view(items) def printer(items...
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/mvc/base.py#L24-L55
[ "def setup(function: Callable):\n model._model_views.append(function)\n return function\n" ]
# See End Of File For Licensing from inspect import signature from functools import wraps from typing import Union, Callable, Optional from spectate.core import Watchable, watched, Data, MethodSpectator from .utils import members __all__ = ["Model", "Control", "view", "unview", "views"] def views(model: "Model") ...
rmorshea/spectate
spectate/mvc/base.py
Control.before
python
def before(self, callback: Union[Callable, str]) -> "Control": if isinstance(callback, Control): callback = callback._before self._before = callback return self
Register a control method that reacts before the trigger method is called. Parameters: callback: The control method. If given as a callable, then that function will be used as the callback. If given as a string, then the control will look up a method ...
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/mvc/base.py#L137-L149
null
class Control: """An object used to define control methods on a :class:`Model` A "control" method on a :class:`Model` is one which reacts to another method being called. For example there is a control method on the :class:`~spectate.mvc.models.List` which responds when :meth:`~spectate.mvc.models.L...
rmorshea/spectate
spectate/mvc/base.py
Control.after
python
def after(self, callback: Union[Callable, str]) -> "Control": if isinstance(callback, Control): callback = callback._after self._after = callback return self
Register a control method that reacts after the trigger method is called. Parameters: callback: The control method. If given as a callable, then that function will be used as the callback. If given as a string, then the control will look up a method w...
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/mvc/base.py#L151-L163
null
class Control: """An object used to define control methods on a :class:`Model` A "control" method on a :class:`Model` is one which reacts to another method being called. For example there is a control method on the :class:`~spectate.mvc.models.List` which responds when :meth:`~spectate.mvc.models.L...
rmorshea/spectate
spectate/mvc/events.py
hold
python
def hold(model: Model, reducer: Optional[Callable] = None) -> Iterator[list]: if not isinstance(model, Model): raise TypeError("Expected a Model, not %r." % model) events = [] restore = model.__dict__.get("_notify_model_views") model._notify_model_views = lambda e: events.extend(e) try: ...
Temporarilly withold change events in a modifiable list. All changes that are captured within a "hold" context are forwarded to a list which is yielded to the user before being sent to views of the given ``model``. If desired, the user may modify the list of events before the context is left in order t...
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/mvc/events.py#L12-L76
null
from contextlib import contextmanager from typing import Iterator, Callable, Optional from spectate import Data from .base import Model __all__ = ["hold", "mute", "rollback"] @contextmanager @contextmanager def rollback( model: Model, undo: Optional[Callable] = None, *args, **kwargs ) -> Iterator[list]: ...
rmorshea/spectate
spectate/mvc/events.py
rollback
python
def rollback( model: Model, undo: Optional[Callable] = None, *args, **kwargs ) -> Iterator[list]: with hold(model, *args, **kwargs) as events: try: yield events except Exception as error: if undo is not None: with mute(model): undo(mode...
Withold events if an error occurs. Generall operate Parameters: model: The model object whose change events may be witheld. undo: An optional function for reversing any changes that may have taken place. Its signature is ``(model, events, error)`` where ``mo...
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/mvc/events.py#L80-L156
null
from contextlib import contextmanager from typing import Iterator, Callable, Optional from spectate import Data from .base import Model __all__ = ["hold", "mute", "rollback"] @contextmanager def hold(model: Model, reducer: Optional[Callable] = None) -> Iterator[list]: """Temporarilly withold change events in a...
rmorshea/spectate
spectate/mvc/events.py
mute
python
def mute(model: Model): if not isinstance(model, Model): raise TypeError("Expected a Model, not %r." % model) restore = model.__dict__.get("_notify_model_views") model._notify_model_views = lambda e: None try: yield finally: if restore is None: del model._notify_m...
Block a model's views from being notified. All changes within a "mute" context will be blocked. No content is yielded to the user as in :func:`hold`, and the views of the model are never notified that changes took place. Parameters: mode: The model whose change events will be blocked. Exa...
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/mvc/events.py#L160-L197
null
from contextlib import contextmanager from typing import Iterator, Callable, Optional from spectate import Data from .base import Model __all__ = ["hold", "mute", "rollback"] @contextmanager def hold(model: Model, reducer: Optional[Callable] = None) -> Iterator[list]: """Temporarilly withold change events in a...
rmorshea/spectate
spectate/core.py
expose
python
def expose(*methods): def setup(base): return expose_as(base.__name__, base, *methods) return setup
A decorator for exposing the methods of a class. Parameters ---------- *methods : str A str representation of the methods that should be exposed to callbacks. Returns ------- decorator : function A function accepting one argument - the class whose methods will be expose...
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/core.py#L250-L273
null
# See End Of File For Licensing import sys import inspect import collections from functools import wraps try: from inspect import signature, Parameter, Signature except ImportError: from funcsigs import signature, Parameter, Signature __all__ = [ "expose", "expose_as", "watch", "watched", ...
rmorshea/spectate
spectate/core.py
expose_as
python
def expose_as(name, base, *methods): classdict = {} for method in methods: if not hasattr(base, method): raise AttributeError( "Cannot expose '%s', because '%s' " "instances lack this method" % (method, base.__name__) ) else: cl...
Return a new type with certain methods that are exposed to callback registration. Parameters ---------- name : str The name of the new type. base : type A type such as list or dict. *methods : str A str representation of the methods that should be exposed to callbacks. ...
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/core.py#L276-L302
null
# See End Of File For Licensing import sys import inspect import collections from functools import wraps try: from inspect import signature, Parameter, Signature except ImportError: from funcsigs import signature, Parameter, Signature __all__ = [ "expose", "expose_as", "watch", "watched", ...
rmorshea/spectate
spectate/core.py
watchable
python
def watchable(value): check = issubclass if inspect.isclass(value) else isinstance return check(value, Watchable)
Returns True if the given value is a :class:`Watchable` subclass or instance.
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/core.py#L305-L308
null
# See End Of File For Licensing import sys import inspect import collections from functools import wraps try: from inspect import signature, Parameter, Signature except ImportError: from funcsigs import signature, Parameter, Signature __all__ = [ "expose", "expose_as", "watch", "watched", ...
rmorshea/spectate
spectate/core.py
watch
python
def watch(value, spectator_type=Spectator): if isinstance(value, Watchable): wtype = type(value) else: raise TypeError("Expected a Watchable, not %r." % value) spectator = getattr(value, "_instance_spectator", None) if not isinstance(spectator, Spectator): spectator = spectator_t...
Register a :class:`Specatator` to a :class:`Watchable` and return it. In order to register callbacks to an eventful object, you need to create a Spectator that will watch it for you. A :class:`Specatator` is a relatively simple object that has methods for adding, deleting, and triggering callbacks. To ...
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/core.py#L311-L341
null
# See End Of File For Licensing import sys import inspect import collections from functools import wraps try: from inspect import signature, Parameter, Signature except ImportError: from funcsigs import signature, Parameter, Signature __all__ = [ "expose", "expose_as", "watch", "watched", ...
rmorshea/spectate
spectate/core.py
watched
python
def watched(cls, *args, **kwargs): value = cls(*args, **kwargs) return value, watch(value)
Create and return a :class:`Watchable` with its :class:`Specatator`. See :func:`watch` for more info on :class:`Specatator` registration. Parameters ---------- cls: type: A subclass of :class:`Watchable` *args: Positional arguments used to create the instance **kwargs: ...
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/core.py#L344-L359
[ "def watch(value, spectator_type=Spectator):\n \"\"\"Register a :class:`Specatator` to a :class:`Watchable` and return it.\n\n In order to register callbacks to an eventful object, you need to create\n a Spectator that will watch it for you. A :class:`Specatator` is a relatively simple\n object that has...
# See End Of File For Licensing import sys import inspect import collections from functools import wraps try: from inspect import signature, Parameter, Signature except ImportError: from funcsigs import signature, Parameter, Signature __all__ = [ "expose", "expose_as", "watch", "watched", ...
rmorshea/spectate
spectate/core.py
unwatch
python
def unwatch(value): if not isinstance(value, Watchable): raise TypeError("Expected a Watchable, not %r." % value) spectator = watcher(value) try: del value._instance_spectator except Exception: pass return spectator
Return the :class:`Specatator` of a :class:`Watchable` instance.
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/core.py#L362-L371
[ "def watcher(value):\n \"\"\"Return the :class:`Specatator` of a :class:`Watchable` instance.\"\"\"\n if not isinstance(value, Watchable):\n raise TypeError(\"Expected a Watchable, not %r.\" % value)\n return getattr(value, \"_instance_spectator\", None)\n" ]
# See End Of File For Licensing import sys import inspect import collections from functools import wraps try: from inspect import signature, Parameter, Signature except ImportError: from funcsigs import signature, Parameter, Signature __all__ = [ "expose", "expose_as", "watch", "watched", ...
rmorshea/spectate
spectate/core.py
Spectator.callback
python
def callback(self, name, before=None, after=None): if isinstance(name, (list, tuple)): for name in name: self.callback(name, before, after) else: if not isinstance(getattr(self.subclass, name), MethodSpectator): raise ValueError("No method specator...
Add a callback pair to this spectator. You can specify, with keywords, whether each callback should be triggered before, and/or or after a given method is called - hereafter refered to as "beforebacks" and "afterbacks" respectively. Parameters ---------- name: str ...
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/core.py#L74-L117
[ "def callback(self, name, before=None, after=None):\n \"\"\"Add a callback pair to this spectator.\n\n You can specify, with keywords, whether each callback should be triggered\n before, and/or or after a given method is called - hereafter refered to as\n \"beforebacks\" and \"afterbacks\" respectively....
class Spectator(object): """An object for holding callbacks""" def __init__(self, subclass): """Create a Spectator that can be registered to a :class:`Watchable` instance. Parameters ---------- subclass: type A the :class:`Watchable` subclass whose instance this ...
rmorshea/spectate
spectate/core.py
Spectator.remove_callback
python
def remove_callback(self, name, before=None, after=None): if isinstance(name, (list, tuple)): for name in name: self.remove_callback(name, before, after) elif before is None and after is None: del self._callback_registry[name] else: if name in ...
Remove a beforeback, and afterback pair from this Spectator If ``before`` and ``after`` are None then all callbacks for the given method will be removed. Otherwise, only the exact callback pair will be removed. Parameters ---------- name: str The name of the...
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/core.py#L119-L149
[ "def remove_callback(self, name, before=None, after=None):\n \"\"\"Remove a beforeback, and afterback pair from this Spectator\n\n If ``before`` and ``after`` are None then all callbacks for\n the given method will be removed. Otherwise, only the exact\n callback pair will be removed.\n\n Parameters\...
class Spectator(object): """An object for holding callbacks""" def __init__(self, subclass): """Create a Spectator that can be registered to a :class:`Watchable` instance. Parameters ---------- subclass: type A the :class:`Watchable` subclass whose instance this ...
rmorshea/spectate
spectate/core.py
Spectator.call
python
def call(self, obj, name, method, args, kwargs): if name in self._callback_registry: beforebacks, afterbacks = zip(*self._callback_registry.get(name, [])) hold = [] for b in beforebacks: if b is not None: call = Data(name=name, kwargs=kwar...
Trigger a method along with its beforebacks and afterbacks. Parameters ---------- name: str The name of the method that will be called args: tuple The arguments that will be passed to the base method kwargs: dict The keyword args that will be ...
train
https://github.com/rmorshea/spectate/blob/79bd84dd8d00889015ce1d1e190db865a02cdb93/spectate/core.py#L151-L186
null
class Spectator(object): """An object for holding callbacks""" def __init__(self, subclass): """Create a Spectator that can be registered to a :class:`Watchable` instance. Parameters ---------- subclass: type A the :class:`Watchable` subclass whose instance this ...
zmathew/django-backbone
backbone/__init__.py
autodiscover
python
def autodiscover(): # This code is based off django.contrib.admin.__init__ from django.conf import settings try: # Django versions >= 1.9 from django.utils.module_loading import import_module except ImportError: # Django versions < 1.9 from django.utils.importlib import i...
Auto-discover INSTALLED_APPS backbone_api.py modules.
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/__init__.py#L16-L41
null
"""Provides a Backbone.js compatible REST API for your models using Django Admin style registration.""" from __future__ import unicode_literals from backbone.sites import BackboneSite VERSION = (0, 3, 2) __version__ = '.'.join(map(str, VERSION)) site = BackboneSite()
zmathew/django-backbone
backbone/sites.py
BackboneSite.register
python
def register(self, backbone_view_class): if backbone_view_class not in self._registry: self._registry.append(backbone_view_class)
Registers the given backbone view class.
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/sites.py#L10-L15
null
class BackboneSite(object): def __init__(self, name='backbone'): self._registry = [] self.name = name def unregister(self, backbone_view_class): if backbone_view_class in self._registry: self._registry.remove(backbone_view_class) def get_urls(self): from djang...
zmathew/django-backbone
backbone/views.py
BackboneAPIView.queryset
python
def queryset(self, request, **kwargs): qs = self.model._default_manager.all() if self.ordering: qs = qs.order_by(*self.ordering) return qs
Returns the queryset (along with ordering) to be used when retrieving object(s).
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L29-L36
null
class BackboneAPIView(View): model = None # The model to be used for this API definition display_fields = [] # Fields to return for read (GET) requests, display_collection_fields = [] # Specific fields to return for a read (GET) request of a model collection display_detail_fields = [] # Specific field...
zmathew/django-backbone
backbone/views.py
BackboneAPIView.get
python
def get(self, request, id=None, **kwargs): if not self.has_get_permission(request): return HttpResponseForbidden(_('You do not have permission to perform this action.')) if id: obj = get_object_or_404(self.queryset(request, **kwargs), id=id) return self.get_object_de...
Handles get requests for either the collection or an object detail.
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L38-L49
null
class BackboneAPIView(View): model = None # The model to be used for this API definition display_fields = [] # Fields to return for read (GET) requests, display_collection_fields = [] # Specific fields to return for a read (GET) request of a model collection display_detail_fields = [] # Specific field...
zmathew/django-backbone
backbone/views.py
BackboneAPIView.get_object_detail
python
def get_object_detail(self, request, obj): if self.display_detail_fields: display_fields = self.display_detail_fields else: display_fields = self.display_fields data = self.serialize(obj, ['id'] + list(display_fields)) return HttpResponse(self.json_dumps(data), c...
Handles get requests for the details of the given object.
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L51-L61
null
class BackboneAPIView(View): model = None # The model to be used for this API definition display_fields = [] # Fields to return for read (GET) requests, display_collection_fields = [] # Specific fields to return for a read (GET) request of a model collection display_detail_fields = [] # Specific field...
zmathew/django-backbone
backbone/views.py
BackboneAPIView.get_collection
python
def get_collection(self, request, **kwargs): qs = self.queryset(request, **kwargs) if self.display_collection_fields: display_fields = self.display_collection_fields else: display_fields = self.display_fields if self.paginate_by is not None: page = r...
Handles get requests for the list of objects.
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L63-L88
null
class BackboneAPIView(View): model = None # The model to be used for this API definition display_fields = [] # Fields to return for read (GET) requests, display_collection_fields = [] # Specific fields to return for a read (GET) request of a model collection display_detail_fields = [] # Specific field...
zmathew/django-backbone
backbone/views.py
BackboneAPIView.post
python
def post(self, request, id=None, **kwargs): if id: # No posting to an object detail page return HttpResponseForbidden() else: if not self.has_add_permission(request): return HttpResponseForbidden(_('You do not have permission to perform this action.'))...
Handles post requests.
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L90-L101
null
class BackboneAPIView(View): model = None # The model to be used for this API definition display_fields = [] # Fields to return for read (GET) requests, display_collection_fields = [] # Specific fields to return for a read (GET) request of a model collection display_detail_fields = [] # Specific field...
zmathew/django-backbone
backbone/views.py
BackboneAPIView.add_object
python
def add_object(self, request): try: # backbone sends data in the body in json format # Conditional statement is for backwards compatibility with Django <= 1.3 data = json.loads(request.body if hasattr(request, 'body') else request.raw_post_data) except ValueError: ...
Adds an object.
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L103-L133
null
class BackboneAPIView(View): model = None # The model to be used for this API definition display_fields = [] # Fields to return for read (GET) requests, display_collection_fields = [] # Specific fields to return for a read (GET) request of a model collection display_detail_fields = [] # Specific field...
zmathew/django-backbone
backbone/views.py
BackboneAPIView.put
python
def put(self, request, id=None, **kwargs): if id: obj = get_object_or_404(self.queryset(request), id=id) if not self.has_update_permission(request, obj): return HttpResponseForbidden(_('You do not have permission to perform this action.')) else: ...
Handles put requests.
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L135-L147
null
class BackboneAPIView(View): model = None # The model to be used for this API definition display_fields = [] # Fields to return for read (GET) requests, display_collection_fields = [] # Specific fields to return for a read (GET) request of a model collection display_detail_fields = [] # Specific field...
zmathew/django-backbone
backbone/views.py
BackboneAPIView.update_object
python
def update_object(self, request, obj): try: # backbone sends data in the body in json format # Conditional statement is for backwards compatibility with Django <= 1.3 data = json.loads(request.body if hasattr(request, 'body') else request.raw_post_data) except Val...
Updates an object.
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L149-L169
null
class BackboneAPIView(View): model = None # The model to be used for this API definition display_fields = [] # Fields to return for read (GET) requests, display_collection_fields = [] # Specific fields to return for a read (GET) request of a model collection display_detail_fields = [] # Specific field...
zmathew/django-backbone
backbone/views.py
BackboneAPIView.get_form_instance
python
def get_form_instance(self, request, data=None, instance=None): defaults = {} if self.form: defaults['form'] = self.form if self.fields: defaults['fields'] = self.fields return modelform_factory(self.model, **defaults)(data=data, instance=instance)
Returns an instantiated form to be used for adding or editing an object. The `instance` argument is the model instance (passed only if this form is going to be used for editing an existing object).
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L171-L183
null
class BackboneAPIView(View): model = None # The model to be used for this API definition display_fields = [] # Fields to return for read (GET) requests, display_collection_fields = [] # Specific fields to return for a read (GET) request of a model collection display_detail_fields = [] # Specific field...
zmathew/django-backbone
backbone/views.py
BackboneAPIView.delete
python
def delete(self, request, id=None): if id: obj = get_object_or_404(self.queryset(request), id=id) if not self.has_delete_permission(request, obj): return HttpResponseForbidden(_('You do not have permission to perform this action.')) else: retur...
Handles delete requests.
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L185-L197
null
class BackboneAPIView(View): model = None # The model to be used for this API definition display_fields = [] # Fields to return for read (GET) requests, display_collection_fields = [] # Specific fields to return for a read (GET) request of a model collection display_detail_fields = [] # Specific field...
zmathew/django-backbone
backbone/views.py
BackboneAPIView.has_add_permission
python
def has_add_permission(self, request): perm_string = '%s.add_%s' % (self.model._meta.app_label, self.model._meta.object_name.lower() ) return request.user.has_perm(perm_string)
Returns True if the requesting user is allowed to add an object, False otherwise.
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L212-L219
null
class BackboneAPIView(View): model = None # The model to be used for this API definition display_fields = [] # Fields to return for read (GET) requests, display_collection_fields = [] # Specific fields to return for a read (GET) request of a model collection display_detail_fields = [] # Specific field...
zmathew/django-backbone
backbone/views.py
BackboneAPIView.has_update_permission
python
def has_update_permission(self, request, obj): perm_string = '%s.change_%s' % (self.model._meta.app_label, self.model._meta.object_name.lower() ) return request.user.has_perm(perm_string)
Returns True if the requesting user is allowed to update the given object, False otherwise.
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L231-L238
null
class BackboneAPIView(View): model = None # The model to be used for this API definition display_fields = [] # Fields to return for read (GET) requests, display_collection_fields = [] # Specific fields to return for a read (GET) request of a model collection display_detail_fields = [] # Specific field...
zmathew/django-backbone
backbone/views.py
BackboneAPIView.serialize
python
def serialize(self, obj, fields): data = {} remaining_fields = [] for field in fields: if callable(field): # Callable data[field.__name__] = field(obj) elif hasattr(self, field) and callable(getattr(self, field)): # Method on the view da...
Serializes a single model instance to a Python dict, based on the specified list of fields.
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L259-L295
null
class BackboneAPIView(View): model = None # The model to be used for this API definition display_fields = [] # Fields to return for read (GET) requests, display_collection_fields = [] # Specific fields to return for a read (GET) request of a model collection display_detail_fields = [] # Specific field...
zmathew/django-backbone
backbone/views.py
BackboneAPIView.json_dumps
python
def json_dumps(self, data, **options): params = {'sort_keys': True, 'indent': 2} params.update(options) # This code is based off django's built in JSON serializer if json.__version__.split('.') >= ['2', '1', '3']: # Use JS strings to represent Python Decimal instances (ticket...
Wrapper around `json.dumps` that uses a special JSON encoder.
train
https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L297-L307
null
class BackboneAPIView(View): model = None # The model to be used for this API definition display_fields = [] # Fields to return for read (GET) requests, display_collection_fields = [] # Specific fields to return for a read (GET) request of a model collection display_detail_fields = [] # Specific field...
nakagami/pyfirebirdsql
firebirdsql/utils.py
hex_to_bytes
python
def hex_to_bytes(s): if len(s) % 2: s = b'0' + s ia = [int(s[i:i+2], 16) for i in range(0, len(s), 2)] # int array return bs(ia) if PYTHON_MAJOR_VER == 3 else b''.join([chr(c) for c in ia])
convert hex string to bytes
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/utils.py#L43-L50
[ "def bs(byte_array):\n if PYTHON_MAJOR_VER == 2:\n return ''.join([chr(c) for c in byte_array])\n else:\n return bytes(byte_array)\n" ]
############################################################################## # Copyright (c) 2014-2018, Hajime Nakagami<nakagami@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * ...
nakagami/pyfirebirdsql
firebirdsql/srp.py
client_seed
python
def client_seed(a=random.randrange(0, 1 << SRP_KEY_SIZE)): if DEBUG: a = DEBUG_PRIVATE_KEY N, g, k = get_prime() A = pow(g, a, N) if DEBUG_PRINT: print('a=', binascii.b2a_hex(long2bytes(a)), end='\n') print('A=', binascii.b2a_hex(long2bytes(A)), end='\n') return A, a
A: Client public key a: Client private key
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/srp.py#L181-L193
[ "def get_prime():\n N = 0xE67D2E994B2F900C3F41F08F5BB2627ED0D49EE1FE767A52EFCD565CD6E768812C3E1E9CE8F0A8BEA6CB13CD29DDEBF7A96D4A93B55D488DF099A15C89DCB0640738EB2CBDD9A8F7BAB561AB1B0DC1C6CDABF303264A08D1BCA932D1F1EE428B619D970F342ABA9A65793B8B2F041AE5364350C16F735F56ECBCA87BD57B29E7\n g = 2\n\n #k = bytes2l...
############################################################################## # Copyright (c) 2014-2016, Hajime Nakagami<nakagami@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * ...
nakagami/pyfirebirdsql
firebirdsql/srp.py
server_seed
python
def server_seed(v, b=random.randrange(0, 1 << SRP_KEY_SIZE)): N, g, k = get_prime() if DEBUG: b = DEBUG_PRIVATE_KEY gb = pow(g, b, N) kv = (k * v) % N B = (kv + gb) % N if DEBUG_PRINT: print("v", binascii.b2a_hex(long2bytes(v)), end='\n') print('b=', binascii.b2a_hex(long...
B: Server public key b: Server private key
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/srp.py#L196-L215
[ "def get_prime():\n N = 0xE67D2E994B2F900C3F41F08F5BB2627ED0D49EE1FE767A52EFCD565CD6E768812C3E1E9CE8F0A8BEA6CB13CD29DDEBF7A96D4A93B55D488DF099A15C89DCB0640738EB2CBDD9A8F7BAB561AB1B0DC1C6CDABF303264A08D1BCA932D1F1EE428B619D970F342ABA9A65793B8B2F041AE5364350C16F735F56ECBCA87BD57B29E7\n g = 2\n\n #k = bytes2l...
############################################################################## # Copyright (c) 2014-2016, Hajime Nakagami<nakagami@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * ...
nakagami/pyfirebirdsql
firebirdsql/srp.py
client_session
python
def client_session(user, password, salt, A, B, a): N, g, k = get_prime() u = get_scramble(A, B) x = getUserHash(salt, user, password) # x gx = pow(g, x, N) # g^x kgx = (k * gx) % N # kg^x diff = (B - kgx) % N # B - kg^x ux = (u ...
Client session secret Both: u = H(A, B) User: x = H(s, p) (user enters password) User: S = (B - kg^x) ^ (a + ux) (computes session key) User: K = H(S)
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/srp.py#L218-L249
[ "def get_prime():\n N = 0xE67D2E994B2F900C3F41F08F5BB2627ED0D49EE1FE767A52EFCD565CD6E768812C3E1E9CE8F0A8BEA6CB13CD29DDEBF7A96D4A93B55D488DF099A15C89DCB0640738EB2CBDD9A8F7BAB561AB1B0DC1C6CDABF303264A08D1BCA932D1F1EE428B619D970F342ABA9A65793B8B2F041AE5364350C16F735F56ECBCA87BD57B29E7\n g = 2\n\n #k = bytes2l...
############################################################################## # Copyright (c) 2014-2016, Hajime Nakagami<nakagami@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * ...
nakagami/pyfirebirdsql
firebirdsql/srp.py
server_session
python
def server_session(user, password, salt, A, B, b): N, g, k = get_prime() u = get_scramble(A, B) v = get_verifier(user, password, salt) vu = pow(v, u, N) # v^u Avu = (A * vu) % N # Av^u session_secret = pow(Avu, b, N) # (Av^u) ^ b K = hash_di...
Server session secret Both: u = H(A, B) Host: S = (Av^u) ^ b (computes session key) Host: K = H(S)
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/srp.py#L252-L271
[ "def get_prime():\n N = 0xE67D2E994B2F900C3F41F08F5BB2627ED0D49EE1FE767A52EFCD565CD6E768812C3E1E9CE8F0A8BEA6CB13CD29DDEBF7A96D4A93B55D488DF099A15C89DCB0640738EB2CBDD9A8F7BAB561AB1B0DC1C6CDABF303264A08D1BCA932D1F1EE428B619D970F342ABA9A65793B8B2F041AE5364350C16F735F56ECBCA87BD57B29E7\n g = 2\n\n #k = bytes2l...
############################################################################## # Copyright (c) 2014-2016, Hajime Nakagami<nakagami@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * ...
nakagami/pyfirebirdsql
firebirdsql/srp.py
client_proof
python
def client_proof(user, password, salt, A, B, a, hash_algo): N, g, k = get_prime() K = client_session(user, password, salt, A, B, a) n1 = bytes2long(hash_digest(hashlib.sha1, N)) n2 = bytes2long(hash_digest(hashlib.sha1, g)) if DEBUG_PRINT: print('n1-1=', binascii.b2a_hex(long2bytes(n1)), en...
M = H(H(N) xor H(g), H(I), s, A, B, K)
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/srp.py#L274-L296
[ "def bytes2long(s):\n n = 0\n for c in s:\n n <<= 8\n n += ord(c)\n return n\n", "def get_prime():\n N = 0xE67D2E994B2F900C3F41F08F5BB2627ED0D49EE1FE767A52EFCD565CD6E768812C3E1E9CE8F0A8BEA6CB13CD29DDEBF7A96D4A93B55D488DF099A15C89DCB0640738EB2CBDD9A8F7BAB561AB1B0DC1C6CDABF303264A08D1BCA93...
############################################################################## # Copyright (c) 2014-2016, Hajime Nakagami<nakagami@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * ...
nakagami/pyfirebirdsql
firebirdsql/decfloat.py
dpd_to_int
python
def dpd_to_int(dpd): b = [None] * 10 b[9] = 1 if dpd & 0b1000000000 else 0 b[8] = 1 if dpd & 0b0100000000 else 0 b[7] = 1 if dpd & 0b0010000000 else 0 b[6] = 1 if dpd & 0b0001000000 else 0 b[5] = 1 if dpd & 0b0000100000 else 0 b[4] = 1 if dpd & 0b0000010000 else 0 b[3] = 1 if dpd & 0b000...
Convert DPD encodined value to int (0-999) dpd: DPD encoded value. 10bit unsigned int
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/decfloat.py#L47-L100
null
############################################################################## # Copyright (c) 2018, Hajime Nakagami<nakagami@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redis...
nakagami/pyfirebirdsql
firebirdsql/decfloat.py
calc_significand
python
def calc_significand(prefix, dpd_bits, num_bits): # https://en.wikipedia.org/wiki/Decimal128_floating-point_format#Densely_packed_decimal_significand_field num_segments = num_bits // 10 segments = [] for i in range(num_segments): segments.append(dpd_bits & 0b1111111111) dpd_bits >>= 10 ...
prefix: High bits integer value dpd_bits: dpd encoded bits num_bits: bit length of dpd_bits
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/decfloat.py#L103-L121
[ "def dpd_to_int(dpd):\n \"\"\"\n Convert DPD encodined value to int (0-999)\n dpd: DPD encoded value. 10bit unsigned int\n \"\"\"\n b = [None] * 10\n b[9] = 1 if dpd & 0b1000000000 else 0\n b[8] = 1 if dpd & 0b0100000000 else 0\n b[7] = 1 if dpd & 0b0010000000 else 0\n b[6] = 1 if dpd & 0...
############################################################################## # Copyright (c) 2018, Hajime Nakagami<nakagami@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redis...
nakagami/pyfirebirdsql
firebirdsql/decfloat.py
decimal128_to_decimal
python
def decimal128_to_decimal(b): "decimal128 bytes to Decimal" v = decimal128_to_sign_digits_exponent(b) if isinstance(v, Decimal): return v sign, digits, exponent = v return Decimal((sign, Decimal(digits).as_tuple()[1], exponent))
decimal128 bytes to Decimal
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/decfloat.py#L216-L222
[ "def decimal128_to_sign_digits_exponent(b):\n # https://en.wikipedia.org/wiki/Decimal128_floating-point_format\n sign = 1 if ord(b[0]) & 0x80 else 0\n combination_field = ((ord(b[0]) & 0x7f) << 10) + (ord(b[1]) << 2) + (ord(b[2]) >> 6)\n if (combination_field & 0b11111000000000000) == 0b1111100000000000...
############################################################################## # Copyright (c) 2018, Hajime Nakagami<nakagami@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redis...
nakagami/pyfirebirdsql
firebirdsql/wireprotocol.py
WireProtocol.str_to_bytes
python
def str_to_bytes(self, s): "convert str to bytes" if (PYTHON_MAJOR_VER == 3 or (PYTHON_MAJOR_VER == 2 and type(s) == unicode)): return s.encode(charset_map.get(self.charset, self.charset)) return s
convert str to bytes
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/wireprotocol.py#L227-L232
null
class WireProtocol(object): buffer_length = 1024 op_connect = 1 op_exit = 2 op_accept = 3 op_reject = 4 op_protocol = 5 op_disconnect = 6 op_response = 9 op_attach = 19 op_create = 20 op_detach = 21 op_transaction = 29 op_commit = 30 op_rollback = 31 op_open_...
nakagami/pyfirebirdsql
firebirdsql/wireprotocol.py
WireProtocol.bytes_to_str
python
def bytes_to_str(self, b): "convert bytes array to raw string" if PYTHON_MAJOR_VER == 3: return b.decode(charset_map.get(self.charset, self.charset)) return b
convert bytes array to raw string
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/wireprotocol.py#L234-L238
null
class WireProtocol(object): buffer_length = 1024 op_connect = 1 op_exit = 2 op_accept = 3 op_reject = 4 op_protocol = 5 op_disconnect = 6 op_response = 9 op_attach = 19 op_create = 20 op_detach = 21 op_transaction = 29 op_commit = 30 op_rollback = 31 op_open_...
nakagami/pyfirebirdsql
firebirdsql/wireprotocol.py
WireProtocol.bytes_to_ustr
python
def bytes_to_ustr(self, b): "convert bytes array to unicode string" return b.decode(charset_map.get(self.charset, self.charset))
convert bytes array to unicode string
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/wireprotocol.py#L240-L242
null
class WireProtocol(object): buffer_length = 1024 op_connect = 1 op_exit = 2 op_accept = 3 op_reject = 4 op_protocol = 5 op_disconnect = 6 op_response = 9 op_attach = 19 op_create = 20 op_detach = 21 op_transaction = 29 op_commit = 30 op_rollback = 31 op_open_...
nakagami/pyfirebirdsql
firebirdsql/wireprotocol.py
WireProtocol.params_to_blr
python
def params_to_blr(self, trans_handle, params): "Convert parameter array to BLR and values format." ln = len(params) * 2 blr = bs([5, 2, 4, 0, ln & 255, ln >> 8]) if self.accept_version < PROTOCOL_VERSION13: values = bs([]) else: # start with null indicator...
Convert parameter array to BLR and values format.
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/wireprotocol.py#L318-L417
[ "def bs(byte_array):\n if PYTHON_MAJOR_VER == 2:\n return ''.join([chr(c) for c in byte_array])\n else:\n return bytes(byte_array)\n", "def bint_to_bytes(val, nbytes): # Convert int value to big endian bytes.\n v = abs(val)\n b = []\n for n in range(nbytes):\n b.append((v >...
class WireProtocol(object): buffer_length = 1024 op_connect = 1 op_exit = 2 op_accept = 3 op_reject = 4 op_protocol = 5 op_disconnect = 6 op_response = 9 op_attach = 19 op_create = 20 op_detach = 21 op_transaction = 29 op_commit = 30 op_rollback = 31 op_open_...
nakagami/pyfirebirdsql
firebirdsql/xsqlvar.py
calc_blr
python
def calc_blr(xsqlda): "Calculate BLR from XSQLVAR array." ln = len(xsqlda) * 2 blr = [5, 2, 4, 0, ln & 255, ln >> 8] for x in xsqlda: sqltype = x.sqltype if sqltype == SQL_TYPE_VARYING: blr += [37, x.sqllen & 255, x.sqllen >> 8] elif sqltype == SQL_TYPE_TEXT: ...
Calculate BLR from XSQLVAR array.
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/xsqlvar.py#L216-L242
[ "def bs(byte_array):\n if PYTHON_MAJOR_VER == 2:\n return ''.join([chr(c) for c in byte_array])\n else:\n return bytes(byte_array)\n" ]
############################################################################## # Copyright (c) 2009-2018, Hajime Nakagami<nakagami@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * ...
nakagami/pyfirebirdsql
firebirdsql/xsqlvar.py
XSQLVAR._parse_date
python
def _parse_date(self, raw_value): "Convert raw data to datetime.date" nday = bytes_to_bint(raw_value) + 678882 century = (4 * nday - 1) // 146097 nday = 4 * nday - 1 - 146097 * century day = nday // 4 nday = (4 * day + 3) // 1461 day = 4 * day + 3 - 1461 * nday ...
Convert raw data to datetime.date
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/xsqlvar.py#L118-L138
[ "def bytes_to_bint(b, u=False): # Read as big endian\n if u:\n fmtmap = {1: 'B', 2: '>H', 4: '>L', 8: '>Q'}\n else:\n fmtmap = {1: 'b', 2: '>h', 4: '>l', 8: '>q'}\n fmt = fmtmap.get(len(b))\n if fmt is None:\n raise InternalError(\"Invalid bytes length:%d\" % (len(b), ))\n...
class XSQLVAR: type_length = { SQL_TYPE_VARYING: -1, SQL_TYPE_SHORT: 4, SQL_TYPE_LONG: 4, SQL_TYPE_FLOAT: 4, SQL_TYPE_TIME: 4, SQL_TYPE_DATE: 4, SQL_TYPE_DOUBLE: 8, SQL_TYPE_TIMESTAMP: 8, SQL_TYPE_BLOB: 8, SQL_TYPE_ARRAY: 8, SQL...
nakagami/pyfirebirdsql
firebirdsql/xsqlvar.py
XSQLVAR._parse_time
python
def _parse_time(self, raw_value): "Convert raw data to datetime.time" n = bytes_to_bint(raw_value) s = n // 10000 m = s // 60 h = m // 60 m = m % 60 s = s % 60 return (h, m, s, (n % 10000) * 100)
Convert raw data to datetime.time
train
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/xsqlvar.py#L140-L148
[ "def bytes_to_bint(b, u=False): # Read as big endian\n if u:\n fmtmap = {1: 'B', 2: '>H', 4: '>L', 8: '>Q'}\n else:\n fmtmap = {1: 'b', 2: '>h', 4: '>l', 8: '>q'}\n fmt = fmtmap.get(len(b))\n if fmt is None:\n raise InternalError(\"Invalid bytes length:%d\" % (len(b), ))\n...
class XSQLVAR: type_length = { SQL_TYPE_VARYING: -1, SQL_TYPE_SHORT: 4, SQL_TYPE_LONG: 4, SQL_TYPE_FLOAT: 4, SQL_TYPE_TIME: 4, SQL_TYPE_DATE: 4, SQL_TYPE_DOUBLE: 8, SQL_TYPE_TIMESTAMP: 8, SQL_TYPE_BLOB: 8, SQL_TYPE_ARRAY: 8, SQL...
bioidiap/bob.bio.spear
bob/bio/spear/utils/__init__.py
ensure_dir
python
def ensure_dir(dirname): try: # Tries to create the directory os.makedirs(dirname) except OSError: # Check that the directory exists if os.path.isdir(dirname): pass else: raise
Creates the directory dirname if it does not already exist, taking into account concurrent 'creation' on the grid. An exception is thrown if a file (rather than a directory) already exists.
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/__init__.py#L26-L37
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Laurent El Shafey <Laurent.El-Shafey@idiap.ch> # Roy Wallace <roy.wallace@idiap.ch> # Elie Khoury <Elie.Khoury@idiap.ch> # # Copyright (C) 2012-2013 Idiap Research Institute, Martigny, Switzerland # # This program is free software: you can redistribute it and/or m...
bioidiap/bob.bio.spear
bob/bio/spear/utils/__init__.py
probes_used_generate_vector
python
def probes_used_generate_vector(probe_files_full, probe_files_model): import numpy as np C_probesUsed = np.ndarray((len(probe_files_full),), 'bool') C_probesUsed.fill(False) c=0 for k in sorted(probe_files_full.keys()): if probe_files_model.has_key(k): C_probesUsed[c] = True c+=1 return C_probesUsed
Generates boolean matrices indicating which are the probes for each model
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/__init__.py#L66-L75
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Laurent El Shafey <Laurent.El-Shafey@idiap.ch> # Roy Wallace <roy.wallace@idiap.ch> # Elie Khoury <Elie.Khoury@idiap.ch> # # Copyright (C) 2012-2013 Idiap Research Institute, Martigny, Switzerland # # This program is free software: you can redistribute it and/or m...
bioidiap/bob.bio.spear
bob/bio/spear/utils/__init__.py
probes_used_extract_scores
python
def probes_used_extract_scores(full_scores, same_probes): if full_scores.shape[1] != same_probes.shape[0]: raise "Size mismatch" import numpy as np model_scores = np.ndarray((full_scores.shape[0],np.sum(same_probes)), 'float64') c=0 for i in range(0,full_scores.shape[1]): if same_probes[i]: for j in...
Extracts a matrix of scores for a model, given a probes_used row vector of boolean
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/__init__.py#L77-L88
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Laurent El Shafey <Laurent.El-Shafey@idiap.ch> # Roy Wallace <roy.wallace@idiap.ch> # Elie Khoury <Elie.Khoury@idiap.ch> # # Copyright (C) 2012-2013 Idiap Research Institute, Martigny, Switzerland # # This program is free software: you can redistribute it and/or m...
bioidiap/bob.bio.spear
bob/bio/spear/utils/__init__.py
read
python
def read(filename): # Depricated: use load() function from bob.bio.spear.database.AudioBioFile #TODO: update xbob.sox first. This will enable the use of formats like NIST sphere and other #import xbob.sox #audio = xbob.sox.reader(filename) #(rate, data) = audio.load() # We consider there is only 1 channel i...
Read audio file
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/__init__.py#L91-L105
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Laurent El Shafey <Laurent.El-Shafey@idiap.ch> # Roy Wallace <roy.wallace@idiap.ch> # Elie Khoury <Elie.Khoury@idiap.ch> # # Copyright (C) 2012-2013 Idiap Research Institute, Martigny, Switzerland # # This program is free software: you can redistribute it and/or m...
bioidiap/bob.bio.spear
bob/bio/spear/utils/__init__.py
normalize_std_array
python
def normalize_std_array(vector): # Initializes variables length = 1 n_samples = len(vector) mean = numpy.ndarray((length,), 'float64') std = numpy.ndarray((length,), 'float64') mean.fill(0) std.fill(0) # Computes mean and variance for array in vector: x = array.astype('float64') mean += x ...
Applies a unit mean and variance normalization to an arrayset
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/__init__.py#L109-L134
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Laurent El Shafey <Laurent.El-Shafey@idiap.ch> # Roy Wallace <roy.wallace@idiap.ch> # Elie Khoury <Elie.Khoury@idiap.ch> # # Copyright (C) 2012-2013 Idiap Research Institute, Martigny, Switzerland # # This program is free software: you can redistribute it and/or m...
bioidiap/bob.bio.spear
bob/bio/spear/utils/__init__.py
smoothing
python
def smoothing(labels, smoothing_window): if numpy.sum(labels)< smoothing_window: return labels segments = [] for k in range(1,len(labels)-1): if labels[k]==0 and labels[k-1]==1 and labels[k+1]==1 : labels[k]=1 for k in range(1,len(labels)-1): if labels[k]==1 and labels[k-1]==0 and labels[k+1]...
Applies a smoothing on VAD
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/__init__.py#L137-L198
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Laurent El Shafey <Laurent.El-Shafey@idiap.ch> # Roy Wallace <roy.wallace@idiap.ch> # Elie Khoury <Elie.Khoury@idiap.ch> # # Copyright (C) 2012-2013 Idiap Research Institute, Martigny, Switzerland # # This program is free software: you can redistribute it and/or m...
bioidiap/bob.bio.spear
bob/bio/spear/preprocessor/External.py
External._conversion
python
def _conversion(self, input_signal, vad_file): e = bob.ap.Energy(rate_wavsample[0], self.win_length_ms, self.win_shift_ms) energy_array = e(rate_wavsample[1]) labels = self.use_existing_vad(energy_array, vad_file) return labels
Converts an external VAD to follow the Spear convention. Energy is used in order to avoind out-of-bound array indexes.
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/preprocessor/External.py#L65-L75
null
class External(Base): """Uses external VAD and converts it to fit the format used by Spear""" def __init__( self, win_length_ms = 20., # 20 ms win_shift_ms = 10., # 10 ms **kwargs ): # call base class constructor with its set of parameters Preprocessor.__init__(...
bioidiap/bob.bio.spear
bob/bio/spear/preprocessor/Mod_4Hz.py
Mod_4Hz.mod_4hz
python
def mod_4hz(self, rate_wavsample): # Set parameters wl = self.win_length_ms ws = self.win_shift_ms nf = self.n_filters f_min = self.f_min f_max = self.f_max pre = self.pre_emphasis_coef c = bob.ap.Spectrogram(rate_wavsample[0], wl, ws, nf, f_min, f_max, pre) c.energy_filter=True ...
Computes and returns the 4Hz modulation energy features for the given input wave file
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/preprocessor/Mod_4Hz.py#L168-L194
[ "def smoothing(labels, smoothing_window):\n \"\"\" Applies a smoothing on VAD\"\"\"\n\n if numpy.sum(labels)< smoothing_window:\n return labels\n segments = []\n for k in range(1,len(labels)-1):\n if labels[k]==0 and labels[k-1]==1 and labels[k+1]==1 :\n labels[k]=1\n for k in range(1,len(labels)-1)...
class Mod_4Hz(Base): """VAD based on the modulation of the energy around 4 Hz and the energy """ def __init__( self, max_iterations = 10, # 10 iterations for the convergence_threshold = 0.0005, variance_threshold = 0.0005, win_length_ms = 20., # 20 ms win_shift_ms =...
bioidiap/bob.bio.spear
bob/bio/spear/extractor/CQCCFeatures.py
CQCCFeatures.read_matlab_files
python
def read_matlab_files(self, biofile, directory, extension): import bob.io.matlab # return the numpy array read from the data_file data_path = biofile.make_path(directory, extension) return bob.io.base.load(data_path)
Read pre-computed CQCC Matlab features here
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/extractor/CQCCFeatures.py#L45-L52
null
class CQCCFeatures(Preprocessor, Extractor): """ This class should be used as a preprocessor (converts matlab data into HDF5) and an extractor (reads saved data) Converts pre-computed with Matlab CQCC features into numpy array suitable for Bob-based experiments. CQCC features are obtained using CQCC Ma...
bioidiap/bob.bio.spear
bob/bio/spear/preprocessor/Base.py
Base.write_data
python
def write_data(self, data, data_file, compression=0): f = bob.io.base.HDF5File(data_file, 'w') f.set("rate", data[0], compression=compression) f.set("data", data[1], compression=compression) f.set("labels", data[2], compression=compression)
Writes the given *preprocessed* data to a file with the given name.
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/preprocessor/Base.py#L18-L24
null
class Base (Preprocessor): """Performs color space adaptations and data type corrections for the given image""" def __init__(self, **kwargs): Preprocessor.__init__(self, **kwargs) # Each class needs to have a constructor taking # all the parameters that are required for the preprocessing as arguments ...
bioidiap/bob.bio.spear
bob/bio/spear/script/baselines.py
command_line_arguments
python
def command_line_arguments(command_line_parameters): # create parser parser = argparse.ArgumentParser(description='Execute baseline algorithms with default parameters', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # add parameters # - the algorithm to execute parser.add_argument('-a', '--algorith...
Defines the command line parameters that are accepted.
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/script/baselines.py#L38-L78
null
#!../bin/python from __future__ import print_function import subprocess import os import sys import argparse import bob.bio.base import bob.core logger = bob.core.log.setup("bob.bio.spear") # This is the default set of algorithms that can be run using this script. all_databases = bob.bio.base.resource_keys('databas...
bioidiap/bob.bio.spear
bob/bio/spear/preprocessor/Energy_2Gauss.py
Energy_2Gauss._compute_energy
python
def _compute_energy(self, rate_wavsample): e = bob.ap.Energy(rate_wavsample[0], self.win_length_ms, self.win_shift_ms) energy_array = e(rate_wavsample[1]) labels = self._voice_activity_detection(energy_array) # discard isolated speech a number of frames defined in smoothing_window labels = utils.sm...
retreive the speech / non speech labels for the speech sample given by the tuple (rate, wave signal)
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/preprocessor/Energy_2Gauss.py#L122-L132
null
class Energy_2Gauss(Base): """Extracts the Energy""" def __init__( self, max_iterations = 10, # 10 iterations for the convergence_threshold = 0.0005, variance_threshold = 0.0005, win_length_ms = 20., # 20 ms win_shift_ms = 10., # 10 ms smoothing_wind...
bioidiap/bob.bio.spear
bob/bio/spear/utils/extraction.py
calc_mean
python
def calc_mean(c0, c1=[]): if c1 != []: return (numpy.mean(c0, 0) + numpy.mean(c1, 0)) / 2. else: return numpy.mean(c0, 0)
Calculates the mean of the data.
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/extraction.py#L32-L37
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Pavel Korshunov <Pavel.Korshunov@idiap.ch> # Tue 22 Sep 17:21:35 CEST 2015 # # Copyright (C) 2012-2015 Idiap Research Institute, Martigny, Switzerland # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General...
bioidiap/bob.bio.spear
bob/bio/spear/utils/extraction.py
calc_std
python
def calc_std(c0, c1=[]): if c1 == []: return numpy.std(c0, 0) prop = float(len(c0)) / float(len(c1)) if prop < 1: p0 = int(math.ceil(1 / prop)) p1 = 1 else: p0 = 1 p1 = int(math.ceil(prop)) return numpy.std(numpy.vstack(p0 * [c0] + p1 * [c1]), 0)
Calculates the variance of the data.
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/extraction.py#L40-L51
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Pavel Korshunov <Pavel.Korshunov@idiap.ch> # Tue 22 Sep 17:21:35 CEST 2015 # # Copyright (C) 2012-2015 Idiap Research Institute, Martigny, Switzerland # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General...
bioidiap/bob.bio.spear
bob/bio/spear/utils/extraction.py
calc_mean_std
python
def calc_mean_std(c0, c1=[], nonStdZero=False): mi = calc_mean(c0, c1) std = calc_std(c0, c1) if (nonStdZero): std[std == 0] = 1 return mi, std
Calculates both the mean of the data.
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/extraction.py#L59-L66
[ "def calc_mean(c0, c1=[]):\n \"\"\" Calculates the mean of the data.\"\"\"\n if c1 != []:\n return (numpy.mean(c0, 0) + numpy.mean(c1, 0)) / 2.\n else:\n return numpy.mean(c0, 0)\n", "def calc_std(c0, c1=[]):\n \"\"\" Calculates the variance of the data.\"\"\"\n if c1 == []:\n ...
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Pavel Korshunov <Pavel.Korshunov@idiap.ch> # Tue 22 Sep 17:21:35 CEST 2015 # # Copyright (C) 2012-2015 Idiap Research Institute, Martigny, Switzerland # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General...
bioidiap/bob.bio.spear
bob/bio/spear/utils/extraction.py
vad_filter_features
python
def vad_filter_features(vad_labels, features, filter_frames="trim_silence"): if not features.size: raise ValueError("vad_filter_features(): data sample is empty, no features extraction is possible") vad_labels = numpy.asarray(vad_labels, dtype=numpy.int8) features = numpy.asarray(features, dtype=n...
Trim the spectrogram to remove silent head/tails from the speech sample. Keep all remaining frames or either speech or non-speech only @param: filter_frames: the value is either 'silence_only' (keep the speech, remove everything else), 'speech_only' (only keep the silent parts), 'trim_silence' (trim silent ...
train
https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/extraction.py#L69-L120
null
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Pavel Korshunov <Pavel.Korshunov@idiap.ch> # Tue 22 Sep 17:21:35 CEST 2015 # # Copyright (C) 2012-2015 Idiap Research Institute, Martigny, Switzerland # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General...
datacamp/protowhat
protowhat/sct_syntax.py
F._from_func
python
def _from_func(cls, f, *args, _attr_scts=None, **kwargs): func_chain = cls(attr_scts=_attr_scts) func_chain._stack.append([f, args, kwargs]) return func_chain
Creates a function chain starting with the specified SCT (f), and its arguments.
train
https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/sct_syntax.py#L101-L105
null
class F(Chain): def __init__(self, stack=None, attr_scts=None): self._crnt_sct = None self._stack = [] if stack is None else stack self._waiting_on_call = False self._attr_scts = {} if attr_scts is None else attr_scts def __call__(self, *args, **kwargs): if self._crnt_sc...
datacamp/protowhat
protowhat/checks/check_files.py
check_file
python
def check_file( state, fname, missing_msg="Did you create a file named `{}`?", is_dir_msg="Want to check a file named `{}`, but found a directory.", parse=True, use_fs=True, use_solution=False, ): if use_fs: p = Path(fname) if not p.exists(): state.report(Fee...
Test whether file exists, and make its contents the student code. Note: this SCT fails if the file is a directory.
train
https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_files.py#L7-L50
[ "def _get_fname(state, attr, fname):\n code_dict = getattr(state, attr)\n if not isinstance(code_dict, Mapping):\n raise TypeError(\n \"Can't get {} from state.{}, which must be a \" \"dictionary or Mapping.\"\n )\n\n return code_dict.get(fname)\n" ]
from pathlib import Path from collections.abc import Mapping from protowhat.Feedback import Feedback def _get_fname(state, attr, fname): code_dict = getattr(state, attr) if not isinstance(code_dict, Mapping): raise TypeError( "Can't get {} from state.{}, which must be a " "dictionary or ...
datacamp/protowhat
protowhat/checks/check_files.py
has_dir
python
def has_dir(state, fname, incorrect_msg="Did you create a directory named `{}`?"): if not Path(fname).is_dir(): state.report(Feedback(incorrect_msg.format(fname))) return state
Test whether a directory exists.
train
https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_files.py#L63-L68
null
from pathlib import Path from collections.abc import Mapping from protowhat.Feedback import Feedback def check_file( state, fname, missing_msg="Did you create a file named `{}`?", is_dir_msg="Want to check a file named `{}`, but found a directory.", parse=True, use_fs=True, use_solution=F...
datacamp/protowhat
protowhat/utils_ast.py
dump
python
def dump(node, config): if config.is_node(node): fields = OrderedDict() for name in config.fields_iter(node): attr = config.field_val(node, name) if attr is not None: fields[name] = dump(attr, config) return {"type": config.node_type(node), "data": fie...
Convert a node tree to a simple nested dict All steps in this conversion are configurable using DumpConfig dump dictionary node: {"type": str, "data": dict}
train
https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/utils_ast.py#L30-L48
null
from ast import AST from collections import OrderedDict class DumpConfig: def __init__( self, is_node=lambda node: isinstance(node, AST), node_type=lambda node: node.__class__.__name__, fields_iter=lambda node: node._fields, field_val=lambda node, field: getattr(node, field...
datacamp/protowhat
protowhat/utils.py
legacy_signature
python
def legacy_signature(**kwargs_mapping): def signature_decorator(f): @wraps(f) def wrapper(*args, **kwargs): redirected_kwargs = { kwargs_mapping[k] if k in kwargs_mapping else k: v for k, v in kwargs.items() } return f(*args, **red...
This decorator makes it possible to call a function using old argument names when they are passed as keyword arguments. @legacy_signature(old_arg1='arg1', old_arg2='arg2') def func(arg1, arg2=1): return arg1 + arg2 func(old_arg1=1) == 2 func(old_arg1=1, old_arg2=2) == 3
train
https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/utils.py#L4-L28
null
from functools import wraps
datacamp/protowhat
protowhat/State.py
State.to_child
python
def to_child(self, append_message="", **kwargs): bad_pars = set(kwargs) - set(self._child_params) if bad_pars: raise KeyError("Invalid init params for State: %s" % ", ".join(bad_pars)) child = copy(self) for k, v in kwargs.items(): setattr(child, k, v) c...
Basic implementation of returning a child state
train
https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/State.py#L120-L137
null
class State: def __init__( self, student_code, solution_code, pre_exercise_code, student_conn, solution_conn, student_result, solution_result, reporter, force_diagnose=False, highlighting_disabled=False, solution_ast=Non...