Heuristically pretty print a path argument
483775
def emit_path_arg(keywordstr, arg, fd, indent, max_line_len, line_len, eol):
    """"""

    quote = '"'

    arg = escape_str(arg)

    if not(need_new_line(max_line_len, line_len, arg)):
        fd.write(" " + quote + arg + quote)
        return False

    ## FIXME: we should split the path on '/' and '[]' into multiple lines
    ## and then print each line

    num_chars = max_line_len - line_len
    if num_chars <= 0:
        # really small max_line_len; we give up
        fd.write(" " + quote + arg + quote)
        return False

    while num_chars > 2 and arg[num_chars - 1:num_chars].isalnum():
        num_chars -= 1
    fd.write(" " + quote + arg[:num_chars] + quote)
    arg = arg[num_chars:]
    keyword_cont = ((len(keywordstr) - 1) * ' ') + '+'
    while arg != '':
        line_len = len(
            "%s%s %s%s%s%s" % (indent, keyword_cont, quote, arg, quote, eol))
        num_chars = len(arg) - (line_len - max_line_len)
        while num_chars > 2 and arg[num_chars - 1:num_chars].isalnum():
            num_chars -= 1
        fd.write('\n' + indent + keyword_cont + " " +
                 quote + arg[:num_chars] + quote)
        arg = arg[num_chars:]
882542
def displayable_path(path, separator=u'; '):
    
    if isinstance(path, (list, tuple)):
        return separator.join(displayable_path(p) for p in path)
    elif isinstance(path, six.text_type):
        return path
    elif not isinstance(path, bytes):
        # A non-string object: just get its unicode representation.
        return six.text_type(path)

    try:
        return path.decode(_fsencoding(), 'ignore')
    except (UnicodeError, LookupError):
        return path.decode('utf8', 'ignore')
349585
def main(args=None):
    
    parser = ArgumentParser(
        prog='baseline',
        description=DESCRIPTION)

    parser.add_argument(
        'path', nargs='*',
        help='module or directory path')

    parser.add_argument(
        '--movepath', help='location to move script updates')

    parser.add_argument(
        '-w', '--walk', action='store_true',
        help='recursively walk directories')

    args = parser.parse_args(args)

    paths = args.path or ['.']

    paths = [path for pattern in paths for path in glob(pattern)]

    if args.walk:
        for dirpath in (p for p in paths if os.path.isdir(p)):
            for root, _dirs, files in os.walk(dirpath):
                paths += (os.path.join(root, filename) for filename in files)
    else:
        for dirpath in (p for p in paths if os.path.isdir(p)):
            paths += (os.path.join(dirpath, pth) for pth in os.listdir(dirpath))

    update_paths = [
        os.path.relpath(p) for p in paths if p.lower().endswith(UPDATE_EXT)]

    exitcode = 0

    if update_paths:
        script_paths = [pth[:-len(UPDATE_EXT)] + '.py' for pth in update_paths]

        print('Found updates for:')
        for path in script_paths:
            print('  ' + path)
        print()

        if not args.movepath:
            try:
                input('Hit [ENTER] to update, [Ctrl-C] to cancel ')
            except KeyboardInterrupt:
                print()
                print('Update canceled.')
                exitcode = 1
            else:
                print()

        if exitcode == 0:
            for script_path, update_path in zip(script_paths, update_paths):
                if args.movepath:
                    script_path = os.path.join(args.movepath, script_path)
                    if update_path.startswith('..'):
                        raise RuntimeError(
                            'destination outside of move path: ' + script_path)
                    script_dirpath = os.path.dirname(script_path)
                    if not os.path.isdir(script_dirpath):
                        os.makedirs(script_dirpath)
                with open(update_path) as update:
                    new_content = update.read()
                with open(script_path, 'w') as script:
                    script.write(new_content)
                os.remove(update_path)
                print(update_path + ' -> ' + script_path)

    return exitcode
