Ejemplo n.º 1
0
    def ref(self, path):
        cmd, path = path[0], path[1:]
        if '^' not in path and '/' not in path:
            name = path.strip()
            ret = True
        else:
            try:
                m1 = path.index('/')
            except ValueError:
                m1 = len(path)
            try:
                m2 = path.index('^')
            except ValueError:
                m2 = len(path)
            pos = min(m1, m2)
            name, rest = path[:pos].strip(), path[pos:]
            ret = False

        if cmd == '/':
            next = self.find(name)
        elif cmd == '^':
            next = self.rfind(name)

        if ret:
            return next
        else:
            return next.ref(rest)
Ejemplo n.º 2
0
 def getModuleNameFromPath(self, path):
     moduleIdx = path.index("Modules")
     leftSlashIdx = path.index(self.slash, moduleIdx)
     rightSlashIdx = len(path)
     if self.slash in path[leftSlashIdx + 1:]:
         rightSlashIdx = path.index(self.slash, leftSlashIdx + 1)
     return path[leftSlashIdx + 1: rightSlashIdx]
Ejemplo n.º 3
0
    def ref(self, path):
        cmd, path = path[0], path[1:]
        if '^' not in path and '/' not in path:
            name = path.strip()
            ret = True
        else:
            try:
                m1 = path.index('/')
            except ValueError:
                m1 = len(path)
            try:
                m2 = path.index('^')
            except ValueError:
                m2 = len(path)
            pos = min(m1, m2)
            name, rest = path[:pos].strip(), path[pos:]
            ret = False

        if cmd == '/':
            next = self.find(name)
        elif cmd == '^':
            next = self.rfind(name)

        if ret:
            return next
        else:
            return next.ref(rest)
Ejemplo n.º 4
0
 def prefix(self):
     if 'VIRTUAL_ENV' in os.environ:
         return os.environ['VIRTUAL_ENV']
     path = os.path.split(sys.executable)[0]
     if 'Framework' in path:
         return path[:path.index('Framework')]
     else:
         return path[:path.index('bin') - 1]
Ejemplo n.º 5
0
def pathNums(filename):
    nodeList = readYaml(filename)
    paths = []
    for i in range(len(nodeList)):     
        for j in range(len(nodeList[i]["node"]["edges"])):
            path = nodeList[i]["node"]["edges"][j]["edge_id"]
            paths.append([[path[:path.index("_")]], [path[path.index("_")+1:]]])
    return paths
Ejemplo n.º 6
0
def url2operationsNew(url, base):
    # http://localhost:8080/image_service/00-cQF6rVVAs3iYXWt4Xdh2i/sub/2/@/slice:,,1,1/tile:2,26,9,512/depth:8,d,u,cs/format:jpeg
    subpath = None
    query = []

    path = filter(None, url.split('/')) # split and remove empty
    path = path[path.index(base)+1:] # isolate query part
    if path[0].lower() in ['image', 'images']:
        path = path[1:]
    resource_id = path.pop(0)

    # parse subpath
    if '@' in path:
        sp = []
        p = path.pop(0)
        while p != '@' and p is not None:
            sp.append(unquote(p))
            p = path.pop(0)
        if len(sp)>0:
            subpath = '/%s'%('/'.join(sp))

    for p in path:
        v = p.split(':', 1)
        name = unquote(v[0].replace('+', ' '))
        try:
            value = unquote(v[1].replace('+', ' '))
        except IndexError:
            value = ''
        query.append((name, value))
    return resource_id, subpath, query
Ejemplo n.º 7
0
Archivo: path.py Proyecto: tilky/rssit
def questionmark(path):
    if "?" not in path:
        return (path, {})

    firstidx = path.index("?")
    kvs = path[firstidx:]
    idx = 0

    options = {}

    while idx < len(kvs):
        kvs = kvs[idx + 1:]

        if "?" in kvs:
            idx = len(kvs)
        if "&" in kvs:
            idx = kvs.index("&")
        else:
            idx = len(kvs)

        kv = kvs[:idx]

        if "=" not in kv:
            continue

        eq = kv.index("=")

        key = kv[:eq]
        value = rssit.config.parse_value_simple(
            urllib.parse.unquote(kv[eq + 1:]))

        options[key] = value

    return (path[:firstidx], options)
Ejemplo n.º 8
0
def adduTorrent(torrenturl,path):
  print torrenturl
  token = getToken()			
  url = 'http://'+UT_ADDRESS+':'+UT_PORT+'/gui/?token=' + token + '&action=list-dirs&t=1370371190822'
  data = myClient.HttpCmd(url)
  
  data = unicode(data, 'utf-8', errors='ignore')
  json_response = simplejson.loads(data)
  path = de_unc(path)
  #xbmc.executebuiltin('Notification("'+ path +'","' +path+'")')
  i = 0
  trovato = 0
  subpath = ""
  for dir in json_response['download-dirs']:
    npath = dir['path'].upper()
    if path.find(npath)>=0:
	   trovato = i
	   subpath = path[path.index(dir['path'].upper())+len(dir['path']):]
	   break
    i = i + 1

  

  #xbmc.executebuiltin('Notification("'+ urllib.quote(torrenturl,'') +'","")') 
  url = 'http://'+UT_ADDRESS+':'+UT_PORT+'/gui/?token=' + token + '&action=add-url&s=' + urllib.quote(torrenturl,'') + '&download_dir={0}&path='.format(i) + urllib.quote(subpath,'') +'&t=1370375169507'
  
  data = myClient.HttpCmd(url)
