jiahuimbzuai/CoQuIR huggingface dataset:
// PHYSICALPATH_FUNC [c]
PHYSICALPATH_FUNC(mod_alias_physical_handler) {
	plugin_data *p = p_d;
	int uri_len, basedir_len;
	char *uri_ptr;
	size_t k;

	if (buffer_is_empty(con->physical.path)) return HANDLER_GO_ON;

	mod_alias_patch_connection(srv, con, p);

	/* not to include the tailing slash */
	basedir_len = buffer_string_length(con->physical.basedir);
	if ('/' == con->physical.basedir->ptr[basedir_len-1]) --basedir_len;
	uri_len = buffer_string_length(con->physical.path) - basedir_len;
	uri_ptr = con->physical.path->ptr + basedir_len;

	for (k = 0; k < p->conf.alias->used; k++) {
		data_string *ds = (data_string *)p->conf.alias->data[k];
		int alias_len = buffer_string_length(ds->key);

		if (alias_len > uri_len) continue;
		if (buffer_is_empty(ds->key)) continue;

		if (0 == (con->conf.force_lowercase_filenames ?
					strncasecmp(uri_ptr, ds->key->ptr, alias_len) :
					strncmp(uri_ptr, ds->key->ptr, alias_len))) {
			/* matched */

			buffer_copy_buffer(con->physical.basedir, ds->value);
			buffer_copy_buffer(srv->tmp_buf, ds->value);
			buffer_append_string(srv->tmp_buf, uri_ptr + alias_len);
			buffer_copy_buffer(con->physical.path, srv->tmp_buf);

			return HANDLER_GO_ON;
		}
	}

	/* not found */
	return HANDLER_GO_ON;
}
// download_check_files [python]
    def download_check_files(self, filelist):
        # only admins and allowed users may download
        if not cherrypy.session['admin']:
            uo = self.useroptions.forUser(self.getUserId())
            if not uo.getOptionValue('media.may_download'):
                return 'not_permitted'
        # make sure nobody tries to escape from basedir
        for f in filelist:
            # don't allow to traverse up in the file system
            if '/../' in f or f.startswith('../'):
                return 'invalid_file'
            # CVE-2015-8309: do not allow absolute file paths
            if os.path.isabs(f):
                return 'invalid_file'
        # make sure all files are smaller than maximum download size
        size_limit = cherry.config['media.maximum_download_size']
        try:
            if self.model.file_size_within_limit(filelist, size_limit):
                return 'ok'
            else:
                return 'too_big'
        except OSError as e:        # use OSError for python2 compatibility
            return str(e)
// download_check_files [python]
    def download_check_files(self, filelist):
        # only admins and allowed users may download
        if not cherrypy.session['admin']:
            uo = self.useroptions.forUser(self.getUserId())
            if not uo.getOptionValue('media.may_download'):
                return 'not_permitted'
        # make sure nobody tries to escape from basedir
        for f in filelist:
            if '/../' in f:
                return 'invalid_file'
        # make sure all files are smaller than maximum download size
        size_limit = cherry.config['media.maximum_download_size']
        try:
            if self.model.file_size_within_limit(filelist, size_limit):
                return 'ok'
            else:
                return 'too_big'
        except OSError as e:        # use OSError for python2 compatibility
            return str(e)
// get_files [python]
    def get_files(self, submit_id, password=None, astree=False):
        """
        Returns files from a submitted analysis.
        @param password: The password to unlock container archives with
        @param astree: sflock option; determines the format in which the files are returned
        @return: A tree of files
        """
        submit = Database().view_submit(submit_id)
        files, duplicates = [], []

        for data in submit.data["data"]:
            if data["type"] == "file":
                filename = Storage.get_filename_from_path(data["data"])
                filepath = os.path.join(submit.tmp_path, filename)

                unpacked = sflock.unpack(
                    filepath=filepath, password=password, duplicates=duplicates
                )

                if astree:
                    unpacked = unpacked.astree(sanitize=True)

                files.append(unpacked)
            elif data["type"] == "url":
                files.append({
                    "filename": data["data"],
                    "filepath": "",
                    "relapath": "",
                    "selected": True,
                    "size": 0,
                    "type": "url",
                    "package": "ie",
                    "extrpath": [],
                    "duplicate": False,
                    "children": [],
                    "mime": "text/html",
                    "finger": {
                        "magic_human": "url",
                        "magic": "url"
                    }
                })
            else:
                raise RuntimeError(
                    "Unknown data entry type: %s" % data["type"]
                )

        return files
// get_files [python]
    def get_files(self, submit_id, password=None, astree=False):
        """
        Returns files from a submitted analysis.
        @param password: The password to unlock container archives with
        @param astree: sflock option; determines the format in which the files are returned
        @return: A tree of files
        """
        submit = Database().view_submit(submit_id)
        files, duplicates = [], []

        for data in submit.data["data"]:
            if data["type"] == "file":
                filename = Storage.get_filename_from_path(data["data"])
                filepath = os.path.join(submit.tmp_path, data["data"])
                filedata = open(filepath, "rb").read()

                unpacked = sflock.unpack(
                    filepath=filename, contents=filedata,
                    password=password, duplicates=duplicates
                )

                if astree:
                    unpacked = unpacked.astree()

                files.append(unpacked)
            elif data["type"] == "url":
                files.append({
                    "filename": data["data"],
                    "filepath": "",
                    "relapath": "",
                    "selected": True,
                    "size": 0,
                    "type": "url",
                    "package": "ie",
                    "extrpath": [],
                    "duplicate": False,
                    "children": [],
                    "mime": "text/html",
                    "finger": {
                        "magic_human": "url",
                        "magic": "url"
                    }
                })
            else:
                raise RuntimeError(
                    "Unknown data entry type: %s" % data["type"]
                )

        return {
            "files": files,
            "path": submit.tmp_path,
        }
