Python ordereddict.OrderedDict() Examples
The following are 30
code examples of ordereddict.OrderedDict().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ordereddict
, or try the search function
.
Example #1
Source File: test_workarea.py From alibuild with GNU General Public License v3.0 | 7 votes |
def test_referenceSourceExistsNonWriteable(self, mock_is_writeable, mock_os, mock_debug, mock_path, mock_execute, mock_getstatusoutput): # Reference sources exists but cannot be written # The reference repo is set nevertheless but not updated mock_path.exists.side_effect = lambda x: True mock_is_writeable.side_effect = lambda x: False mock_os.path.join.side_effect = join mock_getstatusoutput.side_effect = allow_directory_creation mock_git_clone = MagicMock(return_value=None) mock_git_fetch = MagicMock(return_value=None) mock_execute.side_effect = lambda x, **k: allow_git_clone(x, mock_git_clone, mock_git_fetch, *k) spec = OrderedDict({"source": "https://github.com/alisw/AliRoot"}) referenceSources = "sw/MIRROR" reference = abspath(referenceSources) + "/aliroot" mock_os.makedirs.reset_mock() mock_git_clone.reset_mock() mock_git_fetch.reset_mock() updateReferenceRepoSpec(referenceSources=referenceSources, p="AliRoot", spec=spec, fetch=True) mock_os.makedirs.assert_called_with('%s/sw/MIRROR' % getcwd()) self.assertEqual(mock_git_fetch.call_count, 0, "Expected no calls to git fetch (called %d times instead)" % mock_git_fetch.call_count) self.assertEqual(mock_git_clone.call_count, 0, "Expected no calls to git clone (called %d times instead)" % mock_git_clone.call_count) self.assertEqual(spec.get("reference"), reference) self.assertEqual(True, call('Updating references.') in mock_debug.mock_calls)
Example #2
Source File: xmltodict.py From SalesforceXyTools with Apache License 2.0 | 6 votes |
def startElement(self, full_name, attrs): name = self._build_name(full_name) attrs = self._attrs_to_dict(attrs) if attrs and self.namespace_declarations: attrs['xmlns'] = self.namespace_declarations self.namespace_declarations = OrderedDict() self.path.append((name, attrs or None)) if len(self.path) > self.item_depth: self.stack.append((self.item, self.data)) if self.xml_attribs: attr_entries = [] for key, value in attrs.items(): key = self.attr_prefix+self._build_name(key) if self.postprocessor: entry = self.postprocessor(self.path, key, value) else: entry = (key, value) if entry: attr_entries.append(entry) attrs = self.dict_constructor(attr_entries) else: attrs = None self.item = attrs or None self.data = []
Example #3
Source File: api.py From SalesforceXyTools with Apache License 2.0 | 6 votes |
def updated(self, start, end, headers=None): # pylint: disable=line-too-long """Gets a list of updated records Use the SObject Get Updated resource to get a list of updated (modified or added) records for the specified object. .../updated/?start=2014-03-20T00:00:00+00:00&end=2014-03-22T00:00:00+00:00 * start -- start datetime object * end -- end datetime object * headers -- a dict with additional request headers. """ url = urljoin( self.base_url, 'updated/?start={start}&end={end}'.format( start=date_to_iso8601(start), end=date_to_iso8601(end) ) ) result = self._call_salesforce(method='GET', url=url, headers=headers) return result.json(object_pairs_hook=OrderedDict)
Example #4
Source File: yamlordereddictloader.py From python-yamlordereddictloader with MIT License | 6 votes |
def construct_mapping(self, node, deep=False): if isinstance(node, yaml.MappingNode): self.flatten_mapping(node) else: msg = 'expected a mapping node, but found %s' % node.id raise yaml.constructor.ConstructError(None, None, msg, node.start_mark) mapping = OrderedDict() for key_node, value_node in node.value: key = self.construct_object(key_node, deep=deep) try: hash(key) except TypeError as err: raise yaml.constructor.ConstructError( 'while constructing a mapping', node.start_mark, 'found unacceptable key (%s)' % err, key_node.start_mark) value = self.construct_object(value_node, deep=deep) mapping[key] = value return mapping
Example #5
Source File: api.py From SalesforceXyTools with Apache License 2.0 | 6 votes |
def deleted(self, start, end, headers=None): # pylint: disable=line-too-long """Gets a list of deleted records Use the SObject Get Deleted resource to get a list of deleted records for the specified object. .../deleted/?start=2013-05-05T00:00:00+00:00&end=2013-05-10T00:00:00+00:00 * start -- start datetime object * end -- end datetime object * headers -- a dict with additional request headers. """ url = urljoin( self.base_url, 'deleted/?start={start}&end={end}'.format( start=date_to_iso8601(start), end=date_to_iso8601(end) ) ) result = self._call_salesforce(method='GET', url=url, headers=headers) return result.json(object_pairs_hook=OrderedDict)
Example #6
Source File: api.py From SalesforceXyTools with Apache License 2.0 | 6 votes |
def create(self, data, headers=None): """Creates a new SObject using a POST to `.../{object_name}/`. Returns a dict decoded from the JSON payload returned by Salesforce. Arguments: * data -- a dict of the data to create the SObject from. It will be JSON-encoded before being transmitted. * headers -- a dict with additional request headers. """ result = self._call_salesforce( method='POST', url=self.base_url, data=json.dumps(data), headers=headers ) return result.json(object_pairs_hook=OrderedDict)
Example #7
Source File: ese.py From cracke-dit with MIT License | 6 votes |
def __addItem(self, entry): dataDefinitionHeader = ESENT_DATA_DEFINITION_HEADER(entry['EntryData']) catalogEntry = ESENT_CATALOG_DATA_DEFINITION_ENTRY(entry['EntryData'][len(dataDefinitionHeader):]) itemName = self.__parseItemName(entry) if catalogEntry['Type'] == CATALOG_TYPE_TABLE: self.__tables[itemName] = OrderedDict() self.__tables[itemName]['TableEntry'] = entry self.__tables[itemName]['Columns'] = OrderedDict() self.__tables[itemName]['Indexes'] = OrderedDict() self.__tables[itemName]['LongValues'] = OrderedDict() self.__currentTable = itemName elif catalogEntry['Type'] == CATALOG_TYPE_COLUMN: self.__tables[self.__currentTable]['Columns'][itemName] = entry self.__tables[self.__currentTable]['Columns'][itemName]['Header'] = dataDefinitionHeader self.__tables[self.__currentTable]['Columns'][itemName]['Record'] = catalogEntry elif catalogEntry['Type'] == CATALOG_TYPE_INDEX: self.__tables[self.__currentTable]['Indexes'][itemName] = entry elif catalogEntry['Type'] == CATALOG_TYPE_LONG_VALUE: self.__addLongValue(entry) else: LOG.error('Unknown type 0x%x' % catalogEntry['Type']) raise
Example #8
Source File: api.py From SalesforceXyTools with Apache License 2.0 | 6 votes |
def get_by_custom_id(self, custom_id_field, custom_id, headers=None): """Return an ``SFType`` by custom ID Returns the result of a GET to `.../{object_name}/{custom_id_field}/{custom_id}` as a dict decoded from the JSON payload returned by Salesforce. Arguments: * custom_id_field -- the API name of a custom field that was defined as an External ID * custom_id - the External ID value of the SObject to get * headers -- a dict with additional request headers. """ custom_url = urljoin( self.base_url, '{custom_id_field}/{custom_id}'.format( custom_id_field=custom_id_field, custom_id=custom_id ) ) result = self._call_salesforce( method='GET', url=custom_url, headers=headers ) return result.json(object_pairs_hook=OrderedDict)
Example #9
Source File: api.py From SalesforceXyTools with Apache License 2.0 | 6 votes |
def describe_layout(self, record_id, headers=None): """Returns the layout of the object Returns the result of a GET to `.../{object_name}/describe/layouts/<recordid>` as a dict decoded from the JSON payload returned by Salesforce. Arguments: * record_id -- the Id of the SObject to get * headers -- a dict with additional request headers. """ custom_url_part = 'describe/layouts/{record_id}'.format( record_id=record_id ) result = self._call_salesforce( method='GET', url=urljoin(self.base_url, custom_url_part), headers=headers ) return result.json(object_pairs_hook=OrderedDict)
Example #10
Source File: xml2dict.py From hand-detection.PyTorch with MIT License | 6 votes |
def startElement(self, full_name, attrs): name = self._build_name(full_name) attrs = self._attrs_to_dict(attrs) if attrs and self.namespace_declarations: attrs['xmlns'] = self.namespace_declarations self.namespace_declarations = OrderedDict() self.path.append((name, attrs or None)) if len(self.path) > self.item_depth: self.stack.append((self.item, self.data)) if self.xml_attribs: attr_entries = [] for key, value in attrs.items(): key = self.attr_prefix+self._build_name(key) if self.postprocessor: entry = self.postprocessor(self.path, key, value) else: entry = (key, value) if entry: attr_entries.append(entry) attrs = self.dict_constructor(attr_entries) else: attrs = None self.item = attrs or None self.data = []
Example #11
Source File: ese.py From CVE-2017-7494 with GNU General Public License v3.0 | 6 votes |
def __addItem(self, entry): dataDefinitionHeader = ESENT_DATA_DEFINITION_HEADER(entry['EntryData']) catalogEntry = ESENT_CATALOG_DATA_DEFINITION_ENTRY(entry['EntryData'][len(dataDefinitionHeader):]) itemName = self.__parseItemName(entry) if catalogEntry['Type'] == CATALOG_TYPE_TABLE: self.__tables[itemName] = OrderedDict() self.__tables[itemName]['TableEntry'] = entry self.__tables[itemName]['Columns'] = OrderedDict() self.__tables[itemName]['Indexes'] = OrderedDict() self.__tables[itemName]['LongValues'] = OrderedDict() self.__currentTable = itemName elif catalogEntry['Type'] == CATALOG_TYPE_COLUMN: self.__tables[self.__currentTable]['Columns'][itemName] = entry self.__tables[self.__currentTable]['Columns'][itemName]['Header'] = dataDefinitionHeader self.__tables[self.__currentTable]['Columns'][itemName]['Record'] = catalogEntry elif catalogEntry['Type'] == CATALOG_TYPE_INDEX: self.__tables[self.__currentTable]['Indexes'][itemName] = entry elif catalogEntry['Type'] == CATALOG_TYPE_LONG_VALUE: self.__addLongValue(entry) else: LOG.error('Unknown type 0x%x' % catalogEntry['Type']) raise
Example #12
Source File: keyboard.py From deepWordBug with Apache License 2.0 | 6 votes |
def resolve_sequence(text, mapper, codes): r""" Return :class:`Keystroke` instance for given sequence ``text``. The given ``text`` may extend beyond a matching sequence, such as ``u\x1b[Dxxx`` returns a :class:`Keystroke` instance of attribute :attr:`Keystroke.sequence` valued only ``u\x1b[D``. It is up to determine that ``xxx`` remains unresolved. :arg text: string of characters received from terminal input stream. :arg OrderedDict mapper: unicode multibyte sequences, such as ``u'\x1b[D'`` paired by their integer value (260) :arg dict codes: a :type:`dict` of integer values (such as 260) paired by their mnemonic name, such as ``'KEY_LEFT'``. :rtype: Keystroke """ for sequence, code in mapper.items(): if text.startswith(sequence): return Keystroke(ucs=sequence, code=code, name=codes[code]) return Keystroke(ucs=text and text[0] or u'')
Example #13
Source File: core.py From jinjasql with MIT License | 6 votes |
def _prepare_query(self, template, data): try: _thread_local.bind_params = OrderedDict() _thread_local.param_style = self.param_style _thread_local.param_index = 0 query = template.render(data) bind_params = _thread_local.bind_params if self.param_style in ('named', 'pyformat'): bind_params = dict(bind_params) elif self.param_style in ('qmark', 'numeric', 'format', 'asyncpg'): bind_params = list(bind_params.values()) return query, bind_params finally: del _thread_local.bind_params del _thread_local.param_style del _thread_local.param_index
Example #14
Source File: utilities.py From alibuild with GNU General Public License v3.0 | 6 votes |
def parseDefaults(disable, defaultsGetter, log): defaultsMeta, defaultsBody = defaultsGetter() # Defaults are actually special packages. They can override metadata # of any other package and they can disable other packages. For # example they could decide to switch from ROOT 5 to ROOT 6 and they # could disable alien for O2. For this reason we need to parse their # metadata early and extract the override and disable data. defaultsDisable = asList(defaultsMeta.get("disable", [])) for x in defaultsDisable: log("Package %s has been disabled by current default." % x) disable.extend(defaultsDisable) if type(defaultsMeta.get("overrides", OrderedDict())) != OrderedDict: return ("overrides should be a dictionary", None, None) overrides, taps = OrderedDict(), {} commonEnv = {"env": defaultsMeta["env"]} if "env" in defaultsMeta else {} overrides["defaults-release"] = commonEnv for k, v in defaultsMeta.get("overrides", {}).items(): f = k.split("@", 1)[0].lower() if "@" in k: taps[f] = "dist:"+k overrides[f] = dict(**(v or {})) return (None, overrides, taps)
Example #15
Source File: test_workarea.py From alibuild with GNU General Public License v3.0 | 6 votes |
def test_referenceSourceExistsWriteable(self, mock_is_writeable, mock_os, mock_debug, mock_path, mock_execute, mock_getstatusoutput): # Reference sources exists and can be written # The reference repo is set nevertheless but not updated mock_path.exists.side_effect = lambda x: True mock_is_writeable.side_effect = lambda x: True mock_os.path.join.side_effect = join mock_getstatusoutput.side_effect = allow_directory_creation mock_git_clone = MagicMock(return_value=None) mock_git_fetch = MagicMock(return_value=None) mock_execute.side_effect = lambda x, **k: allow_git_clone(x, mock_git_clone, mock_git_fetch, *k) spec = OrderedDict({"source": "https://github.com/alisw/AliRoot"}) referenceSources = "sw/MIRROR" reference = abspath(referenceSources) + "/aliroot" mock_os.makedirs.reset_mock() mock_git_clone.reset_mock() mock_git_fetch.reset_mock() updateReferenceRepoSpec(referenceSources=referenceSources, p="AliRoot", spec=spec, fetch=True) mock_os.makedirs.assert_called_with('%s/sw/MIRROR' % getcwd()) self.assertEqual(mock_git_fetch.call_count, 1, "Expected one call to git fetch (called %d times instead)" % mock_git_fetch.call_count) self.assertEqual(mock_git_clone.call_count, 0, "Expected no calls to git clone (called %d times instead)" % mock_git_clone.call_count) self.assertEqual(spec.get("reference"), reference) self.assertEqual(True, call('Updating references.') in mock_debug.mock_calls)
Example #16
Source File: test_workarea.py From alibuild with GNU General Public License v3.0 | 6 votes |
def test_referenceBasedirExistsWriteable(self, mock_is_writeable, mock_os, mock_debug, mock_path, mock_execute, mock_getstatusoutput): """ The referenceSources directory exists and it's writeable Reference sources are already there """ mock_path.exists.side_effect = lambda x: True mock_is_writeable.side_effect = lambda x: True mock_os.path.join.side_effect = join mock_getstatusoutput.side_effect = allow_directory_creation mock_git_clone = MagicMock(return_value=None) mock_git_fetch = MagicMock(return_value=None) mock_execute.side_effect = lambda x, **k: allow_git_clone(x, mock_git_clone, mock_git_fetch, *k) spec = OrderedDict({"source": "https://github.com/alisw/AliRoot"}) referenceSources = "sw/MIRROR" reference = abspath(referenceSources) + "/aliroot" mock_os.makedirs.reset_mock() mock_git_clone.reset_mock() mock_git_fetch.reset_mock() updateReferenceRepo(referenceSources=referenceSources, p="AliRoot", spec=spec) mock_os.makedirs.assert_called_with('%s/sw/MIRROR' % getcwd()) self.assertEqual(mock_git_fetch.call_count, 1, "Expected one call to git fetch (called %d times instead)" % mock_git_fetch.call_count)
Example #17
Source File: test_workarea.py From alibuild with GNU General Public License v3.0 | 6 votes |
def test_referenceBasedirNotExistsWriteable(self, mock_is_writeable, mock_os, mock_debug, mock_path, mock_execute, mock_getstatusoutput): """ The referenceSources directory exists and it's writeable Reference sources are not already there """ mock_path.exists.side_effect = reference_sources_do_not_exists mock_is_writeable.side_effect = lambda x: False # not writeable mock_os.path.join.side_effect = join mock_os.makedirs.side_effect = lambda x: True mock_getstatusoutput.side_effect = allow_directory_creation mock_git_clone = MagicMock(return_value=None) mock_git_fetch = MagicMock(return_value=None) mock_execute.side_effect = lambda x, **k: allow_git_clone(x, mock_git_clone, mock_git_fetch, *k) spec = OrderedDict({"source": "https://github.com/alisw/AliRoot"}) referenceSources = "sw/MIRROR" reference = abspath(referenceSources) + "/aliroot" mock_os.makedirs.reset_mock() mock_git_clone.reset_mock() mock_git_fetch.reset_mock() updateReferenceRepo(referenceSources=referenceSources, p="AliRoot", spec=spec) mock_path.exists.assert_called_with('%s/sw/MIRROR/aliroot' % getcwd()) mock_os.makedirs.assert_called_with('%s/sw/MIRROR' % getcwd()) self.assertEqual(mock_git_clone.call_count, 0, "Expected no calls to git clone (called %d times instead)" % mock_git_clone.call_count)
Example #18
Source File: api.py From SalesforceXyTools with Apache License 2.0 | 6 votes |
def describe(self): """Describes all available objects """ url = self.base_url + "sobjects" result = self._call_salesforce('GET', url) if result.status_code != 200: raise SalesforceGeneralError(url, 'describe', result.status_code, result.content) json_result = result.json(object_pairs_hook=OrderedDict) if len(json_result) == 0: return None else: return json_result # SObject Handler
Example #19
Source File: api.py From SalesforceXyTools with Apache License 2.0 | 6 votes |
def restful(self, path, params, method='GET'): """Allows you to make a direct REST call if you know the path Arguments: * path: The path of the request Example: sobjects/User/ABC123/password' * params: dict of parameters to pass to the path * method: HTTP request method, default GET """ url = self.base_url + path result = self._call_salesforce(method, url, params=params) if result.status_code != 200: raise SalesforceGeneralError(url, path, result.status_code, result.content) json_result = result.json(object_pairs_hook=OrderedDict) if len(json_result) == 0: return None else: return json_result # Search Functions
Example #20
Source File: api.py From SalesforceXyTools with Apache License 2.0 | 6 votes |
def query(self, query, **kwargs): """Return the result of a Salesforce SOQL query as a dict decoded from the Salesforce response JSON payload. Arguments: * query -- the SOQL query to send to Salesforce, e.g. `SELECT Id FROM Lead WHERE Email = "waldo@somewhere.com"` """ url = self.base_url + 'query/' params = {'q': query} # `requests` will correctly encode the query string passed as `params` result = self._call_salesforce('GET', url, params=params, **kwargs) if result.status_code != 200: _exception_handler(result) return result.json(object_pairs_hook=OrderedDict)
Example #21
Source File: api.py From SalesforceXyTools with Apache License 2.0 | 5 votes |
def set_password(self, user, password): """Sets the password of a user salesforce dev documentation link: https://www.salesforce.com/us/developer/docs/api_rest/Content/dome_sobject_user_password.htm Arguments: * user: the userID of the user to set * password: the new password """ url = self.base_url + 'sobjects/User/%s/password' % user params = {'NewPassword': password} result = self._call_salesforce('POST', url, data=json.dumps(params)) # salesforce return 204 No Content when the request is successful if result.status_code != 200 and result.status_code != 204: raise SalesforceGeneralError(url, 'User', result.status_code, result.content) json_result = result.json(object_pairs_hook=OrderedDict) if len(json_result) == 0: return None else: return json_result # pylint: disable=invalid-name
Example #22
Source File: api.py From SalesforceXyTools with Apache License 2.0 | 5 votes |
def describe(self, headers=None): """Returns the result of a GET to `.../{object_name}/describe` as a dict decoded from the JSON payload returned by Salesforce. Arguments: * headers -- a dict with additional request headers. """ result = self._call_salesforce( method='GET', url=urljoin(self.base_url, 'describe'), headers=headers ) return result.json(object_pairs_hook=OrderedDict)
Example #23
Source File: api.py From SalesforceXyTools with Apache License 2.0 | 5 votes |
def query_more( self, next_records_identifier, identifier_is_url=False, **kwargs): """Retrieves more results from a query that returned more results than the batch maximum. Returns a dict decoded from the Salesforce response JSON payload. Arguments: * next_records_identifier -- either the Id of the next Salesforce object in the result, or a URL to the next record in the result. * identifier_is_url -- True if `next_records_identifier` should be treated as a URL, False if `next_records_identifer` should be treated as an Id. """ if identifier_is_url: # Don't use `self.base_url` here because the full URI is provided url = (u'https://{instance}{next_record_url}' .format(instance=self.sf_instance, next_record_url=next_records_identifier)) else: url = self.base_url + 'query/{next_record_id}' url = url.format(next_record_id=next_records_identifier) result = self._call_salesforce('GET', url, **kwargs) if result.status_code != 200: _exception_handler(result) return result.json(object_pairs_hook=OrderedDict)
Example #24
Source File: api.py From SalesforceXyTools with Apache License 2.0 | 5 votes |
def metadata(self, headers=None): """Returns the result of a GET to `.../{object_name}/` as a dict decoded from the JSON payload returned by Salesforce. Arguments: * headers -- a dict with additional request headers. """ result = self._call_salesforce('GET', self.base_url, headers=headers) return result.json(object_pairs_hook=OrderedDict)
Example #25
Source File: ese.py From cracke-dit with MIT License | 5 votes |
def __init__(self, fileName, pageSize = 8192, isRemote = False): self.__fileName = fileName self.__pageSize = pageSize self.__DB = None self.__DBHeader = None self.__totalPages = None self.__tables = OrderedDict() self.__currentTable = None self.__isRemote = isRemote self.mountDB()
Example #26
Source File: alphabeticalattributes.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def __iter__(self): for token in _base.Filter.__iter__(self): if token["type"] in ("StartTag", "EmptyTag"): attrs = OrderedDict() for name, value in sorted(token["data"].items(), key=lambda x: x[0]): attrs[name] = value token["data"] = attrs yield token
Example #27
Source File: alphabeticalattributes.py From vnpy_crypto with MIT License | 5 votes |
def __iter__(self): for token in base.Filter.__iter__(self): if token["type"] in ("StartTag", "EmptyTag"): attrs = OrderedDict() for name, value in sorted(token["data"].items(), key=lambda x: x[0]): attrs[name] = value token["data"] = attrs yield token
Example #28
Source File: pipdeptree.py From pipdeptree with MIT License | 5 votes |
def sort(self): """Return sorted tree in which the underlying _obj dict is an OrderedDict, sorted alphabetically by the keys :returns: Instance of same class with OrderedDict """ return self.__class__(sorted_tree(self._obj)) # Methods required by the abstract base class Mapping
Example #29
Source File: __init__.py From pipenv with MIT License | 5 votes |
def __init__(self, parameters=None, return_annotation=_empty, __validate_parameters__=True): '''Constructs Signature from the given list of Parameter objects and 'return_annotation'. All arguments are optional. ''' if parameters is None: params = OrderedDict() else: if __validate_parameters__: params = OrderedDict() top_kind = _POSITIONAL_ONLY for idx, param in enumerate(parameters): kind = param.kind if kind < top_kind: msg = 'wrong parameter order: {0} before {1}' msg = msg.format(top_kind, param.kind) raise ValueError(msg) else: top_kind = kind name = param.name if name is None: name = str(idx) param = param.replace(name=name) if name in params: msg = 'duplicate parameter name: {0!r}'.format(name) raise ValueError(msg) params[name] = param else: params = OrderedDict(((param.name, param) for param in parameters)) self._parameters = params self._return_annotation = return_annotation
Example #30
Source File: __init__.py From pipenv with MIT License | 5 votes |
def parameters(self): try: return types.MappingProxyType(self._parameters) except AttributeError: return OrderedDict(self._parameters.items())