jiahuimbzuai/CoQuIR huggingface dataset:
// _singleton_init [python]
    def _singleton_init(self, configuration = None):
        super(ApplicationConfiguration, self)._singleton_init()
        self.log = logging.getLogger('%s.%s' % (__name__, self.__class__.__name__))
        self.jeos_images = { }

        if configuration != None:
            if not isinstance(configuration, dict):
                raise Exception("ApplicationConfiguration configuration argument must be a dict")
            self.log.debug("ApplicationConfiguration passed a dictionary - ignoring any local config files including JEOS configs")
            self.configuration = configuration
        else:
            self.configuration = self.__parse_arguments()
            self.__parse_jeos_images()

        if not 'debug' in self.configuration:
            if 'nodebug' in self.configuration:
                # Slightly confusing, I know - For daemon mode we have a debug argument with default False
                # For cli, we debug by default and have a nodebug argument with default False
                # Rest of the code assumes a 'debug' value in app_config so set it here
                self.configuration['debug'] = not self.configuration['nodebug']
            else:
                # This most likely means we are being used as a module/library and are not running CLI or daemon
                self.configuration['debug'] = False

        if not 'secondary' in self.configuration:
            # We use this in the non-daemon context so it needs to be set
            # TODO: Something cleaner?
            self.configuration['secondary'] = False
// send_file [python]
@app.route('/output_files/<path:filename>', methods = ['GET', 'OPTIONS'])
def send_file(filename):
  filename = secure_filename(filename)
  if not controller:
    return createCrossOriginResponse(
        status=403, body='Instance already shut down!')
  elif controller.is_vod():
    # If streaming mode is vod, needs to wait until packager is completely
    # done packaging contents.
    while True:
      status = controller.check_status()
      if status == node_base.ProcessStatus.Finished:
        break
      elif status != node_base.ProcessStatus.Running:
        return createCrossOriginResponse(
            status=500, body='Some processes exited with non-zero exit codes')

      time.sleep(1)
  else:
    # If streaming mode is live, needs to wait for specific content in
    # manifest until it can be loaded by the player.
    if filename.endswith('.mpd'):
      while not dashStreamsReady(OUTPUT_DIR + filename):
        time.sleep(1)
    elif filename.endswith('.m3u8') and not filename.startswith('stream_'):
      while not hlsStreamsReady(OUTPUT_DIR + filename):
        time.sleep(1)

  # Sending over requested files.
  try:
    response = flask.send_file(OUTPUT_DIR + filename)
  except FileNotFoundError:
    response = flask.Response(response='File not found', status=404)

  response.headers.add('Access-Control-Allow-Origin', '*')
  response.headers.add('Access-Control-Allow-Headers', 'RANGE')
  return response
// send_file [python]
@app.route('/output_files/<path:filename>', methods = ['GET', 'OPTIONS'])
def send_file(filename):
  if not controller:
    return createCrossOriginResponse(
        status=403, body='Instance already shut down!')
  elif controller.is_vod():
    # If streaming mode is vod, needs to wait until packager is completely
    # done packaging contents.
    while True:
      status = controller.check_status()
      if status == node_base.ProcessStatus.Finished:
        break
      elif status != node_base.ProcessStatus.Running:
        return createCrossOriginResponse(
            status=500, body='Some processes exited with non-zero exit codes')

      time.sleep(1)
  else:
    # If streaming mode is live, needs to wait for specific content in
    # manifest until it can be loaded by the player.
    if filename.endswith('.mpd'):
      while not dashStreamsReady(OUTPUT_DIR + filename):
        time.sleep(1)
    elif filename.endswith('.m3u8') and not filename.startswith('stream_'):
      while not hlsStreamsReady(OUTPUT_DIR + filename):
        time.sleep(1)

  # Sending over requested files.
  try:
    response = flask.send_file(OUTPUT_DIR + filename)
  except FileNotFoundError:
    response = flask.Response(response='File not found', status=404)

  response.headers.add('Access-Control-Allow-Origin', '*')
  response.headers.add('Access-Control-Allow-Headers', 'RANGE')
  return response