// dd_delete_item [c]
int dd_delete_item(struct dump_dir *dd, const char *name)
{
    if (!dd->locked)
        error_msg_and_die("dump_dir is not opened"); /* bug */

    if (!str_is_correct_filename(name))
        error_msg_and_die("Cannot delete item. '%s' is not a valid file name", name);

    char *path = concat_path_file(dd->dd_dirname, name);
    int res = unlink(path);

    if (res < 0)
    {
        if (errno == ENOENT)
            errno = res = 0;
        else
            perror_msg("Can't delete file '%s'", path);
    }

    free(path);
    return res;
}
// dd_delete_item [c]
int dd_delete_item(struct dump_dir *dd, const char *name)
{
    if (!dd->locked)
        error_msg_and_die("dump_dir is not opened"); /* bug */

    char *path = concat_path_file(dd->dd_dirname, name);
    int res = unlink(path);

    if (res < 0)
    {
        if (errno == ENOENT)
            errno = res = 0;
        else
            perror_msg("Can't delete file '%s'", path);
    }

    free(path);
    return res;
}
// render [python]
	def render(self, request):
		action = "download"
		if "action" in request.args:
			action = request.args["action"][0]

		if "file" in request.args:
			filename = lenient_force_utf_8(request.args["file"][0])
			filename = sanitise_filename_slashes(os.path.realpath(filename))

			if not os.path.exists(filename):
				return "File '%s' not found" % (filename)

			if action == "stream":
				name = "stream"
				if "name" in request.args:
					name = request.args["name"][0]

				port = config.OpenWebif.port.value
				proto = 'http'
				if request.isSecure():
					port = config.OpenWebif.https_port.value
					proto = 'https'
				ourhost = request.getHeader('host')
				m = re.match('.+\:(\d+)$', ourhost)
				if m is not None:
					port = m.group(1)

				response = "#EXTM3U\n#EXTVLCOPT--http-reconnect=true\n#EXTINF:-1,%s\n%s://%s:%s/file?action=download&file=%s" % (name, proto, request.getRequestHostname(), port, quote(filename))
				request.setHeader("Content-Disposition", 'attachment;filename="%s.m3u"' % name)
				request.setHeader("Content-Type", "application/x-mpegurl")
				return response
			elif action == "delete":
				request.setResponseCode(http.OK)
				return "TODO: DELETE FILE: %s" % (filename)
			elif action == "download":
				request.setHeader("Content-Disposition", "attachment;filename=\"%s\"" % (filename.split('/')[-1]))
				rfile = static.File(filename, defaultType = "application/octet-stream")
				return rfile.render(request)
			else: 
				return "wrong action parameter"

		if "dir" in request.args:
			path = request.args["dir"][0]
			pattern = '*'
			data = []
			if "pattern" in request.args:
				pattern = request.args["pattern"][0]
			directories = []
			files = []
			if fileExists(path):
				try:
					files = glob.glob(path+'/'+pattern)
				except:
					files = []
				files.sort()
				tmpfiles = files[:]
				for x in tmpfiles:
					if os.path.isdir(x):
						directories.append(x + '/')
						files.remove(x)
				data.append({"result": True,"dirs": directories,"files": files})
			else:
				data.append({"result": False,"message": "path %s not exits" % (path)})
			request.setHeader("content-type", "application/json; charset=utf-8")
			return json.dumps(data, indent=2)
// render [python]
	def render(self, request):
		action = "download"
		if "action" in request.args:
			action = request.args["action"][0]

		if "file" in request.args:
			filename = request.args["file"][0].decode('utf-8', 'ignore').encode('utf-8')
			filename = re.sub("^/+", "/", os.path.realpath(filename))

			if not os.path.exists(filename):
				return "File '%s' not found" % (filename)

			if action == "stream":
				name = "stream"
				if "name" in request.args:
					name = request.args["name"][0]

				port = config.OpenWebif.port.value
				proto = 'http'
				if request.isSecure():
					port = config.OpenWebif.https_port.value
					proto = 'https'
				ourhost = request.getHeader('host')
				m = re.match('.+\:(\d+)$', ourhost)
				if m is not None:
					port = m.group(1)

				response = "#EXTM3U\n#EXTVLCOPT--http-reconnect=true\n#EXTINF:-1,%s\n%s://%s:%s/file?action=download&file=%s" % (name, proto, request.getRequestHostname(), port, quote(filename))
				request.setHeader("Content-Disposition", 'attachment;filename="%s.m3u"' % name)
				request.setHeader("Content-Type", "application/x-mpegurl")
				return response
			elif action == "delete":
				request.setResponseCode(http.OK)
				return "TODO: DELETE FILE: %s" % (filename)
			elif action == "download":
				request.setHeader("Content-Disposition", "attachment;filename=\"%s\"" % (filename.split('/')[-1]))
				rfile = static.File(filename, defaultType = "application/octet-stream")
				return rfile.render(request)
			else: 
				return "wrong action parameter"

		if "dir" in request.args:
			path = request.args["dir"][0]
			pattern = '*'
			data = []
			if "pattern" in request.args:
				pattern = request.args["pattern"][0]
			directories = []
			files = []
			if fileExists(path):
				try:
					files = glob.glob(path+'/'+pattern)
				except:
					files = []
				files.sort()
				tmpfiles = files[:]
				for x in tmpfiles:
					if os.path.isdir(x):
						directories.append(x + '/')
						files.remove(x)
				data.append({"result": True,"dirs": directories,"files": files})
			else:
				data.append({"result": False,"message": "path %s not exits" % (path)})
			request.setHeader("content-type", "application/json; charset=utf-8")
			return json.dumps(data, indent=2)
// _inject_net_into_fs [python]
def _inject_net_into_fs(net, fs, execute=None):
    """Inject /etc/network/interfaces into the filesystem rooted at fs.

    net is the contents of /etc/network/interfaces.
    """
    netdir = _join_and_check_path_within_fs(fs, 'etc', 'network')
    utils.execute('mkdir', '-p', netdir, run_as_root=True)
    utils.execute('chown', 'root:root', netdir, run_as_root=True)
    utils.execute('chmod', 755, netdir, run_as_root=True)

    netfile = os.path.join('etc', 'network', 'interfaces')
    _inject_file_into_fs(fs, netfile, net)
