Evaluates a file containing a Python params dictionary.
12345
def eval_py(self, _globals, _locals):
        
        try:
            params = eval(self.script, _globals, _locals)
        except NameError as e:
            raise Exception(
                'Failed to evaluate parameters: {}'
                .format(str(e))
            )
        except ResolutionError as e:
            raise Exception('GetOutput: {}'.format(str(e)))

        return params
142356
def load_parameters(self, source):
        """"""
        with open(source) as parameters_source:
            loaded = yaml.safe_load(parameters_source.read())
            for k, v in loaded.items():
                if isinstance(v, str):
                    loaded[k] = "'"+v+"'"
            return loaded
326413
def evaluate(module_name: str, fname: str, verbose: bool):
    
    if verbose:
        print("Testing {}".format(fname))
    spec = importlib.util.spec_from_file_location(module_name, fname)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
314645
def evaluate(contents, jsonnet_library_paths=None):
    '''
    
    '''

    if not jsonnet_library_paths:
        jsonnet_library_paths = __salt__['config.option'](
                'jsonnet.library_paths', ['.'])
    return salt.utils.json.loads(
            _jsonnet.evaluate_snippet(
                "snippet",
                contents,
                import_callback=partial(
                    _import_callback, library_paths=jsonnet_library_paths)))
442819
def file_type(filename, param='rb'):
    """"""
    magic_dict = {
        b"\x1f\x8b\x08": "gz",
        b"\x42\x5a\x68": "bz2",
        b"\x50\x4b\x03\x04": "zip"
    }
    if param.startswith('w'):
        return filename.split('.')[-1]
    max_len = max(len(x) for x in magic_dict)
    with open(filename, 'rb') as f:
        file_start = f.read(max_len)
    for magic, filetype in list(magic_dict.items()):
        if file_start.startswith(magic):
            return filetype
    return "no match"
1245981
def parse_yaml_file(self, path):
        """"""
        with open(path, 'r') as fp:
            data = yaml.safe_load(fp)

        if not data:
            return {}

        def traverse(namespace, d):
            cfg = {}
            for key, val in d.items():
                if isinstance(d[key], dict):
                    cfg.update(traverse(namespace + [key], d[key]))
                else:
                    if not isinstance(val, str):
                        # All values should be double-quoted strings so they
                        # parse as strings; anything else is a configuration
                        # error at parse-time
                        raise ConfigurationError(
                            'Invalid value %r in file %s: values must be double-quoted strings' % (
                                val, path
                            )
                        )

                    cfg['_'.join(namespace + [key]).upper()] = val

            return cfg

        return traverse([], data)
593169
def paras(self: object, fileids: str):
        

        for text in self.texts(fileids):
            for para in text.split('\n\n'):
                yield para
182203
def make_param_dict_from_file(self,path_to_params):
        
        # then we were given a path to a parameter file
        param_list = list(csv.reader(open(path_to_params,"rb")))
        # delete empty elements (if any)
        param_file = [x for x in param_list if x != []]
        # make dict of [wavenames] = raw_params
        name_list = []
        param_list = []
        # get header names for each param (names of param_list columns)
        param_colnames = param_file[0][1:] # 0th element is "Name" or "Wavename"
        # start from 1.  (row 0 is the header)
        for i in np.arange(1, len(param_file)):
            name_list.append(param_file[i][0])
            param_list.append(param_file[i][1:])
        # remove ' ' blank spaces from param_list
        param_list = [[x.strip() for x in y] for y in param_list]
        param_dict = {}
        # i loops through param_colnames, j loops thru param values per wave
        for i in np.arange(0, len(param_colnames)):
            param_dict[param_colnames[i]] = []
            for j in np.arange(0,len(name_list)):
                param_dict[param_colnames[i]].append(param_list[j][i])
        # now we have param_dict, and name_list
        self._param_dict = param_dict
        self._row_names = name_list
827402
def from_file(cls, filename):
        """"""
        try:
            with open(filename, "r") as fh:
                return cls.from_dict(yaml.safe_load(fh))
        except Exception as exc:
            print("Error while reading TaskManager parameters from %s\n" % filename)
            raise