974683
function printDanglingComments(path, options, sameIndent, filter) {
  const parts = [];
  const node = path.getValue();

  if (!node || !node.comments) {
    return "";
  }

  path.each(commentPath => {
    const comment = commentPath.getValue();
    if (
      comment &&
      !comment.leading &&
      !comment.trailing &&
      (!filter || filter(comment))
    ) {
      parts.push(printComment(commentPath, options));
    }
  }, "comments");

  if (parts.length === 0) {
    return "";
  }

  if (sameIndent) {
    return join(hardline, parts);
  }
  return indent(concat([hardline, join(hardline, parts)]));
}
1232653
def print_files(opts, file_paths):
    
    print("Parsing the following files:")
    for file_path in file_paths:
        print("  " + strip_prefix(file_path, opts.abs_input))
    print("--------------------")
    print(str(len(file_paths)) + " total\n")
87798
function extractPaths(obj, newKeys, ...paths) {
  const nkLen = newKeys.length;
  const pLen = paths.length;

  const curried = curry(assignKeysAtPaths, obj, newKeys, paths);

  return nkLen > pLen ? curried(nkLen) : curried(pLen);
}
13615
def parse_path(f1, f2):

    """"""

    import glob

    # if second argument is missing or is a wild card, point it
    # to the current directory
    f2 = f2.strip()
    if f2 == '' or f2 == '*':
        f2 = './'

    # if the first argument is a directory, use all GEIS files
    if os.path.isdir(f1):
        f1 = os.path.join(f1, '*.??h')
    list1 = glob.glob(f1)
    list1 = [name for name in list1 if name[-1] == 'h' and name[-4] == '.']

    # if the second argument is a directory, use file names in the
    # first argument to construct file names, i.e.
    # abc.xyh will be converted to abc_xyf.fits
    if os.path.isdir(f2):
        list2 = []
        for file in list1:
            name = os.path.split(file)[-1]
            fitsname = name[:-4] + '_' + name[-3:-1] + 'f.fits'
            list2.append(os.path.join(f2, fitsname))
    else:
        list2 = [s.strip() for s in f2.split(",")]

    if list1 == [] or list2 == []:
        err_msg = ""
        if list1 == []:
            err_msg += "Input files `{:s}` not usable/available. ".format(f1)

        if list2 == []:
            err_msg += "Input files `{:s}` not usable/available. ".format(f2)

        raise IOError(err_msg)

    else:
        return list1, list2
380
function generatePath(path = "/", params = {}) {
  return path === "/" ? path : compilePath(path)(params, { pretty: true });
}
871795
function valueFromPath(o, path = []) {
  return path.reduce((ret, seg) => isObject(ret) && ret[seg], o);
}
816057
function checkPath(path) {
    const integerKeySegments =
        path.filter(segment => (/^(0|[1-9][0-9]*)$/.test(segment)));
    if (integerKeySegments.length) {
        warn(`Integer keys will come first in object iteration even if ` +
             `other keys are defined before. Wrap key with '/' to avoid ` +
             `this behavior (${
                integerKeySegments
                    .map(segment => `"${segment}" => "/${segment}/"`).join(', ')
              }).`);
    }
}
491810
function (name, paths) {
    
    var patternBits = name.split("-");
    
    var i = 1;
    var c = patternBits.length;
    
    var patternType = patternBits[0];
    while ((paths[patternType] === undefined) && (i < c)) {
      patternType += "-"+patternBits[i];
      i++;
    }
    
    var pattern = name.slice(patternType.length+1,name.length);
    
    return [patternType, pattern];
    
  }
1029242
def mkpath(*args)
      args[0] = {} unless args[0]
      args[0] = args[0].merge(mode: 0700) unless args[0][:mode]
      FileUtils.mkpath(self.to_s, *args)
    end
283639
def path(args):
  """"""

  from .query import Database
  db = Database()

  output = sys.stdout
  if args.selftest:
    from bob.db.utils import null
    output = null()

  r = db.paths(args.id, prefix=args.directory, suffix=args.extension)
  for path in r: output.write('%s\n' % path)

  if not r: return 1

  return 0
556495
def print_paths(self):
        '''
        
        '''
        for path_key, path_value in self.paths.items():
            # Handler for request in path
            self.current_path = path_key
            for request_key, request_value in path_value.items():
                if request_key == 'parameters':
                    continue
                self.get_main_title(path_key, request_key)
                self.get_description(request_value)
                self.get_status_code_and_schema_rst(request_value['responses'])
                self.get_params(path_value['parameters'], 'param')
                self.get_params(request_value['parameters'], 'query')
