def _run_befater_plugin(type: (RUN_AFTER, RUN_BEFORE), fname: str, plugin_name: str, activate_phrase: str, speech_input: str) -> None: """ runs a plugin :param type: (RUN_AFTER, RUN_BEFORE) type of the plugin syntax: <plugin type> example: RUN_AFTER :param fname: str file path of the plugin file syntax: <filename> example: "/home/pi/test.py" :param plugin_name: str name of the plugin syntax: <plugin name> example: "TestPlugin" :param activate_phrase: str activate phrase, which calls the skill class to which the plugin belongs syntax: <activate phrase> example: "Start test plugin" :param speech_input: str speech input, which calls the skill class to which the plugin belongs syntax: <speech input> example: "Start test plugin" :return: None :since: 0.1.0 """ from sys import path path.insert(1, _aion_data_path + "/" + type.lower()) exec("__import__('" + fname + "')." + plugin_name + "(" + activate_phrase + ", " + speech_input + ").main()")
def generate(): db.init_db() @db.transactionnal def generate_urls(): urls = [] for fct in web.static_pages_fcts: urls = urls + fct() return urls urls = generate_urls() print urls print "Generation of the static content" for url in urls: with web.app.test_request_context(url, method="GET"): print "Generating", url x = web.app.dispatch_request() path = [] parent = url while parent != '/': tmp = os.path.split(parent) path.insert(0, tmp[1]) parent = tmp[0] path = os.path.join(*path) path = os.path.join(config.dist_folder, path) if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) with open(path, "w") as f: if type(x) == str or type(x) == unicode: f.write(x) else: f.write(x.data)
def use(self): from r2.lib.template_helpers import static path = [g.static_path, self.name] if g.uncompressedJS: path.insert(1, "js") return script_tag.format(src=static(os.path.join(*path)))
def __init__(self, setting, widgetname = None, root = None, maxlevels = -1): """Take the setting given, and propagate it to other widgets, according to the parameters here. If widgetname is given then only propagate it to widgets with the name given. widgets are located from the widget given (root if not set) Up to maxlevels levels of widgets are changed (<0 means infinite) """ self.val = setting.val self.widgetname = widgetname if root: self.rootpath = root.path else: self.rootpath = None self.maxlevels = maxlevels # work out path of setting relative to widget path = [] s = setting while not s.isWidget(): path.insert(0, s.name) s = s.parent self.setpath = path[1:] self.widgettype = s.typename
def __set_plugin_search_path(self): from sys import path if not (self.__editor.core_plugin_folder in path): path.insert(0, self.__editor.core_plugin_folder) if not (self.__editor.home_plugin_folder in path): path.insert(0, self.__editor.home_plugin_folder) return
def xmlPath(element): '''Return a simple, unambiguous path for an XML element''' path = [] while True: parent = element.getparent() name = element.tag if name.startswith(POM_NS_PREFIX): name = name[len(POM_NS_PREFIX):] if parent is None: path.insert(0, '/%s' % name) break expr = etree.ETXPath(element.tag) children = expr(parent) #print 'xmlPath',element.tag,children index = children.index(element) if len(children) == 1: item = '/%s' % name else: item = '/%s[%d]' % (name, index) path.insert(0, item) element = parent return ''.join(path)
def dijkstra(graph, start, end): Q = set() dist = {} prev = {} for pos in graph.keys(): dist[pos] = float('inf') prev[pos] = None Q.add(pos) dist[start] = 0.0 while len(Q) > 0: u = get_min_dist(Q, dist) Q.remove(u) for neighbour in graph[u]: alt = dist[u] + 1.0 if alt < dist[neighbour]: dist[neighbour] = alt prev[neighbour] = u path = [] u = end if u in prev or u == start: while u: path.insert(0, u) u = prev.get(u) return path, dist
def chain_wires(wires): assert wires.num_vertices > 0 visited = np.zeros(wires.num_vertices, dtype=bool) path = [0] visited[0] = True while not np.all(visited): front = path[0] front_neighbors = wires.get_vertex_neighbors(int(front)) for v in front_neighbors: if visited[v]: continue path.insert(0, v) visited[v] = True break end = path[-1] end_neighbors = wires.get_vertex_neighbors(int(end)) for v in end_neighbors: if visited[v]: continue visited[v] = True path.append(v) break first_neighbors = wires.get_vertex_neighbors(int(path[0])).squeeze() if len(path) > 2 and path[-1] in first_neighbors: # Close the loop. path.append(path[0]) path = wires.vertices[path] return path
def _serve_file(self, mime_type, *path): path = list(path) path.insert(0, 'other') path.insert(0, os.path.dirname(__file__)) with open(os.path.join(*path), 'rb') as f: return '200 OK', f.read(), mime_type
def get_css_path(node): path = [get_element(node)] for parent in node.parents: if parent.name == 'body': break path.insert(0, get_element(parent)) return ' > '.join(path)
def url(self, absolute=False, mangle_name=False): from r2.lib.template_helpers import static path = [g.static_path, self.name] if g.uncompressedJS: path.insert(1, "js") return static(os.path.join(*path), absolute, mangle_name)
def BuildPath(self, p, ax, plt, start_time): """ Build path out of the searching result Args: p: the end point ax: something associated with the drawing plt:plotlib object start_time: the start time of this execution Return: A list of points, forming a path from start to end """ path = [] while True: path.insert(0, p) # Insert first if self.IsStartPoint(p): break else: p = p.parent for p in path: # rec = Rectangle((p.x, p.y), 1, 1, color='g') # ax.add_patch(rec) if DEBUG_LEVEL >= PLOT: plt.draw() self.SaveImage(plt) end_time = time.time() if DEBUG_LEVEL == DEBUG: print('===== Algorithm finish in', int(end_time - start_time), ' seconds') return path
def _get_classes_from_json(self): for filename in ("labels.txt", "classes.json"): path = os.path.join(self.samples_dir, filename) if not os.path.exists(path): raise VergeMLError("{} is missing".format(filename)) with open(path) as f: if filename == "labels.txt": items = filter( None, map(methodcaller("strip"), f.read().splitlines())) labels = Labels(items) else: self.classes = json.load(f) files = {} # prefix the sample with input_dir for k, v in self.classes['files'].items(): # on windows and linux, separator is / path = k.split("/") path.insert(0, self.samples_dir) fname = os.path.join(*path) files[fname] = v self.classes['files'] = files self.meta['labels'] = labels
def __init__(self, setting, widgetname = None, root = None, maxlevels = -1): """Take the setting given, and propagate it to other widgets, according to the parameters here. If widgetname is given then only propagate it to widgets with the name given. widgets are located from the widget given (root if not set) Up to maxlevels levels of widgets are changed (<0 means infinite) """ self.val = setting.val self.widgetname = widgetname if root: self.rootpath = root.path else: self.rootpath = None self.maxlevels = maxlevels # work out path of setting relative to widget path = [] s = setting while not s.iswidget: path.insert(0, s.name) s = s.parent self.setpath = path[1:] self.widgettype = s.typename
def path(self): path = [self.name] parent = self.parent while parent: path.insert(0, parent.name) parent = parent.parent return '/'.join(path)
def get_import_path(type, relative_to=None): relativity = [] if relative_to is None: path = [] tmp = type while tmp.parent is not None: path.insert(0, tmp) tmp = tmp.parent else: tmp2 = relative_to while tmp2.parent is not None: relativity.append('.') path = [] tmp = type while tmp.parent is not None: path.insert(0, tmp) if tmp.parent is tmp2.parent: break tmp = tmp.parent else: tmp2 = tmp2.parent continue break return ''.join(relativity) + '.'.join(part.identifier.lower_case for part in path)
def vengine_gen_find_module(self, module_name, path, so_suffixes): global _ma_triplet if _ma_triplet is None: try: import subprocess as sp p = sp.Popen(["gcc", "-print-multiarch"], stdout=sp.PIPE) _ma_triplet = str(p.communicate()[0].decode().strip()) except: import warnings warnings.warn( 'failed to detect multiarch paths, please install gcc') for so_suffix in so_suffixes + [ '.%s-%s.so' % (imp.get_tag(), _ma_triplet) ]: basename = module_name + so_suffix if path is None: path = sys.path # import from non root package would try __pycache__ which is # cleaned by pypy installation path.insert(0, "/usr/lib/pypy/dist-packages/zmq/backend/cffi") for dirname in path: filename = os.path.join(dirname, basename) if os.path.isfile(filename): return filename
def _process_path(self, path): """ Take a path and set the space and parent """ path = normalize_path(self.path).split("/") if not self.has_space(): spacePath = path.pop(0) try: self.space = Space.objects.get(path=spacePath) except ObjectDoesNotExist: # Space might not be included in path, add it back to path path.insert(0, spacePath) parentPath = path[0:-1] if len(path) >= 1: self.path = path[-1] else: self.path = "" parentPath = filter(len, parentPath) # remove empty path sections if parentPath: self.parent = Document.objects.get_by_path( parentPath, space=self.space, create=True)
def _backport_which(cmd, mode=os.F_OK | os.X_OK, path=None): """Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path. """ # Check that a given file can be accessed with the correct mode. # Additionally check that `file` is not a directory, as on Windows # directories pass the os.access check. def _access_check(fn, mode): return (os.path.exists(fn) and os.access(fn, mode) and not os.path.isdir(fn)) # If we're given a path with a directory part, look it up directly rather # than referring to PATH directories. This includes checking relative to the # current directory, e.g. ./script if os.path.dirname(cmd): if _access_check(cmd, mode): return cmd return None if path is None: path = os.environ.get("PATH", os.defpath) if not path: return None path = path.split(os.pathsep) if sys.platform == "win32": # The current directory takes precedence on Windows. if not os.curdir in path: path.insert(0, os.curdir) # PATHEXT is necessary to check on Windows. pathext = os.environ.get("PATHEXT", "").split(os.pathsep) # See if the given file matches any of the expected path extensions. # This will allow us to short circuit when given "python.exe". # If it does match, only test that one, otherwise we have to try # others. if any(cmd.lower().endswith(ext.lower()) for ext in pathext): files = [cmd] else: files = [cmd + ext for ext in pathext] else: # On other platforms you don't have things like PATHEXT to tell you # what file suffixes are executable, so just pass on cmd as-is. files = [cmd] seen = set() for dir in path: normdir = os.path.normcase(dir) if not normdir in seen: seen.add(normdir) for thefile in files: name = os.path.join(dir, thefile) if _access_check(name, mode): return name return None
def directory(request, project_slug): project = Project.objects.get(slug=project_slug) directory = request.GET.get("directory") items = [] for name in os.listdir(os.path.join(project.root, directory)): path = os.path.normpath(os.path.join(directory, name)) if os.path.isdir(os.path.join(project.root, path)): items.append({"type": "directory", "value": path, "text": name}) for name in os.listdir(os.path.join(project.root, directory)): path = os.path.normpath(os.path.join(directory, name)) if not os.path.isdir(os.path.join(project.root, path)): items.append({"type": "file", "value": path, "text": name}) path = [] while not os.path.samefile(project.root, os.path.join(project.root, directory)): path.insert(0, { "value": directory, "text": os.path.basename(directory) }) directory = os.path.dirname(directory) path.insert(0, {"value": directory, "text": "Home"}) result = { "path": path, "items": items, } return JsonResponse(result)
def chain_wires(wires): assert (wires.num_vertices > 0) visited = np.zeros(wires.num_vertices, dtype=bool) path = [0] visited[0] = True while not np.all(visited): front = path[0] front_neighbors = wires.get_vertex_neighbors(int(front)) for v in front_neighbors: if visited[v]: continue path.insert(0, v) visited[v] = True break end = path[-1] end_neighbors = wires.get_vertex_neighbors(int(end)) for v in end_neighbors: if visited[v]: continue visited[v] = True path.append(v) break first_neighbors = wires.get_vertex_neighbors(int(path[0])).squeeze() if len(path) > 2 and path[-1] in first_neighbors: # Close the loop. path.append(path[0]) path = wires.vertices[path] return path
def astar_all(start, goal_func, neighbors_func, heuristic_func): explored = set() frontier = [start] came_from = {} g = {start: 0} h = {start: heuristic_func(start)} f = {start: h[start]} while frontier: current = frontier.pop(0) explored.add(current) if goal_func(current): path = [] node = current while node: path.insert(0, node) node = came_from.get(node) yield path, g[current] continue for neighbor, distance in neighbors_func(current): if neighbor in explored: continue distance += g[current] if neighbor not in frontier: frontier.append(neighbor) g[neighbor] = distance h[neighbor] = heuristic_func(neighbor) f[neighbor] = distance + h[neighbor] came_from[neighbor] = current elif distance < g[neighbor]: g[neighbor] = distance f[neighbor] = distance + h[neighbor] came_from[neighbor] = current frontier.sort(key=lambda node: (f[node], h[node]))
def get_path(tag): path = [] cur = tag while cur != None: path.insert(0, cur.name) cur = cur.parent return "root" + ".".join(path)
def getcwd(self): path = [] curr = self.cwd_item while curr: self.read_item_data(curr, get_name=True) path.insert(0, curr['name'] if curr['name'] else '') curr = self.get_item_by_pos(curr['parent_pos']) if curr['parent_pos'] > 0 else None return os.path.join(*path)
def retracePath(self, n): node = self.getNodeAt(n.index) path.insert(0,node) if n.parent == None: return path retracePath(self, n.parent) return path
def _get_default_search_path(): path = sys.path # The first element of sys.path is the current directory of this # script, not the user's current directory. So, insert the empty # string (standing in for the current directory) at the start of # the list. path.insert(0, '') return path
def get_fqn(type): path = [] tmp = type while tmp.parent is not None: path.insert(0, tmp) tmp = tmp.parent return '.'.join(name_to_string(part) for part in path)
def get_L_groundtruth(self): from sys import path import os dir = os.path.abspath(self.datadir) path.insert(0, dir) # make the configuration available, temporarilly from config import cfg as cfg_gt path.pop(0) # restore the path again return cfg_gt["world"]["L"]
def which(cmd, mode=os.F_OK | os.X_OK, env=None): """Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `env` defaults to os.environ, if not supplied. """ # Check that a given file can be accessed with the correct mode. # Additionally check that `file` is not a directory, as on Windows # directories pass the os.access check. def _access_check(fn, mode): return (os.path.exists(fn) and os.access(fn, mode) and not os.path.isdir(fn)) # Short circuit. If we're given a full path which matches the mode # and it exists, we're done here. if _access_check(cmd, mode): return cmd if env is None: env = os.environ path = env.get("PATH", os.defpath).split(os.pathsep) if sys.platform == "win32": # The current directory takes precedence on Windows. if not os.curdir in path: path.insert(0, os.curdir) # PATHEXT is necessary to check on Windows. default_pathext = \ '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC' pathext = env.get("PATHEXT", default_pathext).split(os.pathsep) # See if the given file matches any of the expected path extensions. # This will allow us to short circuit when given "python.exe". matches = [cmd for ext in pathext if cmd.lower().endswith(ext.lower())] # If it does match, only test that one, otherwise we have to try # others. files = [cmd] if matches else [cmd + ext.lower() for ext in pathext] else: # On other platforms you don't have things like PATHEXT to tell you # what file suffixes are executable, so just pass on cmd as-is. files = [cmd] seen = set() for dir in path: dir = os.path.normcase(dir) if not dir in seen: seen.add(dir) for thefile in files: name = os.path.join(dir, thefile) # On windows the system paths might have %systemroot% name = os.path.expandvars(name) if _access_check(name, mode): return name return None
def _path_from(parent, child): if os.path.split(parent)[1] == '': parent = os.path.split(parent)[0] path = [] while parent != child: child, dirname = os.path.split(child) path.insert(0, dirname) assert os.path.split(child)[0] != child return path
def list_paths(self): '''''' self.connect() device = self.dmd.Devices.findDevice(self.options.device) if device is None: DEFAULTLOG.error("Device '{}' not found.".format( self.options.device)) return from Acquisition import aq_chain from Products.ZenRelations.RelationshipBase import RelationshipBase all_paths = set() included_paths = set() class_summary = collections.defaultdict(set) for component in device.getDeviceComponents(): for facet in component.get_facets(recurse_all=True): path = [] for obj in aq_chain(facet): if obj == component: break if isinstance(obj, RelationshipBase): path.insert(0, obj.id) all_paths.add(component.meta_type + ":" + "/".join(path) + ":" + facet.meta_type) for facet in component.get_facets(): path = [] for obj in aq_chain(facet): if obj == component: break if isinstance(obj, RelationshipBase): path.insert(0, obj.id) all_paths.add(component.meta_type + ":" + "/".join(path) + ":" + facet.meta_type) included_paths.add(component.meta_type + ":" + "/".join(path) + ":" + facet.meta_type) class_summary[component.meta_type].add(facet.meta_type) print "Paths\n-----\n" for path in sorted(all_paths): if path in included_paths: if "/" not in path: # normally all direct relationships are included print "DIRECT " + path else: # sometimes extra paths are pulled in due to extra_paths # configuration. print "EXTRA " + path else: print "EXCLUDE " + path print "\nClass Summary\n-------------\n" for source_class in sorted(class_summary.keys()): print "{} is reachable from {}".format( source_class, ", ".join(sorted(class_summary[source_class])))
def get_full_path(o): path = [] intermediate = o while intermediate != udm.null: path.insert(0, (intermediate.name, intermediate.type.name)) intermediate = intermediate.parent return '/'.join( ["{0} ({1})".format(name, typeName) for (name, typeName) in path])
def main( projects ): for project in projects: path = project.split( '/' ) print path if project.startswith('app'): path.insert(3 , 'trunk' ) elif project.startswith('qing'): path.insert(2 , 'trunk') svn_url = base_url + '/'.join( path ) abpath = cratePath( home +'/' + project ) checkout( svn_url , abpath )
def which(cmd, mode=os.F_OK | os.X_OK, env=None): """Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `env` defaults to os.environ, if not supplied. """ # Check that a given file can be accessed with the correct mode. # Additionally check that `file` is not a directory, as on Windows # directories pass the os.access check. def _access_check(fn, mode): return (os.path.exists(fn) and os.access(fn, mode) and not os.path.isdir(fn)) # Short circuit. If we're given a full path which matches the mode # and it exists, we're done here. if _access_check(cmd, mode): return cmd if env is None: env = os.environ path = env.get("PATH", os.defpath).split(os.pathsep) if sys.platform == "win32": # The current directory takes precedence on Windows. if not os.curdir in path: path.insert(0, os.curdir) # PATHEXT is necessary to check on Windows. pathext = env.get("PATHEXT", "").split(os.pathsep) # See if the given file matches any of the expected path extensions. # This will allow us to short circuit when given "python.exe". matches = [cmd for ext in pathext if cmd.lower().endswith(ext.lower())] # If it does match, only test that one, otherwise we have to try # others. files = [cmd] if matches else [cmd + ext.lower() for ext in pathext] else: # On other platforms you don't have things like PATHEXT to tell you # what file suffixes are executable, so just pass on cmd as-is. files = [cmd] seen = set() for dir in path: dir = os.path.normcase(dir) if not dir in seen: seen.add(dir) for thefile in files: name = os.path.join(dir, thefile) if _access_check(name, mode): return name return None
def printMazePathCost(maze, node, visited): path = [] while node.getParent() != None: x, y = node.getCargo() path.insert(0, (x, y)) maze[x][y] = "0" node = node.parent printMaze(maze) print("\nSOLUTION: ", path) print("\nSOLUTION COST: ", len(path)) print("\n# OF EXPANDED NODES:{} \n".format(len(visited)))
def get_dijkstra_path(src, dst, graph_dic): if src not in graph_dic or dst not in graph_dic: print(src, 'or', dst, 'not found in graph_dic') return path = [] prev = dst while prev is not -1: path.insert(0, prev) prev = graph_dic.get(prev)['prev'] #print(path) return path
def list_paths(self): '''''' self.connect() device = self.dmd.Devices.findDevice(self.options.device) if device is None: DEFAULTLOG.error("Device '{}' not found.".format(self.options.device)) return from Acquisition import aq_chain from Products.ZenRelations.RelationshipBase import RelationshipBase all_paths = set() included_paths = set() class_summary = collections.defaultdict(set) for component in device.getDeviceComponents(): for facet in component.get_facets(recurse_all=True): path = [] for obj in aq_chain(facet): if obj == component: break if isinstance(obj, RelationshipBase): path.insert(0, obj.id) all_paths.add(component.meta_type + ":" + "/".join(path) + ":" + facet.meta_type) for facet in component.get_facets(): path = [] for obj in aq_chain(facet): if obj == component: break if isinstance(obj, RelationshipBase): path.insert(0, obj.id) all_paths.add(component.meta_type + ":" + "/".join(path) + ":" + facet.meta_type) included_paths.add(component.meta_type + ":" + "/".join(path) + ":" + facet.meta_type) class_summary[component.meta_type].add(facet.meta_type) print "Paths\n-----\n" for path in sorted(all_paths): if path in included_paths: if "/" not in path: # normally all direct relationships are included print "DIRECT " + path else: # sometimes extra paths are pulled in due to extra_paths # configuration. print "EXTRA " + path else: print "EXCLUDE " + path print "\nClass Summary\n-------------\n" for source_class in sorted(class_summary.keys()): print "{} is reachable from {}".format(source_class, ", ".join(sorted(class_summary[source_class])))
def _search_data(data, search): for field in search: path = field.split('.') if len(path) == 1: continue path.insert(0, 'models') v = data for key in path: if key in v: v = v[key] if v != search[field]: return False return True
def path(self): """ Return list of endpoints in the path up to this one. """ path = [] ep = self while ep.table: path.insert(0, ep) ep = ep.parent return path
def _add_venv(path, filename): """Add the virtualenv's bin directory, if in a virtualenv""" filename = os.path.realpath(filename) # Resolve symlinks filepath = os.path.dirname(filename) parts = filepath.split(os.path.sep) for index in range(1, len(parts) - 1): root = os.path.join(*parts[:-index]) activate = os.path.sep + os.path.join(root, 'bin', 'activate') if os.path.exists(activate): path.insert(0, os.path.sep + os.path.join(root, 'bin')) break
def _search_data(data, search): for field, expect in search.items(): path = field.split('.') if len(path) == 1: #TODO(robnagler) is this a bug? Why would you supply a search path # value that didn't want to be searched. continue path.insert(0, 'models') v = data for key in path: if key in v: v = v[key] if v != expect: return False return True
def OptimizePathSlide(self, path, frict = Sf): ''' Optimize by sliding WP along segments ''' i = 0 while i+2 < len(path): temp = self.SlideMove(path[i],path[i+1],path[i+2],frict=frict) if temp == None: # remove path[i+1] path.remove(path[i+1]) # Keep i unchanged else: index = path.index(path[i+1]) path.insert(index, temp) i = i + 1 return path
def get_seq_path_step(elem=None, accum=None): if accum is None: return [ [('STOP', SIBLING_EDGE)] ] call = elem['call'] for path in accum: path.insert(0, (call, SIBLING_EDGE)) accum.insert(0, list(chain( [(call, CHILD_EDGE)], (('{}#{}'.format(i, state), SIBLING_EDGE) for i, state in enumerate(elem['states'])), [('STOP', SIBLING_EDGE)] ))) return accum
def explode_path(db, invalid=None, file_id=None, directory_id=None): assert invalid is None assert (file_id is None) != (directory_id is None) cursor = db.cursor() path = [] if file_id is not None: cursor.execute("SELECT * FROM filepath(%s)", (file_id,)) else: path.append(directory_id) if not directory_id: return path cursor.execute("SELECT * FROM directorypath(%s)", (directory_id,)) for (directory_id,) in cursor: path.insert(0, directory_id) return path
def __init__(self, name, version): self.name = name self.version = version self.logger = logging.getLogger("generator.%s-%s" % (name, version)) self.cwd = os.path.dirname(__file__) # Get the environment self._env = dict(os.environ) path = self._env.get("PATH", "").split(":") pythonpath = self._env.get("PYTHONPATH", "").split(":") # Add epydoc paths to the environment epydoc = os.path.join(self.cwd, "generator-epydoc") path.insert(0, os.path.join(epydoc, "scripts")) pythonpath.insert(0, epydoc) # Add pydoctor paths to the environment pydoctor = os.path.join(self.cwd, "generator-pydoctor") path.insert(0, os.path.join(pydoctor, "bin")) pythonpath.insert(0, pydoctor) self._env["PATH"] = ":".join(path) self._env["PYTHONPATH"] = ":".join(pythonpath) # pydoctor goes on our own pythonpath too sys.path.insert(0, pydoctor) # Create the downloads directory self.downloads = os.path.join(self.cwd, "_downloads") # Create the working directory for this package self.work = os.path.join(self.cwd, "_work/%s-%s" % (name, version)) if os.path.exists(self.work): shutil.rmtree(self.work) os.makedirs(self.work) # Output directories self.safe_name = "%s_%s" % (name, version) for bad_char in "-.": self.safe_name = self.safe_name.replace(bad_char, "_") self.output_data = os.path.join(self.cwd, self.OUTPUT_DATA % (name, version)) self.output_zip = os.path.join(self.cwd, self.OUTPUT_ZIP % self.safe_name)
def directory(request, project_slug): project = Project.objects.get(slug=project_slug) directory = request.GET.get("directory") items = [] for name in os.listdir(os.path.join(project.root, directory)): path = os.path.normpath(os.path.join(directory, name)) if os.path.isdir(os.path.join(project.root, path)): items.append({"type": "directory", "value": path, "text": name}) for name in os.listdir(os.path.join(project.root, directory)): path = os.path.normpath(os.path.join(directory, name)) if not os.path.isdir(os.path.join(project.root, path)): items.append({"type": "file", "value": path, "text": name}) path = [] while not os.path.samefile(project.root, os.path.join(project.root, directory)): path.insert(0, {"value": directory, "text": os.path.basename(directory)}) directory = os.path.dirname(directory) path.insert(0, {"value": directory, "text": "Home"}) result = { "path": path, "items": items, } return JsonResponse(result)
def vengine_gen_find_module(self, module_name, path, so_suffixes): global _ma_triplet if _ma_triplet is None: try: import subprocess as sp p = sp.Popen(["gcc", "-print-multiarch"], stdout=sp.PIPE) _ma_triplet = str(p.communicate()[0].decode().strip()) except: import warnings warnings.warn('failed to detect multiarch paths, please install gcc') for so_suffix in so_suffixes + ['.%s-%s.so' % (imp.get_tag(), _ma_triplet)]: basename = module_name + so_suffix if path is None: path = sys.path # import from non root package would try __pycache__ which is # cleaned by pypy installation path.insert(0, "/usr/lib/pypy/dist-packages/zmq/backend/cffi") for dirname in path: filename = os.path.join(dirname, basename) if os.path.isfile(filename): return filename
def register_layer(self, relpath, name, out): """Register a file system directory as skin layer """ print >>out, "register skin layers" skinstool = getToolByName(self, 'portal_skins') if name not in skinstool.objectIds(): kupu_plone_skin_dir = minimalpath(os.path.join(kupu_package_dir, relpath)) createDirectoryView(skinstool, kupu_plone_skin_dir, name) print >>out, "The layer '%s' was added to the skins tool" % name # put this layer into all known skins for skinName in skinstool.getSkinSelections(): path = skinstool.getSkinPath(skinName) path = [i.strip() for i in path.split(',')] try: if name not in path: path.insert(path.index('custom')+1, name) except ValueError: if name not in path: path.append(name) path = ','.join(path) skinstool.addSkinSelection(skinName, path)
def File_selector_widget(initial_path, only_directories=0): def query_func(path, only_directories=only_directories): path = apply(os.path.join,path) if sys.platform == 'win32' and path == '': list = [ ] for i in range(24): item = chr(ord('C')+i)+':\\' if os.path.exists(item): list.append(item) return list if os.path.isdir(path): try: list = filter(lambda x: x[:1] != '.', os.listdir(path)) except: return [ ] if only_directories: list = filter(lambda x,path=path: os.path.isdir(os.path.join(path,x)), list) list.sort() return list else: return None initial_path = os.path.abspath(initial_path) path = [ ] while 1: initial_path, name = os.path.split(initial_path) if not name: break path.insert(0,name) path.insert(0,initial_path) if sys.platform == 'win32': path.insert(0,'') return Tree(path, query_func, lambda x: x or 'My computer')
def __init__(self, filename, ui='transcribe.ui', *args): builder = Gtk.Builder() builder.add_from_file(os.path.join(os.path.dirname(__file__), ui)) self.accelerators = Gtk.AccelGroup() self.window = builder.get_object('window') self.window.add_accel_group(self.accelerators) sw = builder.get_object('scrolledwindow') self.textbuffer = GtkSource.Buffer() self.lm = GtkSource.LanguageManager() path = self.lm.get_search_path() path.insert(0, os.path.join(os.path.dirname(__file__))) self.lm.set_search_path(path) self.textbuffer.set_language(self.lm.get_language('transcribe')) self.sourceview = GtkSource.View.new_with_buffer(self.textbuffer) self.sourceview.set_wrap_mode(Gtk.WrapMode.WORD_CHAR) self.sourceview.set_show_line_marks(True) self.sourceview.set_pixels_below_lines(self.SPACE_BELOW_LINES) sw.add(self.sourceview) self.play_button = builder.get_object('play_button') self.label_time = builder.get_object('label_time') self.label_duration = builder.get_object('label_duration') self.audio_slider = builder.get_object('audio_slider') #self.audio_slider.set_range(0, 100) self.audio_slider.set_increments(self.AUDIO_STEP, self.AUDIO_PAGE) box_speed = builder.get_object('box_speed') self.speed_slider = Gtk.Scale(orientation=Gtk.Orientation.HORIZONTAL) # self.speed_slider = builder.get_object('speed_slider') self.speed_slider.set_digits(2) self.speed_slider.set_range(0.10, 3) self.speed_slider.set_increments(self.SPEED_STEP, self.SPEED_PAGE) self.speed_slider.set_value(1.00) self.speed_slider.add_mark(1.00, Gtk.PositionType.BOTTOM, None) self.speed_slider.connect('value-changed', self.on_speed_slider_change) self.speed_slider.connect('grab-focus', self.on_speed_slider_grab_focus) box_speed.pack_start(self.speed_slider, True, True, 0) self.sourceview.connect("event-after", self.on_view_event_after) self.window.add_events(Gdk.EventType.KEY_PRESS | Gdk.EventType.KEY_RELEASE) self.window.connect('key-press-event', self.on_window_key_press) self.add_accelerator(self.play_button, '<ctrl>p', 'clicked') self.add_accelerator(self.play_button, '<ctrl>space', 'clicked') self.add_accelerator(self.play_button, 'F5', 'clicked') self.add_accelerator(self.speed_slider, '<alt>s', 'grab-focus') self.add_accelerator(self.audio_slider, '<alt>a', 'grab-focus') self.add_accelerator(self.sourceview, '<alt>t', 'grab-focus') builder.connect_signals(self) title = '%s - %s' % (self.APP_NAME, os.path.basename(filename)) self.window.set_title(title) self.audio = pipeline.Audio(filename) self.audio.connect('update-duration', self.on_audio_duration) self.audio.connect('finished', self.on_audio_finished)
items[row[0]] = ' - '.join(sorted(text, key=len)) childEntities = {} for row in csv.reader(open(childEntityFile)): childEntities[row[0]] = row[1] filesystemEntities = {} for row in csv.reader(open(filesystemEntityFile)): filesystemEntities[row[0]] = row[1] fileCaptions = {} for id, caption in items.iteritems(): path = [] pathId = id while filesystemEntities[pathId] != '\\N': path.insert(0, filesystemEntities[pathId]) if pathId not in childEntities: break pathId = childEntities[pathId] if len(path) == 0: continue fileCaptions[os.path.join(*path)] = caption for path, caption in fileCaptions.iteritems(): if not os.path.isfile(path): continue metadata = pyexiv2.ImageMetadata(path) metadata.read() # Preserve any existing caption.
def which_files(file, mode=os.F_OK | os.X_OK, path=None, pathext=None): """ Generate full paths, where the file*is accesible under mode and is located in the directory passed as a part of the file name, or in any directory on path if a base file name is passed. The mode matches an existing executable file by default. The path defaults to the PATH environment variable, or to os.defpath if the PATH variable is not set. On Windows, a current directory is searched before directories in the PATH variable, but not before directories in an explicitly passed path string or iterable. The pathext is used to match files with any of the extensions appended to file. On Windows, it defaults to the ``PATHEXT`` environment variable. If the PATHEXT variable is not set, then the default pathext value is hardcoded for different Windows versions, to match the actual search performed on command execution. On Windows <= 4.x, ie. NT and older, it defaults to '.COM;.EXE;.BAT;.CMD'. On Windows 5.x, ie. 2k/XP/2003, the extensions '.VBS;.VBE;.JS;.JSE;.WSF;.WSH' are appended, On Windows >= 6.x, ie. Vista/2008/7, the extension '.MSC' is further appended. The actual search on command execution may differ under Wine, which may use a different default value, that is not treated specially here. In each directory, the file is first searched without any additional extension, even when a pathext string or iterable is explicitly passed. >>> def test(expected, *args, **argd): ... result = list(which_files(*args, **argd)) ... assert result == expected, 'which_files: %s != %s' % (result, expected) ... ... try: ... result = [ which(*args, **argd) ] ... except IOError: ... result = [] ... assert result[:1] == expected[:1], 'which: %s != %s' % (result[:1], expected[:1]) >>> ### Set up >>> import stat, tempfile >>> dir = tempfile.mkdtemp(prefix='test-') >>> ext = '.ext' >>> tmp = tempfile.NamedTemporaryFile(prefix='command-', suffix=ext, dir=dir) >>> name = tmp.name >>> file = os.path.basename(name) >>> here = os.path.join(os.curdir, file) >>> nonexistent = '%s-nonexistent' % name >>> path = os.pathsep.join([ nonexistent, name, dir, dir ]) ... # Test also that duplicates are removed, and non-existent objects ... # or non-directories in path do not trigger any exceptions. >>> ### Test permissions >>> test(_windows and [name] or [], file, path=path) >>> test(_windows and [name] or [], file, mode=os.X_OK, path=path) ... # executable flag is not needed on Windows >>> test([name], file, mode=os.F_OK, path=path) >>> test([name], file, mode=os.R_OK, path=path) >>> test([name], file, mode=os.W_OK, path=path) >>> test([name], file, mode=os.R_OK|os.W_OK, path=path) >>> os.chmod(name, stat.S_IRWXU) >>> test([name], file, mode=os.R_OK|os.W_OK|os.X_OK, path=path) >>> ### Test paths >>> _save_path = os.environ.get('PATH', '') >>> cwd = os.getcwd() >>> test([], file, path='') >>> test([], file, path=nonexistent) >>> test([], nonexistent, path=path) >>> test([name], file, path=path) >>> test([name], name, path=path) >>> test([name], name, path='') >>> test([name], name, path=nonexistent) >>> os.chdir(dir) >>> test([name], file, path=path) >>> test([here], file, path=os.curdir) >>> test([name], name, path=os.curdir) >>> test([], file, path='') >>> test([], file, path=nonexistent) >>> os.environ['PATH'] = path >>> test(_windows and [here] or [name], file) ... # current directory is always searched first on Windows >>> os.environ['PATH'] = os.curdir >>> test([here], file) >>> test([name], name) >>> os.environ['PATH'] = '' >>> test(_windows and [here] or [], file) >>> os.environ['PATH'] = nonexistent >>> test(_windows and [here] or [], file) >>> os.chdir(cwd) >>> os.environ['PATH'] = path >>> test([name], file) >>> os.environ['PATH'] = _save_path >>> ### Test extensions >>> test([], file[:-4], path=path, pathext='') >>> test([], file[:-4], path=path, pathext=nonexistent) >>> test([name], file[:-4], path=path, pathext=ext) >>> test([name], file, path=path, pathext=ext) >>> test([name], file, path=path, pathext='') >>> test([name], file, path=path, pathext=nonexistent) >>> ### Tear down >>> tmp.close() >>> os.rmdir(dir) """ filepath, file = os.path.split(file) if filepath: path = (filepath,) elif path is None: path = os.environ.get('PATH', os.defpath).split(os.pathsep) if _windows and not os.curdir in path: path.insert(0, os.curdir) # current directory is always searched first on Windows elif isinstance(path, basestring): path = path.split(os.pathsep) if pathext is None: pathext = [''] if _windows: pathext += (os.environ.get('PATHEXT', '') or _getwinpathext()).lower().split(os.pathsep) elif isinstance(pathext, basestring): pathext = pathext.split(os.pathsep) if not '' in pathext: pathext.insert(0, '') # always check command without extension, even for an explicitly passed pathext seen = set() for dir in path: if dir: # only non-empty directories are searched id = os.path.normcase(os.path.abspath(dir)) if not id in seen: # each directory is searched only once seen.add(id) woex = os.path.join(dir, file) for ext in pathext: name = woex + ext if os.path.exists(name) and os.access(name, mode): yield name