// _inject_net_into_fs [python]
def _inject_net_into_fs(net, fs, execute=None):
    """Inject /etc/network/interfaces into the filesystem rooted at fs.

    net is the contents of /etc/network/interfaces.
    """
    netdir = os.path.join(os.path.join(fs, 'etc'), 'network')
    utils.execute('mkdir', '-p', netdir, run_as_root=True)
    utils.execute('chown', 'root:root', netdir, run_as_root=True)
    utils.execute('chmod', 755, netdir, run_as_root=True)
    netfile = os.path.join(netdir, 'interfaces')
    utils.execute('tee', netfile, process_input=net, run_as_root=True)
// canonicalize [python]
    def canonicalize(self):
        """::

            path = path.canonicalize()

        Canonicalize path by resolving ``.`` and ``..``, in addition ``...`` will be
        treated as ``.`` to protect from path traversal attacks.

            # "/foo/baz"
            Pyjo.Path.new('/foo/./bar/../baz').canonicalize()

            # "/../baz"
            Pyjo.Path.new('/foo/../bar/../../baz').canonicalize()

            # "/foo/bar"
            Pyjo.Path.new('/foo/.../bar').canonicalize()
        """
        parts = self.parts
        i = 0
        while i < len(parts):
            if parts[i] == '' or parts[i] == '.' or parts[i] == '...':
                parts.pop(i)
            elif i < 1 or parts[i] != '..' or parts[i - 1] == '..':
                i += 1
            else:
                i -= 1
                parts.pop(i)
                parts.pop(i)

        if not parts:
            self.trailing_slash = False

        return self
// canonicalize [python]
    def canonicalize(self):
        """::

            path = path.canonicalize()

        Canonicalize path. ::

            # "/foo/baz"
            Pyjo.Path.new('/foo/./bar/../baz').canonicalize()

            # "/../baz"
            Pyjo.Path.new('/foo/../bar/../../baz').canonicalize()
        """
        parts = self.parts
        i = 0
        while i < len(parts):
            if parts[i] == '.' or parts[i] == '':
                parts.pop(i)
            elif i < 1 or parts[i] != '..' or parts[i - 1] == '..':
                i += 1
            else:
                i -= 1
                parts.pop(i)
                parts.pop(i)

        if not parts:
            self.trailing_slash = False

        return self
// CWebSock::GetSkinPath [cpp]
CString CWebSock::GetSkinPath(const CString& sSkinName) {
    const CString sSkin = sSkinName.Replace_n("/", "_").Replace_n(".", "_");

    CString sRet = CZNC::Get().GetZNCPath() + "/webskins/" + sSkin;

    if (!CFile::IsDir(sRet)) {
        sRet = CZNC::Get().GetCurPath() + "/webskins/" + sSkin;

        if (!CFile::IsDir(sRet)) {
            sRet = CString(_SKINDIR_) + "/" + sSkin;
        }
    }

    return sRet + "/";
}
// CWebSock::GetSkinPath [cpp]
CString CWebSock::GetSkinPath(const CString& sSkinName) {
    CString sRet = CZNC::Get().GetZNCPath() + "/webskins/" + sSkinName;

    if (!CFile::IsDir(sRet)) {
        sRet = CZNC::Get().GetCurPath() + "/webskins/" + sSkinName;

        if (!CFile::IsDir(sRet)) {
            sRet = CString(_SKINDIR_) + "/" + sSkinName;
        }
    }

    return sRet + "/";
}
// addKey [python]
def addKey(client):
	"""Adds a new key with the specified name and contents.
	Returns an error if a key with the specified name already exists.
	"""
	global BAD_REQUEST
	global CREATED

	validateClient(client)
	client_pub_key = loadClientRSAKey(client)
	token_data = decodeRequestToken(request.data, client_pub_key)
	validateNewKeyData(token_data)
	validateKeyName(token_data['name'])

	# Use 'x' flag so we can throw an error if a key with this name already exists
	try:
		with open('keys/%s/%s.key' % (client, token_data['name']), 'x') as f:
			f.write(token_data['key'])
	except FileExistsError:
		raise FoxlockError(BAD_REQUEST, "Key '%s' already exists" % token_data['name'])

	return 'Key successfully created', CREATED
// addKey [python]
def addKey(client):
	"""Adds a new key with the specified name and contents.
	Returns an error if a key with the specified name already exists.
	"""
	global BAD_REQUEST
	global CREATED

	validateClient(client)

	client_pub_key = loadClientRSAKey(client)
	token_data = decodeRequestToken(request.data, client_pub_key)
	validateNewKeyData(token_data)

	# Use 'x' flag so we can throw an error if a key with this name already exists
	try:
		with open('keys/%s/%s.key' % (client, token_data['name']), 'x') as f:
			f.write(token_data['key'])
	except FileExistsError:
		raise FoxlockError(BAD_REQUEST, "Key '%s' already exists" % token_data['name'])

	return 'Key successfully created', CREATED