Ejemplo n.º 9
0
def generate_tile(request,color_scheme,user_id,zoom,x,y):
    '''
        This view will generate the png file for the current request
    '''
    path = request.path

    path = path[path.index(color_scheme)-1:] # Removing the /gheat/ from the url
    
    fspath = translate(ROOT, path)

    if os.path.exists(fspath):
        return fspath

    color_scheme = color_schemes[color_scheme]
    tile = backend.Tile(color_scheme, dots, zoom, x, y, fspath, request.user)
    if tile.is_empty():
        fspath = color_scheme.get_empty_fspath(zoom)
        log.debug('serving empty tile, request: %s, file %s' % (path,fspath))
    elif tile.is_stale() or ALWAYS_BUILD:
        log.debug('rebuilding %s' % path)
        tile.rebuild()
        tile.save()
    else:
        log.debug('serving cached tile %s' % path)

    return fspath
Ejemplo n.º 10
0
def getHTMLFile(curdir, path):
	defaultAppendix = ['html','htm']
	
	idx = path.find('?')
	if idx != -1:	path = path[:path.find('?')]
		
	print 'no ? path =',path
	if path == '/':
		# Check for existence of default files.
		for item in defaultAppendix:
			#print curdir+path+'index.'+item
			if os.path.isfile(curdir+path+'index.'+item) == True:
				return curdir+path+'index.'+item
	else:
		if os.path.isfile(curdir+path) == True:	
			return curdir+path
		# Append html or htm as default if we can't find any match for given filename
		for item in defaultAppendix:
			# handle htm <-> html
			idx = path.find('.htm')
			if idx != -1:	path = path[:path.index('.htm')]
			print 'handled path',path
			if os.path.isfile(curdir+path+'.'+item) == True:
				return curdir+path+'.'+item	
	return ''
Ejemplo n.º 11
0
Archivo: path.py Proyecto: qsniyg/rssit
def questionmark(path):
    if "?" not in path:
        return (path, {})

    firstidx = path.index("?")
    kvs = path[firstidx:]
    idx = 0

    options = {}

    while idx < len(kvs):
        kvs = kvs[idx + 1:]

        if "?" in kvs:
            idx = len(kvs)
        if "&" in kvs:
            idx = kvs.index("&")
        else:
            idx = len(kvs)

        kv = kvs[:idx]

        if "=" not in kv:
            continue

        eq = kv.index("=")

        key = kv[:eq]
        value = rssit.config.parse_value_simple(urllib.parse.unquote(kv[eq + 1:]))

        options[key] = value

    return (path[:firstidx], options)
Ejemplo n.º 12
0
def url2operationsOld(url, base):
    # http://localhost:8080/image_service/00-cQF6rVVAs3iYXWt4Xdh2i/sub/2?slice=,,1,1&tile=2,26,9,512&depth=8,d,u,cs&fuse=0,0,255;255,255,255;255,0,0;0,255,0;:m&format=jpeg
    resource_id = None
    subpath = None

    # process UUID and path
    path = filter(None, url.split('?', 1)[0].split('/')) # split and remove empty
    path = path[path.index(base)+1:] # isolate query part
    if path[0].lower() in ['image', 'images']:
        path = path[1:]
    resource_id = path.pop(0)
    if len(path)>0:
        path = [unquote(p) for p in path]
        subpath = '/%s'%('/'.join(path))

    # process query string
    scheme, netloc, url, params, querystring, fragment = urlparse(url)

    #pairs = [s2 for s1 in querystring.split('&') for s2 in s1.split(';')]
    pairs = [s1 for s1 in querystring.split('&')]
    query = []
    for name_value in pairs:
        if not name_value:
            continue
        nv = name_value.split('=', 1)
        if len(nv) != 2:
            nv.append('')

        name = unquote(nv[0].replace('+', ' '))
        value = unquote(nv[1].replace('+', ' '))
        query.append((name, value))

    return resource_id, subpath, query
Ejemplo n.º 13
0
def _get_projects():
    project_path = "C:\Users\kbonnet\Desktop\Confidence Shot Tool\Projects"
    projects = {}
    for path, dirs, files in os.walk(project_path):
        if dirs == ['Alignments', 'Profiles']:
            project_name = path[path.index('Projects'):].replace('Projects\\', '')
            projects[project_name] = path
    return projects
Ejemplo n.º 14
0
def get_paths(paths):
    if paths:
        for path in paths:
            if ':' in path:
                path = path[:path.index(':')]
            yield path
    else:
        yield 'manoseimas'
Ejemplo n.º 15
0
Archivo: IDA.py Proyecto: Sabinu/IDA
def clip_path(path, folder):
    ''' clips path sequence at folder
        returns path from folder(except) to the end, except file
    '''
    path = path.split(os.sep)
    clip = path.index(folder)
    output = os.sep.join(path[clip + 1:])
    return output
 def _execute(self, data=None):
     cygwin_tmp = local.CYGWIN_ROOT + "/tmp"
     (f, path) = tempfile.mkstemp(prefix="emacs", suffix=self.suffix, dir=cygwin_tmp)
     os.close(f)
     os.unlink(path)
     cygwin_path = path[path.index("tmp") - 1:].replace("\\", "/")
     emacs_path = local.CYGWIN_ROOT + "/bin/emacsclient-w32.exe"
     RunApp(emacs_path, "-c", "-n", cygwin_path).execute()
Ejemplo n.º 17
0
 def _execute(self, data=None):
     cygwin_tmp = local.CYGWIN_ROOT + "/tmp"
     (f, path) = tempfile.mkstemp(prefix="emacs", suffix=self.suffix, dir=cygwin_tmp)
     os.close(f)
     os.unlink(path)
     cygwin_path = path[path.index("tmp") - 1:].replace("\\", "/")
     emacs_path = local.CYGWIN_ROOT + "/bin/emacsclient-w32.exe"
     RunApp(emacs_path, "-c", "-n", cygwin_path).execute()
Ejemplo n.º 18
0
def get_paths(paths):
    if paths:
        for path in paths:
            if ':' in path:
                path = path[:path.index(':')]
            yield path
    else:
        yield 'manoseimas'
Ejemplo n.º 19
0
def path2long_name(path):
    '''
    Converts an absolute file path of a .java file into the class's long name.
    Assumes that the file is in a directory named 'test'.
    '''
    long_name = path[path.index('test') + 1:]
    long_name = '.'.join(long_name)
    long_name = long_name[0:long_name.index('.java')]
    return long_name
