Restore object from mat-file. TODO: determine format specification
767588
def restore(self, filename):
        
        matfile = loadmat(filename)

        if matfile['dim'] == 1:
            matfile['solution'] = matfile['solution'][0, :]

        self.elapsed_time = matfile['elapsed_time'][0, 0]
        self.solution = matfile['solution']

        return self
10514
def _read_mat_mnu0(filename):
    
    print('read_mag_single_file: {0}'.format(filename))

    mat = sio.loadmat(filename, squeeze_me=True)
    # check the version
    version = mat['MP']['Version'].item()
    if version != 'FZJ-EZ-2017':
        raise Exception(
            'This data format is not supported (expected: FZJ-EZ-2017)' +
            ' got: {}'.format(version)
        )

    df_emd = _extract_emd(mat, filename=filename)
    df_md = _extract_md(mat)

    return df_emd, df_md
1137948
def _reconstruct_data(values, dtype, original):
    
    from pandas import Index
    if is_extension_array_dtype(dtype):
        values = dtype.construct_array_type()._from_sequence(values)
    elif is_datetime64tz_dtype(dtype) or is_period_dtype(dtype):
        values = Index(original)._shallow_copy(values, name=None)
    elif is_bool_dtype(dtype):
        values = values.astype(dtype)

        # we only support object dtypes bool Index
        if isinstance(original, Index):
            values = values.astype(object)
    elif dtype is not None:
        values = values.astype(dtype)

    return values
651975
def convert_coco_stuff_mat(data_dir, out_dir):
    """"""
    sets = ['train', 'val']
    categories = []
    json_name = 'coco_stuff_%s.json'
    ann_dict = {}
    for data_set in sets:
        file_list = os.path.join(data_dir, '%s.txt')
        images = []
        with open(file_list % data_set) as f:
            for img_id, img_name in enumerate(f):
                img_name = img_name.replace('coco', 'COCO').strip('\n')
                image = {}
                mat_file = os.path.join(
                    data_dir, 'annotations/%s.mat' % img_name)
                data = h5py.File(mat_file, 'r')
                labelMap = data.get('S')
                if len(categories) == 0:
                    labelNames = data.get('names')
                    for idx, n in enumerate(labelNames):
                        categories.append(
                            {"id": idx, "name": ''.join(chr(i) for i in data[
                                n[0]])})
                    ann_dict['categories'] = categories
                scipy.misc.imsave(
                    os.path.join(data_dir, img_name + '.png'), labelMap)
                image['width'] = labelMap.shape[0]
                image['height'] = labelMap.shape[1]
                image['file_name'] = img_name
                image['seg_file_name'] = img_name
                image['id'] = img_id
                images.append(image)
        ann_dict['images'] = images
        print("Num images: %s" % len(images))
        with open(os.path.join(out_dir, json_name % data_set), 'wb') as outfile:
            outfile.write(json.dumps(ann_dict))
956357
def restore_type(self, type):
        

        # All dialects
        mapping = {
            ARRAY: 'array',
            sa.Boolean: 'boolean',
            sa.Date: 'date',
            sa.DateTime: 'datetime',
            sa.Float: 'number',
            sa.Integer: 'integer',
            JSONB: 'object',
            JSON: 'object',
            sa.Numeric: 'number',
            sa.Text: 'string',
            sa.Time: 'time',
            sa.VARCHAR: 'string',
            UUID: 'string',
        }

        # Get field type
        field_type = None
        for key, value in mapping.items():
            if isinstance(type, key):
                field_type = value

        # Not supported
        if field_type is None:
            message = 'Type "%s" is not supported'
            raise tableschema.exceptions.StorageError(message % type)

        return field_type
263725
function(obj) {
    //todo: support file type (useful?)
    var result = {};
    result.boundry = '-------------------------------'+Math.floor(Math.random()*1000000000);
    var lines = [];
    for(var p in obj){
        if (obj.hasOwnProperty(p)) {
            lines.push(
                '--'+result.boundry+"\n"+
                'Content-Disposition: form-data; name="'+p+'"'+"\n"+
                "\n"+
                obj[p]+"\n"
            );
        }
    }
    lines.push( '--'+result.boundry+'--' );
    result.body = lines.join('');
    result.length = result.body.length;
    result.type = 'multipart/form-data; boundary='+result.boundry;
    return result;
  }
886957
def _parse_mat_file(self, file_path):
        """"""
        mat_file_sections = self._extract_mat_sections(file_path)
        return self._analyse_mat_sections(mat_file_sections)
914567
def _unpack_object_array(inp, source, prescatter):
    
    raise NotImplementedError("Currently not used with record/struct/object improvements")
    base_rec, attr = source.rsplit(".", 1)
    new_name = "%s_%s_unpack" % (inp["name"], base_rec.replace(".", "_"))
    prescatter[base_rec].append((new_name, attr, _to_variable_type(inp["type"]["items"])))
    return new_name, prescatter