// dd_save_text [c]
void dd_save_text(struct dump_dir *dd, const char *name, const char *data)
{
    if (!dd->locked)
        error_msg_and_die("dump_dir is not opened"); /* bug */

    if (!str_is_correct_filename(name))
        error_msg_and_die("Cannot save text. '%s' is not a valid file name", name);

    char *full_path = concat_path_file(dd->dd_dirname, name);
    save_binary_file(full_path, data, strlen(data), dd->dd_uid, dd->dd_gid, dd->mode);
    free(full_path);
}
// dd_save_text [c]
void dd_save_text(struct dump_dir *dd, const char *name, const char *data)
{
    if (!dd->locked)
        error_msg_and_die("dump_dir is not opened"); /* bug */

    char *full_path = concat_path_file(dd->dd_dirname, name);
    save_binary_file(full_path, data, strlen(data), dd->dd_uid, dd->dd_gid, dd->mode);
    free(full_path);
}
// misc_file_checks [python]
    def misc_file_checks(self):

        print_header("MISC FILE CHECKS")

        #
        # Check for recommended and mandatory files
        #

        filenames = ("manifest.json", "LICENSE", "README.md",
                     "scripts/install", "scripts/remove",
                     "scripts/upgrade",
                     "scripts/backup", "scripts/restore")
        non_mandatory = ("script/backup", "script/restore")

        for filename in filenames:
            if file_exists(self.path + "/" + filename):
                continue
            elif filename in non_mandatory:
                print_warning("Consider adding a file %s" % filename)
            else:
                print_error("File %s is mandatory" % filename)

        #
        # Deprecated php-fpm.ini thing
        #

        if file_exists(self.path + "/conf/php-fpm.ini"):
            print_warning(
                "Using a separate php-fpm.ini file is deprecated. "
                "Please merge your php-fpm directives directly in the pool file. "
                "(c.f. https://github.com/YunoHost-Apps/nextcloud_ynh/issues/138 )"
            )

        #
        # Deprecated usage of 'add_header' in nginx conf
        #

        for filename in os.listdir(self.path + "/conf"):
            if not os.path.isfile(self.path + "/conf/" + filename):
                continue
            content = open(self.path + "/conf/" + filename).read()
            if "location" in content and "add_header" in content:
                print_warning(
                    "Do not use 'add_header' in the nginx conf. Use 'more_set_headers' instead. "
                    "(See https://www.peterbe.com/plog/be-very-careful-with-your-add_header-in-nginx "
                    "and https://github.com/openresty/headers-more-nginx-module#more_set_headers )"
                )
// dd_save_binary [c]
void dd_save_binary(struct dump_dir* dd, const char* name, const char* data, unsigned size)
{
    if (!dd->locked)
        error_msg_and_die("dump_dir is not opened"); /* bug */

    if (!str_is_correct_filename(name))
        error_msg_and_die("Cannot save binary. '%s' is not a valid file name", name);

    char *full_path = concat_path_file(dd->dd_dirname, name);
    save_binary_file(full_path, data, size, dd->dd_uid, dd->dd_gid, dd->mode);
    free(full_path);
}
// dd_save_binary [c]
void dd_save_binary(struct dump_dir* dd, const char* name, const char* data, unsigned size)
{
    if (!dd->locked)
        error_msg_and_die("dump_dir is not opened"); /* bug */

    char *full_path = concat_path_file(dd->dd_dirname, name);
    save_binary_file(full_path, data, size, dd->dd_uid, dd->dd_gid, dd->mode);
    free(full_path);
}
// pascal_case [python]
def pascal_case(value: str) -> str:
    return stringcase.pascalcase(_sanitize(value))
// pascal_case [python]
def pascal_case(value: str) -> str:
    return stringcase.pascalcase(value)
// cleanup_pathname [c]
cleanup_pathname(struct archive_write_disk *a)
{
	char *dest, *src;
	char separator = '\0';

	dest = src = a->name;
	if (*src == '\0') {
		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
		    "Invalid empty pathname");
		return (ARCHIVE_FAILED);
	}

#if defined(__CYGWIN__)
	cleanup_pathname_win(a);
#endif
	/* Skip leading '/'. */
	if (*src == '/') {
		if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
			                  "Path is absolute");
			return (ARCHIVE_FAILED);
		}

		separator = *src++;
	}

	/* Scan the pathname one element at a time. */
	for (;;) {
		/* src points to first char after '/' */
		if (src[0] == '\0') {
			break;
		} else if (src[0] == '/') {
			/* Found '//', ignore second one. */
			src++;
			continue;
		} else if (src[0] == '.') {
			if (src[1] == '\0') {
				/* Ignore trailing '.' */
				break;
			} else if (src[1] == '/') {
				/* Skip './'. */
				src += 2;
				continue;
			} else if (src[1] == '.') {
				if (src[2] == '/' || src[2] == '\0') {
					/* Conditionally warn about '..' */
					if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
						archive_set_error(&a->archive,
						    ARCHIVE_ERRNO_MISC,
						    "Path contains '..'");
						return (ARCHIVE_FAILED);
					}
				}
				/*
				 * Note: Under no circumstances do we
				 * remove '..' elements.  In
				 * particular, restoring
				 * '/foo/../bar/' should create the
				 * 'foo' dir as a side-effect.
				 */
			}
		}

		/* Copy current element, including leading '/'. */
		if (separator)
			*dest++ = '/';
		while (*src != '\0' && *src != '/') {
			*dest++ = *src++;
		}

		if (*src == '\0')
			break;

		/* Skip '/' separator. */
		separator = *src++;
	}
	/*
	 * We've just copied zero or more path elements, not including the
	 * final '/'.
	 */
	if (dest == a->name) {
		/*
		 * Nothing got copied.  The path must have been something
		 * like '.' or '/' or './' or '/././././/./'.
		 */
		if (separator)
			*dest++ = '/';
		else
			*dest++ = '.';
	}
	/* Terminate the result. */
	*dest = '\0';
	return (ARCHIVE_OK);
}
// cleanup_pathname [c]
cleanup_pathname(struct archive_write_disk *a)
{
	char *dest, *src;
	char separator = '\0';

	dest = src = a->name;
	if (*src == '\0') {
		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
		    "Invalid empty pathname");
		return (ARCHIVE_FAILED);
	}

#if defined(__CYGWIN__)
	cleanup_pathname_win(a);
