Create Site from dict representation
513427
def from_dict(cls, d):
        
        atoms_n_occu = {}
        for sp_occu in d["species"]:
            if "oxidation_state" in sp_occu and Element.is_valid_symbol(
                    sp_occu["element"]):
                sp = Specie.from_dict(sp_occu)
            elif "oxidation_state" in sp_occu:
                sp = DummySpecie.from_dict(sp_occu)
            else:
                sp = Element(sp_occu["element"])
            atoms_n_occu[sp] = sp_occu["occu"]
        props = d.get("properties", None)
        return cls(atoms_n_occu, d["xyz"], properties=props)
676149
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'response_type' in _dict:
            args['response_type'] = _dict.get('response_type')
        else:
            raise ValueError(
                'Required property \'response_type\' not present in DialogRuntimeResponseGeneric JSON'
            )
        if 'text' in _dict:
            args['text'] = _dict.get('text')
        if 'time' in _dict:
            args['time'] = _dict.get('time')
        if 'typing' in _dict:
            args['typing'] = _dict.get('typing')
        if 'source' in _dict:
            args['source'] = _dict.get('source')
        if 'title' in _dict:
            args['title'] = _dict.get('title')
        if 'description' in _dict:
            args['description'] = _dict.get('description')
        if 'preference' in _dict:
            args['preference'] = _dict.get('preference')
        if 'options' in _dict:
            args['options'] = [
                DialogNodeOutputOptionsElement._from_dict(x)
                for x in (_dict.get('options'))
            ]
        if 'message_to_human_agent' in _dict:
            args['message_to_human_agent'] = _dict.get('message_to_human_agent')
        if 'topic' in _dict:
            args['topic'] = _dict.get('topic')
        if 'dialog_node' in _dict:
            args['dialog_node'] = _dict.get('dialog_node')
        if 'suggestions' in _dict:
            args['suggestions'] = [
                DialogSuggestion._from_dict(x)
                for x in (_dict.get('suggestions'))
            ]
        return cls(**args)
81328
def exportSite(self, location):
        
        params = {
            "location" : location,
            "f" : "json"
        }
        url = self._url + "/exportSite"
        return self._post(url=url, param_dict=params)
766171
def create(self, num_sites):
        
        super(Internet, self).create(num_sites)
        #print('building websites')
        for _ in range(0,num_sites):
            self.websites.append(Website())
348998
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'age' in _dict:
            args['age'] = FaceAge._from_dict(_dict.get('age'))
        if 'gender' in _dict:
            args['gender'] = FaceGender._from_dict(_dict.get('gender'))
        if 'face_location' in _dict:
            args['face_location'] = FaceLocation._from_dict(
                _dict.get('face_location'))
        return cls(**args)
564877
def from_api_response(cls, reddit_session, json_dict):
        """"""
        # The Multireddit response contains the Subreddits attribute as a list
        # of dicts of the form {'name': 'subredditname'}.
        # We must convert each of these into a Subreddit object.
        json_dict['subreddits'] = [Subreddit(reddit_session, item['name'])
                                   for item in json_dict['subreddits']]
        return cls(reddit_session, None, None, json_dict)
116139
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'document_id' in _dict:
            args['document_id'] = _dict.get('document_id')
        else:
            raise ValueError(
                'Required property \'document_id\' not present in DocumentStatus JSON'
            )
        if 'configuration_id' in _dict:
            args['configuration_id'] = _dict.get('configuration_id')
        if 'status' in _dict:
            args['status'] = _dict.get('status')
        else:
            raise ValueError(
                'Required property \'status\' not present in DocumentStatus JSON'
            )
        if 'status_description' in _dict:
            args['status_description'] = _dict.get('status_description')
        else:
            raise ValueError(
                'Required property \'status_description\' not present in DocumentStatus JSON'
            )
        if 'filename' in _dict:
            args['filename'] = _dict.get('filename')
        if 'file_type' in _dict:
            args['file_type'] = _dict.get('file_type')
        if 'sha1' in _dict:
            args['sha1'] = _dict.get('sha1')
        if 'notices' in _dict:
            args['notices'] = [
                Notice._from_dict(x) for x in (_dict.get('notices'))
            ]
        else:
            raise ValueError(
                'Required property \'notices\' not present in DocumentStatus JSON'
            )
        return cls(**args)
