Search is not available for this dataset
text
stringlengths
75
104k
def configuration_signature(config): """ Return a signature for a configuration (xml_generator_configuration_t) object. This can then be used as a key in the cache. This method must take into account anything about a configuration that could cause the declarations generated to be different ...
def __load(file_name): """ Load pickled cache from file and return the object. """ if os.path.exists(file_name) and not os.path.isfile(file_name): raise RuntimeError( 'Cache should be initialized with valid full file name') if not os.path.exists(file_name): ...
def update(self, source_file, configuration, declarations, included_files): """ Update a cached record with the current key and value contents. """ record = record_t( source_signature=file_signature(source_file), config_signature=configuration_signature(configuration), ...
def cached_value(self, source_file, configuration): """ Attempt to lookup the cached declarations for the given file and configuration. Returns None if declaration not found or signature check fails. """ key = record_t.create_key(source_file, configuration) if ...
def instance(self, inst): """ Called by __parse_xml_file in source_reader. """ self.__inst = inst # use inst, to reduce attribute access time if isinstance(inst, declarations.declaration_t) and \ inst.location is not None and \ inst.loca...
def find_version(file_path): """ Find the version of pygccxml. Used by setup.py and the sphinx's conf.py. Inspired by https://packaging.python.org/single_source_version/ Args: file_path (str): path to the file containing the version. """ with io.open( os.path.join( ...
def __read_byte_size(decl, attrs): """Using duck typing to set the size instead of in constructor""" size = attrs.get(XML_AN_SIZE, 0) # Make sure the size is in bytes instead of bits decl.byte_size = int(size) / 8
def __read_byte_offset(decl, attrs): """Using duck typing to set the offset instead of in constructor""" offset = attrs.get(XML_AN_OFFSET, 0) # Make sure the size is in bytes instead of bits decl.byte_offset = int(offset) / 8
def __read_byte_align(decl, attrs): """Using duck typing to set the alignment""" align = attrs.get(XML_AN_ALIGN, 0) # Make sure the size is in bytes instead of bits decl.byte_align = int(align) / 8
def bind_aliases(decls): """ This function binds between class and it's typedefs. :param decls: list of all declarations :rtype: None """ visited = set() typedefs = [ decl for decl in decls if isinstance(decl, declarations.typedef_t)] for decl in typedefs: type_ = dec...
def before_all(ctx): """ Pulls down busybox:latest before anything is tested. """ ctx.client = get_client() try: ctx.client.inspect_image(IMAGE) except NotFound: ctx.client.pull(IMAGE)
def after_scenario(ctx, scenario): """ Cleans up docker containers used as test fixtures after test completes. """ if hasattr(ctx, 'container') and hasattr(ctx, 'client'): try: ctx.client.remove_container(ctx.container, force=True) except: pass
def set_blocking(fd, blocking=True): """ Set the given file-descriptor blocking or non-blocking. Returns the original blocking status. """ old_flag = fcntl.fcntl(fd, fcntl.F_GETFL) if blocking: new_flag = old_flag & ~ os.O_NONBLOCK else: new_flag = old_flag | os.O_NONBLOCK...
def select(read_streams, write_streams, timeout=0): """ Select the streams from `read_streams` that are ready for reading, and streams from `write_streams` ready for writing. Uses `select.select()` internally but only returns two lists of ready streams. """ exception_streams = [] try: ...
def read(self, n=4096): """ Return `n` bytes of data from the Stream, or None at end of stream. """ while True: try: if hasattr(self.fd, 'recv'): return self.fd.recv(n) return os.read(self.fd.fileno(), n) except...
def write(self, data): """ Write `data` to the Stream. Not all data may be written right away. Use select to find when the stream is writeable, and call do_write() to flush the internal buffer. """ if not data: return None self.buffer += data ...
def do_write(self): """ Flushes as much pending data from the internal write buffer as possible. """ while True: try: written = 0 if hasattr(self.fd, 'send'): written = self.fd.send(self.buffer) else: ...
def read(self, n=4096): """ Read up to `n` bytes of data from the Stream, after demuxing. Less than `n` bytes of data may be returned depending on the available payload, but the number of bytes returned will never exceed `n`. Because demuxing involves scanning 8-byte headers, t...
def flush(self, n=4096): """ Flush `n` bytes of data from the reader Stream to the writer Stream. Returns the number of bytes that were actually flushed. A return value of zero is not an error. If EOF has been reached, `None` is returned. """ try: r...
def is_done(self): """ Returns True if the read stream is done (either it's returned EOF or the pump doesn't have wait_for_output set), and the write side does not have pending bytes to send. """ return (not self.wait_for_output or self.eof) and \ not (ha...
def start(client, container, interactive=True, stdout=None, stderr=None, stdin=None, logs=None): """ Present the PTY of the container inside the current process. This is just a wrapper for PseudoTerminal(client, container).start() """ operation = RunOperation(client, container, interactive=interac...
def exec_command( client, container, command, interactive=True, stdout=None, stderr=None, stdin=None): """ Run provided command via exec API in provided container. This is just a wrapper for PseudoTerminal(client, container).exec_command() """ exec_id = exec_create(client, container, comman...
def size(fd): """ Return a tuple (rows,cols) representing the size of the TTY `fd`. The provided file descriptor should be the stdout stream of the TTY. If the TTY size cannot be determined, returns None. """ if not os.isatty(fd.fileno()): return None try: dims = struct.u...
def start(self): """ Saves the current terminal attributes and makes the tty raw. This method returns None immediately. """ if os.isatty(self.fd.fileno()) and self.israw(): self.original_attributes = termios.tcgetattr(self.fd) tty.setraw(self.fd)
def stop(self): """ Restores the terminal attributes back to before setting raw mode. If the raw terminal was not started, does nothing. """ if self.original_attributes is not None: termios.tcsetattr( self.fd, termios.TCSADRAIN, ...
def start(self): """ Start trapping WINCH signals and resizing the PTY. This method saves the previous WINCH handler so it can be restored on `stop()`. """ def handle(signum, frame): if signum == signal.SIGWINCH: self.pty.resize() se...
def stop(self): """ Stop trapping WINCH signals and restore the previous WINCH handler. """ if self.original_handler is not None: signal.signal(signal.SIGWINCH, self.original_handler)
def start(self, sockets=None, **kwargs): """ Present the PTY of the container inside the current process. This will take over the current process' TTY until the container's PTY is closed. """ pty_stdin, pty_stdout, pty_stderr = sockets or self.sockets() pumps = ...
def israw(self, **kwargs): """ Returns True if the PTY should operate in raw mode. If the container was not started with tty=True, this will return False. """ if self.raw is None: info = self._container_info() self.raw = self.stdout.isatty() and info['Co...
def sockets(self): """ Returns a tuple of sockets connected to the pty (stdin,stdout,stderr). If any of the sockets are not attached in the container, `None` is returned in the tuple. """ info = self._container_info() def attach_socket(key): if info...
def resize(self, height, width, **kwargs): """ resize pty within container """ self.client.resize(self.container, height=height, width=width)
def start(self, sockets=None, **kwargs): """ start execution """ stream = sockets or self.sockets() pumps = [] if self.interactive: pumps.append(io.Pump(io.Stream(self.stdin), stream, wait_for_output=False)) pumps.append(io.Pump(stream, io.Stream(sel...
def israw(self, **kwargs): """ Returns True if the PTY should operate in raw mode. If the exec was not started with tty=True, this will return False. """ if self.raw is None: self.raw = self.stdout.isatty() and self.is_process_tty() return self.raw
def sockets(self): """ Return a single socket which is processing all I/O to exec """ socket = self.client.exec_start(self.exec_id, socket=True, tty=self.interactive) stream = io.Stream(socket) if self.is_process_tty(): return stream else: ...
def resize(self, height, width, **kwargs): """ resize pty of an execed process """ self.client.exec_resize(self.exec_id, height=height, width=width)
def _exec_info(self): """ Caching wrapper around client.exec_inspect """ if self._info is None: self._info = self.client.exec_inspect(self.exec_id) return self._info
def resize(self, size=None): """ Resize the container's PTY. If `size` is not None, it must be a tuple of (height,width), otherwise it will be determined by the size of the current TTY. """ if not self.operation.israw(): return size = size or tty.si...
def format_number(x): """Format number to string Function converts a number to string. For numbers of class :class:`float`, up to 17 digits will be used to print the entire floating point number. Any padding zeros will be removed at the end of the number. See :ref:`user-guide:int` and :ref:`user-guide...
def format_optional_vector(x): """Format a (N,) :class:`numpy.ndarray` into a NRRD optional vector string Function converts a (N,) :class:`numpy.ndarray` or :obj:`None` into a string using NRRD vector format. If the input :obj:`x` is :obj:`None`, then :obj:`vector` will be 'none' See :ref:`user-guide:...
def write(filename, data, header=None, detached_header=False, relative_data_path=True, custom_field_map=None, compression_level=9, index_order='F'): """Write :class:`numpy.ndarray` to NRRD file The :obj:`filename` parameter specifies the absolute or relative filename to write the NRRD file to. If the...
def parse_vector(x, dtype=None): """Parse NRRD vector from string into (N,) :class:`numpy.ndarray`. See :ref:`user-guide:int vector` and :ref:`user-guide:double vector` for more information on the format. Parameters ---------- x : :class:`str` String containing NRRD vector dtype : data...
def parse_matrix(x, dtype=None): """Parse NRRD matrix from string into (M,N) :class:`numpy.ndarray`. See :ref:`user-guide:int matrix` and :ref:`user-guide:double matrix` for more information on the format. Parameters ---------- x : :class:`str` String containing NRRD matrix dtype : dat...
def parse_optional_matrix(x): """Parse optional NRRD matrix from string into (M,N) :class:`numpy.ndarray` of :class:`float`. Function parses optional NRRD matrix from string into an (M,N) :class:`numpy.ndarray` of :class:`float`. This function works the same as :meth:`parse_matrix` except if a row vector i...
def parse_number_list(x, dtype=None): """Parse NRRD number list from string into (N,) :class:`numpy.ndarray`. See :ref:`user-guide:int list` and :ref:`user-guide:double list` for more information on the format. Parameters ---------- x : :class:`str` String containing NRRD number list d...
def parse_number_auto_dtype(x): """Parse number from string with automatic type detection. Parses input string and converts to a number using automatic type detection. If the number contains any fractional parts, then the number will be converted to float, otherwise the number will be converted to an int. ...
def _determine_datatype(fields): """Determine the numpy dtype of the data.""" # Convert the NRRD type string identifier into a NumPy string identifier using a map np_typestring = _TYPEMAP_NRRD2NUMPY[fields['type']] # This is only added if the datatype has more than one byte and is not using ASCII enco...
def _validate_magic_line(line): """For NRRD files, the first four characters are always "NRRD", and remaining characters give information about the file format version >>> _validate_magic_line('NRRD0005') 8 >>> _validate_magic_line('NRRD0006') Traceback (most recent call last): ... ...
def read_header(file, custom_field_map=None): """Read contents of header and parse values from :obj:`file` :obj:`file` can be a filename indicating where the NRRD header is located or a string iterator object. If a filename is specified, then the file will be opened and closed after the header is read from...
def read_data(header, fh=None, filename=None, index_order='F'): """Read data from file into :class:`numpy.ndarray` The two parameters :obj:`fh` and :obj:`filename` are optional depending on the parameters but it never hurts to specify both. The file handle (:obj:`fh`) is necessary if the header is attached...
def read(filename, custom_field_map=None, index_order='F'): """Read a NRRD file and return the header and data See :ref:`user-guide:Reading NRRD files` for more information on reading NRRD files. .. note:: Users should be aware that the `index_order` argument needs to be consistent between `nr...
def valid_beat_duration(duration): """Return True when log2(duration) is an integer.""" if duration == 0: return False elif duration == 1: return True else: r = duration while r != 1: if r % 2 == 1: return False r /= 2 retur...
def add_notes(self, note, duration=None): """Add a Note, note as string or NoteContainer to the last Bar. If the Bar is full, a new one will automatically be created. If the Bar is not full but the note can't fit in, this method will return False. True otherwise. An Instrument...
def get_notes(self): """Return an iterator that iterates through every bar in the this track.""" for bar in self.bars: for beat, duration, notes in bar: yield beat, duration, notes
def from_chords(self, chords, duration=1): """Add chords to the Track. The given chords should be a list of shorthand strings or list of list of shorthand strings, etc. Each sublist divides the value by 2. If a tuning is set, chords will be expanded so they have a proper ...
def get_tuning(self): """Return a StringTuning object. If an instrument is set and has a tuning it will be returned. Otherwise the track's one will be used. """ if self.instrument and self.instrument.tuning: return self.instrument.tuning return self.tuning
def set_tuning(self, tuning): """Set the tuning attribute on both the Track and its instrument (when available). Tuning should be a StringTuning or derivative object. """ if self.instrument: self.instrument.tuning = tuning self.tuning = tuning return ...
def transpose(self, interval, up=True): """Transpose all the notes in the track up or down the interval. Call transpose() on every Bar. """ for bar in self.bars: bar.transpose(interval, up) return self
def set_meter(self, meter): """Set the meter of this bar. Meters in mingus are represented by a single tuple. If the format of the meter is not recognised, a MeterFormatError will be raised. """ # warning should raise exception if _meter.valid_beat_duration(mete...
def place_notes(self, notes, duration): """Place the notes on the current_beat. Notes can be strings, Notes, list of strings, list of Notes or a NoteContainer. Raise a MeterFormatError if the duration is not valid. Return True if succesful, False otherwise (ie. the Bar hasn't ...
def place_notes_at(self, notes, at): """Place notes at the given index.""" for x in self.bar: if x[0] == at: x[0][2] += notes
def remove_last_entry(self): """Remove the last NoteContainer in the Bar.""" self.current_beat -= 1.0 / self.bar[-1][1] self.bar = self.bar[:-1] return self.current_beat
def is_full(self): """Return False if there is room in this Bar for another NoteContainer, True otherwise.""" if self.length == 0.0: return False if len(self.bar) == 0: return False if self.current_beat >= self.length - 0.001: return True ...
def change_note_duration(self, at, to): """Change the note duration at the given index to the given duration.""" if valid_beat_duration(to): diff = 0 for x in self.bar: if diff != 0: x[0][0] -= diff if x[0] == at: ...
def get_range(self): """Return the highest and the lowest note in a tuple.""" (min, max) = (100000, -1) for cont in self.bar: for note in cont[2]: if int(note) < int(min): min = note elif int(note) > int(max): ma...
def transpose(self, interval, up=True): """Transpose the notes in the bar up or down the interval. Call transpose() on all NoteContainers in the bar. """ for cont in self.bar: cont[2].transpose(interval, up)
def determine_chords(self, shorthand=False): """Return a list of lists [place_in_beat, possible_chords].""" chords = [] for x in self.bar: chords.append([x[0], x[2].determine(shorthand)]) return chords
def determine_progression(self, shorthand=False): """Return a list of lists [place_in_beat, possible_progressions].""" res = [] for x in self.bar: res.append([x[0], progressions.determine(x[2].get_note_names(), self.key.key, shorthand)]) return res
def get_note_names(self): """Return a list of unique note names in the Bar.""" res = [] for cont in self.bar: for x in cont[2].get_note_names(): if x not in res: res.append(x) return res
def parse_midi_file_header(self, fp): """Read the header of a MIDI file and return a tuple containing the format type, number of tracks and parsed time division information.""" # Check header try: if fp.read(4) != 'MThd': raise HeaderError('Not a valid MIDI fi...
def parse_time_division(self, bytes): """Parse the time division found in the header of a MIDI file and return a dictionary with the boolean fps set to indicate whether to use frames per second or ticks per beat. If fps is True, the values SMPTE_frames and clock_ticks will also be ...
def parse_track(self, fp): """Parse a MIDI track from its header to its events. Return a list of events and the number of bytes that were read. """ events = [] chunk_size = self.parse_track_header(fp) bytes = chunk_size while chunk_size > 0: (delta_ti...
def parse_midi_event(self, fp): """Parse a MIDI event. Return a dictionary and the number of bytes read. """ chunk_size = 0 try: ec = self.bytes_to_int(fp.read(1)) chunk_size += 1 self.bytes_read += 1 except: raise IOError(...
def parse_track_header(self, fp): """Return the size of the track chunk.""" # Check the header try: h = fp.read(4) self.bytes_read += 4 except: raise IOError("Couldn't read track header from file. Byte %d." % self.bytes_read) ...
def parse_midi_file(self, file): """Parse a MIDI file. Return the header -as a tuple containing respectively the MIDI format, the number of tracks and the time division-, the parsed track data and the number of bytes read. """ try: f = open(file, 'r') ...
def parse_varbyte_as_int(self, fp, return_bytes_read=True): """Read a variable length byte from the file and return the corresponding integer.""" result = 0 bytes_read = 0 r = 0x80 while r & 0x80: try: r = self.bytes_to_int(fp.read(1)) ...
def set_note(self, name='C', octave=4, dynamics={}): """Set the note to name in octave with dynamics. Return the objects if it succeeded, raise an NoteFormatError otherwise. """ dash_index = name.split('-') if len(dash_index) == 1: if notes.is_valid_note(name...
def change_octave(self, diff): """Change the octave of the note to the current octave + diff.""" self.octave += diff if self.octave < 0: self.octave = 0
def transpose(self, interval, up=True): """Transpose the note up or down the interval. Examples: >>> a = Note('A') >>> a.transpose('3') >>> a 'C#-5' >>> a.transpose('3', False) >>> a 'A-4' """ (old, o_octave) = (self.name, self.oct...
def from_int(self, integer): """Set the Note corresponding to the integer. 0 is a C on octave 0, 12 is a C on octave 1, etc. Example: >>> Note().from_int(12) 'C-1' """ self.name = notes.int_to_note(integer % 12) self.octave = integer // 12 return...
def from_hertz(self, hertz, standard_pitch=440): """Set the Note name and pitch, calculated from the hertz value. The standard_pitch argument can be used to set the pitch of A-4, from which the rest is calculated. """ value = ((log((float(hertz) * 1024) / standard_pitch, 2) + ...
def to_shorthand(self): """Give the traditional Helmhotz pitch notation. Examples: >>> Note('C-4').to_shorthand() "c'" >>> Note('C-3').to_shorthand() 'c' >>> Note('C-2').to_shorthand() 'C' >>> Note('C-1').to_shorthand() 'C,' """ ...
def from_shorthand(self, shorthand): """Convert from traditional Helmhotz pitch notation. Examples: >>> Note().from_shorthand("C,,") 'C-0' >>> Note().from_shorthand("C") 'C-2' >>> Note().from_shorthand("c'") 'C-4' """ name = '' oct...
def interval(key, start_note, interval): """Return the note found at the interval starting from start_note in the given key. Raise a KeyError exception if start_note is not a valid note. Example: >>> interval('C', 'D', 1) 'E' """ if not notes.is_valid_note(start_note): raise Ke...
def get_interval(note, interval, key='C'): """Return the note an interval (in half notes) away from the given note. This will produce mostly theoretical sound results, but you should use the minor and major functions to work around the corner cases. """ intervals = map(lambda x: (notes.note_to_int(...
def measure(note1, note2): """Return an integer in the range of 0-11, determining the half note steps between note1 and note2. Examples: >>> measure('C', 'D') 2 >>> measure('D', 'C') 10 """ res = notes.note_to_int(note2) - notes.note_to_int(note1) if res < 0: return 12 -...
def augment_or_diminish_until_the_interval_is_right(note1, note2, interval): """A helper function for the minor and major functions. You should probably not use this directly. """ cur = measure(note1, note2) while cur != interval: if cur > interval: note2 = notes.diminish(note2)...
def invert(interval): """Invert an interval. Example: >>> invert(['C', 'E']) ['E', 'C'] """ interval.reverse() res = list(interval) interval.reverse() return res
def determine(note1, note2, shorthand=False): """Name the interval between note1 and note2. Examples: >>> determine('C', 'E') 'major third' >>> determine('C', 'Eb') 'minor third' >>> determine('C', 'E#') 'augmented third' >>> determine('C', 'Ebb') 'diminished third' This wo...
def from_shorthand(note, interval, up=True): """Return the note on interval up or down. Examples: >>> from_shorthand('A', 'b3') 'C' >>> from_shorthand('D', '2') 'E' >>> from_shorthand('E', '2', False) 'D' """ # warning should be a valid note. if not notes.is_valid_note(note)...
def is_consonant(note1, note2, include_fourths=True): """Return True if the interval is consonant. A consonance is a harmony, chord, or interval considered stable, as opposed to a dissonance. This function tests whether the given interval is consonant. This basically means that it checks whether t...
def is_perfect_consonant(note1, note2, include_fourths=True): """Return True if the interval is a perfect consonant one. Perfect consonances are either unisons, perfect fourths or fifths, or octaves (which is the same as a unison in this model). Perfect fourths are usually included as well, but are co...
def add_track(self, track): """Add a track to the composition. Raise an UnexpectedObjectError if the argument is not a mingus.containers.Track object. """ if not hasattr(track, 'bars'): raise UnexpectedObjectError("Unexpected object '%s', " "expec...
def add_note(self, note): """Add a note to the selected tracks. Everything container.Track supports in __add__ is accepted. """ for n in self.selected_tracks: self.tracks[n] + note
def cfunc(name, result, *args): """Build and apply a ctypes prototype complete with parameter flags.""" atypes = [] aflags = [] for arg in args: atypes.append(arg[1]) aflags.append((arg[2], arg[0]) + arg[3:]) return CFUNCTYPE(result, *atypes)((name, _fl), tuple(aflags))
def fluid_synth_write_s16_stereo(synth, len): """Return generated samples in stereo 16-bit format. Return value is a Numpy array of samples. """ import numpy buf = create_string_buffer(len * 4) fluid_synth_write_s16(synth, len, buf, 0, 2, buf, 1, 2) return numpy.fromstring(buf[:], dtype=num...
def start(self, driver=None): """Start audio output driver in separate background thread. Call this function any time after creating the Synth object. If you don't call this function, use get_samples() to generate samples. Optional keyword argument: driver: which audi...
def program_select(self, chan, sfid, bank, preset): """Select a program.""" return fluid_synth_program_select(self.synth, chan, sfid, bank, preset)
def noteon(self, chan, key, vel): """Play a note.""" if key < 0 or key > 128: return False if chan < 0: return False if vel < 0 or vel > 128: return False return fluid_synth_noteon(self.synth, chan, key, vel)
def noteoff(self, chan, key): """Stop a note.""" if key < 0 or key > 128: return False if chan < 0: return False return fluid_synth_noteoff(self.synth, chan, key)
def cc(self, chan, ctrl, val): """Send control change value. The controls that are recognized are dependent on the SoundFont. Values are always 0 to 127. Typical controls include: 1: vibrato 7: volume 10: pan (left to right) 11: expression (soft...