INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Apply a two - pole all - pass filter. An all - pass filter changes the audio’s frequency to phase relationship without changing its frequency to amplitude relationship. The filter is described in detail in at http:// musicdsp. org/ files/ Audio - EQ - Cookbook. txt | def allpass(self, frequency, width_q=2.0):
'''Apply a two-pole all-pass filter. An all-pass filter changes the
audio’s frequency to phase relationship without changing its frequency
to amplitude relationship. The filter is described in detail in at
http://musicdsp.org/files/Audio-EQ-Cook... |
Apply a two - pole Butterworth band - pass filter with the given central frequency and ( 3dB - point ) band - width. The filter rolls off at 6dB per octave ( 20dB per decade ) and is described in detail in http:// musicdsp. org/ files/ Audio - EQ - Cookbook. txt | def bandpass(self, frequency, width_q=2.0, constant_skirt=False):
'''Apply a two-pole Butterworth band-pass filter with the given central
frequency, and (3dB-point) band-width. The filter rolls off at 6dB per
octave (20dB per decade) and is described in detail in
http://musicdsp.org/file... |
Changes pitch by specified amounts at specified times. The pitch - bending algorithm utilises the Discrete Fourier Transform ( DFT ) at a particular frame rate and over - sampling rate. | def bend(self, n_bends, start_times, end_times, cents, frame_rate=25,
oversample_rate=16):
'''Changes pitch by specified amounts at specified times.
The pitch-bending algorithm utilises the Discrete Fourier Transform
(DFT) at a particular frame rate and over-sampling rate.
... |
Apply a biquad IIR filter with the given coefficients. | def biquad(self, b, a):
'''Apply a biquad IIR filter with the given coefficients.
Parameters
----------
b : list of floats
Numerator coefficients. Must be length 3
a : list of floats
Denominator coefficients. Must be length 3
See Also
---... |
Change the number of channels in the audio signal. If decreasing the number of channels it mixes channels together if increasing the number of channels it duplicates. | def channels(self, n_channels):
'''Change the number of channels in the audio signal. If decreasing the
number of channels it mixes channels together, if increasing the number
of channels it duplicates.
Note: This overrides arguments used in the convert effect!
Parameters
... |
Add a chorus effect to the audio. This can makeasingle vocal sound like a chorus but can also be applied to instrumentation. | def chorus(self, gain_in=0.5, gain_out=0.9, n_voices=3, delays=None,
decays=None, speeds=None, depths=None, shapes=None):
'''Add a chorus effect to the audio. This can makeasingle vocal sound
like a chorus, but can also be applied to instrumentation.
Chorus resembles an echo effe... |
Compand ( compress or expand ) the dynamic range of the audio. | def compand(self, attack_time=0.3, decay_time=0.8, soft_knee_db=6.0,
tf_points=[(-70, -70), (-60, -20), (0, 0)],
):
'''Compand (compress or expand) the dynamic range of the audio.
Parameters
----------
attack_time : float, default=0.3
The time... |
Comparable with compression this effect modifies an audio signal to make it sound louder. | def contrast(self, amount=75):
'''Comparable with compression, this effect modifies an audio signal to
make it sound louder.
Parameters
----------
amount : float
Amount of enhancement between 0 and 100.
See Also
--------
compand, mcompand
... |
Converts output audio to the specified format. | def convert(self, samplerate=None, n_channels=None, bitdepth=None):
'''Converts output audio to the specified format.
Parameters
----------
samplerate : float, default=None
Desired samplerate. If None, defaults to the same as input.
n_channels : int, default=None
... |
Apply a DC shift to the audio. | def dcshift(self, shift=0.0):
'''Apply a DC shift to the audio.
Parameters
----------
shift : float
Amount to shift audio between -2 and 2. (Audio is between -1 and 1)
See Also
--------
highpass
'''
if not is_number(shift) or shift <... |
Apply Compact Disc ( IEC 60908 ) de - emphasis ( a treble attenuation shelving filter ). Pre - emphasis was applied in the mastering of some CDs issued in the early 1980s. These included many classical music albums as well as now sought - after issues of albums by The Beatles Pink Floyd and others. Pre - emphasis shoul... | def deemph(self):
'''Apply Compact Disc (IEC 60908) de-emphasis (a treble attenuation
shelving filter). Pre-emphasis was applied in the mastering of some
CDs issued in the early 1980s. These included many classical music
albums, as well as now sought-after issues of albums by The Beatles... |
Delay one or more audio channels such that they start at the given positions. | def delay(self, positions):
'''Delay one or more audio channels such that they start at the given
positions.
Parameters
----------
positions: list of floats
List of times (in seconds) to delay each audio channel.
If fewer positions are given than the numb... |
Downsample the signal by an integer factor. Only the first out of each factor samples is retained the others are discarded. | def downsample(self, factor=2):
'''Downsample the signal by an integer factor. Only the first out of
each factor samples is retained, the others are discarded.
No decimation filter is applied. If the input is not a properly
bandlimited baseband signal, aliasing will occur. This may be d... |
Makes audio easier to listen to on headphones. Adds ‘cues’ to 44. 1kHz stereo audio so that when listened to on headphones the stereo image is moved from inside your head ( standard for headphones ) to outside and in front of the listener ( standard for speakers ). | def earwax(self):
'''Makes audio easier to listen to on headphones. Adds ‘cues’ to 44.1kHz
stereo audio so that when listened to on headphones the stereo image is
moved from inside your head (standard for headphones) to outside and in
front of the listener (standard for speakers).
... |
Add echoing to the audio. | def echo(self, gain_in=0.8, gain_out=0.9, n_echos=1, delays=[60],
decays=[0.4]):
'''Add echoing to the audio.
Echoes are reflected sound and can occur naturally amongst mountains
(and sometimes large buildings) when talking or shouting; digital echo
effects emulate this beh... |
Apply a two - pole peaking equalisation ( EQ ) filter to boost or reduce around a given frequency. This effect can be applied multiple times to produce complex EQ curves. | def equalizer(self, frequency, width_q, gain_db):
'''Apply a two-pole peaking equalisation (EQ) filter to boost or
reduce around a given frequency.
This effect can be applied multiple times to produce complex EQ curves.
Parameters
----------
frequency : float
... |
Add a fade in and/ or fade out to an audio file. Default fade shape is 1/ 4 sine wave. | def fade(self, fade_in_len=0.0, fade_out_len=0.0, fade_shape='q'):
'''Add a fade in and/or fade out to an audio file.
Default fade shape is 1/4 sine wave.
Parameters
----------
fade_in_len : float, default=0.0
Length of fade-in (seconds). If fade_in_len = 0,
... |
Use SoX’s FFT convolution engine with given FIR filter coefficients. | def fir(self, coefficients):
'''Use SoX’s FFT convolution engine with given FIR filter coefficients.
Parameters
----------
coefficients : list
fir filter coefficients
'''
if not isinstance(coefficients, list):
raise ValueError("coefficients must ... |
Apply a flanging effect to the audio. | def flanger(self, delay=0, depth=2, regen=0, width=71, speed=0.5,
shape='sine', phase=25, interp='linear'):
'''Apply a flanging effect to the audio.
Parameters
----------
delay : float, default=0
Base delay (in miliseconds) between 0 and 30.
depth : f... |
Apply amplification or attenuation to the audio signal. | def gain(self, gain_db=0.0, normalize=True, limiter=False, balance=None):
'''Apply amplification or attenuation to the audio signal.
Parameters
----------
gain_db : float, default=0.0
Gain adjustment in decibels (dB).
normalize : bool, default=True
If Tru... |
Apply a high - pass filter with 3dB point frequency. The filter can be either single - pole or double - pole. The filters roll off at 6dB per pole per octave ( 20dB per pole per decade ). | def highpass(self, frequency, width_q=0.707, n_poles=2):
'''Apply a high-pass filter with 3dB point frequency. The filter can be
either single-pole or double-pole. The filters roll off at 6dB per pole
per octave (20dB per pole per decade).
Parameters
----------
frequency... |
Apply an odd - tap Hilbert transform filter phase - shifting the signal by 90 degrees. This is used in many matrix coding schemes and for analytic signal generation. The process is often written as a multiplication by i ( or j ) the imaginary unit. An odd - tap Hilbert transform filter has a bandpass characteristic att... | def hilbert(self, num_taps=None):
'''Apply an odd-tap Hilbert transform filter, phase-shifting the signal
by 90 degrees. This is used in many matrix coding schemes and for
analytic signal generation. The process is often written as a
multiplication by i (or j), the imaginary unit. An odd... |
Loudness control. Similar to the gain effect but provides equalisation for the human auditory system. | def loudness(self, gain_db=-10.0, reference_level=65.0):
'''Loudness control. Similar to the gain effect, but provides
equalisation for the human auditory system.
The gain is adjusted by gain_db and the signal is equalised according
to ISO 226 w.r.t. reference_level.
Parameters... |
The multi - band compander is similar to the single - band compander but the audio is first divided into bands using Linkwitz - Riley cross - over filters and a separately specifiable compander run on each band. | def mcompand(self, n_bands=2, crossover_frequencies=[1600],
attack_time=[0.005, 0.000625], decay_time=[0.1, 0.0125],
soft_knee_db=[6.0, None],
tf_points=[[(-47, -40), (-34, -34), (-17, -33), (0, 0)],
[(-47, -40), (-34, -34), (-15, -33), (0, 0)]],
... |
Calculate a profile of the audio for use in noise reduction. Running this command does not effect the Transformer effects chain. When this function is called the calculated noise profile file is saved to the profile_path. | def noiseprof(self, input_filepath, profile_path):
'''Calculate a profile of the audio for use in noise reduction.
Running this command does not effect the Transformer effects
chain. When this function is called, the calculated noise profile
file is saved to the `profile_path`.
... |
Reduce noise in the audio signal by profiling and filtering. This effect is moderately effective at removing consistent background noise such as hiss or hum. | def noisered(self, profile_path, amount=0.5):
'''Reduce noise in the audio signal by profiling and filtering.
This effect is moderately effective at removing consistent
background noise such as hiss or hum.
Parameters
----------
profile_path : str
Path to a n... |
Normalize an audio file to a particular db level. This behaves identically to the gain effect with normalize = True. | def norm(self, db_level=-3.0):
'''Normalize an audio file to a particular db level.
This behaves identically to the gain effect with normalize=True.
Parameters
----------
db_level : float, default=-3.0
Output volume (db)
See Also
--------
gai... |
Out Of Phase Stereo effect. Mixes stereo to twin - mono where each mono channel contains the difference between the left and right stereo channels. This is sometimes known as the karaoke effect as it often has the effect of removing most or all of the vocals from a recording. | def oops(self):
'''Out Of Phase Stereo effect. Mixes stereo to twin-mono where each
mono channel contains the difference between the left and right stereo
channels. This is sometimes known as the 'karaoke' effect as it often
has the effect of removing most or all of the vocals from a rec... |
Apply non - linear distortion. | def overdrive(self, gain_db=20.0, colour=20.0):
'''Apply non-linear distortion.
Parameters
----------
gain_db : float, default=20
Controls the amount of distortion (dB).
colour : float, default=20
Controls the amount of even harmonic content in the output... |
Add silence to the beginning or end of a file. Calling this with the default arguments has no effect. | def pad(self, start_duration=0.0, end_duration=0.0):
'''Add silence to the beginning or end of a file.
Calling this with the default arguments has no effect.
Parameters
----------
start_duration : float
Number of seconds of silence to add to beginning.
end_du... |
Apply a phasing effect to the audio. | def phaser(self, gain_in=0.8, gain_out=0.74, delay=3, decay=0.4, speed=0.5,
modulation_shape='sinusoidal'):
'''Apply a phasing effect to the audio.
Parameters
----------
gain_in : float, default=0.8
Input volume between 0 and 1
gain_out: float, default... |
Pitch shift the audio without changing the tempo. | def pitch(self, n_semitones, quick=False):
'''Pitch shift the audio without changing the tempo.
This effect uses the WSOLA algorithm. The audio is chopped up into
segments which are then shifted in the time domain and overlapped
(cross-faded) at points where their waveforms are most sim... |
Change the audio sampling rate ( i. e. resample the audio ) to any given samplerate. Better the resampling quality = slower runtime. | def rate(self, samplerate, quality='h'):
'''Change the audio sampling rate (i.e. resample the audio) to any
given `samplerate`. Better the resampling quality = slower runtime.
Parameters
----------
samplerate : float
Desired sample rate.
quality : str
... |
Remix the channels of an audio file. | def remix(self, remix_dictionary=None, num_output_channels=None):
'''Remix the channels of an audio file.
Note: volume options are not yet implemented
Parameters
----------
remix_dictionary : dict or None
Dictionary mapping output channel to list of input channel(s)... |
Repeat the entire audio count times. | def repeat(self, count=1):
'''Repeat the entire audio count times.
Parameters
----------
count : int, default=1
The number of times to repeat the audio.
'''
if not isinstance(count, int) or count < 1:
raise ValueError("count must be a postive int... |
Add reverberation to the audio using the ‘freeverb’ algorithm. A reverberation effect is sometimes desirable for concert halls that are too small or contain so many people that the hall’s natural reverberance is diminished. Applying a small amount of stereo reverb to a ( dry ) mono signal will usually make it sound mor... | def reverb(self, reverberance=50, high_freq_damping=50, room_scale=100,
stereo_depth=100, pre_delay=0, wet_gain=0, wet_only=False):
'''Add reverberation to the audio using the ‘freeverb’ algorithm.
A reverberation effect is sometimes desirable for concert halls that
are too small ... |
Reverse the audio completely | def reverse(self):
'''Reverse the audio completely
'''
effect_args = ['reverse']
self.effects.extend(effect_args)
self.effects_log.append('reverse')
return self |
Removes silent regions from an audio file. | def silence(self, location=0, silence_threshold=0.1,
min_silence_duration=0.1, buffer_around_silence=False):
'''Removes silent regions from an audio file.
Parameters
----------
location : int, default=0
Where to remove silence. One of:
* 0 to rem... |
Apply a sinc kaiser - windowed low - pass high - pass band - pass or band - reject filter to the signal. | def sinc(self, filter_type='high', cutoff_freq=3000,
stop_band_attenuation=120, transition_bw=None,
phase_response=None):
'''Apply a sinc kaiser-windowed low-pass, high-pass, band-pass, or
band-reject filter to the signal.
Parameters
----------
filter_t... |
Adjust the audio speed ( pitch and tempo together ). | def speed(self, factor):
'''Adjust the audio speed (pitch and tempo together).
Technically, the speed effect only changes the sample rate information,
leaving the samples themselves untouched. The rate effect is invoked
automatically to resample to the output sample rate, using its defa... |
Display time and frequency domain statistical information about the audio. Audio is passed unmodified through the SoX processing chain. | def stat(self, input_filepath, scale=None, rms=False):
'''Display time and frequency domain statistical information about the
audio. Audio is passed unmodified through the SoX processing chain.
Unlike other Transformer methods, this does not modify the transformer
effects chain. Instead... |
Calculates the power spectrum ( 4096 point DFT ). This method internally invokes the stat command with the - freq option. | def power_spectrum(self, input_filepath):
'''Calculates the power spectrum (4096 point DFT). This method
internally invokes the stat command with the -freq option.
Note: The file is downmixed to mono prior to computation.
Parameters
----------
input_filepath : str
... |
Display time domain statistical information about the audio channels. Audio is passed unmodified through the SoX processing chain. Statistics are calculated and displayed for each audio channel | def stats(self, input_filepath):
'''Display time domain statistical information about the audio
channels. Audio is passed unmodified through the SoX processing chain.
Statistics are calculated and displayed for each audio channel
Unlike other Transformer methods, this does not modify th... |
Change the audio duration ( but not its pitch ). ** Unless factor is close to 1 use the tempo effect instead. ** | def stretch(self, factor, window=20):
'''Change the audio duration (but not its pitch).
**Unless factor is close to 1, use the tempo effect instead.**
This effect is broadly equivalent to the tempo effect with search set
to zero, so in general, its results are comparatively poor; it is
... |
Swap stereo channels. If the input is not stereo pairs of channels are swapped and a possible odd last channel passed through. | def swap(self):
'''Swap stereo channels. If the input is not stereo, pairs of channels
are swapped, and a possible odd last channel passed through.
E.g., for seven channels, the output order will be 2, 1, 4, 3, 6, 5, 7.
See Also
----------
remix
'''
eff... |
Time stretch audio without changing pitch. | def tempo(self, factor, audio_type=None, quick=False):
'''Time stretch audio without changing pitch.
This effect uses the WSOLA algorithm. The audio is chopped up into
segments which are then shifted in the time domain and overlapped
(cross-faded) at points where their waveforms are mos... |
Boost or cut the treble ( lower ) frequencies of the audio using a two - pole shelving filter with a response similar to that of a standard hi - fi’s tone - controls. This is also known as shelving equalisation. | def treble(self, gain_db, frequency=3000.0, slope=0.5):
'''Boost or cut the treble (lower) frequencies of the audio using a
two-pole shelving filter with a response similar to that of a standard
hi-fi’s tone-controls. This is also known as shelving equalisation.
The filters are describe... |
Apply a tremolo ( low frequency amplitude modulation ) effect to the audio. The tremolo frequency in Hz is giv en by speed and the depth as a percentage by depth ( default 40 ). | def tremolo(self, speed=6.0, depth=40.0):
'''Apply a tremolo (low frequency amplitude modulation) effect to the
audio. The tremolo frequency in Hz is giv en by speed, and the depth
as a percentage by depth (default 40).
Parameters
----------
speed : float
Tre... |
Excerpt a clip from an audio file given the start timestamp and end timestamp of the clip within the file expressed in seconds. If the end timestamp is set to None or left unspecified it defaults to the duration of the audio file. | def trim(self, start_time, end_time=None):
'''Excerpt a clip from an audio file, given the start timestamp and end timestamp of the clip within the file, expressed in seconds. If the end timestamp is set to `None` or left unspecified, it defaults to the duration of the audio file.
Parameters
--... |
Voice Activity Detector. Attempts to trim silence and quiet background sounds from the ends of recordings of speech. The algorithm currently uses a simple cepstral power measurement to detect voice so may be fooled by other things especially music. | def vad(self, location=1, normalize=True, activity_threshold=7.0,
min_activity_duration=0.25, initial_search_buffer=1.0,
max_gap=0.25, initial_pad=0.0):
'''Voice Activity Detector. Attempts to trim silence and quiet
background sounds from the ends of recordings of speech. The alg... |
Apply an amplification or an attenuation to the audio signal. | def vol(self, gain, gain_type='amplitude', limiter_gain=None):
'''Apply an amplification or an attenuation to the audio signal.
Parameters
----------
gain : float
Interpreted according to the given `gain_type`.
If `gain_type' = 'amplitude', `gain' is a positive a... |
Lets a user join a room on a specific Namespace. | def join(self, room):
"""Lets a user join a room on a specific Namespace."""
self.socket.rooms.add(self._get_room_name(room)) |
Lets a user leave a room on a specific Namespace. | def leave(self, room):
"""Lets a user leave a room on a specific Namespace."""
self.socket.rooms.remove(self._get_room_name(room)) |
Main SocketIO management function call from within your Framework of choice s view. | def socketio_manage(environ, namespaces, request=None, error_handler=None,
json_loads=None, json_dumps=None):
"""Main SocketIO management function, call from within your Framework of
choice's view.
The ``environ`` variable is the WSGI ``environ``. It is used to extract
Socket objec... |
This is the default error handler you can override this when calling: func: socketio. socketio_manage. | def default_error_handler(socket, error_name, error_message, endpoint,
msg_id, quiet):
"""This is the default error handler, you can override this when
calling :func:`socketio.socketio_manage`.
It basically sends an event through the socket with the 'error' name.
See document... |
Keep a reference of the callback on this socket. | def _save_ack_callback(self, msgid, callback):
"""Keep a reference of the callback on this socket."""
if msgid in self.ack_callbacks:
return False
self.ack_callbacks[msgid] = callback |
Fetch the callback for a given msgid if it exists otherwise return None | def _pop_ack_callback(self, msgid):
"""Fetch the callback for a given msgid, if it exists, otherwise,
return None"""
if msgid not in self.ack_callbacks:
return None
return self.ack_callbacks.pop(msgid) |
This function must/ will be called when a socket is to be completely shut down closed by connection timeout connection error or explicit disconnection from the client. | def kill(self, detach=False):
"""This function must/will be called when a socket is to be completely
shut down, closed by connection timeout, connection error or explicit
disconnection from the client.
It will call all of the Namespace's
:meth:`~socketio.namespace.BaseNamespace.... |
Detach this socket from the server. This should be done in conjunction with kill () once all the jobs are dead detach the socket for garbage collection. | def detach(self):
"""Detach this socket from the server. This should be done in
conjunction with kill(), once all the jobs are dead, detach the
socket for garbage collection."""
log.debug("Removing %s from server sockets" % self)
if self.sessid in self.server.sockets:
... |
Get multiple messages in case we re going through the various XHR - polling methods on which we can pack more than one message if the rate is high and encode the payload for the HTTP channel. | def get_multiple_client_msgs(self, **kwargs):
"""Get multiple messages, in case we're going through the various
XHR-polling methods, on which we can pack more than one message if the
rate is high, and encode the payload for the HTTP channel."""
client_queue = self.client_queue
ms... |
Send an error to the user using the custom or default ErrorHandler configured on the [ TODO: Revise this ] Socket/ Handler object. | def error(self, error_name, error_message, endpoint=None, msg_id=None,
quiet=False):
"""Send an error to the user, using the custom or default
ErrorHandler configured on the [TODO: Revise this] Socket/Handler
object.
:param error_name: is a simple string, for easy associat... |
Calling this method will call the: meth: ~socketio. namespace. BaseNamespace. disconnect method on all the active Namespaces that were open killing all their jobs and sending disconnect packets for each of them. | def disconnect(self, silent=False):
"""Calling this method will call the
:meth:`~socketio.namespace.BaseNamespace.disconnect` method on
all the active Namespaces that were open, killing all their
jobs and sending 'disconnect' packets for each of them.
Normally, the Global namesp... |
This removes a Namespace object from the socket. | def remove_namespace(self, namespace):
"""This removes a Namespace object from the socket.
This is usually called by
:meth:`~socketio.namespace.BaseNamespace.disconnect`.
"""
if namespace in self.active_ns:
del self.active_ns[namespace]
if len(self.active_n... |
Low - level interface to queue a packet on the wire ( encoded as wire protocol | def send_packet(self, pkt):
"""Low-level interface to queue a packet on the wire (encoded as wire
protocol"""
self.put_client_msg(packet.encode(pkt, self.json_dumps)) |
Spawn a new Greenlet attached to this Socket instance. | def spawn(self, fn, *args, **kwargs):
"""Spawn a new Greenlet, attached to this Socket instance.
It will be monitored by the "watcher" method
"""
log.debug("Spawning sub-Socket Greenlet: %s" % fn.__name__)
job = gevent.spawn(fn, *args, **kwargs)
self.jobs.append(job)
... |
This is the loop that takes messages from the queue for the server to consume decodes them and dispatches them. | def _receiver_loop(self):
"""This is the loop that takes messages from the queue for the server
to consume, decodes them and dispatches them.
It is the main loop for a socket. We join on this process before
returning control to the web framework.
This process is not tracked by... |
Spawns the reader loop. This is called internall by socketio_manage (). | def _spawn_receiver_loop(self):
"""Spawns the reader loop. This is called internall by
socketio_manage().
"""
job = gevent.spawn(self._receiver_loop)
self.jobs.append(job)
return job |
Watch out if we ve been disconnected in that case kill all the jobs. | def _watcher(self):
"""Watch out if we've been disconnected, in that case, kill
all the jobs.
"""
while True:
gevent.sleep(1.0)
if not self.connected:
for ns_name, ns in list(six.iteritems(self.active_ns)):
ns.recv_disconnect()... |
Start the heartbeat Greenlet to check connection health. | def _heartbeat(self):
"""Start the heartbeat Greenlet to check connection health."""
interval = self.config['heartbeat_interval']
while self.connected:
gevent.sleep(interval)
# TODO: this process could use a timeout object like the disconnect
# timeout t... |
This functions returns a list of jobs | def _spawn_heartbeat(self):
"""This functions returns a list of jobs"""
self.spawn(self._heartbeat)
self.spawn(self._heartbeat_timeout) |
Encode an attribute dict into a byte string. | def encode(data, json_dumps=default_json_dumps):
"""
Encode an attribute dict into a byte string.
"""
payload = ''
msg = str(MSG_TYPES[data['type']])
if msg in ['0', '1']:
# '1::' [path] [query]
msg += '::' + data['endpoint']
if 'qs' in data and data['qs'] != '':
... |
Decode a rawstr packet arriving from the socket into a dict. | def decode(rawstr, json_loads=default_json_loads):
"""
Decode a rawstr packet arriving from the socket into a dict.
"""
decoded_msg = {}
try:
# Handle decoding in Python<3.
rawstr = rawstr.decode('utf-8')
except AttributeError:
pass
split_data = rawstr.split(":", 3)
... |
ACL system: make the method_name accessible to the current socket | def add_acl_method(self, method_name):
"""ACL system: make the method_name accessible to the current socket"""
if isinstance(self.allowed_methods, set):
self.allowed_methods.add(method_name)
else:
self.allowed_methods = set([method_name]) |
ACL system: ensure the user will not have access to that method. | def del_acl_method(self, method_name):
"""ACL system: ensure the user will not have access to that method."""
if self.allowed_methods is None:
raise ValueError(
"Trying to delete an ACL method, but none were"
+ " defined yet! Or: No ACL restrictions yet, why w... |
If you override this NONE of the functions in this class will be called. It is responsible for dispatching to: meth: process_event ( which in turn calls on_ * () and recv_ * () methods ). | def process_packet(self, packet):
"""If you override this, NONE of the functions in this class
will be called. It is responsible for dispatching to
:meth:`process_event` (which in turn calls ``on_*()`` and
``recv_*()`` methods).
If the packet arrived here, it is because it belo... |
This function dispatches event messages to the correct functions. You should override this method only if you are not satisfied with the automatic dispatching to on_ - prefixed methods. You could then implement your own dispatch. See the source code for inspiration. | def process_event(self, packet):
"""This function dispatches ``event`` messages to the correct
functions. You should override this method only if you are not
satisfied with the automatic dispatching to
``on_``-prefixed methods. You could then implement your own dispatch.
See the... |
You should always use this function to call the methods as it checks if the user is allowed according to the ACLs. | def call_method_with_acl(self, method_name, packet, *args):
"""You should always use this function to call the methods,
as it checks if the user is allowed according to the ACLs.
If you override :meth:`process_packet` or
:meth:`process_event`, you should definitely want to use this
... |
This function is used to implement the two behaviors on dispatched on_ * () and recv_ * () method calls. | def call_method(self, method_name, packet, *args):
"""This function is used to implement the two behaviors on dispatched
``on_*()`` and ``recv_*()`` method calls.
Those are the two behaviors:
* If there is only one parameter on the dispatched method and
it is named ``packet``... |
Use this to use the configured error_handler yield an error message to your application. | def error(self, error_name, error_message, msg_id=None, quiet=False):
"""Use this to use the configured ``error_handler`` yield an
error message to your application.
:param error_name: is a short string, to associate messages to recovery
methods
:param error_m... |
Use send to send a simple string message. | def send(self, message, json=False, callback=None):
"""Use send to send a simple string message.
If ``json`` is True, the message will be encoded as a JSON object
on the wire, and decoded on the other side.
This is mostly for backwards compatibility. ``emit()`` is more fun.
:... |
Use this to send a structured event with a name and arguments to the client. | def emit(self, event, *args, **kwargs):
"""Use this to send a structured event, with a name and arguments, to
the client.
By default, it uses this namespace's endpoint. You can send messages on
other endpoints with something like:
``self.socket['/other_endpoint'].emit()``.
... |
Spawn a new process attached to this Namespace. | def spawn(self, fn, *args, **kwargs):
"""Spawn a new process, attached to this Namespace.
It will be monitored by the "watcher" process in the Socket. If the
socket disconnects, all these greenlets are going to be killed, after
calling BaseNamespace.disconnect()
This method use... |
Send a disconnect packet so that the user knows it has been disconnected ( booted actually ). This will trigger an onDisconnect () call on the client side. | def disconnect(self, silent=False):
"""Send a 'disconnect' packet, so that the user knows it has been
disconnected (booted actually). This will trigger an onDisconnect()
call on the client side.
Over here, we will kill all ``spawn``ed processes and remove the
namespace from the... |
Return an existing or new client Socket. | def get_socket(self, sessid=''):
"""Return an existing or new client Socket."""
socket = self.sockets.get(sessid)
if sessid and not socket:
return None # you ask for a session that doesn't exist!
if socket is None:
socket = Socket(self, self.config)
... |
Handles post from the Add room form on the homepage and redirects to the new room. | def create():
"""
Handles post from the "Add room" form on the homepage, and
redirects to the new room.
"""
name = request.form.get("name")
if name:
room, created = get_or_create(ChatRoom, name=name)
return redirect(url_for('room', slug=room.slug))
return redirect(url_for('ro... |
Auto - discover INSTALLED_APPS sockets. py modules and fail silently when not present. NOTE: socketio_autodiscover was inspired/ copied from django. contrib. admin autodiscover | def autodiscover():
"""
Auto-discover INSTALLED_APPS sockets.py modules and fail silently when
not present. NOTE: socketio_autodiscover was inspired/copied from
django.contrib.admin autodiscover
"""
global LOADING_SOCKETIO
if LOADING_SOCKETIO:
return
LOADING_SOCKETIO = True
... |
This function deals with * ONE INCOMING REQUEST * from the web. | def handle_one_response(self):
"""This function deals with *ONE INCOMING REQUEST* from the web.
It will wire and exchange message to the queues for long-polling
methods, otherwise, will stay alive for websockets.
"""
path = self.environ.get('PATH_INFO')
# Kick non-sock... |
This will fetch the messages from the Socket s queue and if there are many messes pack multiple messages in one payload and return | def get_messages_payload(self, socket, timeout=None):
"""This will fetch the messages from the Socket's queue, and if
there are many messes, pack multiple messages in one payload and return
"""
try:
msgs = socket.get_multiple_client_msgs(timeout=timeout)
data = se... |
Encode list of messages. Expects messages to be unicode. | def encode_payload(self, messages):
"""Encode list of messages. Expects messages to be unicode.
``messages`` - List of raw messages to encode, if necessary
"""
if not messages or messages[0] is None:
return ''
if len(messages) == 1:
return messages[0].e... |
This function can extract multiple messages from one HTTP payload. Some times the XHR/ JSONP/.. transports can pack more than one message on a single packet. They are encoding following the WebSocket semantics which need to be reproduced here to unwrap the messages. | def decode_payload(self, payload):
"""This function can extract multiple messages from one HTTP payload.
Some times, the XHR/JSONP/.. transports can pack more than one message
on a single packet. They are encoding following the WebSocket
semantics, which need to be reproduced here to un... |
Just quote out stuff before sending it out | def write(self, data):
"""Just quote out stuff before sending it out"""
args = parse_qs(self.handler.environ.get("QUERY_STRING"))
if "i" in args:
i = args["i"]
else:
i = "0"
# TODO: don't we need to quote this data in here ?
super(JSONPolling, self... |
This is sent to all in the room ( in this particular Namespace ) | def emit_to_room(self, room, event, *args):
"""This is sent to all in the room (in this particular Namespace)"""
pkt = dict(type="event",
name=event,
args=args,
endpoint=self.ns_name)
room_name = self._get_room_name(room)
for sessi... |
This is sent to all in the sockets in this particular Namespace including itself. | def broadcast_event(self, event, *args):
"""
This is sent to all in the sockets in this particular Namespace,
including itself.
"""
pkt = dict(type="event",
name=event,
args=args,
endpoint=self.ns_name)
for sessid,... |
Add a parent to this role and add role itself to the parent s children set. you should override this function if neccessary. | def add_parent(self, parent):
"""Add a parent to this role,
and add role itself to the parent's children set.
you should override this function if neccessary.
Example::
logged_user = RoleMixin('logged_user')
student = RoleMixin('student')
student.add... |
Add allowing rules. | def allow(self, role, method, resource, with_children=True):
"""Add allowing rules.
:param role: Role of this rule.
:param method: Method to allow in rule, include GET, POST, PUT etc.
:param resource: Resource also view function.
:param with_children: Allow role's children in ru... |
Add denying rules. | def deny(self, role, method, resource, with_children=False):
"""Add denying rules.
:param role: Role of this rule.
:param method: Method to deny in rule, include GET, POST, PUT etc.
:param resource: Resource also view function.
:param with_children: Deny role's children in rule ... |
Exempt a view function from being checked permission | def exempt(self, resource):
"""Exempt a view function from being checked permission
:param resource: The view function exempt from checking.
"""
if resource not in self._exempt:
self._exempt.append(resource) |
Check whether role is allowed to access resource | def is_allowed(self, role, method, resource):
"""Check whether role is allowed to access resource
:param role: Role to be checked.
:param method: Method to be checked.
:param resource: View function to be checked.
"""
return (role, method, resource) in self._allowed |
Check wherther role is denied to access resource | def is_denied(self, role, method, resource):
"""Check wherther role is denied to access resource
:param role: Role to be checked.
:param method: Method to be checked.
:param resource: View function to be checked.
"""
return (role, method, resource) in self._denied |
Initialize application in Flask - RBAC. Adds ( RBAC app ) to flask extensions. Adds hook to authenticate permission before request. | def init_app(self, app):
"""Initialize application in Flask-RBAC.
Adds (RBAC, app) to flask extensions.
Adds hook to authenticate permission before request.
:param app: Flask object
"""
app.config.setdefault('RBAC_USE_WHITE', False)
self.use_white = app.config['... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.