#endif
	/* Skip leading '/'. */
	if (*src == '/')
		separator = *src++;

	/* Scan the pathname one element at a time. */
	for (;;) {
		/* src points to first char after '/' */
		if (src[0] == '\0') {
			break;
		} else if (src[0] == '/') {
			/* Found '//', ignore second one. */
			src++;
			continue;
		} else if (src[0] == '.') {
			if (src[1] == '\0') {
				/* Ignore trailing '.' */
				break;
			} else if (src[1] == '/') {
				/* Skip './'. */
				src += 2;
				continue;
			} else if (src[1] == '.') {
				if (src[2] == '/' || src[2] == '\0') {
					/* Conditionally warn about '..' */
					if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
						archive_set_error(&a->archive,
						    ARCHIVE_ERRNO_MISC,
						    "Path contains '..'");
						return (ARCHIVE_FAILED);
					}
				}
				/*
				 * Note: Under no circumstances do we
				 * remove '..' elements.  In
				 * particular, restoring
				 * '/foo/../bar/' should create the
				 * 'foo' dir as a side-effect.
				 */
			}
		}

		/* Copy current element, including leading '/'. */
		if (separator)
			*dest++ = '/';
		while (*src != '\0' && *src != '/') {
			*dest++ = *src++;
		}

		if (*src == '\0')
			break;

		/* Skip '/' separator. */
		separator = *src++;
	}
	/*
	 * We've just copied zero or more path elements, not including the
	 * final '/'.
	 */
	if (dest == a->name) {
		/*
		 * Nothing got copied.  The path must have been something
		 * like '.' or '/' or './' or '/././././/./'.
		 */
		if (separator)
			*dest++ = '/';
		else
			*dest++ = '.';
	}
	/* Terminate the result. */
	*dest = '\0';
	return (ARCHIVE_OK);
}
// list [python]
    def list(self, keyfilter='/'):
        path = self._absolute_key(keyfilter)
        if path != '/':
            path = path.rstrip('/')
        try:
            result = self.etcd.read(path, recursive=True)
        except etcd.EtcdKeyNotFound:
            return None
        except etcd.EtcdException as err:
            log_error("Error listing %s: [%r]" % (keyfilter, repr(err)))
            raise CSStoreError('Error occurred while trying to list keys')

        value = set()
        for entry in result.get_subtree():
            if entry.key == path:
                continue
            name = entry.key[len(path):]
            if entry.dir and not name.endswith('/'):
                name += '/'
            value.add(name.lstrip('/'))
        return sorted(value)
// list [python]
    def list(self, keyfilter='/'):
        path = os.path.join(self.namespace, keyfilter)
        if path != '/':
            path = path.rstrip('/')
        try:
            result = self.etcd.read(path, recursive=True)
        except etcd.EtcdKeyNotFound:
            return None
        except etcd.EtcdException as err:
            log_error("Error listing %s: [%r]" % (keyfilter, repr(err)))
            raise CSStoreError('Error occurred while trying to list keys')

        value = set()
        for entry in result.get_subtree():
            if entry.key == path:
                continue
            name = entry.key[len(path):]
            if entry.dir and not name.endswith('/'):
                name += '/'
            value.add(name.lstrip('/'))
        return sorted(value)
// imap_hcache_open [c]
header_cache_t *imap_hcache_open(struct ImapData *idata, const char *path)
{
  struct ImapMbox mx;
  struct Url url;
  char cachepath[PATH_MAX];
  char mbox[PATH_MAX];

  if (path)
    imap_cachepath(idata, path, mbox, sizeof(mbox));
  else
  {
    if (!idata->ctx || imap_parse_path(idata->ctx->path, &mx) < 0)
      return NULL;

    imap_cachepath(idata, mx.mbox, mbox, sizeof(mbox));
    FREE(&mx.mbox);
  }

  if (strstr(mbox, "/../") || (strcmp(mbox, "..") == 0) || (strncmp(mbox, "../", 3) == 0))
    return NULL;
  size_t len = strlen(mbox);
  if ((len > 3) && (strcmp(mbox + len - 3, "/..") == 0))
    return NULL;

  mutt_account_tourl(&idata->conn->account, &url);
  url.path = mbox;
  url_tostring(&url, cachepath, sizeof(cachepath), U_PATH);

  return mutt_hcache_open(HeaderCache, cachepath, imap_hcache_namer);
}
// imap_hcache_open [c]
header_cache_t *imap_hcache_open(struct ImapData *idata, const char *path)
{
  struct ImapMbox mx;
  struct Url url;
  char cachepath[PATH_MAX];
  char mbox[PATH_MAX];

  if (path)
    imap_cachepath(idata, path, mbox, sizeof(mbox));
  else
  {
    if (!idata->ctx || imap_parse_path(idata->ctx->path, &mx) < 0)
      return NULL;

    imap_cachepath(idata, mx.mbox, mbox, sizeof(mbox));
    FREE(&mx.mbox);
  }

  mutt_account_tourl(&idata->conn->account, &url);
  url.path = mbox;
  url_tostring(&url, cachepath, sizeof(cachepath), U_PATH);

  return mutt_hcache_open(HeaderCache, cachepath, imap_hcache_namer);
}
// _normalize [python]
    def _normalize(self, metaerrors):
        """Normalize output format to be usable by Anaconda's linting frontend
        """

        errors = []
        for error in metaerrors:
            last_path = os.path.join(
                os.path.basename(os.path.dirname(self.filepath)),
                os.path.basename(self.filepath)
            )
            if last_path not in error.get('path', ''):
                continue

            error_type = error.get('severity', 'X').capitalize()[0]
            if error_type == 'X':
                continue
            if error_type not in ['E', 'W']:
                error_type = 'V'
            errors.append({
                'underline_range': True,
                'lineno': error.get('line', 0),
                'offset': error.get('col', 0),
                'raw_message': error.get('message', ''),
                'code': 0,
                'level': error_type,
                'message': '[{0}] {1} ({2}): {3}'.format(
                    error_type,
                    error.get('linter', 'none'),
                    error.get('severity', 'none'),
                    error.get('message')
                )
            })

        return errors
// _normalize [python]
    def _normalize(self, metaerrors):
        """Normalize output format to be usable by Anaconda's linting frontend
        """

        errors = []
        for error in metaerrors:
            if self.filepath not in error.get('path', ''):
                continue

            error_type = error.get('severity', 'X').capitalize()[0]
            if error_type == 'X':
                continue
            if error_type not in ['E', 'W']:
                error_type = 'V'
            errors.append({
                'underline_range': True,
                'lineno': error.get('line', 0),
                'offset': error.get('col', 0),
                'raw_message': error.get('message', ''),
                'code': 0,
                'level': error_type,
                'message': '[{0}] {1} ({2}): {3}'.format(
                    error_type,
                    error.get('linter', 'none'),
                    error.get('severity', 'none'),
                    error.get('message')
                )
            })

        return errors
