rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self.assertEquals(([], []), expand_to_packages('ros'))
self.assertEquals(([], []), expand_to_packages('ros_comm'))
def test_expand_to_packages(self): from roslib.stacks import expand_to_packages try: # it's possible to accidentally pass in a sequence type # like a string and get weird results, so check that we # don't self.assertEquals(([], []), expand_to_packages('ros')) self.fail("expand_to_packages should only take in a list of ...
valid, invalid = expand_to_packages(['ros', 'bogus_one'])
valid, invalid = expand_to_packages(['ros_comm', 'bogus_one'])
def test_expand_to_packages(self): from roslib.stacks import expand_to_packages try: # it's possible to accidentally pass in a sequence type # like a string and get weird results, so check that we # don't self.assertEquals(([], []), expand_to_packages('ros')) self.fail("expand_to_packages should only take in a list of ...
check = ['rospy', 'roscpp', 'rospack', 'rosmake', 'roslib', 'rostest', 'std_msgs']
check = ['rospy', 'roscpp', 'rostest', 'std_msgs']
def test_expand_to_packages(self): from roslib.stacks import expand_to_packages try: # it's possible to accidentally pass in a sequence type # like a string and get weird results, so check that we # don't self.assertEquals(([], []), expand_to_packages('ros')) self.fail("expand_to_packages should only take in a list of ...
path = os.path.normpath(roslib.rospack.rospackexec(['find', 'test_roslib'])) self.assertEquals((path, 'test_roslib'), roslib.packages.get_dir_pkg(path)) self.assertEquals((path, 'test_roslib'), roslib.packages.get_dir_pkg(os.path.join(path, 'test')))
path = os.path.abspath(roslib.rospack.rospackexec(['find', 'test_roslib'])) res = roslib.packages.get_dir_pkg(path) res = (os.path.abspath(res[0]), res[1]) self.assertEquals((path, 'test_roslib'), res) res = roslib.packages.get_dir_pkg(os.path.join(path, 'test')) res = (os.path.abspath(res[0]), res[1]) self.assertEqua...
def test_get_dir_pkg(self): import roslib.packages import roslib.rospack path = os.path.normpath(roslib.rospack.rospackexec(['find', 'test_roslib']))
test_roslib_depends = ['rospack', 'roslib', 'rosclean', 'rosgraph', 'roslang', 'rospy', 'rosmaster', 'xmlrpcpp', 'rosconsole', 'roscpp', 'rosout', 'roslaunch', 'rostest', 'std_msgs', 'std_srvs', 'rosgraph_msgs', 'rosunit']
test_roslib_depends = ['rospack', 'roslib', 'rosclean', 'rosgraph', 'roslang', 'rospy', 'rosmaster', 'xmlrpcpp', 'rosconsole', 'roscpp', 'rosout', 'roslaunch', 'rostest', 'std_msgs', 'std_srvs', 'rosgraph_msgs', 'rosunit', 'roscpp_serialization', 'rostime', 'cpp_common', 'roscpp_traits']
def test_ROSPackages(self): from roslib.packages import ROSPackages rp = ROSPackages()
def test_load_param_mappings(self): from roslib.params import load_command_line_node_params self.assertEquals({}, load_command_line_node_params([])) self.assertEquals({}, load_command_line_node_params(['foo'])) self.assertEquals({}, load_command_line_node_params(['_foo'])) self.assertEquals({}, load_command_line_node_p...
def test_load_manifest(self): import roslib roslib.load_manifest('test_roslib') def test_interactive(self): import roslib import roslib.scriptutil self.failIf(roslib.is_interactive(), "interactive should be false by default") for v in [True, False]: roslib.set_interactive(v) self.assertEquals(v, roslib.is_interacti...
def test_load_param_mappings(self): from roslib.params import load_command_line_node_params self.assertEquals({}, load_command_line_node_params([])) self.assertEquals({}, load_command_line_node_params(['foo'])) self.assertEquals({}, load_command_line_node_params(['_foo'])) self.assertEquals({}, load_command_line_node_p...
if __name__ == '__main__': rosunit.unitrun(PKG, 'test_params', ParamsTest, coverage_packages=['roslib.params'])
def test_load_param_mappings(self): from roslib.params import load_command_line_node_params self.assertEquals({}, load_command_line_node_params([])) self.assertEquals({}, load_command_line_node_params(['foo'])) self.assertEquals({}, load_command_line_node_params(['_foo'])) self.assertEquals({}, load_command_line_node_p...
parser.add_option( "--split", dest="split", default=False, callback=handle_split, action="callback", help="Split the bag what maximum size or duariton is reached")
parser.add_option( "--split", dest="split", default=False, callback=handle_split, action="callback", help="Split the bag when maximum size or duariton is reached")
def record_cmd(argv): parser = optparse.OptionParser(usage="rosbag record TOPIC1 [TOPIC2 TOPIC3 ...]", description="Record a bag file with the contents of specified topics.", formatter=optparse.IndentedHelpFormatter()) parser.add_option("-a", "--all", dest="all", default=False, action="store_true",...
parser.add_option( "--duration", dest="duration", type='string',action="store", help="Record a bag of maximum duration DURATION", metavar="DURATION")
parser.add_option( "--duration", dest="duration", type='string',action="store", help="Record a bag of maximum duration DURATION in seconds, unless 'm', or 'h' is appended.", metavar="DURATION")
def record_cmd(argv): parser = optparse.OptionParser(usage="rosbag record TOPIC1 [TOPIC2 TOPIC3 ...]", description="Record a bag file with the contents of specified topics.", formatter=optparse.IndentedHelpFormatter()) parser.add_option("-a", "--all", dest="all", default=False, action="store_true",...
remap_context.add_remap(self._remap_tag(t, context, ros_config))
r = self._remap_tag(t, context, ros_config) if r is not None: remap_context.add_remap(r)
def _node_tag(self, tag, context, ros_config, default_machine, is_test=False, verbose=True): """ Process XML <node> or <test> tag @param tag: DOM node @type tag: Node @param context: namespace context @type context: L{LoaderContext} @param params: ROS parameter list @type params: [L{Param}] @param clear_params: list...
def _smart_load_blobs(self, barray, indices): """ Load an ndarray of BLOBs from a set of refs indices,
def _smart_load_blobs(self, barray, refs): """ Load an ndarray of BLOBs from a set of refs refs,
def _smart_load_blobs(self, barray, indices): """ Load an ndarray of BLOBs from a set of refs indices, taking into account not to instantiate duplicate objects for the same BLOBs """ ui, _, idx = np.unique(indices, return_index=True, return_inverse=True) idx = idx.reshape(indices.shape) assert (ui >= 0).all() # Negativ...
objects for the same BLOBs """ ui, _, idx = np.unique(indices, return_index=True, return_inverse=True) idx = idx.reshape(indices.shape) assert (ui >= 0).all()
objects for the same BLOBs. The input array of refs must be one-dimensional. The output is a 1D array of blobs, corresponding to the refs. """ assert len(refs.shape) == 1 ui, _, idx = np.unique(refs, return_index=True, return_inverse=True) assert (ui >= 0).all()
def _smart_load_blobs(self, barray, indices): """ Load an ndarray of BLOBs from a set of refs indices, taking into account not to instantiate duplicate objects for the same BLOBs """ ui, _, idx = np.unique(indices, return_index=True, return_inverse=True) idx = idx.reshape(indices.shape) assert (ui >= 0).all() # Negativ...
def fetch_blobs(self, cell_id, table, column, indices, include_cached=False):
def fetch_blobs(self, cell_id, table, column, refs, include_cached=False):
def fetch_blobs(self, cell_id, table, column, indices, include_cached=False): # short-circuit if there's nothing to be loaded if len(indices) == 0: return np.empty(indices.shape, dtype=np.object_)
if len(indices) == 0: return np.empty(indices.shape, dtype=np.object_)
if len(refs) == 0: return np.empty(refs.shape, dtype=np.object_) shape = refs.shape refs = refs.reshape(refs.size)
def fetch_blobs(self, cell_id, table, column, indices, include_cached=False): # short-circuit if there's nothing to be loaded if len(indices) == 0: return np.empty(indices.shape, dtype=np.object_)
blobs = np.append( self._smart_load_blobs(b1, indices[indices > 0]), self._smart_load_blobs(b2, -indices[indices < 0]) ) assert False, 'Test this bit'
blobs = np.empty(len(refs), dtype=object) blobs[refs >= 0] = self._smart_load_blobs(b1, refs[refs >= 0]), blobs[ refs < 0] = self._smart_load_blobs(b2, -refs[ refs < 0]),
def fetch_blobs(self, cell_id, table, column, indices, include_cached=False): # short-circuit if there's nothing to be loaded if len(indices) == 0: return np.empty(indices.shape, dtype=np.object_)
blobs = self._smart_load_blobs(b1, indices)
blobs = self._smart_load_blobs(b1, refs) blobs = blobs.reshape(shape)
def fetch_blobs(self, cell_id, table, column, indices, include_cached=False): # short-circuit if there's nothing to be loaded if len(indices) == 0: return np.empty(indices.shape, dtype=np.object_)
return self.__getitem__(idx)
return self[idx] def _fitskw_dumb(hdrs, kw): res = [] for ahdr in hdrs: hdr = pyfits.Header( txtfile=StringIO(ahdr) ) res.append(hdr[kw]) return res def fitskw(hdrs, kw): """ Intelligently extract a keyword kw from an arbitrarely shaped object ndarray of FITS headers. """ shape = hdrs.shape hdrs = hdrs.reshape(hdrs....
def __call__(self, *args): """ Apply numpy indexing on a per-row basis. A rough equivalent of: self[ arange(len(self)) , *args]
col = cat.fetch_blobs(cell_id=self.cell_id, table=table, column=name, indices=col, include_cached=include_cached)
refs = col col = cat.fetch_blobs(cell_id=self.cell_id, table=table, column=name, refs=refs, include_cached=include_cached) assert refs.shape == col.shape
def load_column(self, name, table, catname): # Load the column from table 'table' of the catalog 'catname' # Also cache the loaded tablet, for future reuse
offs += next
if next != END_MARKER: offs += next
def _get_cells_recursive(self, outcells, bounds_xy, bounds_t, i = 0, j = 0, lev = 0, dx = 2.): """ Helper for get_cells(). See documentation of get_cells() for usage """ w2 = 1 << (lev-1) x, y = (i - w2 + 0.5)*dx, (j - w2 + 0.5)*dx
nworkers = cpu_count()
nworkers = int(os.getenv('NWORKERS', cpu_count()))
def where(cond, a, b): """ A readable C-ish ternary operator. """ return a if cond else b
parallel = parallel and not self.DEBUG
parallel = parallel and self.nworkers > 1 and not self.DEBUG
def imap_unordered(self, input, mapper, mapper_args=(), return_index=False, progress_callback=None, progress_callback_stage='map'): """ Execute in parallel a callable <mapper> on all values of iterable <input>, ensuring that no more than ~nworkers results are pending in the output queue """ if progress_callback == None...
for (det_cell, idx) in idx_list.iteritems():
for (det_cell, idx_) in idx_list.iteritems(): idx = np.searchsorted(idxin, idx_) assert (idxin[idx] == idx_).all()
def _exp_id_load(kv, exp_cat): #-- This kernel is called once for each exp_cat cell referenced from det_cat # # kv = (exp_cell, detexps) with # detexps = [ (det_cell1, exps1), (det_cell, exps2), ... ] # where exps are the list of exp_ids to load, and det_cell # are the cells that should get a copy of each of those #...
for (file, nloaded, nin) in pool.imap_unordered(sweep_files, import_from_sweeps_aux, (cat,)):
for (file, nloaded, nin) in pool.imap_unordered(sweep_files, import_from_sweeps_aux, (cat,), progress_callback=pool2.progress_pass):
def import_from_sweeps(catdir, sweep_files, create=False): """ Import SDSS (stellar) catalog from a collection of SDSS sweep files. Note: Assumes underlying shared storage for all catalog cells (i.e., any worker is able to write to any cell). """ if create: # Create the new database cat = catalog.Catalog(catdir, name=...
print(' ===> Imported ' + file + ('[%d/%d, %5.2f%%] +%-6d %9d' % (at, len(sweep_files), 100 * float(at) / len(sweep_files), nloaded, ntot)))
t1 = time.time() time_pass = (t1 - t0) / 60 time_tot = time_pass / at * len(sweep_files) sfile = "..." + file[-67:] if len(file) > 70 else file print(' ===> Imported %-70s [%d/%d, %5.2f%%] +%-6d %9d (%.0f/%.0f min.)' % (sfile, at, len(sweep_files), 100 * float(at) / len(sweep_files), nloaded, ntot, time_pass, time_tot...
def import_from_sweeps(catdir, sweep_files, create=False): """ Import SDSS (stellar) catalog from a collection of SDSS sweep files. Note: Assumes underlying shared storage for all catalog cells (i.e., any worker is able to write to any cell). """ if create: # Create the new database cat = catalog.Catalog(catdir, name=...
print >> sys.stderr, "Failed to find " . numpy_include + '/numpy/arrayobject.h'
print >> sys.stderr, "Failed to find " + numpy_include + '/numpy/arrayobject.h'
def new_hook(type, value, traceback): if type != exceptions.KeyboardInterrupt: old_excepthook(type, value, traceback) else: pass
blobs = np.array(objlist, dtype=np.object_)
blobs = np.empty(len(objlist), dtype=object) blobs[:] = objlist
def _smart_load_blobs(self, barray, refs): """ Load an ndarray of BLOBs from a set of refs refs, taking into account not to instantiate duplicate objects for the same BLOBs. The input array of refs must be one-dimensional. The output is a 1D array of blobs, corresponding to the refs. """ ##return np.ones(len(refs), dt...
if len(tables) == 0: tables = [ self.primary_table ]
tables = set(tables) tables.add(self.primary_table)
def get_cells(self, foot=All, return_bounds=False, tables=[]): """ Return a list of (cell_id, footprint) tuples completely covering the requested footprint. The footprint can either be a Polyon, a specific cell_id integer, a (t0, t1) time tuple, or an array of these. """ # Handle all-sky requests, and scalars if foot ...
tables = [ 'join:' + catname for catname, _ in join_clause if catname != self.name ]
tables = set() for catname, _ in join_clause: if catname == self.name: continue v = self.joined_catalogs[catname] tables.update((v['table_from'], v['table_to']))
def map_reduce(self, query, mapper, reducer=None, foot=All, testbounds=True, include_cached=False, nworkers=None, progress_callback=None, _pass_empty=False): """ A MapReduce implementation, where rows from individual cells get mapped by the mapper, with the result reduced by the reducer. Mapper, reducer, and all *_arg...
logging.info("Here")
def _obj_det_match(cells, db, obj_tabname, det_tabname, o2d_tabname, radius, _rematching=False): """ This kernel assumes: a) det_table and obj_table have equal partitioning (equally sized/enumerated spatial cells) b) both det_table and obj_table have up-to-date neighbor caches c) temporal det_table cells within this sp...
parser.add_argument('-h', '--help', action='store_true', dest='help', default=False,
parser.add_argument('-h', '--help', action=HelpAction,
def makeParser(self): """Add a help option (:option:`-h` or :option:`--help`) to the parser created by the parent class.
options = self.parser.parse_args(cmdLineArgs[1:]) if options.help:
try: options = self.parser.parse_args(cmdLineArgs[1:]) except HelpException:
def __call__(self, cmdLineArgs, **kwArgs): """Execute the operation implemented by this object.
raise CommandLineError(_("Unknown operation '%s'") % args[0])
raise CommandLineError(_("Unknown operation '%s'") % options.operation)
def run(self, options, **kwArgs): if options.operation is None: sys.stdout.write(_("RelRDF - A system for storage, analysis and" " comparison of RDF models\n")) sys.stdout.write("https://launchpad.net/relrdf\n\n") sys.stdout.write(_("Operations:\n"))
def __init__(self, foo, bar, baz):
def __init__(self, foo='The Real Foo', bar=39, baz=False):
def __init__(self, foo, bar, baz): self.foo = foo self.bar = bar self.baz = baz
raise ConfigurationError(str(e))
raise ConfigurationError(unicode(e))
def getConfigClass(path): # This is implemented this way in order to import only the modules # that are requested. try: module = _getModule(path[0]) except InstantiationError, e: raise ConfigurationError(str(e)) return module.getConfigClass(path[1:])
option_tuple = self._parse_optional(arg_string)
option_tuple = self._parse_optional(arg_string, contiguous)
def _parse_known_args(self, arg_strings, namespace, contiguous): # replace arg strings that are file references if self.fromfile_prefix_chars is not None: arg_strings = self._read_args_from_files(arg_strings)
def _parse_optional(self, arg_string):
def _parse_optional(self, arg_string, contiguous=False):
def _parse_optional(self, arg_string): # if it's an empty string, it was meant to be a positional if not arg_string: return None
options = ', '.join([option_string for action, option_string, explicit_arg in option_tuples]) tup = arg_string, options self.error(_('ambiguous option: %s could match %s') % tup)
if contiguous: return None else: options = ', '.join([option_string for action, option_string, explicit_arg in option_tuples]) tup = arg_string, options self.error(_('ambiguous option: %s could match %s') % tup)
def _parse_optional(self, arg_string): # if it's an empty string, it was meant to be a positional if not arg_string: return None
assert dcl is not None
def _set_cache_(self, attr): # the direct algorithm is fastest and most direct if there is only one # delta. Also, the extra overhead might not be worth it for items smaller # than X - definitely the case in python, every function call costs # huge amounts of time # if len(self._dstreams) * self._bstream.size < self.k_...
__slots__ = ('frozen', ) def __init__(self): self.frozen = False
__slots__ = tuple()
def check_integrity(self, target_size=-1): """Verify the list has non-overlapping chunks only, and the total size matches target_size :param target_size: if not -1, the total size of the chain must be target_size :raise AssertionError: if the size doen't match""" if target_size > -1: assert self[-1].rbound() == target_...
remaining streams""" assert self is not bdcl if self.frozen == 1: return False
remaining streams if False is returned"""
def connect_with_next_base(self, bdcl): """Connect this chain with the next level of our base delta chunklist. The goal in this game is to mark as many of our chunks rigid, hence they cannot be changed by any of the upcoming bases anymore. Once all our chunks are marked like that, we can stop all processing :param bdcl...
sold = slen
def connect_with_next_base(self, bdcl): """Connect this chain with the next level of our base delta chunklist. The goal in this game is to mark as many of our chunks rigid, hence they cannot be changed by any of the upcoming bases anymore. Once all our chunks are marked like that, we can stop all processing :param bdcl...
assert dc.to == ccl.lbound() and dc.rbound() == cdc.rbound()
def connect_with_next_base(self, bdcl): """Connect this chain with the next level of our base delta chunklist. The goal in this game is to mark as many of our chunks rigid, hence they cannot be changed by any of the upcoming bases anymore. Once all our chunks are marked like that, we can stop all processing :param bdcl...
self.frozen = True
def connect_with_next_base(self, bdcl): """Connect this chain with the next level of our base delta chunklist. The goal in this game is to mark as many of our chunks rigid, hence they cannot be changed by any of the upcoming bases anymore. Once all our chunks are marked like that, we can stop all processing :param bdcl...
ext_modules=[Extension('gitdb._perf', ['_fun.c', '_delta_apply.c'])],
ext_modules=[Extension('gitdb._perf', ['_fun.c', '_delta_apply.c'], include_dirs=['.'])],
def get_data_files(self): """Can you feel the pain ? So, in python2.5 and python2.4 coming with maya, the line dealing with the ``plen`` has a bug which causes it to truncate too much. It is fixed in the system interpreters as they receive patches, and shows how bad it is if something doesn't have proper unittests. The...
curl_manager.call_after_perform(self.check_status_line)
try: code = self.status_code = int(line.split()[1]) except Exception, e: logging.warn("Error parsing status line (%r): %s", line, e) self.status_code = 200 else: if 300 <= code <= 399 and code != 301: self.saw_temporary_redirect = True
def header_func(self, line): line = line.strip() if line.startswith("HTTP"): curl_manager.call_after_perform(self.check_status_line) return if line == '': if 'location' in self.headers: # doing a redirect, clear out the headers self.headers = {} elif not self.headers_finished: curl_manager.call_after_perform(self.on_he...
def check_status_line(self): code = self.handle.getinfo(pycurl.RESPONSE_CODE) if 300 <= code <= 399 and code != 301: self.saw_temporary_redirect = True self.status_code = code
def on_headers_finished(self): if self.header_callback: eventloop.add_idle(self.header_callback, 'httpclient header callback', args=(self._make_callback_info(),))
self.rules = []
def __init__ (self, search_string): self.string = search_string self.parse_string() self.rules = []
self.rules = []
def parse_string(self): inquote = False i = 0 while i < len (self.string) and self.string[i] == ' ': i += 1 laststart = i self.rules = [] while (i < len(self.string)): i = laststart while (i < len(self.string)): if self.string[i] == '"': inquote = not inquote if not inquote and self.string[i] == ' ': break if self.stri...
pass
devices.clean_database(self.device)
def unlink(self): pass
os.unlink(message.item.video_path)
item = message.item device = message.item.device if os.path.exists(item.video_path): os.unlink(item.video_path) if (item.thumbnail and item.thumbnail.startswith(device.mount) and os.path.exists(item.thumbnail)): os.unlink(item.thumbnail)
def handle_delete_device_video(self, message): os.unlink(message.item.video_path) messages.ItemsChanged('device', message.item.device.id, [], [], [message.item.id]).send_to_frontend()
def handle_mediakey(self, *mmkeys):
def handle_mediakey(self, application, *mmkeys): if application != 'Miro': return
def handle_mediakey(self, *mmkeys): for key in mmkeys: if key == "Play": app.widgetapp.on_play_clicked() elif key == "Stop": app.widgetapp.on_stop_clicked() elif key == "Next": app.widgetapp.on_forward_clicked() elif key == "Previous": app.widgetapp.on_previous_clicked()
if info.file_format.split()[0] in self.device.info.audio_types:
if (info.file_format and info.file_format.split()[0] in device_info.audio_types):
def add_items(self, item_infos): for info in item_infos: if self._exists(info): continue # don't recopy stuff if info.file_type == 'audio': if info.file_format.split()[0] in self.device.info.audio_types: final_path = os.path.join(self.audio_target_folder, os.path.basename( info.video_path)) try: shutil.copy(info.video_...
self.start_conversion(self.device.info.audio_conversion,
logging.debug('unable to detect format of %r: %s' % ( info.video_path, info.file_format)) self.start_conversion(device_info.audio_conversion,
def add_items(self, item_infos): for info in item_infos: if self._exists(info): continue # don't recopy stuff if info.file_type == 'audio': if info.file_format.split()[0] in self.device.info.audio_types: final_path = os.path.join(self.audio_target_folder, os.path.basename( info.video_path)) try: shutil.copy(info.video_...
self.start_conversion(self.device.info.video_conversion,
self.start_conversion(device_info.video_conversion,
def add_items(self, item_infos): for info in item_infos: if self._exists(info): continue # don't recopy stuff if info.file_type == 'audio': if info.file_format.split()[0] in self.device.info.audio_types: final_path = os.path.join(self.audio_target_folder, os.path.basename( info.video_path)) try: shutil.copy(info.video_...
logging.info("killing conversion task %d", self.process_handle.pid) utils.kill_process(self.process_handle.pid) if os.path.exists(self.temp_output_path) and self.progress < 1.0: clean_up(self.temp_output_path, file_and_directory=True)
if hasattr(self.process_handle, "pid"): logging.info("killing conversion task %d", self.process_handle.pid) utils.kill_process(self.process_handle.pid) if os.path.exists(self.temp_output_path) and self.progress < 1.0: clean_up(self.temp_output_path, file_and_directory=True)
def interrupt(self): logging.info("killing conversion task %d", self.process_handle.pid) utils.kill_process(self.process_handle.pid) if os.path.exists(self.temp_output_path) and self.progress < 1.0: clean_up(self.temp_output_path, file_and_directory=True)
self.started_playing = STOPPED
self.play_state = STOPPED
def select_file(self, iteminfo, success_callback, error_callback): """starts playing the specified file""" filename = iteminfo.video_path
self.started_playing = STOPPED
self.play_state = STOPPED
def __init__(self): logging.info("Initializing VLC") plugin_dir = os.path.join(resources.appRoot(), 'vlc-plugins') self.exc = VLCException()
import traceback
def _open_failure(self): import traceback logging.info("_open_failure\n%s", "".join(traceback.format_stack())) self.callback_info[1]() self.callback_info = None self.media_playing = None
self.started_playing = STOPPED
self.play_state = STOPPED
def select_file(self, iteminfo, callback, errback): """starts playing the specified file""" filename = iteminfo.video_path
self.started_playing = PLAYING
self.play_state = PLAYING
def play(self): libvlc.libvlc_media_player_play(self.media_player, self.exc.ref()) self.exc.check() self.started_playing = PLAYING if self.play_from_time is not None: self.set_current_time(self.play_from_time) self.play_from_time = None
self.started_playing = PAUSED
self.play_state = PAUSED
def pause(self): libvlc.libvlc_media_player_pause(self.media_player, self.exc.ref()) self.exc.check() self.started_playing = PAUSED
self.started_playing = STOPPED
self.play_state = STOPPED
def stop(self): self.callback_info = None self.media_playing = None libvlc.libvlc_media_player_stop(self.media_player, self.exc.ref()) self.exc.check() self.started_playing = STOPPED self.subtitle_info = []
self.started_playing = STOPPED
self.play_state = STOPPED
def reset(self): self.stop() self.play_from_time = None self.started_playing = STOPPED
if not self.started_playing == PLAYING:
if not self.play_state == PLAYING:
def set_current_time(self, seconds): if not self.started_playing == PLAYING: self.play_from_time = seconds return t = int(seconds * 1000) libvlc.libvlc_media_player_set_time(self.media_player, ctypes.c_longlong(t), self.exc.ref()) try: self.exc.check() except VLCError, e: logging.warn("exception setting current time %s...
if info.description_text: text = info.description_text
text, links = self.html_stripper.strip(info.description) if text:
def get_tooltip(self, iter, column): if column == self._sort_name_to_column['name']: info = self.item_list.model[iter][0] if info.description_text: text = info.description_text if len(text) > 1000: text = text[:994] + ' [...]' return text
eventloop.add_idle('description check failed', self.handle_corrupt_torrent)
eventloop.add_idle(self.handle_corrupt_torrent, 'description check failed')
def check_description(self, data): if len(data) > MAX_TORRENT_SIZE or data[0] != 'd': # Bailout if we get too much data or it doesn't begin with # "d" (see #12301 for details) eventloop.add_idle('description check failed', self.handle_corrupt_torrent) return False else: return True
return _("Search All: %(text)s", {"text": self.query})
return unicode(_("Search All: %(text)s", {"text": self.query}))
def get_title(self): if self.query: return _("Search All: %(text)s", {"text": self.query}) return RSSFeedImplBase.get_title(self)
signals.system.connect('new-dialog', dialog_handler)
def test_indexes_same(self): # FIXME - this fails on windows because it's using a non-Windows # database if self.on_windows(): self.assert_(False, "test_indexes_same fails on windows") signals.system.connect('new-dialog', dialog_handler)
menus.MenuItem(_("Services"), "ServicesMenu"),
menus.Menu(_("Services"), "ServicesMenu", []),
def populate_menu(): short_appname = config.get(prefs.SHORT_APP_NAME) menubar = menus.get_menu() # Application menu miroMenuItems = [ extract_menu_item(menubar, "About"), menus.Separator(), extract_menu_item(menubar, "Donate"), extract_menu_item(menubar, "CheckVersion"), menus.Separator(), extract_menu_item(menubar, ...
""" % {'thumburl': resources.url("testdata/democracy-now-unicode-bug.xml")})
""" % {'thumburl': "http://example.com/thumbnail.jpg"})
def write_feed(self): self.write_file("""<?xml version="1.0"?>
self.renderer.stop()
if self.renderer: self.renderer.stop()
def _prepare_remove_renderer(self): if self.in_fullscreen: self.exit_fullscreen() self.renderer.stop()
if (self.info.state in ('downloading', 'paused') and self.info.download_info.rate > 0):
if ((self.info.state == 'downloading' and self.info.download_info.rate > 0) or self.info.state == 'paused'):
def layout(self, layout): if (self.info.state in ('downloading', 'paused') and self.info.download_info.rate > 0): return self.pack_progress_bar(layout) else: return ListViewRenderer.layout(self, layout)
return "%s - %s" % (self.__class__.__name__, self.get_title())
return "%s - %s" % (self.__class__.__name__, stringify(self.get_title()))
def __str__(self): return "%s - %s" % (self.__class__.__name__, self.get_title())
return "Feed - %s" % self.get_title()
return "Feed - %s" % stringify(self.get_title())
def __str__(self): return "Feed - %s" % self.get_title()
stringify(self.ufeed), stringify(error))
self.ufeed, stringify(error))
def _updateErrback(self, error): if not self.ufeed.id_exists(): return logging.warn("WARNING: error in Feed.update for %s -- %s", stringify(self.ufeed), stringify(error)) self.scheduleUpdateEvents(-1) self.updating = False self.ufeed.signal_change(needs_save=False)
stringify(self.ufeed), stringify(url), stringify(error))
self.ufeed, stringify(url), stringify(error))
def _updateErrback(self, error, url): if not self.ufeed.id_exists(): return logging.warn("WARNING: error in Feed.update for %s (%s) -- %s", stringify(self.ufeed), stringify(url), stringify(error)) self.scheduleUpdateEvents(-1) self.updating -= 1 self.check_update_finished() self.ufeed.signal_change(needs_save=False)
return ngettext('%(num).0f day', '%(num).0f days', t_dy, {"num": t_dy})
return ngettext('%(num).0f day', '%(num).0f days', int(t_dy), {"num": t_dy})
def time_string(secs): if secs >= (60 * 60 * 24): t_dy = secs * 1.0 / (60 * 60 * 24) return ngettext('%(num).0f day', '%(num).0f days', t_dy, {"num": t_dy}) if secs >= (60 * 60): t_hr = secs * 1.0 / (60 * 60) return ngettext('%(num).0f hr', '%(num).0f hrs', t_hr, {"num": t_hr}) if secs >= 60: t_min = secs * 1.0 / 60 re...
return ngettext('%(num).0f hr', '%(num).0f hrs', t_hr, {"num": t_hr})
return ngettext('%(num).0f hr', '%(num).0f hrs', int(t_hr), {"num": t_hr})
def time_string(secs): if secs >= (60 * 60 * 24): t_dy = secs * 1.0 / (60 * 60 * 24) return ngettext('%(num).0f day', '%(num).0f days', t_dy, {"num": t_dy}) if secs >= (60 * 60): t_hr = secs * 1.0 / (60 * 60) return ngettext('%(num).0f hr', '%(num).0f hrs', t_hr, {"num": t_hr}) if secs >= 60: t_min = secs * 1.0 / 60 re...
title = os.path.basename(filename)
title = filename_to_unicode(os.path.basename(filename))
def _filename_to_title(self, filename): title = os.path.basename(filename) title = title.rsplit('.', 1)[0] title = title.replace('_', ' ') title = title.lstrip('0123456789. -') t2 = [] for word in title.split(' '): t2.append(word.capitalize()) title = u' '.join(t2) return title
if s == "\n":
if s.isspace():
def strip(self, s): """Takes a string ``s`` and returns the stripped version. """ if not isinstance(s, basestring): return ("", [])
self.log_path = os.path.join(log_folder, "conversion-%d-to-%s-log" % (self.item_info.id, self.converter_info.identifier))
self.log_path = os.path.join(log_folder, "conversion-%d-to-%s.log" % (self.item_info.id, self.converter_info.identifier))
def _start_logging(self, executable, params): log_folder = os.path.dirname(config.get(prefs.LOG_PATHNAME)) self.log_path = os.path.join(log_folder, "conversion-%d-to-%s-log" % (self.item_info.id, self.converter_info.identifier)) self.log_file = file(self.log_path, "w") self._log_progress("STARTING CONVERSION") self._lo...
if not (item.icon_cache.isValid() or
if not item.icon_cache or not (item.icon_cache.isValid() or
def icon_changed(self): """See item.get_thumbnail to figure out which items to send signals for. """ self.signal_change(needs_save=False) for item in self.items: if not (item.icon_cache.isValid() or item.screenshot or item.isContainerItem): item.signal_change(needs_save=False)
folder_column = widgetset.TableColumn('folder', folder_cell_renderer, value=1)
folder_column = widgetset.TableColumn( _('folder'), folder_cell_renderer, value=1)
def __init__(self): self._table = widgetset.TableView(app.watched_folder_manager.model) folder_cell_renderer = widgetset.CellRenderer() folder_cell_renderer.set_text_size(widgetconst.SIZE_SMALL) folder_column = widgetset.TableColumn('folder', folder_cell_renderer, value=1) folder_column.set_min_width(400) checkbox_cell...
visible_column = widgetset.TableColumn('visible', checkbox_cell_renderer, value=2)
visible_column = widgetset.TableColumn( _('visible'), checkbox_cell_renderer, value=2)
def __init__(self): self._table = widgetset.TableView(app.watched_folder_manager.model) folder_cell_renderer = widgetset.CellRenderer() folder_cell_renderer.set_text_size(widgetconst.SIZE_SMALL) folder_column = widgetset.TableColumn('folder', folder_cell_renderer, value=1) folder_column.set_min_width(400) checkbox_cell...
def customize_ffmpeg_parameters(default_parameters):
def customize_ffmpeg_parameters(params):
def customize_ffmpeg_parameters(default_parameters): """Takes a list of parameters and modifies it based on platform-specific issues. Returns the newly modified list of parameters. :param default_parameters: list of parameters to modify :returns: list of modified parameters that will get passed to ffmpeg """ return ...
:param default_parameters: list of parameters to modify
:param params: list of parameters to modify
def customize_ffmpeg_parameters(default_parameters): """Takes a list of parameters and modifies it based on platform-specific issues. Returns the newly modified list of parameters. :param default_parameters: list of parameters to modify :returns: list of modified parameters that will get passed to ffmpeg """ return ...
return default_parameters
if "-acodec" in params: ind = params.index("-acodec") if params[ind+1] == "aac": params[ind+1] = "libfaac" return params
def customize_ffmpeg_parameters(default_parameters): """Takes a list of parameters and modifies it based on platform-specific issues. Returns the newly modified list of parameters. :param default_parameters: list of parameters to modify :returns: list of modified parameters that will get passed to ffmpeg """ return ...
rotater = logging.handlers.RotatingFileHandler(config.get(prefs.LOG_PATHNAME), mode="w", maxBytes=100000, backupCount=5)
try: rotater = logging.handlers.RotatingFileHandler( config.get(prefs.LOG_PATHNAME), mode="w", maxBytes=100000, backupCount=5) except IOError: os.remove(config.get(prefs.LOG_PATHNAME)) rotater = logging.handlers.RotatingFileHandler( config.get(prefs.LOG_PATHNAME), mode="w", maxBytes=100000, backupCount=5)
def setup_logging(inDownloader=False): if inDownloader: if os.environ.get('MIRO_FRONTEND') == 'cli': level = logging.WARN else: level = logging.INFO logging.basicConfig(level=level, format='%(asctime)s %(levelname)-8s %(message)s', stream=sys.stdout) else: if config.get(prefs.APP_VERSION).endswith("git"): level = loggi...
remote_item = item.remote
remote_item = False if item and item.remote: remote_item = True
def on_hotspot_clicked(self, view, hotspot, iter): if hotspot == 'eject-device': # Don't track this tab anymore for music. info = view.model[iter][0] info.mount = False # We must stop the playback if we are playing from the same # share that we are ejecting from. name, host, port = info.id item = app.playback_manager.g...
self.unset_widget()
def reset(self): self.stop() self.unset_widget() self.play_from_time = None self.play_state = STOPPED
_start_pubdate = _start_published
def _start_published(self, attrsD): self.push('published', 1)
_end_pubdate = _end_published
def _end_published(self): value = self.pop('published') self._save('published_parsed', _parse_date(value))
play_pause_menu_item = main_menu.itemAtIndex_(5).submenu().itemAtIndex_(0)
play_pause_menu_item = main_menu.itemAtIndex_(6).submenu().itemAtIndex_(0)
def on_menu_change(menu_manager): main_menu = NSApp().mainMenu() play_pause_menu_item = main_menu.itemAtIndex_(5).submenu().itemAtIndex_(0) play_pause = _menu_structure.get("PlayPauseItem").state_labels[app.menu_manager.play_pause_state] play_pause_menu_item.setTitleWithMnemonic_(play_pause.replace("_", "&"))
subtitles_menu_root = main_menu.itemAtIndex_(5).submenu().itemAtIndex_(15)
subtitles_menu_root = main_menu.itemAtIndex_(6).submenu().itemAtIndex_(15)
def on_playback_change(playback_manager): main_menu = NSApp().mainMenu() subtitles_menu_root = main_menu.itemAtIndex_(5).submenu().itemAtIndex_(15) subtitles_menu = NSMenu.alloc().init() subtitles_menu.setAutoenablesItems_(NO) subtitles_tracks = None if app.playback_manager.is_playing and not app.playback_manager.is_pl...
('size', 'assz'), ('duration', 'astm')]
('size', 'assz')]
def daap_item_fixup(item_id, entry): daapitem = [] # no need for id -> miid because that's the indexing key. # Easy ones - can do a direct translation mapping = [('name', 'minm'), ('enclosure_format', 'asfm'), ('size', 'assz'), ('duration', 'astm')] for p, q in mapping: if isinstance(entry[p], unicode): attribute = (q...
daapitem.append(('astm', entry['duration'] * 1000))
def daap_item_fixup(item_id, entry): daapitem = [] # no need for id -> miid because that's the indexing key. # Easy ones - can do a direct translation mapping = [('name', 'minm'), ('enclosure_format', 'asfm'), ('size', 'assz'), ('duration', 'astm')] for p, q in mapping: if isinstance(entry[p], unicode): attribute = (q...
popup_menu.popup(None, None, None, button, activate_time, status_icon)
popup_menu.popup( None, None, None, button, activate_time, status_icon) def on_menu_enter(self, widget, event): self.using_menu = None def on_menu_leave(self, widget, event): self.using_menu = event.time + 1 def check_using_menu(self, data=None): if ((self.popup_menu is not None and self.using_menu is not None an...
def on_popup_menu(self, status_icon, button, activate_time): popup_menu = gtk.Menu() for label, callback in self.make_popup_menu_items(): if not label and not callback: item = gtk.SeparatorMenuItem() else: item = gtk.ImageMenuItem(label) item.connect('activate', callback) popup_menu.append(item)
self.releaseDateObj = datetime.fromtimestamp( fileutil.getmtime(filename))
def set_release_date(self): try: self.releaseDateObj = datetime.fromtimestamp( fileutil.getmtime(self.filename)) except OSError: self.releaseDateObj = datetime.now()
def set_filename(self, filename): Item.set_filename(self, filename) self.releaseDateObj = datetime.fromtimestamp( fileutil.getmtime(filename))
self.assertEqual(u"<span>\u25cb\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d</span>", i.get_description())
self.assertEqual(u"\u25cb\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d", i.get_description())
def test_valid_utf_feed(self): handle, self.filename = mkstemp(".xml") handle = open(self.filename, "wb") handle.write(u'<?xml version="1.0"?>\n<rss version="2.0">\n <channel>\n <title>Chinese Numbers \u25cb\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d</title>\n <description>Chinese Numbers \u25cb\u4e00...
data_files.append(('', iglob(os.path.join(VCREDIST_PATH, '*'))))
data_files.append(('', iglob(os.path.join(VCREDIST71_PATH, '*')))) data_files.append(('', iglob(os.path.join(VCREDIST90_PATH, '*'))))
def fill_template(templatepath, outpath, **vars): s = open(templatepath, 'rt').read() s = string.Template(s).safe_substitute(**vars) f = open(outpath, "wt") f.write(s) f.close()