Ejemplo n.º 20
0
 def xpathtocss(self, path):
     try:
         s = path[path.index('['):len(path)]
         s = s.replace('"', '')
         s = s.replace('@', '')
     except Exception:
         s = ''
     # извлекает только 1 атрибут
     return s
Ejemplo n.º 21
0
def add_py3_data(path):
    if PY3:
        for item in _PY3_DATA_UPDATES:
            if item in str(path) and "/PY3" not in str(path):
                pos = path.index(item) + len(item)
                if path[pos:pos + 4] == ".zip":
                    pos += 4
                path = path[:pos] + "/PY3" + path[pos:]
                break
    return path
Ejemplo n.º 22
0
def _buildchain(treeName,files):
    tree = ROOT.TChain(treeName)
    for path in files:
        # if # is in the path, it's a zipfile!
        filepath = path if '#' not in path else path[:path.index('#')]
        if not os.path.exists(filepath):
            raise RuntimeError('File '+filepath+' doesn\'t exists')
        tree.Add(path)

    return tree
Ejemplo n.º 23
0
def _path_in_list(path, excludes):
    for exclude in excludes:
        first = exclude[0]
        if first not in path:
            continue
        i = path.index(first)
        subpath = path[i:i + len(exclude)]
        if subpath == exclude:
            return True
    return False
Ejemplo n.º 24
0
def _buildchain(treeName, files):
    tree = ROOT.TChain(treeName)
    for path in files:
        # if # is in the path, it's a zipfile!
        filepath = path if '#' not in path else path[:path.index('#')]
        if not os.path.exists(filepath):
            raise RuntimeError('File ' + filepath + ' doesn\'t exists')
        tree.Add(path)

    return tree
Ejemplo n.º 25
0
def _path_in_list(path, excludes):
    for exclude in excludes:
        first = exclude[0]
        if first not in path:
            continue
        i = path.index(first)
        subpath = path[i:i + len(exclude)]
        if subpath == exclude:
            return True
    return False
Ejemplo n.º 26
0
def add_py3_data(path):
    if PY3:
        for item in _PY3_DATA_UPDATES:
            if item in str(path) and "/PY3" not in str(path):
                pos = path.index(item) + len(item)
                if path[pos:pos + 4] == ".zip":
                    pos += 4
                path = path[:pos] + "/PY3" + path[pos:]
                break
    return path
Ejemplo n.º 27
0
def templatehtml(path):
    if path.endswith("html"):  #vuln
        if "\x00" in path:
            path = path[:path.index("\x00")]

        with open('templatehtml/%s' % path) as f:
            tpl = f.read()
        f.close()
        return render_template_string(tpl)
    else:
        return send_from_directory('templatehtml', path)
Ejemplo n.º 28
0
def writeDataToTxtFile(path: str, data: str):
    folderPath = path[:path.index('/')]

    # Create folder if it not in there yet
    createNewFolder(folderPath)

    if data:
        openFile = open(path, 'w')
        openFile.write("Today is: " + str(da.getCurrentDateTime()) + '\n\n')
        openFile.write(data)
        openFile.close()
Ejemplo n.º 29
0
def get_cover_package(path):
    if ':' in path:
        path = path[:path.index(':')]

    base = os.path.abspath(repeat(os.path.dirname, __file__, 2))
    path = os.path.abspath(path)
    path = os.path.relpath(path, base)
    parts = path.split(os.sep)
    if len(parts) > 1:
        return '.'.join(parts[:2])
    else:
        return parts[0]
Ejemplo n.º 30
0
def panel(request, panel_id):
    if check_status(request) is False:
        return HttpResponseRedirect("Login")

    panel_obj = get_object_or_404(Panel, pk=panel_id)
    if check_school_privilege(panel_obj.School, request) == False:
        return HttpResponseRedirect("electric")
    if panel_obj.rooms() is not None:
        Rooms = panel_obj.rooms()
    if panel_obj.circuits() is not None:
        Circuits = panel_obj.circuits().order_by('id')
    if panel_obj.panels() is not None:
        Panels = panel_obj.panels()
    parray = []
    for i in range(0, len(Circuits)):
        parray.append(Circuits[i])
    name = ""
    rarray = []
    transformers = Transformer.objects.all()
    for i in range(0, len(Panels)):
        a_break = False
        panel = Panels[i]
        path = panel.FQN
        for count in reversed(range(6)):
            for j in range(0, len(transformers)):
                if len(transformers[j].Name) == count:
                    if transformers[j].Name in path:
                        path = path.replace(transformers[j].Name, "")
        name = path[0: path.index(panel.Name) - 1]
        for j in range (0, len(parray)):
            if parray[j].FQN == name and parray[j] not in rarray:
                rarray.append(parray[j])
    for i in range(0, len(rarray)):
        parray.remove(rarray[i])
    if panel_obj.School is not None:
        school = panel_obj.School

    Main = Panel.objects.filter(Name='MSWB')
    if Main.count()>0:
        Main = Main[0]

    picture = "energize_andover/" + panel_obj.Name.replace(" ", "") + ".jpg"
    #if not os.path.exists(picture):
        #picture = None
    if request.POST.get("Edit"):
        #print(request)
        form = PanelEditForm(request.POST)
        return HttpResponse(request, "energize_andover/Panel.html", {'form':form})
    return render(request, 'energize_andover/Panel.html',
                  {'panel' : panel_obj,
                   'Rooms': Rooms, 'Circuits': parray,
                   'Subpanels' : Panels, 'Main' : Main, 'school': school,
                   'picture' : picture})
Ejemplo n.º 31
0
def zsh_expand(path):
    global hashes

    if len(path) > 1 and path[0] == '~' and path[1] != '/':
        if '/' in path:
            end = path.index('/')
        else:
            end = len(path)
        name = path[1:end]
        if name in hashes:
            return hashes[name] + path[end:]
    return vanilla_expand(path)