// dd_load_text_ext [c]
char* dd_load_text_ext(const struct dump_dir *dd, const char *name, unsigned flags)
{
//    if (!dd->locked)
//        error_msg_and_die("dump_dir is not opened"); /* bug */

    if (!str_is_correct_filename(name))
    {
        error_msg("Cannot load text. '%s' is not a valid file name", name);
        if (!(flags & DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE))
            xfunc_die();
    }

    /* Compat with old abrt dumps. Remove in abrt-2.1 */
    if (strcmp(name, "release") == 0)
        name = FILENAME_OS_RELEASE;

    char *full_path = concat_path_file(dd->dd_dirname, name);
    char *ret = load_text_file(full_path, flags);
    free(full_path);

    return ret;
}
// dd_load_text_ext [c]
char* dd_load_text_ext(const struct dump_dir *dd, const char *name, unsigned flags)
{
//    if (!dd->locked)
//        error_msg_and_die("dump_dir is not opened"); /* bug */

    /* Compat with old abrt dumps. Remove in abrt-2.1 */
    if (strcmp(name, "release") == 0)
        name = FILENAME_OS_RELEASE;

    char *full_path = concat_path_file(dd->dd_dirname, name);
    char *ret = load_text_file(full_path, flags);
    free(full_path);

    return ret;
}
// _download_file [python]
    @staticmethod
    def _download_file(bucket, filename, local_dir):
        key = bucket.get_key(filename)
        local_filename = os.path.join(local_dir, os.path.basename(filename))
        key.get_contents_to_filename(local_filename)
        return local_filename
// _download_file [python]
    @staticmethod
    def _download_file(bucket, filename, local_dir):
        key = bucket.get_key(filename)
        local_filename = os.path.join(local_dir, filename)
        key.get_contents_to_filename(local_filename)
        return local_filename
// save [python]
async def save(request):
    # TODO csrf
    data = await request.post()
    item = Item(data['src'])

    # Update name
    new_src = data.get('new_src')
    if new_src:
        new_abspath = os.path.abspath(settings.STORAGE_DIR + new_src)
        if not new_abspath.startswith(settings.STORAGE_DIR):
            return web.Response(status=400, body=b'Invalid Request')

        if new_abspath != item.abspath:
            shutil.move(item.abspath, new_abspath)
            old_backup_abspath = item.backup_abspath
            item = Item(new_src)
            if os.path.isfile(old_backup_abspath):
                shutil.move(old_backup_abspath, item.backup_abspath)

    # Update meta
    for field in item.FORM:
        # TODO handle .repeatable (keywords)
        item.meta[field] = [data.get(field, '')]

    if settings.SAVE_ORIGINALS and not os.path.isfile(item.backup_abspath):
        shutil.copyfile(item.abspath, item.backup_abspath)

    # WISHLIST don't write() if nothing changed
    item.meta.write()

    return web.Response(
        status=200,
        body=json.dumps(item.get_form_fields()).encode('utf8'),
        content_type='application/json',
    )
// save [python]
async def save(request):
    # TODO csrf
    data = await request.post()
    item = Item(data['src'])

    # Update name
    new_src = data.get('new_src')
    if new_src and new_src != data['src']:
        # don't need to worry about html unquote
        shutil.move(item.abspath, settings.STORAGE_DIR + new_src)
        old_backup_abspath = item.backup_abspath
        item = Item(new_src)
        if os.path.isfile(old_backup_abspath):
            shutil.move(old_backup_abspath, item.backup_abspath)

    # Update meta
    for field in item.FORM:
        # TODO handle .repeatable (keywords)
        item.meta[field] = [data.get(field, '')]

    if settings.SAVE_ORIGINALS and not os.path.isfile(item.backup_abspath):
        shutil.copyfile(item.abspath, item.backup_abspath)

    # WISHLIST don't write() if nothing changed
    item.meta.write()

    return web.Response(
        status=200,
        body=json.dumps(item.get_form_fields()).encode('utf8'),
        content_type='application/json',
    )
