Replaces all magic __DIR__ and __FILE__ constants in the file with calculated value
493983
private function replaceMagicDirFileConstants(StreamMetaData $metadata): void
    {
        $magicConstFinder = new NodeFinderVisitor([Dir::class, File::class]);
        $traverser        = new NodeTraverser();
        $traverser->addVisitor($magicConstFinder);
        $traverser->traverse($metadata->syntaxTree);

        /** @var MagicConst[] $magicConstants */
        $magicConstants = $magicConstFinder->getFoundNodes();
        $magicFileValue = $metadata->uri;
        $magicDirValue  = dirname($magicFileValue);
        foreach ($magicConstants as $magicConstantNode) {
            $tokenPosition = $magicConstantNode->getAttribute('startTokenPos');
            $replacement   = $magicConstantNode instanceof Dir ? $magicDirValue : $magicFileValue;

            $metadata->tokenStream[$tokenPosition][1] = "'{$replacement}'";
        }
    }
400322
def write_library_constants():
    """"""
    from tcod._libtcod import lib, ffi
    import tcod.color

    with open("tcod/constants.py", "w") as f:
        all_names = []
        f.write(CONSTANT_MODULE_HEADER)
        for name in dir(lib):
            value = getattr(lib, name)
            if name[:5] == "TCOD_":
                if name.isupper():  # const names
                    f.write("%s = %r\n" % (name[5:], value))
                    all_names.append(name[5:])
            elif name.startswith("FOV"):  # fov const names
                f.write("%s = %r\n" % (name, value))
                all_names.append(name)
            elif name[:6] == "TCODK_":  # key name
                f.write("KEY_%s = %r\n" % (name[6:], value))
                all_names.append("KEY_%s" % name[6:])

        f.write("\n# --- colors ---\n")
        for name in dir(lib):
            if name[:5] != "TCOD_":
                continue
            value = getattr(lib, name)
            if not isinstance(value, ffi.CData):
                continue
            if ffi.typeof(value) != ffi.typeof("TCOD_color_t"):
                continue
            color = tcod.color.Color._new_from_cdata(value)
            f.write("%s = %r\n" % (name[5:], color))
            all_names.append(name[5:])

        all_names = ",\n    ".join('"%s"' % name for name in all_names)
        f.write("\n__all__ = [\n    %s,\n]\n" % (all_names,))

    with open("tcod/event_constants.py", "w") as f:
        all_names = []
        f.write(EVENT_CONSTANT_MODULE_HEADER)
        f.write("# --- SDL scancodes ---\n")
        f.write(
            "%s\n_REVERSE_SCANCODE_TABLE = %s\n"
            % parse_sdl_attrs("SDL_SCANCODE", all_names)
        )

        f.write("\n# --- SDL keyboard symbols ---\n")
        f.write(
            "%s\n_REVERSE_SYM_TABLE = %s\n"
            % parse_sdl_attrs("SDLK", all_names)
        )

        f.write("\n# --- SDL keyboard modifiers ---\n")
        f.write(
            "%s\n_REVERSE_MOD_TABLE = %s\n"
            % parse_sdl_attrs("KMOD", all_names)
        )

        f.write("\n# --- SDL wheel ---\n")
        f.write(
            "%s\n_REVERSE_WHEEL_TABLE = %s\n"
            % parse_sdl_attrs("SDL_MOUSEWHEEL", all_names)
        )
        all_names = ",\n    ".join('"%s"' % name for name in all_names)
        f.write("\n__all__ = [\n    %s,\n]\n" % (all_names,))
94391
function(files, name){
        var reg = /(_STYLE_NAME_|_SCRIPT_NAME_)/gi;
        var tpl = files.replace(reg, function(m,$1,$2){
            if(m == "_STYLE_NAME_"){
                return name;
            }else if(m == "_SCRIPT_NAME_"){
                return name;
            }else{
                return m;
            }
        });
        return tpl;
    }
238604
def replace_attribute(module_name, attribute_name, new_value, dry_run=True):
    """"""
    init_file = '%s/__init__.py' % module_name
    _, tmp_file = tempfile.mkstemp()

    with open(init_file) as input_file:
        with open(tmp_file, 'w') as output_file:
            for line in input_file:
                if line.startswith(attribute_name):
                    line = "%s = '%s'\n" % (attribute_name, new_value)

                output_file.write(line)

    if not dry_run:
        Path(tmp_file).copy(init_file)
    else:
        log.info(diff(tmp_file, init_file, retcode=None))
512969
def filtered_dir(module_name, *, additions={}, **kwargs):
    
    module = importlib.import_module(module_name)

    def __dir__():
        attr_names = set(filtered_attrs(module, **kwargs))
        attr_names.update(additions)
        return sorted(attr_names)

    return __dir__
756960
def update_file(filename, items):
    '''
    '''
    # TODO: Implement something in the templates to denote whether the value
    # being replaced is an XML attribute or a value. Perhaps move to dyanmic
    # XML tree building rather than string replacement.
    should_escape = filename.endswith('addon.xml')

    with open(filename, 'r') as inp:
        text = inp.read()

    for key, val in items.items():
        if should_escape:
            val = saxutils.quoteattr(val)
        text = text.replace('{%s}' % key, val)
    output = text

    with open(filename, 'w') as out:
        out.write(output)