// copy_over [python]
def copy_over(source, dest):
    """
    Copies from the source to the destination, removing the destination
    if it exists and is a directory.
    """
    if os.path.exists(dest) and os.path.isdir(dest):
        shutil.rmtree(dest)
    shutil.copytree(force_bytes(source), force_bytes(dest))
    # mkdtemp will set the directory permissions to 700
    # for the webserver to read them, we need 755
    os.chmod(dest, stat.S_IRWXU | stat.S_IRGRP |
             stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
    shutil.rmtree(source)
// copy_over [python]
def copy_over(source, dest):
    """
    Copies from the source to the destination, removing the destination
    if it exists and is a directory.
    """
    if os.path.exists(dest) and os.path.isdir(dest):
        shutil.rmtree(dest)
    shutil.copytree(source, dest)
    # mkdtemp will set the directory permissions to 700
    # for the webserver to read them, we need 755
    os.chmod(dest, stat.S_IRWXU | stat.S_IRGRP |
             stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
    shutil.rmtree(source)
// testAllConditionalPaths [python]
  def testAllConditionalPaths(self):
    """Enable all paths to get line coverage."""
    self.build_config['vm_tests'] = constants.SIMPLE_AU_TEST_TYPE
    self.options.tests = True
    self.build_config['build_type'] = constants.BUILD_FROM_SOURCE_TYPE
    self.build_config['build_tests'] = True
    self.build_config['archive_build_debug'] = True
    self.build_config['usepkg_chroot'] = True
    self.build_config['usepkg_setup_board'] = True
    self.build_config['usepkg_build_packages'] = True
    self.build_config['images'] = ['base', 'dev', 'test', 'factory_test',
                                   'factory_install']
    self.build_config['useflags'] = ['ALPHA', 'BRAVO', 'CHARLIE']
    self.build_config['skip_toolchain_update'] = False
    self.build_config['nowithdebug'] = False
    self.build_config['hw_tests'] = ['bvt']
    self.build_config['chromeos_official'] = True

    proper_env = {'USE' : ' '.join(self.build_config['useflags'])}

    # Convenience variables.
    fake_autotest_dir = '/fake/autotest'
    autotest_tarball_name = 'autotest.tar'
    full_autotest_tarball_name = 'autotest.tar.bz2'
    test_suites_tarball_name = 'test_suites.tar.bz2'
    autotest_tarball_path = os.path.join(fake_autotest_dir,
                                         autotest_tarball_name)
    full_autotest_tarball_path = os.path.join(fake_autotest_dir,
                                              full_autotest_tarball_name)
    test_suites_tarball_path = os.path.join(fake_autotest_dir,
                                            test_suites_tarball_name)
    tarballs = [autotest_tarball_path, test_suites_tarball_path]
    full_autotest_tarball = full_autotest_tarball_path

    commands.Build(self.build_root,
                   self._current_board,
                   build_autotest=True,
                   usepkg=True,
                   skip_toolchain_update=False,
                   nowithdebug=False,
                   extra_env=proper_env)

    commands.BuildImage(self.build_root, self._current_board,
                        ['test', 'base', 'dev'], version=self.version,
                        root_boost=None, extra_env=proper_env)
    commands.BuildVMImageForTesting(self.build_root, self._current_board,
                                    extra_env=proper_env)
    tempfile.mkdtemp(prefix='autotest').AndReturn(fake_autotest_dir)
    commands.BuildAutotestTarballs(self.build_root, self._current_board,
                                   fake_autotest_dir).AndReturn(tarballs)
    commands.BuildFullAutotestTarball(self.build_root,
                                      self._current_board,
                                      fake_autotest_dir
                                      ).AndReturn(full_autotest_tarball)
    self.archive_stage_mock.AutotestTarballsReady(tarballs)
    self.archive_stage_mock.FullAutotestTarballReady(full_autotest_tarball)
    os.path.isdir(self.latest_cbuildbot).AndReturn(True)
    self.archive_stage_mock.SetVersion(self.version)

    self.mox.ReplayAll()
    self.RunStage()
    self.mox.VerifyAll()
// git_file_info [ruby]
    def git_file_info(path)
      return '  ✓ '.colorize(@colors[:unchanged]) unless @git_status[path]
      Git.colored_status_symbols(@git_status[path].uniq, @colors)
    end
// git_file_info [ruby]
    def git_file_info(path)
      return '  ✓ '.colorize(@colors[:unchanged]) unless @git_status[path]
      Git.colored_status_symbols(@git_status[path], @colors)
    end
// git_dir_info [ruby]
    def git_dir_info(path)
      direct_status = @git_status.fetch("#{path}/", nil)

      return Git.colored_status_symbols(direct_status.uniq, @colors) unless direct_status.nil?

      modes = @git_status.select { |file, mode| file.start_with?(path) && mode != '!!' }

      return '  ✓ '.colorize(@colors[:unchanged]) if modes.empty?

      Git.colored_status_symbols(modes.values.join.uniq, @colors)
    end
// git_dir_info [ruby]
    def git_dir_info(path)
      ignored = @git_status.select { |file, mode| file.start_with?(path) && mode=='!!' }.keys
      present = Dir.deep_entries(path).map { |p| "#{path}/#{p}" }
      return '    ' if (present-ignored).empty?

      modes = (present-ignored).map { |file| @git_status[file] }-[nil]
      return '  ✓ '.colorize(@colors[:unchanged]) if modes.empty?
      Git.colored_status_symbols(modes.join.uniq, @colors)
    end
// git_info [ruby]
    def git_info(path, content)
      return '' unless @git_status

      real_path = File.realdirpath(content.name, path)

      return '    ' unless real_path.start_with? path

      relative_path = real_path.remove(Regexp.new('^' + Regexp.escape(@git_root_path) + '/?'))

      if content.directory?
        git_dir_info(relative_path)
      else
        git_file_info(relative_path)
      end
      # puts "\n\n"
    end
// git_info [ruby]
    def git_info(path, content)
      return '' unless @git_status

      # puts "\n\n"

      relative_path = path.remove(@git_root_path+'/')
      relative_path = relative_path==path ? '' : relative_path+'/'
      content_path  = "#{relative_path}#{content}"

      if content.directory?
        git_dir_info(content_path)
      else
        git_file_info(content_path)
      end
      # puts "\n\n"
    end
// self.status [ruby]
    def self.status(repo_path)
      @git_status = {}

      IO.popen(['git', '-C', repo_path, 'status', '--porcelain', '-z', '-unormal', '--ignored']) do |output|
        output.read.split("\x0").map { |x| x.split(' ', 2) }.each do |mode, file|
          @git_status[file] = mode
        end
      end
      warn "git status failed in #{repo_path}" unless $CHILD_STATUS.success?

      @git_status
    end
// self.status [ruby]
    def self.status(repo_path)
      @git_status = {}

      IO.popen(['git', '-C', repo_path, 'status', '--porcelain', '-z', '-uall', '--ignored']) do |output|
        output.read.split("\x0").map { |x| x.split(' ', 2) }.each do |mode, file|
          @git_status[file] = mode
        end
      end
      warn "git status failed in #{repo_path}" unless $CHILD_STATUS.success?

      @git_status
    end
// get_git_branch [c]
get_git_branch(wchar_t *dst, size_t size)
{
	FILE *fp;
	char *c;
	char pwd[MAXPATHLEN];
	char candidate[MAXPATHLEN];
	char buf[MAX_BRANCH_LEN];
	size_t s;
	struct stat bufstat;
	int found_repo = -1;

	/* start from the working dir */
	strlcpy(pwd, getcwd(NULL, MAXPATHLEN), MAXPATHLEN);

	do {
		snprintf(candidate, MAXPATHLEN, "%s/.git/HEAD", pwd);

		found_repo = stat(candidate, &bufstat);

		if ((c = strrchr(pwd, '/')) == NULL)
			break;

		*c = '\0';
	} while (found_repo != 0 && candidate[1] != '\0');

	if (found_repo == -1)
		return 0;

	fp = fopen(candidate, "r");
	if (fp == NULL) {
		strlcpy(buf, "###", 4);
		return mbstowcs(dst, buf, MAX_BRANCH_LEN);
	}

	s = fread(buf, 1, size, fp);
	fclose(fp);

	buf[MAX_BRANCH_LEN - 1] = '\0';

	/* This is a branch head, just print the branch. */
	if (strncmp(buf, "ref: refs/heads/", 16) == 0) {
		char *nl = strchr(buf, '\n');
		if (nl)
			*(nl) = '\0';
		c = buf + 16;
		return mbstowcs(dst, c, MAX_BRANCH_LEN);
	}

	/* Show all other kinds of ref as-is (does it even exist?) */
	if (strncmp(buf, "ref:", 4) == 0) {
		char *nl = strchr(buf, '\n');
		if (nl) 
			*(nl) = '\0';
		c = buf + 5;
		return mbstowcs(dst, c, MAX_BRANCH_LEN);
	}

	/* That's probably just a changeset, just show the first 6 chars */
	if (s > 6) {
		strlcpy(buf + 6, "...", 4);
		return mbstowcs(dst, buf, MAX_BRANCH_LEN);
	}

	/* We shouldn't get there, but we mind as well no crash. */
	strlcpy(buf, "???", 4);
	return mbstowcs(dst, buf, MAX_BRANCH_LEN);
}
// get_git_branch [c]
get_git_branch(wchar_t *dst, size_t size)
{
	FILE *fp;
	char *c;
	char pwd[MAXPATHLEN];
	char candidate[MAXPATHLEN];
	char buf[MAX_BRANCH_LEN];
	size_t s;
	struct stat bufstat;
	int found_repo = -1;

	/* start from the working dir */
	strlcpy(pwd, getcwd(NULL, MAXPATHLEN), MAXPATHLEN);

	do {
		snprintf(candidate, MAXPATHLEN, "%s/.git/HEAD", pwd);

		found_repo = stat(candidate, &bufstat);

		if ((c = strrchr(pwd, '/')) == NULL)
			break;

		*c = '\0';
	} while (found_repo != 0 && candidate[1] != '\0');

	if (found_repo == -1)
		return 0;

	fp = fopen(candidate, "r");
	if (fp == NULL) {
		strlcpy(buf, "###", 4);
		return mbstowcs(dst, buf, MAX_BRANCH_LEN);
	}

	s = fread(buf, 1, size, fp);
	fclose(fp);

	buf[MAX_BRANCH_LEN] = '\0';

	/* This is a branch head, just print the branch. */
	if (strncmp(buf, "ref: refs/heads/", 16) == 0) {
		char *nl = strchr(buf, '\n');
		if (nl)
			*(nl) = '\0';
		c = buf + 16;
		return mbstowcs(dst, c, MAX_BRANCH_LEN);
	}

	/* Show all other kinds of ref as-is (does it even exist?) */
	if (strncmp(buf, "ref:", 4) == 0) {
		char *nl = strchr(buf, '\n');
		if (nl) 
			*(nl) = '\0';
		c = buf + 5;
		return mbstowcs(dst, c, MAX_BRANCH_LEN);
	}

	/* That's probably just a changeset, just show the first 6 chars */
	if (s > 6) {
		strlcpy(buf + 6, "...", 4);
		return mbstowcs(dst, buf, MAX_BRANCH_LEN);
	}

	/* We shouldn't get there, but we mind as well no crash. */
	strlcpy(buf, "???", 4);
	return mbstowcs(dst, buf, MAX_BRANCH_LEN);
}
// lcbio_cache_local_name [cpp]
static void lcbio_cache_local_name(lcbio_CONNINFO *sock)
{
    switch (sock->sa_local.ss_family) {
        case AF_INET: {
            auto *addr = (struct sockaddr_in *)&sock->sa_local;
            inet_ntop(AF_INET, &(addr->sin_addr), sock->ep_local, sizeof(sock->ep_local));
            strncpy(sock->ep_local2.host, sock->ep_local, sizeof(sock->ep_local2.host));
            snprintf(sock->ep_local2.port, sizeof(sock->ep_local2.port), "%d", (int)ntohs(addr->sin_port));
            size_t len = strlen(sock->ep_local);
            snprintf(sock->ep_local + len, sizeof(sock->ep_local) - len, ":%d", (int)ntohs(addr->sin_port));
        } break;

        case AF_INET6: {
            auto *addr = (struct sockaddr_in6 *)&sock->sa_local;
            inet_ntop(AF_INET6, &(addr->sin6_addr), sock->ep_local, sizeof(sock->ep_local));
            strncpy(sock->ep_local2.host, sock->ep_local, sizeof(sock->ep_local2.host));
            snprintf(sock->ep_local2.port, sizeof(sock->ep_local2.port), "%d", (int)ntohs(addr->sin6_port));
            size_t len = strlen(sock->ep_local);
            snprintf(sock->ep_local + len, sizeof(sock->ep_local) - len, ":%d", (int)ntohs(addr->sin6_port));
        } break;
    }
}
// lcbio_cache_local_name [cpp]
static void lcbio_cache_local_name(lcbio_CONNINFO *sock)
{
    switch (sock->sa_local.ss_family) {
        case AF_INET: {
            auto *addr = (struct sockaddr_in *)&sock->sa_local;
            inet_ntop(AF_INET, &(addr->sin_addr), sock->ep_local, sizeof(sock->ep_local));
            size_t len = strlen(sock->ep_local);
            strcpy(sock->ep_local2.host, sock->ep_local);
            snprintf(sock->ep_local2.port, sizeof(sock->ep_local2), "%d", (int)ntohs(addr->sin_port));
            snprintf(sock->ep_local + len, sizeof(sock->ep_local) - len, ":%d", (int)ntohs(addr->sin_port));
        } break;

        case AF_INET6: {
            auto *addr = (struct sockaddr_in6 *)&sock->sa_local;
            inet_ntop(AF_INET6, &(addr->sin6_addr), sock->ep_local, sizeof(sock->ep_local));
            size_t len = strlen(sock->ep_local);
            strcpy(sock->ep_local2.host, sock->ep_local);
            snprintf(sock->ep_local2.port, sizeof(sock->ep_local2), "%d", (int)ntohs(addr->sin6_port));
            snprintf(sock->ep_local + len, sizeof(sock->ep_local) - len, ":%d", (int)ntohs(addr->sin6_port));
        } break;
    }
}
// set_eeprom_serial_number [c]
set_eeprom_serial_number (EEPROM_HDR *e, char *sn)
{
  strncpy (e->serial, sn, 12);
  _dirty = 1;

  return 0;
}
// set_eeprom_serial_number [c]
set_eeprom_serial_number (EEPROM_HDR *e, char *sn)
{
  strncpy (e->serial, sn, 16);
  _dirty = 1;

  return 0;
}
// pdf_add_bookmark [c]
int pdf_add_bookmark(struct pdf_doc *pdf, struct pdf_object *page,
        const char *name)
{
    struct pdf_object *obj = pdf_add_object(pdf, OBJ_bookmark);
    if (!obj)
        return pdf_set_err(pdf, -ENOMEM, "Insufficient memory");

    if (!page)
        page = pdf->last_objects[OBJ_page];

    if (!page)
        return pdf_set_err(pdf, -EINVAL,
                "Unable to add bookmark, no pages available\n");

    strncpy(obj->bookmark.name, name, sizeof(obj->bookmark.name));
    obj->bookmark.name[sizeof(obj->bookmark.name) - 1] = '\0';
    obj->bookmark.page = page;

    return 0;
}
// pdf_add_bookmark [c]
int pdf_add_bookmark(struct pdf_doc *pdf, struct pdf_object *page,
        const char *name)
{
    struct pdf_object *obj = pdf_add_object(pdf, OBJ_bookmark);
    if (!obj)
        return pdf_set_err(pdf, -ENOMEM, "Insufficient memory");

    if (!page)
        page = pdf->last_objects[OBJ_page];

    if (!page)
        return pdf_set_err(pdf, -EINVAL,
                "Unable to add bookmark, no pages available\n");

    strncpy(obj->bookmark.name, name, sizeof(obj->bookmark.name));
    obj->bookmark.name[sizeof(obj->bookmark.name)] = '\0';
    obj->bookmark.page = page;

    return 0;
}
// al_segment_cwd_prefix [c]
int al_segment_cwd_prefix(char** prompt, unsigned int* prompt_len, int* is_first, int* last_bg, int orientation) {
    char text[16];

    char prefix[16];
    char home[64];
    char cwd[512];
    char *base = cwd;

    if (al_get_home(home, 64) != 0) {
        return -1;
    }
    if (al_get_cwd(cwd, 512) != 0) {
        return -1;
    }

    // check if in home directory
    if (al_string_startswith(cwd, home)) {
        base = cwd+strlen(home);
    }

    // copy first path element into dirs buffer
    if (al_get_dir_count(base) > CWD_LEN) {
        strcpy(prefix, THREE_DOTS); // deep in hirarchy
    } else if (al_string_startswith(cwd, home)) {
        strcpy(prefix, "~"); // home directory
    } else {
        strcpy(prefix, "/"); // everywhere else
    }

    // add segment to prompt buffer
    snprintf(text, 16, " %s ", prefix);
    al_gen_segment(prompt, prompt_len, COLOR_FG_CWD_PREFIX, COLOR_BG_CWD_PREFIX, FNT_BOLD, text, is_first, last_bg, orientation);

    return 0;
}
// al_segment_cwd_prefix [c]
int al_segment_cwd_prefix(char** prompt, unsigned int* prompt_len, int* is_first, int* last_bg, int orientation) {
    char text[16];

    char prefix[16];
    char home[64];
    char cwd[512];
    char *base = cwd;

    if (al_get_home(home, 64) != 0) {
        return -1;
    }
    if (al_get_cwd(cwd, 512) != 0) {
        return -1;
    }

    // check if in home directory
    if (al_string_startswith(cwd, home)) {
        base = cwd+strlen(home);
    }

    // copy first path element into dirs buffer
    if (al_get_dir_count(base) > CWD_LEN) {
        strcpy(prefix, THREE_DOTS); // deep in hirarchy
    } else if (al_string_startswith(cwd, home)) {
        strcpy(prefix, "~"); // home directory
    } else {
        strcpy(prefix, "/"); // everywhere else
    }

    // add segment to prompt buffer
    snprintf(text, 64, " %s ", prefix);
    al_gen_segment(prompt, prompt_len, COLOR_FG_CWD_PREFIX, COLOR_BG_CWD_PREFIX, FNT_BOLD, text, is_first, last_bg, orientation);

    return 0;
}
// kmod_module_new_from_name [c]
KMOD_EXPORT int kmod_module_new_from_name(struct kmod_ctx *ctx,
						const char *name,
						struct kmod_module **mod)
{
	struct kmod_module *m;
	size_t namelen;
	char name_norm[NAME_MAX];

	if (ctx == NULL || name == NULL)
		return -ENOENT;

	modname_normalize(name, name_norm, &namelen);

	m = kmod_pool_get_module(ctx, name_norm);
	if (m != NULL) {
		*mod = kmod_module_ref(m);
		return 0;
	}

	m = calloc(1, sizeof(*m) + namelen + 1);
	if (m == NULL) {
		free(m);
		return -ENOMEM;
	}

	m->ctx = kmod_ref(ctx);
	memcpy(m->name, name_norm, namelen + 1);
	m->refcount = 1;

	kmod_pool_add_module(ctx, m);

	*mod = m;

	return 0;
}
// kmod_module_new_from_name [c]
KMOD_EXPORT int kmod_module_new_from_name(struct kmod_ctx *ctx,
						const char *name,
						struct kmod_module **mod)
{
	struct kmod_module *m;
	size_t namelen;
	char name_norm[NAME_MAX];

	if (ctx == NULL || name == NULL)
		return -ENOENT;

	modname_normalize((char *)name, name_norm, &namelen);

	m = kmod_pool_get_module(ctx, name_norm);
	if (m != NULL) {
		*mod = kmod_module_ref(m);
		return 0;
	}

	m = calloc(1, sizeof(*m) + namelen + 1);
	if (m == NULL) {
		free(m);
		return -ENOMEM;
	}

	m->ctx = kmod_ref(ctx);
	memcpy(m->name, name_norm, namelen + 1);
	m->refcount = 1;

	kmod_pool_add_module(ctx, m);

	*mod = m;

	return 0;
}
// libsoc_pwm_get_polarity [c]
int libsoc_pwm_get_polarity(pwm *pwm)
{
  int polarity;
  char path[STR_BUF];
  char tmp_str[1];

  if (pwm == NULL)
  {
    libsoc_pwm_debug(__func__, -1, -1, "invalid pwm pointer");
    return EXIT_FAILURE;
  }

  sprintf(path, "/sys/class/pwm/pwmchip%d/pwm%d/polarity", pwm->chip, pwm->pwm);

  if (file_read_str(path, tmp_str, 1) == EXIT_FAILURE)
  {
    return EXIT_FAILURE;
  }

  if (strncmp(tmp_str, "i", 1) == 0)
  {
    polarity = INVERSED;
  }
  else if (strncmp(tmp_str, "n", 1) == 0)
  {
    polarity = NORMAL;
  }
  else
  {
    polarity = POLARITY_ERROR;
    return EXIT_FAILURE;
  }

  libsoc_pwm_debug(__func__, pwm->chip, pwm->pwm, "got polarity as %s", pwm_polarity_strings[polarity]);

  return polarity;
}
// libsoc_pwm_get_polarity [c]
int libsoc_pwm_get_polarity(pwm *pwm)
{
  int polarity;
  char path[STR_BUF];
  char tmp_str[1];

  if (pwm == NULL)
  {
    libsoc_pwm_debug(__func__, -1, -1, "invalid pwm pointer");
    return EXIT_FAILURE;
  }

  sprintf(path, "/sys/class/pwm/pwmchip%d/pwm%d/polarity", pwm->chip, pwm->pwm);

  if (file_read_str(path, tmp_str, 1) == EXIT_FAILURE)
  {
    return EXIT_FAILURE;
  }

  tmp_str[1] = NULL;

  if (strncmp(tmp_str, "i", 1) == 0)
  {
    polarity = INVERSED;
  }
  else if (strncmp(tmp_str, "n", 1) == 0)
  {
    polarity = NORMAL;
  }
  else
  {
    polarity = POLARITY_ERROR;
    return EXIT_FAILURE;
  }

  libsoc_pwm_debug(__func__, pwm->chip, pwm->pwm, "got polarity as %s", pwm_polarity_strings[polarity]);

  return polarity;
}
// kmod_module_parse_depline [c]
int kmod_module_parse_depline(struct kmod_module *mod, char *line)
{
	struct kmod_ctx *ctx = mod->ctx;
	struct kmod_list *list = NULL;
	char *p, *saveptr;
	int err, n = 0;

	assert(!mod->init.dep && mod->dep == NULL);
	mod->init.dep = true;

	p = strchr(line, ':');
	if (p == NULL)
		return 0;

	*p = '\0';
	if (mod->path == NULL)
		mod->path = strdup(line);

	p++;

	for (p = strtok_r(p, " \t", &saveptr); p != NULL;
					p = strtok_r(NULL, " \t", &saveptr)) {
		char buf[NAME_MAX];
		const char *modname = path_to_modname(p, buf, NULL);
		struct kmod_module *depmod;

		err = kmod_module_new_from_name(ctx, modname, &depmod);
		if (err < 0) {
			ERR(ctx, "ctx=%p modname=%s error=%s\n",
						ctx, modname, strerror(-err));
			goto fail;
		}

		DBG(ctx, "add dep: %s\n", modname);

		list = kmod_list_append(list, depmod);
		n++;
	}

	DBG(ctx, "%d dependencies for %s\n", n, mod->name);

	mod->dep = list;
	return n;

fail:
	kmod_module_unref_list(list);
	mod->init.dep = false;
	return err;
}
// kmod_module_parse_depline [c]
int kmod_module_parse_depline(struct kmod_module *mod, char *line)
{
	struct kmod_ctx *ctx = mod->ctx;
	struct kmod_list *list = NULL;
	char *p, *saveptr;
	int err, n = 0;

	assert(!mod->init.dep && mod->dep == NULL);
	mod->init.dep = true;

	p = strchr(line, ':');
	if (p == NULL)
		return 0;

	*p = '\0';
	if (mod->path == NULL)
		mod->path = strdup(line);

	p++;

	for (p = strtok_r(p, " \t", &saveptr); p != NULL;
					p = strtok_r(NULL, " \t", &saveptr)) {
		const char *modname = path_to_modname(p, NULL, NULL);
		struct kmod_module *depmod;

		err = kmod_module_new_from_name(ctx, modname, &depmod);
		if (err < 0) {
			ERR(ctx, "ctx=%p modname=%s error=%s\n",
						ctx, modname, strerror(-err));
			goto fail;
		}

		DBG(ctx, "add dep: %s\n", modname);

		list = kmod_list_append(list, depmod);
		n++;
	}

	DBG(ctx, "%d dependencies for %s\n", n, mod->name);

	mod->dep = list;
	return n;

fail:
	kmod_module_unref_list(list);
	mod->init.dep = false;
	return err;
}
// smprintf [c]
smprintf(const char *fmt, ...)
{
	/* FIXME: This code should have
	bound checks, it is vulnerable to
	buffer overflows */
	va_list ap;
	char *ret = NULL;

	va_start(ap, fmt);
	if (vasprintf(&ret, fmt, ap) < 0)
		return NULL;

	va_end(ap);
	return ret;
}
// smprintf [c]
smprintf(const char *fmt, ...)
{
	va_list fmtargs;
	char tmp[120];
	char *ret = NULL;

	va_start(fmtargs, fmt);
	snprintf(tmp, sizeof(tmp)-1, fmt, fmtargs);
	tmp[sizeof(tmp)] = '\0';
	if (asprintf(&ret, "%s", tmp) < 0)
		return NULL;

	va_end(fmtargs);
	return ret;
}
// Writer::Writer [cpp]
Writer::Writer(const char* pathToSave, ToDo& t): todo(t) 
{
	strncpy(path, pathToSave, 255);
	path[255] = '\0';
	file.imbue(locale(""));
}
// Writer::Writer [cpp]
Writer::Writer(const char* pathToSave, ToDo& t): todo(t) 
{
	strncpy(path, pathToSave, 128);
	path[128] = '\0';
	file.imbue(locale(""));
}
// llrpt_alpha [c]
llrpt_alpha (PNODE node, SYMTAB stab, BOOLEAN *eflg)
{
	static char scratch[2];
	INT i;
	PNODE argvar = builtin_args(node);
	PVALUE val = eval_and_coerce(PINT, argvar, stab, eflg);
	if (*eflg) {
		prog_var_error(node, stab, argvar, val, nonint1, "alpha");
		return NULL;
	}
	i = pvalue_to_int(val);
	delete_pvalue_ptr(&val);
	if (i < 1 || i > 26)
		sprintf(scratch, "%c", "X");
	else
		sprintf(scratch, "%c", 'a' + i - 1);
	return create_pvalue_from_string(scratch);
}
// llrpt_alpha [c]
llrpt_alpha (PNODE node, SYMTAB stab, BOOLEAN *eflg)
{
	static char scratch[2];
	INT i;
	PNODE argvar = builtin_args(node);
	PVALUE val = eval_and_coerce(PINT, argvar, stab, eflg);
	if (*eflg) {
		prog_var_error(node, stab, argvar, val, nonint1, "alpha");
		return NULL;
	}
	i = pvalue_to_int(val);
	delete_pvalue_ptr(&val);
	if (i < 1 || i > 26)
		sprintf(scratch, "XX");
	else
		sprintf(scratch, "%c", 'a' + i - 1);
	return create_pvalue_from_string(scratch);
}
// wl_closure_print [c]
wl_closure_print(struct wl_closure *closure, struct wl_object *target, int send)
{
	union wl_value *value;
	int i;
	struct timespec tp;
	unsigned int time;

	clock_gettime(CLOCK_REALTIME, &tp);
	time = (tp.tv_sec * 1000000L) + (tp.tv_nsec / 1000);

	fprintf(stderr, "[%10.3f] %s%s@%d.%s(",
		time / 1000.0,
		send ? " -> " : "",
		target->interface->name, target->id,
		closure->message->name);

	for (i = 2; i < closure->count; i++) {
		if (i > 2)
			fprintf(stderr, ", ");

		value = closure->args[i];
		switch (closure->message->signature[i - 2]) {
		case 'u':
			fprintf(stderr, "%u", value->uint32);
			break;
		case 'i':
			fprintf(stderr, "%d", value->uint32);
			break;
		case 's':
			fprintf(stderr, "\"%s\"", value->string);
			break;
		case 'o':
			if (value->object)
				fprintf(stderr, "%s@%u",
					value->object->interface->name,
					value->object->id);
			else
				fprintf(stderr, "nil");
			break;
		case 'n':
			fprintf(stderr, "new id %u", value->uint32);
			break;
		case 'a':
			fprintf(stderr, "array");
			break;
		case 'h':
			fprintf(stderr, "fd %d", value->uint32);
			break;
		}
	}

	fprintf(stderr, ")\n");
}
// wl_closure_print [c]
wl_closure_print(struct wl_closure *closure, struct wl_object *target, int send)
{
	union wl_value *value;
	char buffer[4] = "\0";
	int i;
	struct timespec tp;
	unsigned int time;

	if (send)
		sprintf(buffer, " -> ");

	clock_gettime(CLOCK_REALTIME, &tp);
	time = (tp.tv_sec * 1000000L) + (tp.tv_nsec / 1000);

	fprintf(stderr, "[%10.3f] %s%s@%d.%s(",
		time / 1000.0,
		buffer,
		target->interface->name, target->id,
		closure->message->name);

	for (i = 2; i < closure->count; i++) {
		if (i > 2)
			fprintf(stderr, ", ");

		value = closure->args[i];
		switch (closure->message->signature[i - 2]) {
		case 'u':
			fprintf(stderr, "%u", value->uint32);
			break;
		case 'i':
			fprintf(stderr, "%d", value->uint32);
			break;
		case 's':
			fprintf(stderr, "\"%s\"", value->string);
			break;
		case 'o':
			if (value->object)
				fprintf(stderr, "%s@%u",
					value->object->interface->name,
					value->object->id);
			else
				fprintf(stderr, "nil");
			break;
		case 'n':
			fprintf(stderr, "new id %u", value->uint32);
			break;
		case 'a':
			fprintf(stderr, "array");
			break;
		case 'h':
			fprintf(stderr, "fd %d", value->uint32);
			break;
		}
	}

	fprintf(stderr, ")\n");
}
// extract_file [c]
static bool extract_file(Unshield* unshield, const char* prefix, int index)
{
  bool success;
  char dirname[256];
  char filename[256];
  char* p;
  int directory = unshield_file_directory(unshield, index);
  char real_output_directory[256];
  char real_filename[256];

  strcpy(dirname, output_directory);
  strcat(dirname, "/");

  if (prefix && prefix[0])
  {
    strcat(dirname, prefix);
    strcat(dirname, "/");
  }

  if (!junk_paths && directory >= 0)
  {
    const char* tmp = unshield_directory_name(unshield, directory);
    if (tmp && tmp[0])
    {
      strcat(dirname, tmp);
      strcat(dirname, "/");
    }
  }

  for (p = dirname + strlen(output_directory); *p != '\0'; p++)
  {
    switch (*p)
    {
      case '\\':
        *p = '/';
        break;

      case ' ':
      case '<':
      case '>':
      case '[':
      case ']':
        *p = '_';
        break;

      default:
        if (!raw_filename)
        {  
          if (!isprint(*p))
            *p = '_';
          else if (make_lowercase)
            *p = tolower(*p);
        }
        break;;
    }
  }

#ifdef HAVE_ICONV
  if (!convert_encoding(dirname, sizeof(dirname)))
  {
    success = false;
    goto exit;
  }
#endif


#if 0
  if (dirname[strlen(dirname)-1] != '/')
    strcat(dirname, "/");
#endif

  make_sure_directory_exists(dirname);

  snprintf(filename, sizeof(filename), "%s%s", 
      dirname, unshield_file_name(unshield, index));

  for (p = filename + strlen(dirname); *p != '\0'; p++)
  {
    if (!raw_filename)
    {
      if (!isprint(*p))
        *p = '_';
      else if (make_lowercase)
        *p = tolower(*p);
    }
  }

#ifdef HAVE_ICONV
  if (!convert_encoding(filename + strlen(dirname),
      sizeof(filename) - strlen(dirname)))
  {
    success = false;
    goto exit;
  }
#endif

  realpath(output_directory, real_output_directory);
  realpath(filename, real_filename);
  if (real_filename == NULL || strncmp(real_filename,
                                       real_output_directory,
                                       strlen(real_output_directory)) != 0)
  {
    fprintf(stderr, "\n\nExtraction failed.\n");
    fprintf(stderr, "Possible directory traversal attack for: %s\n", filename);
    fprintf(stderr, "To be placed at: %s\n\n", real_filename);
    exit_status = 1;
    success = false;
    return success;
  }

  printf("  extracting: %s\n", filename);
  switch (format)
  {
    case FORMAT_NEW:
      success = unshield_file_save(unshield, index, filename);
      break;
    case FORMAT_OLD:
      success = unshield_file_save_old(unshield, index, filename);
      break;
    case FORMAT_RAW:
      success = unshield_file_save_raw(unshield, index, filename);
      break;
  }

exit:
  if (!success)
  {
    fprintf(stderr, "Failed to extract file '%s'.%s\n", 
        unshield_file_name(unshield, index),
        (log_level < 3) ? "Run unshield again with -D 3 for more information." : "");
    unlink(filename);
    exit_status = 1;
  }

  return success;
}
// calibrate_cpuinfo [c]
calibrate_cpuinfo(double *nsofclk, uint64_t *clkofsec)
{
	FILE *f;
	char *line = NULL, unit[11];
	size_t len = 0;
	double freq = 0.0;

	if ((f = fopen(CPUINFO_PATH, "r")) == NULL) {
		return (-1);
	}

	while (getline(&line, &len, f) > 0) {
		if (strncmp(line, "model name", sizeof ("model name") - 1) != 0) {
	    		continue;
		}

		if (sscanf(line + strcspn(line, "@") + 1, "%lf%10s",
			&freq, unit) == 2) {
			if (strcasecmp(unit, "GHz") == 0) {
				freq *= GHZ;
			} else if (strcasecmp(unit, "Mhz") == 0) {
				freq *= MHZ;				
			}
			break;
		}
	}

	free(line);
	fclose(f);

	if (freq == 0.0) {
		return (-1);
	}

	*clkofsec = freq;
	*nsofclk = (double)NS_SEC / *clkofsec;

	debug_print(NULL, 2, "calibrate_cpuinfo: nsofclk = %.4f, "
	    "clkofsec = %lu\n", *nsofclk, *clkofsec);

	return (0);
}
// calibrate_cpuinfo [c]
calibrate_cpuinfo(double *nsofclk, uint64_t *clkofsec)
{
	FILE *f;
	char *line = NULL, unit[10];
	size_t len = 0;
	double freq = 0.0;

	if ((f = fopen(CPUINFO_PATH, "r")) == NULL) {
		return (-1);
	}

	while (getline(&line, &len, f) > 0) {
		if (strncmp(line, "model name", sizeof ("model name") - 1) != 0) {
	    		continue;
		}

		if (sscanf(line + strcspn(line, "@") + 1, "%lf%10s",
			&freq, unit) == 2) {
			if (strcasecmp(unit, "GHz") == 0) {
				freq *= GHZ;
			} else if (strcasecmp(unit, "Mhz") == 0) {
				freq *= MHZ;				
			}
			break;
		}
	}

	free(line);
	fclose(f);

	if (freq == 0.0) {
		return (-1);
	}

	*clkofsec = freq;
	*nsofclk = (double)NS_SEC / *clkofsec;

	debug_print(NULL, 2, "calibrate_cpuinfo: nsofclk = %.4f, "
	    "clkofsec = %lu\n", *nsofclk, *clkofsec);

	return (0);
}
// rf_host_ver [c]
static void rf_host_ver(void)
{
  char *buf = (char *)cur_slot->readbuf;
  int major = 3, minor = 3;
  int remote_major, remote_minor;
  char ver_msg[16];

  if ( strncmp(buf, "RFB ", 4) != 0 || !isdigit(buf[4]) ||
       !isdigit(buf[4]) || !isdigit(buf[5]) || !isdigit(buf[6]) ||
       buf[7] != '.' || !isdigit(buf[8]) || !isdigit(buf[9]) ||
       !isdigit(buf[10]) || buf[11] != '\n' ) {
    log_write(LL_ERROR, "Wrong greeting data received from host");
    aio_close(0);
    return;
  }

  remote_major = atoi(&buf[4]);
  remote_minor = atoi(&buf[8]);
  log_write(LL_INFO, "Remote RFB Protocol version is %d.%d",
            remote_major, remote_minor);

  if (remote_major != major) {
    log_write(LL_ERROR, "Wrong protocol version, expected %d.x", major);
    aio_close(0);
    return;
  } else if (remote_minor != minor) {
    log_write(LL_WARN, "Protocol sub-version does not match (ignoring)");
  }

  sprintf(ver_msg, "RFB %03d.%03d\n", abs(major) % 999, abs(minor) % 999);
  aio_write(NULL, ver_msg, 12);
  aio_setread(rf_host_auth, NULL, 4);
}
// rf_host_ver [c]
static void rf_host_ver(void)
{
  char *buf = (char *)cur_slot->readbuf;
  int major = 3, minor = 3;
  int remote_major, remote_minor;
  char ver_msg[12];

  if ( strncmp(buf, "RFB ", 4) != 0 || !isdigit(buf[4]) ||
       !isdigit(buf[4]) || !isdigit(buf[5]) || !isdigit(buf[6]) ||
       buf[7] != '.' || !isdigit(buf[8]) || !isdigit(buf[9]) ||
       !isdigit(buf[10]) || buf[11] != '\n' ) {
    log_write(LL_ERROR, "Wrong greeting data received from host");
    aio_close(0);
    return;
  }

  remote_major = atoi(&buf[4]);
  remote_minor = atoi(&buf[8]);
  log_write(LL_INFO, "Remote RFB Protocol version is %d.%d",
            remote_major, remote_minor);

  if (remote_major != major) {
    log_write(LL_ERROR, "Wrong protocol version, expected %d.x", major);
    aio_close(0);
    return;
  } else if (remote_minor != minor) {
    log_write(LL_WARN, "Protocol sub-version does not match (ignoring)");
  }

  sprintf(ver_msg, "RFB %03d.%03d\n", abs(major) % 999, abs(minor) % 999);
  aio_write(NULL, ver_msg, 12);
  aio_setread(rf_host_auth, NULL, 4);
}
// dmi_memory_device_size_str [c]
static char *dmi_memory_device_size_str(u16 code)
{
	static char size[16];

	if (code == 0)
		strcpy(size, "Empty");
	else if (code == 0xFFFF)
		strcpy(size, "Unknown");
	else
	{
		if (code & 0x8000)
			sprintf(size, "%u kB", code & 0x7FFF);
		else
			sprintf(size, "%u MB", code);
	}

	return size;
}
// dmi_memory_device_size_str [c]
static char *dmi_memory_device_size_str(u16 code)
{
	static char size[8];

	if (code == 0)
		strcpy(size, "Empty");
	else if (code == 0xFFFF)
		strcpy(size, "Unknown");
	else
	{
		if (code & 0x8000)
			sprintf(size, "%u kB", code & 0x7FFF);
		else
			sprintf(size, "%u MB", code);
	}

	return size;
}
// ld86r [c]
ld86r(argc, argv)
   int argc; char ** argv;
#endif
{
char buf[128];
   FILE * fd, * ifd;
   struct stat st;
   int ar, libarg=0, need_o = 0, got_o = 0;

   for(ar=1; ar<argc; ar++) if( argv[ar][0] == '-' )
   {
      if( argv[ar][1] == 'r' ) need_o = 1;
      if( argv[ar][1] == 'o' ) { got_o++; libarg = 0; }
   }
   else
   {
      if( libarg == 0 ) libarg = ar;
   }

   if( libarg == 0 || got_o > 1 || need_o > got_o )
      fatalerror("-o option required for -r");

   if( (fd =fopen(argv[libarg], "wb")) == 0 ) fatalerror("Cannot open archive");
   if( fwrite(ARMAG, 1, SARMAG, fd) != SARMAG)  fatalerror("Cannot write magic");

   for(ar=1; ar<argc; ar++) if( ar != libarg && argv[ar][0] != '-' )
   {
      char * ptr;
      if( stat(argv[ar], &st) < 0 ) fatalerror("Cannot stat object");
      if((ptr=strchr(argv[ar], '/'))) ptr++; else ptr=argv[ar];
      memset(&arbuf, ' ', sizeof(arbuf));
      strcpy(buf, ptr); strcat(buf, "/                 ");
      strncpy(arbuf.ar_name, buf, sizeof(arbuf.ar_name));
     
      snprintf(arbuf.ar_date, 12, "%-12ld", (long)st.st_mtime);
      snprintf(arbuf.ar_uid, 6, "%-6d", (int)(st.st_uid%1000000L));
      snprintf(arbuf.ar_gid, 6, "%-6d", (int)(st.st_gid%1000000L));
      snprintf(arbuf.ar_mode, 8, "%-8lo", (long)st.st_mode);
      snprintf(arbuf.ar_size, 10, "%-10ld", (long)st.st_size);
      memcpy(arbuf.ar_fmag, ARFMAG, sizeof(arbuf.ar_fmag));

      if( fwrite(&arbuf, 1, sizeof(arbuf), fd) != sizeof(arbuf) )
         fatalerror("Cannot write header");

      ptr = malloc(st.st_size+2);
      if( ptr == 0 ) fatalerror("Out of memory");
      ptr[st.st_size] = ' ';
      if( (ifd = fopen(argv[ar], "rb")) == 0 ) fatalerror("Cannot open input");
      if( fread(ptr, 1, st.st_size, ifd) != st.st_size )
         fatalerror("Cannot read input file");
      fclose(ifd);

      if( st.st_size&1 ) st.st_size++;
      if( fwrite(ptr, 1, st.st_size, fd) != st.st_size )
         fatalerror("Cannot write output file");
   }
   fclose(fd);
   exit(0);
}
// ld86r [c]
ld86r(argc, argv)
   int argc; char ** argv;
#endif
{
char buf[128];
   FILE * fd, * ifd;
   struct stat st;
   int ar, libarg=0, need_o = 0, got_o = 0;

   for(ar=1; ar<argc; ar++) if( argv[ar][0] == '-' )
   {
      if( argv[ar][1] == 'r' ) need_o = 1;
      if( argv[ar][1] == 'o' ) { got_o++; libarg = 0; }
   }
   else
   {
      if( libarg == 0 ) libarg = ar;
   }

   if( libarg == 0 || got_o > 1 || need_o > got_o )
      fatalerror("-o option required for -r");

   if( (fd =fopen(argv[libarg], "wb")) == 0 ) fatalerror("Cannot open archive");
   if( fwrite(ARMAG, 1, SARMAG, fd) != SARMAG)  fatalerror("Cannot write magic");

   for(ar=1; ar<argc; ar++) if( ar != libarg && argv[ar][0] != '-' )
   {
      char * ptr;
      if( stat(argv[ar], &st) < 0 ) fatalerror("Cannot stat object");
      if((ptr=strchr(argv[ar], '/'))) ptr++; else ptr=argv[ar];
      memset(&arbuf, ' ', sizeof(arbuf));
      strcpy(buf, ptr); strcat(buf, "/                 ");
      strncpy(arbuf.ar_name, buf, sizeof(arbuf.ar_name));
      
      sprintf(arbuf.ar_date, "%-12ld", (long)st.st_mtime);
      sprintf(arbuf.ar_uid, "%-6d",    (int)(st.st_uid%1000000L));
      sprintf(arbuf.ar_gid, "%-6d",    (int)(st.st_gid%1000000L));
      sprintf(arbuf.ar_mode, "%-8lo",  (long)st.st_mode);
      sprintf(arbuf.ar_size, "%-10ld", (long)st.st_size);
      memcpy(arbuf.ar_fmag, ARFMAG, sizeof(arbuf.ar_fmag));

      if( fwrite(&arbuf, 1, sizeof(arbuf), fd) != sizeof(arbuf) )
         fatalerror("Cannot write header");

      ptr = malloc(st.st_size+2);
      if( ptr == 0 ) fatalerror("Out of memory");
      ptr[st.st_size] = ' ';
      if( (ifd = fopen(argv[ar], "rb")) == 0 ) fatalerror("Cannot open input");
      if( fread(ptr, 1, st.st_size, ifd) != st.st_size )
         fatalerror("Cannot read input file");
      fclose(ifd);

      if( st.st_size&1 ) st.st_size++;
      if( fwrite(ptr, 1, st.st_size, fd) != st.st_size )
         fatalerror("Cannot write output file");
   }
   fclose(fd);
   exit(0);
}
// SecurityConfig::configure [java]
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
            .and()
            .formLogin()
            .and()
            .httpBasic()
            .and()
            .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }
// SecurityConfig::configure [java]
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
            .and()
            .formLogin()
            .and()
            .httpBasic()
            .and()
            .csrf().disable();
        //.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }
// SecurityConfig::configure [java]
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
			.authorizeRequests()
	        .antMatchers("/api/userinfo", "/api/userinfo/", "/api/user/information", "/api/user/information/").permitAll()
			.antMatchers("/").permitAll()
	        .antMatchers("/static/**/**.{js,html,css,json}").permitAll()
	    	.antMatchers("/**/api/user/**").permitAll()
			.antMatchers("/swagger-ui/**", "/swagger-ui.html", "**/api-docs", "**/api-docs/swagger-config").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_PBUSER')")
			.antMatchers("/**/*.{js,html,css,json}").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_PBUSER')")
	        .antMatchers("/**/app/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_PBUSER')")
	        .anyRequest().authenticated()
	        .and()
	        .oauth2Login()
	        	.successHandler(myAuthenticationSuccessHandler())
	        		.userInfoEndpoint()
	        	.userService(injectLocalRolesOAuth2UserService())
	        .and().and()
	        .logout()
	        .deleteCookies("JSESSIONID")
	        .logoutSuccessHandler(oidcLogoutSuccessHandler());
    }
