/*
see https://github.com/docker/distribution/blob/master/registry/api/v2/names.go
481292
public static void validateRepoName(String name) {
        if (name.isEmpty()) {
            throw new InvalidRepositoryNameException(String.format("Invalid empty repository name \"%s\"", name));
        }

        if (name.length() > RepositoryNameTotalLengthMax) {
            throw new InvalidRepositoryNameException(String.format("Repository name \"%s\" is longer than "
                    + RepositoryNameTotalLengthMax, name));
        }

        String[] components = name.split("/");

        for (String component : components) {
            if (!RepositoryNameComponentAnchoredRegexp.matcher(component).matches()) {
                throw new InvalidRepositoryNameException(String.format(
                        "Repository name \"%s\" is invalid. Component: %s", name, component));
            }
        }
    }
970592
function parse_NameCmt(blob, length, opts) {
	if(opts.biff < 8) { blob.l += length; return; }
	var cchName = blob.read_shift(2);
	var cchComment = blob.read_shift(2);
	var name = parse_XLUnicodeStringNoCch(blob, cchName, opts);
	var comment = parse_XLUnicodeStringNoCch(blob, cchComment, opts);
	return [name, comment];
}
1192070
function getName(tuple) {
    if (Array.isArray(tuple)) {
      var verb = tuple[0]
      var path = getLambdaName(tuple[1])
      return [`${app}-production-${verb}${path}`, `${app}-staging-${verb}${path}`]
    }
    else {
      var path = getLambdaName(tuple)
      return [`${app}-production-get${path}`, `${app}-staging-get${path}`]
    }
  }
463837
function(name) {
    name = name || '';

    // TODO optimize with RegExp

    var nameChain = name.split('.');
    for(var i=0; i<nameChain.length; i++) {
      if(!nameChain[i].match(/[a-zA-Z0-9_]+/)) {
        return false;
      }
    }

    return true;
  }
1285644
function copyNamedProperties(names, src, dst) {
  names.forEach(function(name) {
    const value = src[name];
    if (value !== undefined) {
      dst[name] = value;
    }
  });
}
526760
function encodePackageName(packageName) {
  // Thanks https://github.com/unpkg/npm-http-server/blob/master/modules/RegistryUtils.js
  // for scoped modules help
  let encodedPackageName;
  if (packageName[0] === "@") {
    // For the registry URL, the @ doesn't get URL encoded for some reason
    encodedPackageName = `@${encodeURIComponent(packageName.substring(1))}`;
  } else {
    encodedPackageName = encodeURIComponent(packageName);
  }
  return encodedPackageName;
}
196930
def get_all_tags_with_auth(image_name, branch=None):
    
    logging.debug('Getting %s with authentication' % image_name)
    url = '%s/%s/images' % (API_URL, image_name)

    registry_user = os.environ.get('REGISTRY_USER')
    registry_pass = os.environ.get('REGISTRY_PASS')

    if registry_user is None or registry_pass is None:
        msg = ('The docker image seems to be private and no authentication'
               ' credentials were provided. Please set REGISTRY_USER and'
               ' REGISTRY_PASS environment variables and try again.')
        raise DockerTagNamingException(msg)

    user_credentials = (registry_user, registry_pass)

    headers = {'X-Docker-Token': 'true',
               'Accept': 'application/json',
               'Content-Type': 'application/json'}

    try:
        response = requests.get(url, auth=user_credentials, headers=headers)
    except RequestException, re:
        raise DockerTagNamingException('HTTP request exception "%s"' % re)

    if response.status_code in (404, 401):
        msg = ('Received unexpected status code %s from the registry'
               ' REST API after sending authentication credentials, the image'
               ' might not exist or is private.')
        raise AuthException(msg % response.status_code)

    token = response.headers.get('x-docker-token')
    endpoint = response.headers.get('x-docker-endpoints')

    if token is None:
        raise DockerTagNamingException('No token returned by the REST API')

    if endpoint is None:
        raise DockerTagNamingException('No docker endpoint returned by the'
                                       ' REST API')

    url = 'https://{0}/v1/repositories/{1}/tags'.format(endpoint, image_name)
    headers['Authorization'] = 'Token %s' % token
    try:
        response = requests.get(url, headers=headers)
    except RequestException, re:
        raise DockerTagNamingException('HTTP request exception "%s"' % re)

    if response.status_code in (404,):
        logging.debug('Received unexpected status code %s from the registry'
                      ' REST API, the image might not exist in the registry'
                      ' but was registered in the hub.')
        return []

    if response.status_code != 200:
        msg = ('Received unexpected status code %s from the registry'
               ' REST API. Please report a bug.')
        raise AuthException(msg % response.status_code)

    try:
        json_data = response.json()
    except ValueError:
        msg = 'JSON decode failed! Raw data is: "%s". Please report a bug.'
        raise DockerTagNamingException(msg % (response.content[:25]).strip())

    #
    #   Note that the registry returns a different format
    #
    output = []

    for tag_name in json_data.keys():
        try:
            version = version_parser(tag_name)
        except Exception, e:
            msg = 'Ignoring version tag "%s" with incorrect format: "%s"'
            logging.debug(msg % (tag_name, e))
            continue

        if branch is not None:
            if version.branch != branch:
                continue

        output.append(version)

    def sort_func(version_a, version_b):
        return cmp(version_b.version_number, version_a.version_number)

    output.sort(sort_func)

    return output
883149
function getname(req, res) {
  res.send(null, req.conn.client.name);
}
35004
func (f *FakeDockerClient) idsToNames(ids []string) ([]string, error) {
	names := []string{}
	for _, id := range ids {
		names = append(names, strings.TrimPrefix(f.ContainerMap[id].Name, dockerNamePrefix))
	}
	return names, nil
}
286973
func (d *stiDocker) CheckAndPullImage(name string) (*api.Image, error) {
	name = getImageName(name)
	displayName := name

	if !glog.Is(3) {
		// For less verbose log levels (less than 3), shorten long iamge names like:
		//     "centos/php-56-centos7@sha256:51c3e2b08bd9fadefccd6ec42288680d6d7f861bdbfbd2d8d24960621e4e27f5"
		// to include just enough characters to differentiate the build from others in the docker repository:
		//     "centos/php-56-centos7@sha256:51c3e2b08bd..."
		// 18 characters is somewhat arbitrary, but should be enough to avoid a name collision.
		split := strings.Split(name, "@")
		if len(split) > 1 && len(split[1]) > 18 {
			displayName = split[0] + "@" + split[1][:18] + "..."
		}
	}

	image, err := d.CheckImage(name)
	if err != nil && !strings.Contains(err.(s2ierr.Error).Details.Error(), "No such image") {
		return nil, err
	}
	if image == nil {
		glog.V(1).Infof("Image %q not available locally, pulling ...", displayName)
		return d.PullImage(name)
	}

	glog.V(3).Infof("Using locally available image %q", displayName)
	return image, nil
}
1294589
func parseSandboxName(name string) (*runtimeapi.PodSandboxMetadata, error) {
	// Docker adds a "/" prefix to names. so trim it.
	name = strings.TrimPrefix(name, "/")

	parts := strings.Split(name, nameDelimiter)
	// Tolerate the random suffix.
	// TODO(random-liu): Remove 7 field case when docker 1.11 is deprecated.
	if len(parts) != 6 && len(parts) != 7 {
		return nil, fmt.Errorf("failed to parse the sandbox name: %q", name)
	}
	if parts[0] != kubePrefix {
		return nil, fmt.Errorf("container is not managed by kubernetes: %q", name)
	}

	attempt, err := parseUint32(parts[5])
	if err != nil {
		return nil, fmt.Errorf("failed to parse the sandbox name %q: %v", name, err)
	}

	return &runtimeapi.PodSandboxMetadata{
		Name:      parts[2],
		Namespace: parts[3],
		Uid:       parts[4],
		Attempt:   attempt,
	}, nil
}
1192397
function maybeCreateAliasRecords(result, callback) {

      let records = result.records.ResourceRecordSets.filter(r=> r.Type === 'A').map(r=> r.Name)
      let stagingExists = records.includes(`staging.${domain}.`)
      let productionExists = records.includes(`${domain}.`)
      let skip = stagingExists && productionExists
      if (skip) {
        let records = result.records.ResourceRecordSets.filter(r=> r.Type === 'A')
        let staging = records.find(r=> r.Name === `staging.${domain}.`)
        let production = records.find(r=> r.Name === `${domain}.`)
        console.log(chalk.green.dim('✔ A Records'))
        console.log(chalk.grey(`          Production ${chalk.green.bold.underline(production.Name)}`))
        console.log(chalk.grey(`             Staging ${chalk.green.bold.underline(staging.Name)}`))
        callback()
      }
      else {

        let staging = result.apis.items.find(api=> api.domainName === `staging.${domain}`)
        let production = result.apis.items.find(api=> api.domainName === domain)
        route53.changeResourceRecordSets({
          ChangeBatch: {
            Changes: [{
              Action: 'UPSERT',
              ResourceRecordSet: {
                AliasTarget: {
                  DNSName: production.distributionDomainName,
                  EvaluateTargetHealth: false,
                  HostedZoneId: 'Z2FDTNDATAQYW2', /* ah, yes of course */
                },
                Name: domain,
                Type: "A"
              }
            },
            {
              Action: 'UPSERT',
              ResourceRecordSet: {
                AliasTarget: {
                  DNSName: staging.distributionDomainName,
                  EvaluateTargetHealth: false,
                  HostedZoneId: 'Z2FDTNDATAQYW2', /* ah, yes of course */
                },
                Name: `staging.${domain}`,
                Type: "A"
              }

            }],
            Comment: "defined by .arc @domain " + domain
          },
          HostedZoneId
        },
        function done(err) {
          if (err) callback(err)
          else {
            console.log(chalk.green.dim('✔ Created A Records'))
            callback()
          }
        })
      }
    }