1085835
def _validate_file_roots(file_roots):
    '''
    
    '''
    if not isinstance(file_roots, dict):
        log.warning('The file_roots parameter is not properly formatted,'
                    ' using defaults')
        return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
    return _normalize_roots(file_roots)
1001322
def parse_file_to_dict(self, fname):
        
        print('TODO - parse_file_to_dict' + fname)
        for m in self.maps:
            if m.tpe == 'file':
                if m.key[0:3] == 'col':
                    print('reading column..')
479485
def pyle_evaluate(expressions=None, modules=(), inplace=False, files=None, print_traceback=False):
    """"""

    eval_globals = {}

    eval_globals.update(STANDARD_MODULES)

    for module_arg in modules or ():
        for module in module_arg.strip().split(","):
            module = module.strip()
            if module:
                eval_globals[module] = __import__(module)

    if not expressions:
        # Default 'do nothing' program
        expressions = ['line']

    files = files or ['-']
    eval_locals = {}
    for file in files:
        if file == '-':
            file = sys.stdin

        out_buf = sys.stdout if not inplace else StringIO.StringIO()

        out_line = None
        with (open(file, 'rb') if not hasattr(file, 'read') else file) as in_file:
            for num, line in enumerate(in_file.readlines()):
                was_whole_line = False
                if line[-1] == '\n':
                    was_whole_line = True
                    line = line[:-1]

                expr = ""
                try:
                    for expr in expressions:
                        words = [word.strip()
                                 for word in re.split(r'\s+', line)
                                 if word]
                        eval_locals.update({
                            'line': line, 'words': words,
                            'filename': in_file.name, 'num': num
                            })

                        out_line = eval(expr, eval_globals, eval_locals)

                        if out_line is None:
                            continue

                        # If the result is something list-like or iterable,
                        # output each item space separated.
                        if not isinstance(out_line, str) and not isinstance(out_line, unicode):
                            try:
                                out_line = u' '.join(unicode(part)
                                                     for part in out_line)
                            except:
                                # Guess it wasn't a list after all.
                                out_line = unicode(out_line)

                        line = out_line
                except Exception as e:
                    sys.stdout.flush()
                    sys.stderr.write("At %s:%d ('%s'): `%s`: %s\n" % (
                        in_file.name, num, truncate_ellipsis(line), expr, e))
                    if print_traceback:
                        traceback.print_exc(None, sys.stderr)
                else:
                    if out_line is None:
                        continue

                    out_line = out_line or u''
                    out_buf.write(out_line)
                    if was_whole_line:
                        out_buf.write('\n')
        if inplace:
            with open(file, 'wb') as out_file:
                out_file.write(out_buf.getvalue())
            out_buf.close()
1070324
def raw(cls, exp, files=None):
        
        payload = {'exp': exp}
        if files:
            # TODO: Implement stdin.
            stdin = []
            payload['args'] = json.dumps([stdin, files])
        try:
            return requests.get('http://tryhaskell.org/eval', params=payload).json()
        except ValueError as e:
            raise cls.Error(e)
926297
def params(self):
    """"""
    if hasattr(self, '_params_decoded'):
      return self._params_decoded

    if self.params_blob is not None:
      value_encoded = self.params_blob.open().read()
    else:
      value_encoded = self.params_text

    value = json.loads(value_encoded, cls=util.JsonDecoder)
    if isinstance(value, dict):
      kwargs = value.get('kwargs')
      if kwargs:
        adjusted_kwargs = {}
        for arg_key, arg_value in kwargs.iteritems():
          # Python only allows non-unicode strings as keyword arguments.
          adjusted_kwargs[str(arg_key)] = arg_value
        value['kwargs'] = adjusted_kwargs

    self._params_decoded = value
    return self._params_decoded
373290
def eval(self):
        
        if self.magic:
            return self.magic
        if not self.filename:
            return file_pattern.format(self.alias, self.ext)
        return self.path
304507
def read_dict_from_file(file_path):
    
    with open(file_path) as file:
        lines = file.read().splitlines()

    obj = {}
    for line in lines:
        key, value = line.split(':', maxsplit=1)
        obj[key] = eval(value)

    return obj
391578
def filter_params(self, value):
        
        if value is None:
            return {}

        key = self.target
        if self.lookup_type is not None:
            key += '__' + self.lookup_type
        return { key: value }