// SecurityConfig::configure [java]
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
			.csrf().disable()
			.authorizeRequests()
	        .antMatchers("/api/userinfo", "/api/userinfo/", "/api/user/information", "/api/user/information/").permitAll()
			.antMatchers("/").permitAll()
	        .antMatchers("/static/**/**.{js,html,css,json}").permitAll()
	    	.antMatchers("/**/api/user/**").permitAll()
			.antMatchers("/swagger-ui/**", "/swagger-ui.html", "**/api-docs", "**/api-docs/swagger-config").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_PBUSER')")
			.antMatchers("/**/*.{js,html,css,json}").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_PBUSER')")
	        .antMatchers("/**/app/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_PBUSER')")
	        .anyRequest().authenticated()
	        .and()
	        .oauth2Login()
	        	.successHandler(myAuthenticationSuccessHandler())
	        		.userInfoEndpoint()
	        	.userService(injectLocalRolesOAuth2UserService())
	        .and().and()
	        .logout()
	        .deleteCookies("JSESSIONID")
	        .logoutSuccessHandler(oidcLogoutSuccessHandler());
    }
// UiApplication::SecurityConfiguration::configure [java]
        @Override
        protected void configure(HttpSecurity http) throws Exception {

            String[] patterns = new String[] {"/index.html", "/home.html", "/login1.html", "/xss2.html", "/", "/xss",
                "/login", "/xss1.html", "/resource", "/postcustomer", "/getallcustomer", "/getinfo", "/postxss"};

            // @formatter:off
            //http.httpBasic();
            //http.authorizeRequests().antMatchers("/**").permitAll(); //.anyRequest().authenticated();
            //http.csrf().disable();


            http.headers().httpStrictTransportSecurity();
            http.httpBasic().and().authorizeRequests().antMatchers(patterns).permitAll().anyRequest().authenticated();
            http.csrf().and().addFilterAfter(new CsrfGrantingFilter(), SessionManagementFilter.class);
            //http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());

            // @formatter:on
        }