Ejemplo n.º 32
0
def log_file(filename):
    """
    Log files checked to a log file
    """
    if DEBUG:
        path = filename.split('/')
        try:
            jpos = path.index('jwst')
        except ValueError:
            jpos = 0
        filename = '/'.join(path[jpos:])
        print("Searching " + '/'.join(path[jpos:]))
Ejemplo n.º 33
0
def get_cover_package(path):
    if ':' in path:
        path = path[:path.index(':')]

    base = os.path.abspath(repeat(os.path.dirname, __file__, 2))
    path = os.path.abspath(path)
    path = os.path.relpath(path, base)
    parts = path.split(os.sep)
    if len(parts) > 1:
        return '.'.join(parts[:2])
    else:
        return parts[0]
Ejemplo n.º 34
0
def precompute_distances(grid, keys, doors):
    graph = defaultdict(set)
    positions = []
    for pos, c in grid.items():
        if c == '#':
            continue
        for offset in NEIGHBOUR_OFFSETS:
            candidate = offset_pos(pos, offset)
            value = grid.get(candidate)
            if value is not None and value != '#':
                graph[pos].add(candidate)
                graph[candidate].add(pos)
            if c == '@':
                positions.append(pos)

    door_pos_to_key_pos = {}
    for door, pos in doors.items():
        door_pos_to_key_pos[pos] = keys[door.lower()]

    distances = {}
    items = list(keys.items())
    for start_pos in positions:
        items.append(('@', start_pos))

    for key1, pos1 in items:
        for key2, pos2 in items:
            if key2 == key1:
                distances[(pos1, pos2)] = (set(), set())
                distances[(pos2, pos1)] = (set(), set())
                continue

            if distances.get((key1, key2)):
                continue

            path, _ = dijkstra(graph, pos1, pos2)
            if len(path) < 2:
                continue

            pos_path, path_keys, path_keys_required = keys_and_doors_in_path(
                keys, door_pos_to_key_pos, path, pos1, pos2)
            distances[(pos1, pos2)] = (pos_path, path_keys, path_keys_required)
            distances[(pos2, pos1)] = (pos_path, path_keys, path_keys_required)

            for key in path_keys:
                this_path = path[:path.index(key) + 1]
                this_path, this_keys, this_keys_required = keys_and_doors_in_path(
                    keys, door_pos_to_key_pos, this_path, pos1, key)
                distances[(pos1, key)] = (this_path, this_keys,
                                          this_keys_required)
                distances[(key, pos1)] = (this_path, this_keys,
                                          this_keys_required)

    return distances
Ejemplo n.º 35
0
def upload_manay_dir(ip, port, username, password, local_dir, remote_dir):
    """上传多个目录目录(从windows上传) 
    将本地的local_dir目录下所有的文件,目录都上传到远程服务器的remote_dir目录下面
    所以一般先将更新目录,文件放入到将本地的local_dir目录中
        上传到remote_dir目录中(使用ssh command创建多个目录)
    """
    sftp = return_paramiko_connect(ip, port, username, password)
    ssh = return_ssh_connect(ip, port, username, password)

    if remote_dir[-1] != '/':
        remote_dir = remote_dir + '/'
    all_files = get_all_files_in_local_dir(local_dir)
    for x in all_files:
        #os.path.split(x)[-1]取得是文件的名称
        filename = os.path.split(x)[-1]
        #下面的是将远程目录替换掉本地的目录os.path.split(x)[0]取得是文件的目录
        remote_file = os.path.split(x)[0].replace(local_dir, remote_dir)
        path = remote_file.replace('\\', '/')
        print(path.index(remote_dir))
        print("path1", path[(path.index(remote_dir)) + len(remote_dir) - 3:])
        #要在远程机器上创建的所有目录
        path = path[(path.index(remote_dir)) + len(remote_dir):]
        print("path2", path)
        path = os.path.join(remote_dir, path)
        print("remote_dir", remote_dir)
        print("path3", path)
        # 创建目录 sftp的mkdir也可以,但是不能创建多级目录所以改用ssh创建。
        exec_ssh_command(ssh, 'mkdir -p ' + path)
        remote_filename = path + '/' + filename
        print('Put files...' + filename)
        print('remote_filename...' + remote_filename)
        print("x", x)
        #上传文件
        try:
            sftp.put(x, remote_filename)
            print("上传成功")
        except Exception as e:
            print(log(str(e)))
    sftp.close()
    ssh.close()
Ejemplo n.º 36
0
    def _sign_request_impl(self, request, for_tables=False, use_path_style_uris=None):
        (scheme, host, path, query, fragment) = urlsplit(request.get_full_url())
        if use_path_style_uris:
            path = path[path.index("/") :]

        canonicalized_resource = "/" + self._account + path
        match = re.search(r"comp=[^&]*", query)
        if match is not None:
            canonicalized_resource += "?" + match.group(0)

        if use_path_style_uris is None:
            use_path_style_uris = re.match("^[\d.:]+$", host) is not None

        # RFC 1123
        request.add_header(PREFIX_STORAGE_HEADER + "date", get_azure_time())
        canonicalized_headers = NEW_LINE.join(
            (
                "%s:%s" % (k.lower(), request.get_header(k).strip())
                for k in sorted(request.headers.keys(), lambda x, y: cmp(x.lower(), y.lower()))
                if k.lower().startswith(PREFIX_STORAGE_HEADER)
            )
        )

        # verb
        string_to_sign = request.get_method().upper() + NEW_LINE
        # MD5 not required
        string_to_sign += NEW_LINE
        # Content-Type
        if request.get_header("Content-type") is not None:
            string_to_sign += request.get_header("Content-type")
        string_to_sign += NEW_LINE
        if for_tables:
            string_to_sign += request.get_header(PREFIX_STORAGE_HEADER.capitalize() + "date") + NEW_LINE
        else:
            # Date
            string_to_sign += NEW_LINE
        if not for_tables:
            # Canonicalized headers
            string_to_sign += canonicalized_headers + NEW_LINE
        # Canonicalized resource
        string_to_sign += canonicalized_resource

        request.add_header(
            "Authorization",
            "SharedKey "
            + self._account
            + ":"
            + base64.encodestring(
                hmac.new(self._key, unicode(string_to_sign).encode("utf-8"), hashlib.sha256).digest()
            ).strip(),
        )
        return request