988080
def replaceFieldValuePair( name, fid, filename, value )
      if @fvlist
         name = name.downcase if name
         name = name.gsub( /\W/, "_" )  if name
         @fvlist.each_index{|i|
            if (name and @fvlist[i].include?("<field name='#{name}'")) or
               (fid and @fvlist[i].include?("<field fid='#{fid}'"))
               @fvlist[i] = FieldValuePairXML.new( self, name, fid, filename, value ).to_s
               break
            end
         } 
      end
      @fvlist
   end
1289439
def adjustFiles(rec, op):  # type: (Any, Union[Callable[..., Any], partial[Any]]) -> None
    """"""

    if isinstance(rec, MutableMapping):
        if rec.get("class") == "File":
            rec["path"] = op(rec["path"])
        for d in rec:
            adjustFiles(rec[d], op)
    if isinstance(rec, MutableSequence):
        for d in rec:
            adjustFiles(d, op)
1008373
def set(constants):
    
    if not constants:
        return
    constants = wrap(constants)

    for k, new_value in constants.leaves():
        errors = []
        try:
            old_value = mo_dots_set_attr(sys.modules, k, new_value)
            continue
        except Exception as e:
            errors.append(e)

        # ONE MODULE IS MISSING, THE CALLING MODULE
        try:
            caller_globals = sys._getframe(1).f_globals
            caller_file = caller_globals["__file__"]
            if not caller_file.endswith(".py"):
                raise Exception("do not know how to handle non-python caller")
            caller_module = caller_file[:-3].replace("/", ".")

            path = split_field(k)
            for i, p in enumerate(path):
                if i == 0:
                    continue
                prefix = join_field(path[:1])
                name = join_field(path[i:])
                if caller_module.endswith(prefix):
                    old_value = mo_dots_set_attr(caller_globals, name, new_value)
                    if DEBUG:
                        from mo_logs import Log

                        Log.note(
                            "Changed {{module}}[{{attribute}}] from {{old_value}} to {{new_value}}",
                            module=prefix,
                            attribute=name,
                            old_value=old_value,
                            new_value=new_value
                        )
                    break
        except Exception as e:
            errors.append(e)

        if errors:
            from mo_logs import Log

            Log.error("Can not set constant {{path}}", path=k, cause=errors)
608831
def partial_replace(*indices)
      replacement = experiment.replacement
      new_content = Fast.replace_file @file, experiment.expression do |node, *captures|
        if indices.nil? || indices.empty? || indices.include?(match_index)
          if replacement.parameters.length == 1
            instance_exec node, &replacement
          else
            instance_exec node, *captures, &replacement
          end
        end
      end
      return unless new_content

      write_experiment_file(indices, new_content)
      new_content
    end
904670
def _update_file_args(self, file_mapping):
        """"""
        for key, value in self.args.items():
            new_value = file_mapping.get(value, value)
            if new_value != value:
                self.args[key] = new_value
1246252
def _replace_by(module_function, warn=False):
    """"""
    def decorate(func, module_function=module_function, warn=warn):
        sys.path.append(os.path.dirname(__file__))
        try:
            module, function = module_function.split('.')
            func, oldfunc = getattr(__import__(module), function), func
            globals()['__old_' + func.__name__] = oldfunc
        except Exception:
            if warn:
                warnings.warn("failed to import %s" % module_function)
        sys.path.pop()
        return func

    return decorate
691034
def magic_file(filename):
    
    head, foot = _file_details(filename)
    if not head:
        raise ValueError("Input was empty")
    try:
        info = _identify_all(head, foot, ext_from_filename(filename))
    except PureError:
        info = []
    info.sort(key=lambda x: x.confidence, reverse=True)
    return info
909182
def _adjust_template(filepath, translate):
    
    with open(filepath, 'r') as file:
        filedata = file.read()

    filedata = _multiple_replace(filedata, translate)

    with open(filepath, 'w') as file:
        file.write(filedata)
204099
def clean(self):

        """"""

        for s in self.visible_files.values():
            s.clean()
        for s in [sub[1][x] for sub in self.avail_files.values() for x in sub[1]]: # Double list comprehensions aren't very
            s.clean()
399542
def changiling(self, infile):
        '''
        '''
        gf = infile[31:]
        baby, fetch = (self.word_toaster() for _ in range(2))
        gf = [g.replace(baby, fetch) for g in gf]
        return infile[:31] + gf
57767
def _normalize_roots(file_roots):
    '''
    
    '''
    for saltenv, dirs in six.iteritems(file_roots):
        normalized_saltenv = six.text_type(saltenv)
        if normalized_saltenv != saltenv:
            file_roots[normalized_saltenv] = file_roots.pop(saltenv)
        if not isinstance(dirs, (list, tuple)):
            file_roots[normalized_saltenv] = []
        file_roots[normalized_saltenv] = \
                _expand_glob_path(file_roots[normalized_saltenv])
    return file_roots