Converts a dictionary of variable star data to a `Body` instance.

    Requires `PyEphem <http://rhodesmill.org/pyephem/>`_ to be installed.
429378
def dict_to_body(star_dict):
    
    if ephem is None:  # pragma: no cover
        raise NotImplementedError("Please install PyEphem in order to use dict_to_body.")
    body = ephem.FixedBody()
    body.name = star_dict['name']
    body._ra = ephem.hours(str(star_dict['ra']))
    body._dec = ephem.degrees(str(star_dict['dec']))
    body._epoch = ephem.J2000
    return body
979266
def _body_builder(self, kwargs):
        
        p = {
            'action_name': self.name,
            'service_type': self.service_type,
            'arguments': '',
            }
        if kwargs:
            arguments = [
                self.argument_template % {'name': k, 'value': v}
                for k, v in kwargs.items()
            ]
            p['arguments'] = ''.join(arguments)
        body = self.body_template.strip() % p
        return body
119023
def _json_body_(cls):
        
        json = []
        for series_name, data in six.iteritems(cls._datapoints):
            for point in data:
                json_point = {
                    "measurement": series_name,
                    "fields": {},
                    "tags": {},
                    "time": getattr(point, "time")
                }

                for field in cls._fields:
                    value = getattr(point, field)
                    if value is not None:
                        json_point['fields'][field] = value

                for tag in cls._tags:
                    json_point['tags'][tag] = getattr(point, tag)

                json.append(json_point)
        return json
703398
def _create_body(self, name, label=None, agent=None, ip_addresses=None,
            metadata=None):
        
        label = label or name
        if ip_addresses is not None:
            body = {"label": label}
            if ip_addresses:
                body["ip_addresses"] = ip_addresses
            if agent:
                body["agent_id"] = utils.get_id(agent)
            if metadata:
                body["metadata"] = metadata
        return body
1236489
def decode_body(body, content_type):
        """"""

        if isinstance(body, dict):
            return body
        else:
            try:
                decoded_body = base64.b64decode(body)
            except:
                return body

            if content_type == 'application/json':
                try:
                    return json.loads(decoded_body)
                except:
                    pass

            return decoded_body
1233614
def from_dict(data, ctx):
        

        data = data.copy()

        if data.get('price') is not None:
            data['price'] = ctx.convert_decimal_number(
                data.get('price')
            )

        if data.get('bucketWidth') is not None:
            data['bucketWidth'] = ctx.convert_decimal_number(
                data.get('bucketWidth')
            )

        if data.get('buckets') is not None:
            data['buckets'] = [
                ctx.instrument.PositionBookBucket.from_dict(d, ctx)
                for d in data.get('buckets')
            ]

        return PositionBook(**data)
1017607
def convert_body(url, body):
        
        new_url = "%s.Post" % url
        params = json.loads(body)
        for key in params:
            new_url = "%s&%s=%s" % (new_url, key,
                                    re.sub(' ', '%20',
                                           str(params[key])))
        return new_url
986849
def get_body(name):
    

    body = Pck()[name]
    body.propagate = lambda date: get_orbit(name, date)
    return body
717785
def from_dict(cls, d):
        
        cohp_dict = {}
        efermi = d["efermi"]
        energies = d["energies"]
        structure = Structure.from_dict(d["structure"])
        if "bonds" in d.keys():
            bonds = {bond: {"length": d["bonds"][bond]["length"],
                            "sites": tuple(PeriodicSite.from_dict(site)
                                           for site in d["bonds"][bond]["sites"])}
                     for bond in d["bonds"]}
        else:
            bonds = None
        for label in d["COHP"]:
            cohp = {Spin(int(spin)): np.array(d["COHP"][label][spin])
                    for spin in d["COHP"][label]}
            try:
                icohp = {Spin(int(spin)): np.array(d["ICOHP"][label][spin])
                         for spin in d["ICOHP"][label]}
            except KeyError:
                icohp = None
            if label == "average":
                avg_cohp = Cohp(efermi, energies, cohp, icohp=icohp)
            else:
                cohp_dict[label] = Cohp(efermi, energies, cohp, icohp=icohp)

        if "orb_res_cohp" in d.keys():
            orb_cohp = {}
            for label in d["orb_res_cohp"]:
                orb_cohp[label] = {}
                for orb in d["orb_res_cohp"][label]:
                    cohp = {Spin(int(s)): np.array(
                        d["orb_res_cohp"][label][orb]["COHP"][s],
                        dtype=float)
                        for s in d["orb_res_cohp"][label][orb]["COHP"]}
                    try:
                        icohp = {Spin(int(s)): np.array(
                            d["orb_res_cohp"][label][orb]["ICOHP"][s],
                            dtype=float)
                            for s in d["orb_res_cohp"][label][orb]["ICOHP"]}
                    except KeyError:
                        icohp = None
                    orbitals = [tuple((int(o[0]), Orbital[o[1]])) for o in
                                d["orb_res_cohp"][label][orb]["orbitals"]]
                    orb_cohp[label][orb] = {"COHP": cohp, "ICOHP": icohp,
                                            "orbitals": orbitals}
                # If no total COHPs are present, calculate the total
                # COHPs from the single-orbital populations. Total COHPs
                # may not be present when the cohpgenerator keyword is used
                # in LOBSTER versions 2.2.0 and earlier.
                if label not in d["COHP"] or d["COHP"][label] is None:
                    cohp = {Spin.up: np.sum(np.array(
                        [orb_cohp[label][orb]["COHP"][Spin.up]
                         for orb in orb_cohp[label]]), axis=0)}
                    try:
                        cohp[Spin.down] = np.sum(np.array(
                            [orb_cohp[label][orb]["COHP"][Spin.down]
                             for orb in orb_cohp[label]]), axis=0)
                    except KeyError:
                        pass

                orb_res_icohp = None in [orb_cohp[label][orb]["ICOHP"]
                                         for orb in orb_cohp[label]]
                if (label not in d["ICOHP"] or
                    d["ICOHP"][label] is None) and orb_res_icohp:
                    icohp = {Spin.up: np.sum(np.array(
                        [orb_cohp[label][orb]["ICOHP"][Spin.up]
                         for orb in orb_cohp[label]]), axis=0)}
                    try:
                        icohp[Spin.down] = np.sum(np.array(
                            [orb_cohp[label][orb]["ICOHP"][Spin.down]
                             for orb in orb_cohp[label]]), axis=0)
                    except KeyError:
                        pass
        else:
            orb_cohp = None

        if "average" not in d["COHP"].keys():
            # calculate average
            cohp = np.array([np.array(c)
                             for c in d["COHP"].values()]).mean(axis=0)
            try:
                icohp = np.array([np.array(c)
                                  for c in d["ICOHP"].values()]).mean(axis=0)
            except KeyError:
                icohp = None
            avg_cohp = Cohp(efermi, energies, cohp, icohp=icohp)

        return CompleteCohp(structure, avg_cohp, cohp_dict, bonds=bonds,
                            are_coops=d["are_coops"], orb_res_cohp=orb_cohp)