// UiApplication::SecurityConfiguration::configure [java]
        @Override
        protected void configure(HttpSecurity http) throws Exception {

            String[] patterns = new String[] {"/index.html", "/home.html", "/login1.html", "/xss2.html", "/", "/xss",
                "/login", "/xss1.html", "/resource", "/postcustomer", "/getallcustomer", "/getinfo", "/postxss"};

            // @formatter:off
            //http.httpBasic();
            //http.authorizeRequests().antMatchers("/**").permitAll(); //.anyRequest().authenticated();

            http.headers().httpStrictTransportSecurity();
            http.csrf().disable();
            http.httpBasic().and().authorizeRequests().antMatchers(patterns).permitAll().anyRequest().authenticated();
            http.csrf().and().addFilterAfter(new CsrfGrantingFilter(), SessionManagementFilter.class);
            //http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());

            // @formatter:on
        }
// WebSecurityConfig::configure [java]
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/webjars/**", "/login", "/logout", "/static/**", "/console/*").permitAll();
		http.authorizeRequests().antMatchers("/user/**").hasAnyAuthority(FredBetPermission.PERM_USER_ADMINISTRATION);
		http.authorizeRequests().antMatchers("/admin/**").hasAnyAuthority(FredBetPermission.PERM_ADMINISTRATION);
		http.authorizeRequests().antMatchers("/buildinfo/**").hasAnyAuthority(FredBetPermission.PERM_SYSTEM_INFO);
		http.authorizeRequests().antMatchers("/administration/**").hasAnyAuthority(FredBetPermission.PERM_ADMINISTRATION);

		// Spring Boot Actuator
		http.authorizeRequests().antMatchers("/actuator/health").permitAll();
		http.authorizeRequests().antMatchers("/actuator/**").hasAnyAuthority(FredBetPermission.PERM_ADMINISTRATION);
		
		http.authorizeRequests().anyRequest().authenticated();
		
		http.formLogin().loginPage("/login").defaultSuccessUrl("/matches/upcoming").permitAll();
		http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login").invalidateHttpSession(true)
				.deleteCookies("JSESSIONID", "remember-me").permitAll();
		http.rememberMe().tokenRepository(persistentTokenRepository()).tokenValiditySeconds(REMEMBER_ME_TOKEN_VALIDITY_SECONDS);

		// disable cache control to allow usage of ETAG headers (no image reload
		// if the image has not been changed)
		http.headers().cacheControl().disable();

		if (environment.acceptsProfiles(FredBetProfile.DEV)) {
			// this is for the embedded h2 console
			http.headers().frameOptions().disable();
		}
	}