1126633
def _generate_create_dict(
            self, cpus=None, memory=None, hourly=True,
            hostname=None, domain=None, local_disk=True,
            datacenter=None, os_code=None, image_id=None,
            dedicated=False, public_vlan=None, private_vlan=None,
            private_subnet=None, public_subnet=None,
            userdata=None, nic_speed=None, disks=None, post_uri=None,
            private=False, ssh_keys=None, public_security_groups=None,
            private_security_groups=None, boot_mode=None, **kwargs):
        
        required = [hostname, domain]

        flavor = kwargs.get('flavor', None)
        host_id = kwargs.get('host_id', None)

        mutually_exclusive = [
            {'os_code': os_code, 'image_id': image_id},
            {'cpu': cpus, 'flavor': flavor},
            {'memory': memory, 'flavor': flavor},
            {'flavor': flavor, 'dedicated': dedicated},
            {'flavor': flavor, 'host_id': host_id}
        ]

        if not all(required):
            raise ValueError("hostname, and domain are required")

        for mu_ex in mutually_exclusive:
            if all(mu_ex.values()):
                raise ValueError(
                    'Can only specify one of: %s' % (','.join(mu_ex.keys())))

        data = {
            "startCpus": cpus,
            "maxMemory": memory,
            "hostname": hostname,
            "domain": domain,
            "localDiskFlag": local_disk,
            "hourlyBillingFlag": hourly,
            "supplementalCreateObjectOptions": {
                "bootMode": boot_mode
            }
        }

        if flavor:
            data["supplementalCreateObjectOptions"]["flavorKeyName"] = flavor

        if dedicated and not host_id:
            data["dedicatedAccountHostOnlyFlag"] = dedicated

        if host_id:
            data["dedicatedHost"] = {"id": host_id}

        if private:
            data['privateNetworkOnlyFlag'] = private

        if image_id:
            data["blockDeviceTemplateGroup"] = {"globalIdentifier": image_id}
        elif os_code:
            data["operatingSystemReferenceCode"] = os_code

        if datacenter:
            data["datacenter"] = {"name": datacenter}

        if private_vlan or public_vlan or private_subnet or public_subnet:
            network_components = self._create_network_components(public_vlan, private_vlan,
                                                                 private_subnet, public_subnet)
            data.update(network_components)

        if public_security_groups:
            secgroups = [{'securityGroup': {'id': int(sg)}}
                         for sg in public_security_groups]
            pnc = data.get('primaryNetworkComponent', {})
            pnc['securityGroupBindings'] = secgroups
            data.update({'primaryNetworkComponent': pnc})

        if private_security_groups:
            secgroups = [{'securityGroup': {'id': int(sg)}}
                         for sg in private_security_groups]
            pbnc = data.get('primaryBackendNetworkComponent', {})
            pbnc['securityGroupBindings'] = secgroups
            data.update({'primaryBackendNetworkComponent': pbnc})

        if userdata:
            data['userData'] = [{'value': userdata}]

        if nic_speed:
            data['networkComponents'] = [{'maxSpeed': nic_speed}]

        if disks:
            data['blockDevices'] = [
                {"device": "0", "diskImage": {"capacity": disks[0]}}
            ]

            for dev_id, disk in enumerate(disks[1:], start=2):
                data['blockDevices'].append(
                    {
                        "device": str(dev_id),
                        "diskImage": {"capacity": disk}
                    }
                )

        if post_uri:
            data['postInstallScriptUri'] = post_uri

        if ssh_keys:
            data['sshKeys'] = [{'id': key_id} for key_id in ssh_keys]

        return data
1120647
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'configurations' in _dict:
            args['configurations'] = [
                Configuration._from_dict(x)
                for x in (_dict.get('configurations'))
            ]
        return cls(**args)
1132114
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'contentItems' in _dict:
            args['content_items'] = [
                ContentItem._from_dict(x) for x in (_dict.get('contentItems'))
            ]
        else:
            raise ValueError(
                'Required property \'contentItems\' not present in Content JSON'
            )
        return cls(**args)