// wiki_handle_rest_call [c]
wiki_handle_rest_call(HttpRequest  *req, 
		      HttpResponse *res,
		      char         *func)
{

  if (func != NULL && *func != '\0')
    {
      if (!strcmp(func, "page/get"))
	{
	  char *page = http_request_param_get(req, "page");

	  if (page == NULL)
	    page = http_request_get_query_string(req);

	  if (page && page_name_is_good(page) && (access(page, R_OK) == 0))
	    {
	      http_response_printf(res, "%s", file_read(page));
	      http_response_send(res);
	      return;
	    }  
	}
      else if (!strcmp(func, "page/set"))
	{
	  char *wikitext = NULL, *page = NULL;
	  if( ( (wikitext = http_request_param_get(req, "text")) != NULL)
	      && ( (page = http_request_param_get(req, "page")) != NULL))
	    {
	  if (page_name_is_good(page))
	    {
	      file_write(page, wikitext);
	      http_response_printf(res, "success");
	      http_response_send(res);
	      return;
	    }
	    }
	}
      else if (!strcmp(func, "page/delete"))
	{
	  char *page = http_request_param_get(req, "page");

	  if (page == NULL)
	    page = http_request_get_query_string(req);

	  if (page && page_name_is_good(page) && (unlink(page) > 0))
	    {
	      http_response_printf(res, "success");
	      http_response_send(res);
	      return;  
	    }
	}
      else if (!strcmp(func, "page/exists"))
	{
	  char *page = http_request_param_get(req, "page");

	  if (page == NULL)
	    page = http_request_get_query_string(req);

	  if (page && page_name_is_good(page) && (access(page, R_OK) == 0))
	    {
	      http_response_printf(res, "success");
	      http_response_send(res);
	      return;  
	    }
	}
      else if (!strcmp(func, "pages") || !strcmp(func, "search"))
	{
	  WikiPageList **pages = NULL;
	  int            n_pages, i;
	  char          *expr = http_request_param_get(req, "expr");

	  if (expr == NULL)
	    expr = http_request_get_query_string(req);
	  
	  pages = wiki_get_pages(&n_pages, expr);

	  if (pages)
	    {
	      for (i=0; i<n_pages; i++)
		{
		  struct tm   *pTm;
		  char   datebuf[64];
		  
		  pTm = localtime(&pages[i]->mtime);
		  strftime(datebuf, sizeof(datebuf), "%Y-%m-%d %H:%M", pTm);
		  http_response_printf(res, "%s\t%s\n", pages[i]->name, datebuf);
		}

	      http_response_send(res);
	      return;  
	    }
	}
    }

  http_response_set_status(res, 500, "Error");
  http_response_printf(res, "<html><body>Failed</body></html>\n");
  http_response_send(res);

  return;  
}
// wiki_handle_rest_call [c]
wiki_handle_rest_call(HttpRequest  *req, 
		      HttpResponse *res,
		      char         *func)
{

  if (func != NULL && *func != '\0')
    {
      if (!strcmp(func, "page/get"))
	{
	  char *page = http_request_param_get(req, "page");

	  if (page == NULL)
	    page = http_request_get_query_string(req);

	  if (page && (access(page, R_OK) == 0)) 
	    {
	      http_response_printf(res, "%s", file_read(page));
	      http_response_send(res);
	      return;
	    }  
	}
      else if (!strcmp(func, "page/set"))
	{
	  char *wikitext = NULL, *page = NULL;
	  if( ( (wikitext = http_request_param_get(req, "text")) != NULL)
	      && ( (page = http_request_param_get(req, "page")) != NULL))
	    {
	      file_write(page, wikitext);	      
	      http_response_printf(res, "success");
	      http_response_send(res);
	      return;
	    }
	}
      else if (!strcmp(func, "page/delete"))
	{
	  char *page = http_request_param_get(req, "page");

	  if (page == NULL)
	    page = http_request_get_query_string(req);

	  if (page && (unlink(page) > 0))
	    {
	      http_response_printf(res, "success");
	      http_response_send(res);
	      return;  
	    }
	}
      else if (!strcmp(func, "page/exists"))
	{
	  char *page = http_request_param_get(req, "page");

	  if (page == NULL)
	    page = http_request_get_query_string(req);

	  if (page && (access(page, R_OK) == 0)) 
	    {
	      http_response_printf(res, "success");
	      http_response_send(res);
	      return;  
	    }
	}
      else if (!strcmp(func, "pages") || !strcmp(func, "search"))
	{
	  WikiPageList **pages = NULL;
	  int            n_pages, i;
	  char          *expr = http_request_param_get(req, "expr");

	  if (expr == NULL)
	    expr = http_request_get_query_string(req);
	  
	  pages = wiki_get_pages(&n_pages, expr);

	  if (pages)
	    {
	      for (i=0; i<n_pages; i++)
		{
		  struct tm   *pTm;
		  char   datebuf[64];
		  
		  pTm = localtime(&pages[i]->mtime);
		  strftime(datebuf, sizeof(datebuf), "%Y-%m-%d %H:%M", pTm);
		  http_response_printf(res, "%s\t%s\n", pages[i]->name, datebuf);
		}

	      http_response_send(res);
	      return;  
	    }
	}
    }

  http_response_set_status(res, 500, "Error");
  http_response_printf(res, "<html><body>Failed</body></html>\n");
  http_response_send(res);

  return;  
}
// HPHP::extractFileTo [cpp]
static bool extractFileTo(zip* zip, const std::string &file, std::string& to,
                          char* buf, size_t len) {

  struct zip_stat zipStat;
  // Verify the file to be extracted is actually in the zip file
  if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {
    return false;
  }

  auto clean_file = file;
  auto sep = std::string::npos;
  // Normally would just use std::string::rfind here, but if we want to be
  // consistent between Windows and Linux, even if techincally Linux won't use
  // backslash for a separator, we are checking for both types.
  int idx = file.length() - 1;
  while (idx >= 0) {
    if (FileUtil::isDirSeparator(file[idx])) {
      sep = idx;
      break;
    }
    idx--;
  }
  if (sep != std::string::npos) {
    // make_relative_path so we do not try to put files or dirs in bad
    // places. This securely "cleans" the file.
    clean_file = make_relative_path(file);
    std::string path = to + clean_file;
    bool is_dir_only = true;
    if (sep < file.length() - 1) { // not just a directory
      auto clean_file_dir = HHVM_FN(dirname)(clean_file);
      path = to + clean_file_dir.toCppString();
      is_dir_only = false;
    }

    // Make sure the directory path to extract to exists or can be created
    if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) {
      return false;
    }

    // If we have a good directory to extract to above, we now check whether
    // the "file" parameter passed in is a directory or actually a file.
    if (is_dir_only) { // directory, like /usr/bin/
      return true;
    }
    // otherwise file is actually a file, so we actually extract.
  }

  // We have ensured that clean_file will be added to a relative path by the
  // time we get here.
  to.append(clean_file);

  auto zipFile = zip_fopen_index(zip, zipStat.index, 0);
  FAIL_IF_INVALID_PTR(zipFile);

  auto outFile = fopen(to.c_str(), "wb");
  if (outFile == nullptr) {
    zip_fclose(zipFile);
    return false;
  }

  for (auto n = zip_fread(zipFile, buf, len); n != 0;
       n = zip_fread(zipFile, buf, len)) {
    if (n < 0 || fwrite(buf, sizeof(char), n, outFile) != n) {
      zip_fclose(zipFile);
      fclose(outFile);
      remove(to.c_str());
      return false;
    }
  }

  zip_fclose(zipFile);
  if (fclose(outFile) != 0) {
    return false;
  }

  return true;
}
// HPHP::extractFileTo [cpp]
static bool extractFileTo(zip* zip, const std::string &file, std::string& to,
                          char* buf, size_t len) {
  auto sep = file.rfind('/');
  if (sep != std::string::npos) {
    auto path = to + file.substr(0, sep);
    if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) {
      return false;
    }

    if (sep == file.length() - 1) {
      return true;
    }
  }

  to.append(file);
  struct zip_stat zipStat;
  if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {
    return false;
  }

  auto zipFile = zip_fopen_index(zip, zipStat.index, 0);
  FAIL_IF_INVALID_PTR(zipFile);

  auto outFile = fopen(to.c_str(), "wb");
  if (outFile == nullptr) {
    zip_fclose(zipFile);
    return false;
  }

  for (auto n = zip_fread(zipFile, buf, len); n != 0;
       n = zip_fread(zipFile, buf, len)) {
    if (n < 0 || fwrite(buf, sizeof(char), n, outFile) != n) {
      zip_fclose(zipFile);
      fclose(outFile);
      remove(to.c_str());
      return false;
    }
  }

  zip_fclose(zipFile);
  if (fclose(outFile) != 0) {
    return false;
  }

  return true;
}
// new_goal [python]
def new_goal():
    """
    new goal
    """

    goals_dir_check()

    goal_name_not_ok = True

    click.echo(chalk.blue('Input a single-word name of the goal:'))
    while goal_name_not_ok:
        goal_name = input().strip()
        if goal_name.isalnum():
            goal_name_not_ok = False
        else:
            click.echo(chalk.red('Only alphanumeric characters can be used! Please input the goal name:'))

    if goal_name_exists(goal_name):
        click.echo(chalk.red(
            'A goal with this name already exists. Please type "yoda goals view" to see a list of existing goals'))
    else:
        click.echo(chalk.blue('Input description of the goal:'))
        text = input().strip()

        click.echo(chalk.blue('Input due date for the goal (YYYY-MM-DD):'))
        incorrect_date_format = True
        while incorrect_date_format:
            deadline = input().strip()
            try:
                date_str = datetime.datetime.strptime(deadline, '%Y-%m-%d').strftime('%Y-%m-%d')
                if date_str != deadline:
                    raise ValueError
                incorrect_date_format = False
            except ValueError:
                click.echo(chalk.red("Incorrect data format, should be YYYY-MM-DD. Please repeat:"))

        if os.path.isfile(GOALS_CONFIG_FILE_PATH):
            setup_data = dict(
                name=goal_name,
                text=text,
                deadline=deadline,
                status=0
            )
            append_data_into_file(setup_data, GOALS_CONFIG_FILE_PATH)
        else:
            setup_data = dict(
                entries=[
                    dict(
                        name=goal_name,
                        text=text,
                        deadline=deadline,
                        status=0
                    )
                ]
            )
            input_data(setup_data, GOALS_CONFIG_FILE_PATH)

        input_data(dict(entries=[]), get_goal_file_path(goal_name))