Ejemplo n.º 37
0
    def _sign_request_impl(self,
                           request,
                           for_tables=False,
                           use_path_style_uris=None):
        (scheme, host, path, query, fragment) = \
            urlsplit(request.get_full_url())
        if use_path_style_uris:
            path = path[path.index('/'):]

        canonicalized_resource = "/" + self._account + path
        match = re.search(r'comp=[^&]*', query)
        if match is not None:
            canonicalized_resource += "?" + match.group(0)

        if use_path_style_uris is None:
            use_path_style_uris = re.match('^[\d.:]+$', host) is not None

        #RFC 1123
        request.add_header(PREFIX_STORAGE_HEADER + 'date', get_azure_time())
        canonicalized_headers = NEW_LINE.join(
            ('%s:%s' % (k.lower(), request.get_header(k).strip())
             for k in sorted(request.headers.keys(),
                             lambda x, y: cmp(x.lower(), y.lower()))
             if k.lower().startswith(PREFIX_STORAGE_HEADER)))

        # verb
        string_to_sign = request.get_method().upper() + NEW_LINE
        # MD5 not required
        string_to_sign += NEW_LINE
        # Content-Type
        if request.get_header('Content-type') is not None:
            string_to_sign += request.get_header('Content-type')
        string_to_sign += NEW_LINE
        if for_tables:
            string_to_sign += request.get_header(
                PREFIX_STORAGE_HEADER.capitalize() + 'date') + NEW_LINE
        else:
            # Date
            string_to_sign += NEW_LINE
        if not for_tables:
            # Canonicalized headers
            string_to_sign += canonicalized_headers + NEW_LINE
        # Canonicalized resource
        string_to_sign += canonicalized_resource

        request.add_header(
            'Authorization',
            'SharedKey ' + self._account + ':' + base64.encodestring(
                hmac.new(self._key,
                         unicode(string_to_sign).encode("utf-8"),
                         hashlib.sha256).digest()).strip())
        return request
Ejemplo n.º 38
0
def extract_name(path):
    if path[-1] == '/':
        path = path[:-1]

    path = path.replace('copy', '')
    path = path.replace('.tif', '')
    path = path.replace(' ', '')
    num_slash = path.count('/')
    path = path.replace('/', '', num_slash - 1)

    lslash_index = path.index('/')
    name = path[lslash_index + 1:]

    return name
Ejemplo n.º 39
0
Archivo: util.py Proyecto: bmb/pyazure
    def _sign_request_impl(self, request, for_tables = False, use_path_style_uris = None):
        (scheme, host, path, query, fragment) = \
            urlsplit(request.get_full_url())
        if use_path_style_uris:
            path = path[path.index('/'):]
        
        if use_path_style_uris is None:
            use_path_style_uris = re.match('^[\d.:]+$', host) is not None

        #RFC 1123
        request.add_header(PREFIX_STORAGE_HEADER + 'date', get_azure_time())
        canonicalized_headers = NEW_LINE.join(('%s:%s' % (k.lower(), request.get_header(k).strip()) for k in sorted(request.headers.keys(), lambda x,y: cmp(x.lower(), y.lower())) if k.lower().startswith(PREFIX_STORAGE_HEADER)))

        # verb
        string_to_sign = request.get_method().upper() + NEW_LINE
        
        for field in ['Content-encoding', 'Content-language', 'Content-length', 'Content-MD5', 'Content-Type']:
            if request.has_header(field):
                string_to_sign += request.get_header(field)
            string_to_sign += NEW_LINE
        
        # Date
        if for_tables:
            string_to_sign += request.get_header(PREFIX_STORAGE_HEADER.capitalize() + 'date') + NEW_LINE
        else:
            string_to_sign += NEW_LINE

        for field in ['If-modified-since', 'If-match', 'If-none-match', 'If-unmodified-since', 'Range']:
            if request.get_header(field) is not None:
                string_to_sign += request.get_header(field)
            string_to_sign += NEW_LINE
        
        # Canonicalized headers
        if not for_tables:
            string_to_sign += canonicalized_headers + NEW_LINE
        
        # Canonicalized resource
        string_to_sign +=  "/" + self._account + path
        for key, value in parse_qs(query).iteritems():
            string_to_sign += NEW_LINE
            string_to_sign += key + ":" + value[0]
        
        print string_to_sign
        
        request.add_header('Authorization', 'SharedKey ' + self._account + ':'
            + base64.encodestring(hmac.new(self._key,
            unicode(string_to_sign).encode("utf-8"),
            hashlib.sha256).digest()).strip())
        return request