1020702
def pretty_path(path):
    
    path = fmt.to_utf8(path)
    home_dir = os.path.expanduser("~")
    if path.startswith(home_dir):
        path = "~" + path[len(home_dir):]
    return '"%s"' % (path,)
925874
function print(path, options, print) {
  const n = path.getValue();

  /* istanbul ignore if*/
  if (!n) {
    return "";
  }

  switch (n.type) {
    case "Program": {
      return group(
        join(softline, path.map(print, "body").filter(text => text !== ""))
      );
    }
    case "ElementNode": {
      const tagFirstChar = n.tag[0];
      const isLocal = n.tag.indexOf(".") !== -1;
      const isGlimmerComponent =
        tagFirstChar.toUpperCase() === tagFirstChar || isLocal;
      const hasChildren = n.children.length > 0;
      const isVoid =
        (isGlimmerComponent && !hasChildren) || voidTags.indexOf(n.tag) !== -1;
      const closeTag = isVoid ? concat([" />", softline]) : ">";
      const getParams = (path, print) =>
        indent(
          concat([
            n.attributes.length ? line : "",
            join(line, path.map(print, "attributes")),

            n.modifiers.length ? line : "",
            join(line, path.map(print, "modifiers")),

            n.comments.length ? line : "",
            join(line, path.map(print, "comments"))
          ])
        );

      // The problem here is that I want to not break at all if the children
      // would not break but I need to force an indent, so I use a hardline.
      /**
       * What happens now:
       * <div>
       *   Hello
       * </div>
       * ==>
       * <div>Hello</div>
       * This is due to me using hasChildren to decide to put the hardline in.
       * I would rather use a {DOES THE WHOLE THING NEED TO BREAK}
       */
      return concat([
        group(
          concat([
            "<",
            n.tag,
            getParams(path, print),
            n.blockParams.length ? ` as |${n.blockParams.join(" ")}|` : "",
            ifBreak(softline, ""),
            closeTag
          ])
        ),
        group(
          concat([
            indent(join(softline, [""].concat(path.map(print, "children")))),
            ifBreak(hasChildren ? hardline : "", ""),
            !isVoid ? concat(["</", n.tag, ">"]) : ""
          ])
        )
      ]);
    }
    case "BlockStatement": {
      const pp = path.getParentNode(1);
      const isElseIf =
        pp &&
        pp.inverse &&
        pp.inverse.body[0] === n &&
        pp.inverse.body[0].path.parts[0] === "if";
      const hasElseIf =
        n.inverse &&
        n.inverse.body[0] &&
        n.inverse.body[0].type === "BlockStatement" &&
        n.inverse.body[0].path.parts[0] === "if";
      const indentElse = hasElseIf ? a => a : indent;
      if (n.inverse) {
        return concat([
          isElseIf
            ? concat(["{{else ", printPathParams(path, print), "}}"])
            : printOpenBlock(path, print),
          indent(concat([hardline, path.call(print, "program")])),
          n.inverse && !hasElseIf ? concat([hardline, "{{else}}"]) : "",
          n.inverse
            ? indentElse(concat([hardline, path.call(print, "inverse")]))
            : "",
          isElseIf ? "" : concat([hardline, printCloseBlock(path, print)])
        ]);
      } else if (isElseIf) {
        return concat([
          concat(["{{else ", printPathParams(path, print), "}}"]),
          indent(concat([hardline, path.call(print, "program")]))
        ]);
      }
      /**
       * I want this boolean to be: if params are going to cause a break,
       * not that it has params.
       */
      const hasParams = n.params.length > 0 || n.hash.pairs.length > 0;
      const hasChildren = n.program.body.length > 0;
      return concat([
        printOpenBlock(path, print),
        group(
          concat([
            indent(concat([softline, path.call(print, "program")])),
            hasParams && hasChildren ? hardline : softline,
            printCloseBlock(path, print)
          ])
        )
      ]);
    }
    case "ElementModifierStatement":
    case "MustacheStatement": {
      const pp = path.getParentNode(1);
      const isConcat = pp && pp.type === "ConcatStatement";
      return group(
        concat([
          n.escaped === false ? "{{{" : "{{",
          printPathParams(path, print),
          isConcat ? "" : softline,
          n.escaped === false ? "}}}" : "}}"
        ])
      );
    }
    case "SubExpression": {
      const params = getParams(path, print);
      const printedParams =
        params.length > 0
          ? indent(concat([line, group(join(line, params))]))
          : "";
      return group(
        concat(["(", printPath(path, print), printedParams, softline, ")"])
      );
    }
    case "AttrNode": {
      const isText = n.value.type === "TextNode";
      if (isText && n.value.loc.start.column === n.value.loc.end.column) {
        return concat([n.name]);
      }
      const quote = isText ? '"' : "";
      return concat([n.name, "=", quote, path.call(print, "value"), quote]);
    }
    case "ConcatStatement": {
      return concat([
        '"',
        group(
          indent(
            join(
              softline,
              path
                .map(partPath => print(partPath), "parts")
                .filter(a => a !== "")
            )
          )
        ),
        '"'
      ]);
    }
    case "Hash": {
      return concat([join(line, path.map(print, "pairs"))]);
    }
    case "HashPair": {
      return concat([n.key, "=", path.call(print, "value")]);
    }
    case "TextNode": {
      let leadingSpace = "";
      let trailingSpace = "";

      // preserve a space inside of an attribute node where whitespace present, when next to mustache statement.
      const inAttrNode = path.stack.indexOf("attributes") >= 0;

      if (inAttrNode) {
        const parentNode = path.getParentNode(0);
        const isConcat = parentNode.type === "ConcatStatement";
        if (isConcat) {
          const parts = parentNode.parts;
          const partIndex = parts.indexOf(n);
          if (partIndex > 0) {
            const partType = parts[partIndex - 1].type;
            const isMustache = partType === "MustacheStatement";
            if (isMustache) {
              leadingSpace = " ";
            }
          }
          if (partIndex < parts.length - 1) {
            const partType = parts[partIndex + 1].type;
            const isMustache = partType === "MustacheStatement";
            if (isMustache) {
              trailingSpace = " ";
            }
          }
        }
      }
      return n.chars
        .replace(/^\s+/, leadingSpace)
        .replace(/\s+$/, trailingSpace);
    }
    case "MustacheCommentStatement": {
      const dashes = n.value.indexOf("}}") > -1 ? "--" : "";
      return concat(["{{!", dashes, n.value, dashes, "}}"]);
    }
    case "PathExpression": {
      return n.original;
    }
    case "BooleanLiteral": {
      return String(n.value);
    }
    case "CommentStatement": {
      return concat(["<!--", n.value, "-->"]);
    }
    case "StringLiteral": {
      return printStringLiteral(n.value, options);
    }
    case "NumberLiteral": {
      return String(n.value);
    }
    case "UndefinedLiteral": {
      return "undefined";
    }
    case "NullLiteral": {
      return "null";
    }

    /* istanbul ignore next */
    default:
      throw new Error("unknown glimmer type: " + JSON.stringify(n.type));
  }
}
1252028
function dedot(path) { // eslint-disable-line complexity
  const inpath = `${ path }`;
  let outpath = '';
  const len = inpath.length;

  // Walk over segment by segment.
  // Accumulate output onto outpath.

  // i is the index past last sep considered.
  let i = 0;
  if (len && inpath[0] === sep) {
    outpath = sep;
    i = 1;
  }
  const rootLength = outpath.length;

  for (let nextSep; i < len; i = nextSep + 1) {
    nextSep = apply(indexOf, inpath, [ sep, i ]);
    if (nextSep < 0) {
      nextSep = len;
    }
    const segmentLen = nextSep - i;
    switch (segmentLen) {
      case 0:
        continue;
      case 1:
        if (inpath[i] === '.') {
          continue;
        }
        break;
      case 2:
        if (inpath[i] === '.' && inpath[i + 1] === '.') {
          const lastOutSep = apply(lastIndexOf, outpath, [ sep ]);
          outpath = apply(substring, outpath, [ 0, max(rootLength, lastOutSep) ]);
          continue;
        }
        break;
      default:
        break;
    }
    const segment = apply(substring, inpath, [ i, nextSep ]);
    outpath = outpath + (outpath.length > rootLength ? sep : '') + segment;
  }

  return outpath;
}