// new_goal [python]
def new_goal():
    """
    new goal
    """

    goals_dir_check()

    click.echo(chalk.blue('Input a single-word name of the goal:'))
    goal_name = input().strip()

    if goal_name_exists(goal_name):
        click.echo(chalk.red(
            'A goal with this name already exists. Please type "yoda goals view" to see a list of existing goals'))
    else:
        click.echo(chalk.blue('Input description of the goal:'))
        text = input().strip()

        click.echo(chalk.blue('Input due date for the goal (YYYY-MM-DD):'))
        deadline = input().strip()

        if os.path.isfile(GOALS_CONFIG_FILE_PATH):
            setup_data = dict(
                name=goal_name,
                text=text,
                deadline=deadline,
                status=0
            )
            append_data_into_file(setup_data, GOALS_CONFIG_FILE_PATH)
        else:
            setup_data = dict(
                entries=[
                    dict(
                        name=goal_name,
                        text=text,
                        deadline=deadline,
                        status=0
                    )
                ]
            )
            input_data(setup_data, GOALS_CONFIG_FILE_PATH)

        input_data(dict(entries=[]), get_goal_file_path(goal_name))
// _inject_admin_password_into_fs [python]
def _inject_admin_password_into_fs(admin_passwd, fs, execute=None):
    """Set the root password to admin_passwd

    admin_password is a root password
    fs is the path to the base of the filesystem into which to inject
    the key.

    This method modifies the instance filesystem directly,
    and does not require a guest agent running in the instance.

    """
    # The approach used here is to copy the password and shadow
    # files from the instance filesystem to local files, make any
    # necessary changes, and then copy them back.

    admin_user = 'root'

    fd, tmp_passwd = tempfile.mkstemp()
    os.close(fd)
    fd, tmp_shadow = tempfile.mkstemp()
    os.close(fd)

    passwd_path = _join_and_check_path_within_fs(fs, 'etc', 'passwd')
    shadow_path = _join_and_check_path_within_fs(fs, 'etc', 'shadow')

    utils.execute('cp', passwd_path, tmp_passwd, run_as_root=True)
    utils.execute('cp', shadow_path, tmp_shadow, run_as_root=True)
    _set_passwd(admin_user, admin_passwd, tmp_passwd, tmp_shadow)
    utils.execute('cp', tmp_passwd, passwd_path, run_as_root=True)
    os.unlink(tmp_passwd)
    utils.execute('cp', tmp_shadow, shadow_path, run_as_root=True)
    os.unlink(tmp_shadow)
// _inject_admin_password_into_fs [python]
def _inject_admin_password_into_fs(admin_passwd, fs, execute=None):
    """Set the root password to admin_passwd

    admin_password is a root password
    fs is the path to the base of the filesystem into which to inject
    the key.

    This method modifies the instance filesystem directly,
    and does not require a guest agent running in the instance.

    """
    # The approach used here is to copy the password and shadow
    # files from the instance filesystem to local files, make any
    # necessary changes, and then copy them back.

    admin_user = 'root'

    fd, tmp_passwd = tempfile.mkstemp()
    os.close(fd)
    fd, tmp_shadow = tempfile.mkstemp()
    os.close(fd)

    utils.execute('cp', os.path.join(fs, 'etc', 'passwd'), tmp_passwd,
                  run_as_root=True)
    utils.execute('cp', os.path.join(fs, 'etc', 'shadow'), tmp_shadow,
                  run_as_root=True)
    _set_passwd(admin_user, admin_passwd, tmp_passwd, tmp_shadow)
    utils.execute('cp', tmp_passwd, os.path.join(fs, 'etc', 'passwd'),
                  run_as_root=True)
    os.unlink(tmp_passwd)
    utils.execute('cp', tmp_shadow, os.path.join(fs, 'etc', 'shadow'),
                  run_as_root=True)
    os.unlink(tmp_shadow)