311966
def _do_names(names, fun, path=None):
    '''
    
    '''
    ret = {}
    hosts = find_guests(names, path=path)
    if not hosts:
        return False

    client = salt.client.get_local_client(__opts__['conf_file'])
    for host, sub_names in six.iteritems(hosts):
        cmds = []
        for name in sub_names:
            cmds.append(client.cmd_iter(
                    host,
                    'lxc.{0}'.format(fun),
                    [name],
                    kwarg={'path': path},
                    timeout=60))
        for cmd in cmds:
            data = next(cmd)
            data = data.get(host, {}).get('ret', None)
            if data:
                ret.update({host: data})
    return ret
875386
func Names() []string {
	out := []string{}
	for name := range Registry {
		out = append(out, name)
	}
	sort.Strings(out)
	return out
}
805991
function normalizeName (name) {
  // Normalize directories as a single slash
  name = _(name).toString();
  if (_.isEmpty(name) || name === "/" || name === "//") {
    return "/";
  }

  // Add a leading slash
  if (!_.startsWith(name, "/")) {
    name = "/" + name;
  }

  // Don't allow slashes in the middle
  if (_.includes(name.substring(1, name.length - 1), "/")) {
    throw ono("Resource names cannot contain slashes");
  }

  return name;
}
256717
func names(m map[string]*jsonschema.Schema) []string {
	ret := make([]string, 0, len(m))
	for n := range m {
		ret = append(ret, n)
	}
	sort.Strings(ret)
	return ret
}
1030742
function(appName) {

    // Query docker for list of containers.
    return dockerInstance()
    .then(function(dockerInstance) {
      // Make sure to retry call to list containers.
      return Promise.fromNode(function(cb) {
        dockerInstance.listContainers({all: 1}, cb);
      });
    })
    // Make sure we have a timeout.
    .timeout(30 * 1000)
    // Wrap errors.
    .catch(function(err) {
      throw new VError(err, 'Error querying docker for list of containers.');
    })
    // Filter out containers with invalid status
    .filter(function(data) {
      return data.Status !== 'Removal In Progress';
    })
    // Map docker containers to generic containers.
    .map(toGenericContainer)
    // Filter out nulls and undefineds.
    .filter(_.identity)
    // Filter out all non-kalabox containers
    .filter(function(data) {
      return data.kalabox === true;
    })
    // Filter by app name if an app name was given.
    .then(function(containers) {
      if (appName) {
        return Promise.filter(containers, function(container) {
          return container.app === appName;
        });
      } else {
        return containers;
      }
    });

  }