Ejemplo n.º 40
0
def add_cycle_paths(machine_graph, base_paths, cycle_nodes_group=None):
    """
    在生成的基本路径中添加环路的函数,将生成的路线写入pickle文件
    :param machine_graph: 机器图,networkx的DiGraph格式
    :param base_paths: generate_base_paths生成的基本路径
    :param cycle_nodes_group: 环路组嵌套列表,例如医院区的输入是[["h1_1", "h2_1]]
    :return: 生成的全部路径
    生成路径的格式:嵌套字典,最外层键是元组(卸货位,终分拣格口),第二层键是"hospital"和"without hospital"
                  标志该路线是否包含医院区,值为对应路线的列表
    """

    cycle_label = ["hospital"]  # 添加环路的标签

    if cycle_nodes_group:
        all_paths = {}
        j = 0
        while j < len(cycle_nodes_group):
            label = cycle_label[j]
            cycle_nodes = set(sum(list(nx.simple_cycles(machine_graph)), []))
            for key, path_list in base_paths.items():
                all_paths[key] = {label: [], "without " + label: []}
                all_nodes = set(sum(path_list, []))
                if all_nodes & set(cycle_nodes_group[j]):
                    for i in range(len(path_list)):
                        if set(path_list[i]) & set(cycle_nodes_group[j]):
                            all_paths[key][label].append(path_list[i])
                        else:
                            all_paths[key]["without " + label].append(
                                path_list[i])
                else:
                    add_node = list(all_nodes & cycle_nodes)
                    for i in range(len(path_list)):
                        path = path_list[i]
                        path_new = path[:]
                        all_paths[key]["without " + label].append(path)
                        for node in path:
                            if node not in add_node:
                                continue
                            edge_pair = nx.find_cycle(machine_graph, node)
                            position = path.index(node)
                            for pair in edge_pair:
                                path_new.insert(position + 1, pair[1])
                                position += 1
                            break
                        all_paths[key][label].append(path_new)
            j += 1
        return all_paths
    else:
        return base_paths
def get_path(page, settings):
    ''' Return the dirname relative to PAGE_PATHS prefix. '''
    path = os.path.split(page.get_relative_source_path())[0] + '/'
    path = path.replace(os.path.sep, '/')

    try:
        if path and path.index("plugins") > -1:
            return path
    except ValueError:
        # Try to lstrip the longest prefix first
        for prefix in sorted(settings['PAGE_PATHS'], key=len, reverse=True):
            if not prefix.endswith('/'): prefix += '/'
            if path.startswith(prefix):
                return path[len(prefix):-1]
        raise UnexpectedException('Page outside of PAGE_PATHS ?!?')
Ejemplo n.º 42
0
    def get_server_and_folder_id_from_url(self, url):
        parse_result = urlparse(url)
        paths = parse_result.query.split('/')
        if not 'category' in paths or paths.index(
                'category') >= len(paths) - 1:
            raise Exception('Wrong URL format')
        else:
            category_id = paths[paths.index('category') + 1]
            path = parse_result.path
            if not 'index.php' in path:
                raise Exception('Wrong URL format')

            path = path[0:path.index('index.php')]
            server = parse_result.scheme + '://' + parse_result.netloc + '/' + path
            return server, category_id
Ejemplo n.º 43
0
def find_dirpattern(pattern):
  paths=[]
  paths.extend(vlogs)
  paths.extend(searchs)
  paths.extend(qips)
  for path in paths:
    if pattern in path:
      index=path.index(pattern)
      path=path[:index]
      print path
      if path !="":
        path=os.path.relpath(os.path.join(os.path.join(synpath,path),pattern))
        print path
      else:
        path=os.path.relpath(os.path.join(synpath,pattern))
      return path
Ejemplo n.º 44
0
 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
Ejemplo n.º 45
0
    def AddByTex(self, lines):
        """ add figure by lines """
        path = ""
        caption = ""
        label = ""

        for i in lines:
            it = i.content
            if "includegraphics" in it:
                path = it[it.index("{") + 1 : it.index("}")]
            if "caption" in it:
                caption = it[it.index("{") + 1 : it.index("}")]
            if "label" in it:
                label = it[it.index("{") + 1 : it.index("}")]

        sf1 = SingleFigure(path=path, iformat=path[path.index(".") + 1 :])

        f1 = Figure(tag=label, caption=caption)
        f1.Add(sf1)
        self.Add(f1)
Ejemplo n.º 46
0
def chop_after_include(path, debug):
    """
        Chop off everything after the name include.
        i.e. /home/gander/d/gdc024/include/d/4.3.1/tango/math
        becomes /home/gander/d/gdc024/include
    """
    sub('\n$', '', path)
    #parts = path.split('/')
    #sys.stderr.write("D:20:%s\n" % (parts))
    #up_to_include = ""
    #for part in parts:
    #    up_to_include.join("/" + part)
    #    if part == 'include': break
    #sys.stderr.write("D:25:path.find(\"include/\"): %s\n" \
    #                 % (path.find("include/")))
    #sys.stderr.write("D:27:path.find(\"include/\"): %s\n" \
    #                 % (path.find("/include/")))
    #cut_off = (path.rfind("/include/") + 8)
    cut_off = path.index("/include/")
    cut_off = cut_off + 8
    if debug:
        sys.stderr.write("D:30:path[ :%d ]%s\n" % (cut_off, path[ :cut_off ]))
    return path[ :cut_off ]
Ejemplo n.º 47
0
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)
Ejemplo n.º 48
0
    def link(self, path):
        """ creat a new link of js/css/scss file
        """
        if not os.path.exists(self.current_tag_dir()):
            print('\nWARNING: firstly you must create a tag skeleton.\n')
            exit(2)

        #if not self.args.arguments:
        #print('WARNING: You must supply a file name!')
        #exit(2)
        #path = self.args.arguments[0]
        if not os.path.exists(path):
            print("\nWARNING: '%s' not found.\n" % (path, ))
            exit(2)

        source = os.path.join(self.config.here, path)
        subpath = path[path.index('/') + 1:]

        target = os.path.join(self.current_tag_dir(), 'static', subpath)
        dir_name = os.path.dirname(target)
        if not os.path.exists(dir_name):
            os.mkdir(dir_name)

        try:
            os.symlink(source, target)
        except FileExistsError:
            pass

        #print("\nOK: Created '%s' link.\n" % (target))

        #print("Next steps:")
        #print("   - Update the `code/config.json` file with the new link:")
        #print("         %s" % (subpath,))
        #print("   - Render (web-skeleton render)")
        #print("")

        return 0