796267
def create(cls, api, default_name=None, description=None):
        
        path = 'group'

        data = {}
        if default_name:
            data['default_group_name'] = default_name
        if description:
            data['description'] = description
        if api.domain:
            data['domain'] = api.domain

        response_data = api.request(path, data=data)

        id = response_data['group_id']
        group = cls(api, id)
        group.default_name = response_data['default_group_name']

        return group
401864
def from_dict(cls, d):
        
        return cls(
            d['id'],
            d['start'],
            d['end'],
            Lnk.charspan(d['from'], d['to']) if 'from' in d else None,
            # d.get('paths', [1]),
            form=d['form'],
            surface=d.get('surface'),
            # ipos=
            # lrules=
            pos=zip(d.get('tags', []), d.get('probabilities', []))
        )
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)
1168690
def as_dict(self):
        
        d = {"@module": self.__class__.__module__,
             "@class": self.__class__.__name__,
             "charge": self._charge,
             "spin_multiplicity": self._spin_multiplicity,
             "sites": []}
        for site in self:
            site_dict = site.as_dict()
            del site_dict["@module"]
            del site_dict["@class"]
            d["sites"].append(site_dict)
        return d
1252526
def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self, 'site_collection_path'
                  ) and self.site_collection_path is not None:
            _dict['site_collection_path'] = self.site_collection_path
        if hasattr(self, 'limit') and self.limit is not None:
            _dict['limit'] = self.limit
        return _dict
755474
def construct_url(self):
        """"""
        path = [self.path]
        path.extend([str(x) for x in self.params])

        url = self.client.base_url + '/'.join(x for x in path if x)
        query = self.kwargs.get('query')

        if query:
            # Dict -> List
            if type(query) is dict:
                query = query.items()

            # Remove items with `None` value
            query = [
                (k, v) for (k, v) in query
                if v is not None
            ]

            # Encode query, append to URL
            url += '?' + urlencode(query)

        return url
85524
def initview(request, response_cache=True):
	''''''

	http_host, path_info = ( smart_unicode(part.strip('/')) for part in
		[ request.META['HTTP_HOST'],
			request.META.get('REQUEST_URI', request.META.get('PATH_INFO', '/')) ] )
	query_string = request.META['QUERY_STRING']

	url = '{0}/{1}'.format(http_host, path_info)
	cachekey = u'{0}?{1}'.format(*it.imap(smart_unicode, (path_info, query_string)))
	hostdict = fjcache.hostcache_get() or dict()

	site_id = hostdict[url] if url in hostdict else None
	if site_id and response_cache:
		response = fjcache.cache_get(site_id, cachekey)
		if response: return response, None, cachekey

	if site_id: site = models.Site.objects.get(pk=site_id)
	else: # match site from all of them
		sites = list(models.Site.objects.all())

		if not sites:
			# Somebody is requesting something, but the user
			#  didn't create a site yet. Creating a default one...
			site = models.Site(
				name='Default Feedjack Site/Planet',
				url=request.build_absolute_uri(request.path),
				title='Feedjack Site Title',
				description='Feedjack Site Description.'
					' Please change this in the admin interface.',
				template='bootstrap' )
			site.save()

		else:
			# Select the most matching site possible,
			#  preferring "default" when everything else is equal
			results = defaultdict(list)
			for site in sites:
				relevance, site_url = 0, urlparse(site.url)
				if site_url.netloc == http_host: relevance += 10 # host matches
				if path_info.startswith(site_url.path.strip('/')): relevance += 10 # path matches
				if site.default_site: relevance += 5 # marked as "default"
				results[relevance].append((site_url, site))
			for relevance in sorted(results, reverse=True):
				try: site_url, site = results[relevance][0]
				except IndexError: pass
				else: break
			if site_url.netloc != http_host: # redirect to proper site hostname
				response = HttpResponsePermanentRedirect(
					'http://{0}/{1}{2}'.format( site_url.netloc, path_info,
						'?{0}'.format(query_string) if query_string.strip() else '') )
				return (response, timezone.now()), None, cachekey

		hostdict[url] = site_id = site.id
		fjcache.hostcache_set(hostdict)

	if response_cache:
		response = fjcache.cache_get(site_id, cachekey)
		if response: return response, None, cachekey

	return None, site, cachekey