943092
function format (obj, sub) {
    var x = utils.clone(obj);
    if (x) {
        if ('Binary' === x.constructor.name) {
            x = '[object Buffer]';
        } else if ('ObjectID' === x.constructor.name) {
            var representation = 'ObjectId("' + x.toHexString() + '")';
            x = { inspect: function() { return representation; } };
        } else if ('Date' === x.constructor.name) {
            var representation = 'new Date("' + x.toUTCString() + '")';
            x = { inspect: function() { return representation; } };
        } else if ('Object' === x.constructor.name) {
            var keys = Object.keys(x)
                , i = keys.length
                , key
            while (i--) {
                key = keys[i];
                if (x[key]) {
                    if ('Binary' === x[key].constructor.name) {
                        x[key] = '[object Buffer]';
                    } else if ('Object' === x[key].constructor.name) {
                        x[key] = format(x[key], true);
                    } else if ('ObjectID' === x[key].constructor.name) {
                        ;(function(x){
                            var representation = 'ObjectId("' + x[key].toHexString() + '")';
                            x[key] = { inspect: function() { return representation; } };
                        })(x)
                    } else if ('Date' === x[key].constructor.name) {
                        ;(function(x){
                            var representation = 'new Date("' + x[key].toUTCString() + '")';
                            x[key] = { inspect: function() { return representation; } };
                        })(x)
                    } else if (Array.isArray(x[key])) {
                        x[key] = x[key].map(function (o) {
                            return format(o, true)
                        });
                    }
                }
            }
        }
        if (sub) return x;
    }

    return require('util')
        .inspect(x, false, 10, true)
        .replace(/\n/g, '')
        .replace(/\s{2,}/g, ' ')
}
728384
def _get_pasteas_data(self, dim, obj):
        

        if dim == 0:
            return [[repr(obj)]]
        elif dim == 1:
            return [[repr(o)] for o in obj]
        elif dim == 2:
            return [map(repr, o) for o in obj]
74738
def restore(self, x):
    
    with tf.name_scope("pad_reduce/restore"):
      x = tf.scatter_nd(
          indices=self.nonpad_ids,
          updates=x,
          shape=tf.concat([self.dim_origin, tf.shape(x)[1:]], axis=0),
      )
    return x
94593
def from_obj(cls, container, file_obj):
        """"""
        # RFC 1123: Thu, 07 Jun 2007 18:57:07 GMT
        return cls(container,
                   name=file_obj.name,
                   size=file_obj.size,
                   content_type=file_obj.content_type,
                   last_modified=dt_from_header(file_obj.last_modified),
                   obj_type=cls.choose_type(file_obj.content_type))
1029661
def restore_row(self, row, schema, pk):
        
        result = []
        for field in schema.fields:
            if schema.primary_key and schema.primary_key[0] == field.name:
                if field.type == 'number' and np.isnan(pk):
                    pk = None
                if pk and field.type == 'integer':
                    pk = int(pk)
                result.append(field.cast_value(pk))
            else:
                value = row[field.name]
                if field.type == 'number' and np.isnan(value):
                    value = None
                if value and field.type == 'integer':
                    value = int(value)
                elif field.type == 'datetime':
                    value = value.to_pydatetime()
                result.append(field.cast_value(value))
        return result
289181
def _format_object(obj, format_type=None):
    """"""

    if json_api_settings.FORMAT_KEYS is not None:
        return format_keys(obj, format_type)

    return format_field_names(obj, format_type)
1337931
def reconstruct(self, X=None):
        """"""

        if X is None:
            X = self.X
        return self.D.dot(self.X)
757682
def _reformat(p, buf):
    
    if numpy.ndim(buf) != 1:
        raise ValueError("Buffer ``buf`` must be 1-d.")
    if hasattr(p, 'keys'):
        ans = _gvar.BufferDict(p)
        if ans.size != len(buf):
            raise ValueError(       #
                "p, buf size mismatch: %d, %d"%(ans.size, len(buf)))
        ans = _gvar.BufferDict(ans, buf=buf)
    else:
        if numpy.size(p) != len(buf):
            raise ValueError(       #
                "p, buf size mismatch: %d, %d"%(numpy.size(p), len(buf)))
        ans = numpy.array(buf).reshape(numpy.shape(p))
    return ans
803152
def recover(self, key, value):
        """"""
        if key not in self._dtypes:
            self.read_types()
        if key not in self._dtypes:
            raise ValueError("Unknown datatype for {} and {}".format(key, value))
        return self._dtypes[key][2](value)