Ejemplo n.º 49
0
    def loadResource(self,url):
        chm=globalvalue.chmFile
        if not chm:
            return ''
        path=unicode(url.path())
        try:
            pos=path.index(u'#')
            path=path[0:pos]
        except:
            pass
        path=urldecode(path)
        data=chm.GetFileAsStrByUrl(path)
        if data==None:
            self.setError(404,'')
            return None
        self.setContentTypeHeader(path)
        #self.setHeader(QNetworkRequest.ContentTypeHeader,QVariant("text/html; charset=UTF-8"))
#        ext=os.path.splitext(path)[1].lower()
#        if len(ext)>0:
#            ext=ext[1:]
#        ctt_type=content_type.get(ext,'binary/octet')
#        if ctt_type.lower().startswith('text'):
#            print data.decode('gb18030')
        return data
Ejemplo n.º 50
0
def buildScanCmds(samples, other_options='', echo_options='', origin='', axes='', output_dir='', verbose=False, svd=0):
    """Batch scans in multiple dimensions"""

    samples_ext = samples.split('.')[-1]

    if samples_ext == 'sst':

        state_ext = 'str'

    elif samples_ext == 'tst':

        state_ext = 'tct'

    else:

        raise Exception("Unrecognised samples extension '%s'" % samples_ext)


    path = samples.split('/')

    if path.count('mcmc'):

        ind = path.index('mcmc')

        sub_path = '/'.join(path[ind + 2:])
        sub_path = '.'.join(sub_path.split('.')[0:-1])

    else:
        sub_path = raw_input("Sub-path name: ")



    if not output_dir:
        output_dir = '/home/tclose/Data/Tractography/analysis/scan/%s' % sub_path




    if svd:

        #Round the value of svd up to the nearest multiple of 2.
        if svd % 2:
            svd += 1

        axes = '/home/tclose/Data/Tractography/analysis/svd/%s' % sub_path

        if os.path.isdir(axes):
            try:
                subprocess.call('svn delete --force %s' % axes)
            except OSError:
                shutil.rmtree(axes)

        os.makedirs(axes)

        svd_file = axes + '.' + samples_ext

        svd_cmd = '/home/tclose/Code/Tractography/bin/svd_fibres %s %s -max %d' % (samples, svd_file, svd)

        if verbose:
            print 'SVD Command: '
            print '\n\n%s\n' % svd_cmd

        subprocess.call(svd_cmd, shell=True)

        comp_i = 0

        for dir_i in range(0, svd, 2):

            subdir = 'principle-comp_%d-%d' % (dir_i, dir_i + 1)

            os.mkdir(os.path.join(axes, subdir))


        for comp_i in range(0, svd):

        #Round the value of svd down to the nearest multiple of 2.            
            if comp_i % 2:
                dir_i = comp_i - 1
            else:
                dir_i = comp_i

            subdir = 'principle-comp_%d-%d' % (dir_i, dir_i + 1)

            select_cmd = '/home/tclose/Code/Tractography/bin/select_fibres %s %s/%s/%d.%s -inc %d' % (svd_file, axes, subdir, comp_i, state_ext, comp_i)

            if verbose:
                print 'Select Command: '
                print '\n\n%s\n' % select_cmd

            subprocess.call(select_cmd, shell=True)


        os.remove(svd_file)
        try:
            os.remove(svd_file + 'x')
            os.remove(svd_file + 'xx')
        except OSError:
            None

    elif not axes:

        if state_ext == 'str':

            axes = '/home/tclose/Data/Tractography/analysis/scan/templates/strand/no_intens'

        elif state_ext == 'tct':

            axes = '/home/tclose/Data/Tractography/analysis/scan/templates/tract/no_intens'

        else:

            raise Exception("Unrecognised state extension '%s'" % state_ext)


    # If directory exists, clean all files withinness it first.
    if os.path.isdir(output_dir):
        try:
            subprocess.call('svn delete --force %s' % output_dir)
        except OSError:
            shutil.rmtree(output_dir)

    os.makedirs(output_dir)

    axes_subdir = os.listdir(axes)

    if '.svn' in axes_subdir:
        axes_subdir.remove('.svn')

    global cmds

    cmds = []

    for dir in axes_subdir:

        masks = os.listdir(os.path.join(axes, dir))

        if '.svn' in masks:
            masks.remove('.svn')

        for mask in masks[:]:
            if mask.split('.')[-1] <> state_ext:
                masks.remove(mask)

        mask1 = os.path.join(axes, dir, masks[0])
        mask2 = os.path.join(axes, dir, masks[1])

        if svd:
            strip_mask1 = 'comp_%s' % masks[0]
            strip_mask2 = 'comp_%s' % masks[1]
        else:
            strip_mask1 = '.'.join(masks[0].split('.')[0:-1])
            strip_mask2 = '.'.join(masks[1].split('.')[0:-1])

        echo_cmd = '/home/tclose/code/bin/echo_parameters %s -method scan -output %s/%s_%s.mif -axis1 %s -axis2 %s %s' % (samples, output_dir, strip_mask1, strip_mask2, mask1, mask2, ' '.join(echo_options))

        if verbose:
            print 'Echo Command: '
            print echo_cmd

        echo = subprocess.Popen(echo_cmd, stdout=subprocess.PIPE, shell=True).communicate()[0]

        if not echo:
            raise Exception ('Echo command failed: (%s)' % echo_cmd)

        cmd = '/home/tclose/code/bin/' + echo.strip() + ' ' + other_options

        cmds.append(cmd)

        if verbose:
            print 'Scan Command (echo): '
            print '\n%s\n\n' % cmd




    print "MATLAB plot command:\n\nplot_scan %s -state %s.iter.%s \n\n" % (output_dir, '.'.join(samples.split('.')[0:-1]), samples.split('.')[-1])