436549
def _parse_body(self, body):
    
    if is_python3():
      return json.loads(body.decode('UTF-8'))
    else:
      return json.loads(body)
352596
def _to_dict_fixed_width_arrays(self, var_len_str=True):
        
        self.strings_to_categoricals()
        obs_rec, uns_obs = df_to_records_fixed_width(self._obs, var_len_str)
        var_rec, uns_var = df_to_records_fixed_width(self._var, var_len_str)
        layers = self.layers.as_dict()
        d = {
            'X': self._X,
            'obs': obs_rec,
            'var': var_rec,
            'obsm': self._obsm,
            'varm': self._varm,
            'layers': layers,
            # add the categories to the unstructured annotation
            'uns': {**self._uns, **uns_obs, **uns_var}}

        if self.raw is not None:
            self.strings_to_categoricals(self.raw._var)
            var_rec, uns_var = df_to_records_fixed_width(self.raw._var, var_len_str)
            d['raw.X'] = self.raw.X
            d['raw.var'] = var_rec
            d['raw.varm'] = self.raw.varm
            d['raw.cat'] = uns_var

        return d
791606
def create_from_dictionary(self, datas):
        
        configuration = ObjectConfiguration()

        if "uri" in datas:
            configuration.uri = str(datas["uri"])
        if "title" in datas:
            configuration.title = str(datas["title"])
        if "description" in datas:
            configuration.description = str(datas["description"])

        return configuration
1179218
def create_from_dictionary(self, datas):
        
        if "code" not in datas:
            raise ValueError("A response code must contain a code in \"%s\"." % repr(datas))

        code = ObjectResponseCode()
        self.set_common_datas(code, str(datas["code"]), datas)

        code.code = int(datas["code"])
        if "message" in datas:
            code.message = str(datas["message"])
        elif code.code in self.default_messages.keys():
            code.message = self.default_messages[code.code]
        if "generic" in datas:
            code.generic = to_boolean(datas["generic"])

        return code
648409
def unicode_body(self, ignore_errors=True, fix_special_entities=True):
        

        if not self._unicode_body:
            self._unicode_body = self.convert_body_to_unicode(
                body=self.body,
                bom=self.bom,
                charset=self.charset,
                ignore_errors=ignore_errors,
                fix_special_entities=fix_special_entities,
            )
        return self._unicode_body
974080
def wrap_json_body(func=None, *, preserve_raw_body=False):
    

    if func is None:
        return functools.partial(
            wrap_json_body,
            preserve_raw_body=preserve_raw_body
        )

    @functools.wraps(func)
    def wrapper(request, *args, **kwargs):
        ctype, pdict = parse_header(request.headers.get('Content-Type', ''))
        if preserve_raw_body:
            request.raw_body = request.body
        if ctype == "application/json":
            request.body = json.loads(request.body.decode("utf-8")) if request.body else None
        return func(request, *args, **kwargs)
    return wrapper
142554
def _from_python_type(self, obj, field, pytype):
        """"""
        json_schema = {
            'title': field.attribute or field.name,
        }

        for key, val in TYPE_MAP[pytype].items():
            json_schema[key] = val

        if field.dump_only:
            json_schema['readonly'] = True

        if field.default is not missing:
            json_schema['default'] = field.default

        # NOTE: doubled up to maintain backwards compatibility
        metadata = field.metadata.get('metadata', {})
        metadata.update(field.metadata)

        for md_key, md_val in metadata.items():
            if md_key == 'metadata':
                continue
            json_schema[md_key] = md_val

        if isinstance(field, fields.List):
            json_schema['items'] = self._get_schema_for_field(
                obj, field.container
            )
        return json_schema
898494
def text_to_data(self, text, elt, ps):
        '''
        '''
        prefix,localName = SplitQName(text)
        nsdict = ps.GetElementNSdict(elt)
        prefix = prefix or ''
        try:
            namespaceURI = nsdict[prefix]
        except KeyError, ex:
            raise EvaluateException('cannot resolve prefix(%s)'%prefix,
                ps.Backtrace(elt))
                
        v = (namespaceURI,localName)
        if self.pyclass is not None:
            return self.pyclass(v)    
        return v