Ejemplo n.º 51
0
def expandVars(path, env):
  """Recursively expand shell variables of the form $var and ${var}.

  This function is a copy of os.path.expandvars() with added support for
  recursion.
  
  Unknown variables are replaced with {MISSING_SYMBOL_<varname>}.
  
  @param path: The path to expand.
  @type path: string
  @param env: A dictionary of symbols to their values.
  @type env: dict
  
  @return: The expanded path.
  @rtype: string
  """
  if '$' not in path:
    return path
  import string
  varchars = string.ascii_letters + string.digits + '_-'
  res = ''
  index = 0
  pathlen = len(path)
  while index < pathlen:
    c = path[index]
    if c == '\'':   # no expansion within single quotes
      path = path[index + 1:]
      pathlen = len(path)
      try:
        index = path.index('\'')
        res = res + '\'' + path[:index + 1]
      except ValueError:
        res = res + path
        index = pathlen - 1
    elif c == '$':  # variable or '$$'
      if path[index + 1:index + 2] == '$':
        res = res + c
        index = index + 1
      elif path[index + 1:index + 2] == '{':
        path = path[index + 2:]
        pathlen = len(path)
        try:
          index = path.index('}')
          var = path[:index]
          sliceStart = None
          # Check for an indexed variable.
          if var.endswith(']') and '[' in var:
            m = re.match(r'(.+)\[(\d+)\]', var)
            if m:
              var = m.group(1)
              sliceStart = int(m.group(2))
          if var in env:
            subVar = expandVars(env[var], env)
            if sliceStart is not None:
              subVar = subVar[sliceStart]
            res = res + subVar
          else:
            res = res + '{MISSING_SYMBOL_' + var + '}'
        except ValueError:
          res = res + path
          index = pathlen - 1
      else:
        var = ''
        index = index + 1
        c = path[index:index + 1]
        while c != '' and c in varchars:
          var = var + c
          index = index + 1
          c = path[index:index + 1]
        if var in env:
          res = res + expandVars(env[var], env)
        else:
          res = res + '{MISSING_SYMBOL_' + var + '}'
        if c != '':
          res = res + c
    else:
      res = res + c
    index = index + 1
  return res
Ejemplo n.º 52
0
    def default(self, *path, **args):
        # Convert the path argument into a list (from a tuple).
        path = list(path)

        # If there are no positional arguments, behave as though the root
        # index.html was requested.
        if len(path) == 0:
            path = ["index.html"]

        # Check the first character of the first path component.  If it's a
        # tilde, then assume the path points into a user's home directory.
        if path[0][0] == "~":
            # Only treat this component as a home directory if there is actually
            # text following the tilde (rather than making the server serve
            # files from the home directory of whatever user account it is using
            # to run).
            if len(path[0]) > 1:
                # Expand the home directory, append the tangelo_html
                # subdirectory, and then the tail of the original path.
                path = os.path.expanduser(path[0]).split("/") + ["tangelo_html"] + path[1:]
        else:
            # TODO(choudhury): check a table of configured custom mappings to
            # see if the first path component should be mapped to some other
            # filesystem path.

            # Reaching this point means the path is relative to the server's web
            # root.
            path = current_dir.split("/") + ["web"] + path

        # Check for the word "service" in the path - this indicates the
        # invocation of a web service placed somewhere besides the global
        # services list.
        try:
            service = path.index("service")

            # Make sure there is an actual service name after the "service" path
            # component.
            if len(path) == service + 1:
                raise cherrypy.HTTPError(404, "Did you forget the service name?")

            # Grab the portion of the path that names the service (appending the
            # standard python file extension as well).
            service_path = "/".join(path[:(service+2)]) + ".py"

            # Grab the rest of the path list, as the positional arguments for
            # the service invocation.
            pargs = path[(service+2):]

            # Invoke the service and return the result.
            return invoke_service(service_path, *pargs, **args)
        except ValueError:
            pass

        # Form a path name from the path components.
        finalpath = "/".join(path)

        # If the path represents a directory, first check if the URL is missing
        # a trailing slash - if it is, redirect to a URL with the slash
        # appended; otherwise, append "index.html" to the path spec and
        # continue.
        if os.path.isdir(finalpath):
            if cherrypy.request.path_info[-1] != "/":
                raise cherrypy.HTTPRedirect(cherrypy.request.path_info + "/")
            else:
                finalpath += "/index.html"

        # If the home directory expansion above failed (or something else went
        # wrong), then the filepath will not be an absolute path, and we bail.
        if not os.path.isabs(finalpath):
            raise cherrypy.HTTPError(404)

        # Serve the file.
        return serve_file(finalpath)
Ejemplo n.º 53
0
letters = english + russian + digits

# generate all possible combinations of path roots
paths = [os.path.join(path, letter) for letter in letters 
                                    for path in pathroots]
# leave only existing directories
paths = filter(lambda name: os.path.exists(name), paths)

for path in paths:
    letter = os.path.basename(path)
    # generate the path of a destination root:
    # - extract only letter if the path does not contain any nested path
    #       for example, for 'D:\A' the root is 'A'
    # - keep the letter and the nested path, otherwise
    #       for example, for 'D:\Foo\A' the root is 'Foo\A'
    if path.index(os.sep) == path.rindex(os.sep):
        root = letter
    else:
        root = path[path.index(os.sep) + 1:]
    # iterate through all performers
    for performer in os.listdir(path):
        performerpath = os.path.join(path, performer)
        # iterate through all files in performer's Picture folder
        imagepath = os.path.join(performerpath, 'Picture')
        if os.path.exists(imagepath):
            for imagefile in os.listdir(imagepath):
                srcfile = os.path.join(imagepath, imagefile)
                if not os.path.isfile(srcfile):
                    continue
                # if the file contains only digits (album ID)
                # or starts with 'photo' or 'foto' (performer photo)
Ejemplo n.º 54
0
 def prefix(self):
     path = os.path.split(sys.executable)[0]
     if 'Framework' in path:
         return path[:path.index('Framework')]
     else:
         return path[:path.index('bin')-1]
Ejemplo n.º 55
0
 def prefix(self):
     path = os.path.split(sys.executable)[0]
     if 'Resources' in path:
         return path[:path.index('Resources')]
     else:
         return sys.prefix