How to use the dpath.util function in dpath

To help you get started, we’ve selected a few dpath examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github IntelAI / nauta / applications / cli / packs / tf_training.py View on Github external
def calculate_omp_num_threads(values_dict: dict) -> int:
    """
    Calculates correct value of OMP_NUM_THREADS according to CPU resources requested in template's values.yaml.
    :param values_dict: Dictionary containing template's values,yaml file
    :return: Calculated OMP_NUM_THREADS value
    :raises ValueError, TypeError, KeyError
    """
    if values_dict.get("cpu") and values_dict.get("cpu") != "null":
        cpu_limit = values_dict.get("cpu")
    elif values_dict.get("resources"):
        cpu_limit = dutil.get(values_dict, "resources.limits.cpu", separator='.')
    elif values_dict.get("worker_resources"):
        cpu_limit = dutil.get(values_dict, "worker_resources.limits.cpu", separator='.')
    else:
        raise ValueError('Unable to find requested CPUs count.')

    # We need to handle cases when CPU is provided either as absolute value, or in millicpu format.
    # Convert_k8s_cpu_resource returns cpu request in millicpus, so we divide it by 1000 to get absolute
    # value of cpus, and we make sure that there will be at least one thread.
    return int(max(convert_k8s_cpu_resource(cpu_limit) // 1000, 1))
github akesterson / dpath-python / tests / test_util_get_values.py View on Github external
def test_get_glob_single():
    ehash = {
        "a": {
            "b": {
                "c": {
                    "d": 0,
                    "e": 1,
                    "f": 2
                    }
                }
            }
        }
    assert(dpath.util.get(ehash, '/a/b/*/f') == 2)
    assert(dpath.util.get(ehash, ['a', 'b', '*', 'f']) == 2)
github akesterson / dpath-python / tests / test_unicode.py View on Github external
def test_unicode_search():
    a = {'中': ['zhong']}
    results = [[x[0], x[1]] for x in dpath.util.search(a, '*', yielded=True)]
    print(results)
    assert(len(results) == 1)
    assert(results[0][0] == '中')
    assert(results[0][1] == ['zhong'])
github Mirantis / mos-integration-tests / mos_tests / environment / fuel_client.py View on Github external
def ssl_config(self):
        return dpath.util.get(self.get_settings_data(), '*/public_ssl')
github awemulya / kobo-predict / apps / odk_viewer / views.py View on Github external
from django.template import loader, Context
    from dpath import util as dpath_util
    from dict2xml import dict2xml

    def geopoint_xpaths(username, id_string):
        d = DataDictionary.objects.get(
            user__username=username, id_string=id_string)
        return [e.get_abbreviated_xpath()
                for e in d.get_survey_elements()
                if e.bind.get(u'type') == u'geopoint']

    value = request.GET.get('coordinates')
    xpaths = geopoint_xpaths(username, id_string)
    xml_dict = {}
    for path in xpaths:
        dpath_util.new(xml_dict, path, value)

    context = {'username': username,
               'id_string': id_string,
               'xml_content': dict2xml(xml_dict)}
    instance_xml = loader.get_template("instance_add.xml")\
        .render(Context(context))

    url = settings.ENKETO_API_INSTANCE_IFRAME_URL
    return_url = reverse('thank_you_submission',
                         kwargs={"username": username, "id_string": id_string})
    if settings.DEBUG:
        openrosa_url = "https://dev.formhub.org/{}".format(username)
    else:
        openrosa_url = request.build_absolute_uri("/{}".format(username))
    payload = {'return_url': return_url,
               'form_id': id_string,
github robotcaresystems / RoboticsLanguage / RoboticsLanguage / Transformers / TemporalLogic / Transform.py View on Github external
logic_type = logic.tag

    # interval operator
    if len(logic.getchildren()) > 1:
      logic_type += 'Interval'

    # fill information about logic operator
    logic_name = logic_type + '_' + str(logic_id_counter) + '_'
    logic.attrib['temporalLogicId'] = str(logic_id_counter)
    logic.attrib['temporalLogicName'] = logic_name
    logic.attrib['temporalLogicVariables'] = ','.join(all_variables)

    # add logic update function to all variable involved in this operator
    for variable in all_variables:
      new_parameters = {}
      dpath.util.new(new_parameters, '/Transformers/Base/variables/' + variable + '/operators/assign/post/Cpp',
                     ['logic' + logic_type[0].title() + logic_type[1:] + str(logic_id_counter) + '()'])
      dpath.util.merge(parameters, new_parameters)

    # create text element for the GUI
    if 'HTMLGUI' in parameters['globals']['output']:

      # make a copy of the code to not polute it with extra attributes
      xml_copy = copy.deepcopy(logic)
      root = etree.Element("root")
      root.append(xml_copy)

      # use the RoL serialiser to create the text tag
      Serialise.serialise(root.getchildren()[0], parameters, parameters['language'], 'RoL')

      # annotate tag
      logic.attrib['temporalLogicText'] = root.getchildren()[0].attrib['RoL']
github IntelAI / nauta / applications / experiment-operator / nauta_resources / platform_resource.py View on Github external
async def update(self):
        logger.debug(f'Updating {self.__class__.__name__} {self.name}.')
        k8s_custom_object_api = await CustomResourceApiClient.get()

        patch_body = {}
        if self._fields_to_update:
            for field in self._fields_to_update:
                dpath.util.new(patch_body, field, dpath.util.get(self._body, field, separator='.'), separator='.')
            logger.debug(f'Patch body for {self.__class__.__name__} {self.name}: {patch_body}')
        else:
            logger.debug(f'No fields were changed in {self.__class__.__name__} {self.name}, skipping update.')
            return
        try:
            response = await k8s_custom_object_api.patch_namespaced_custom_object(group=self.api_group_name,
                                                                                  namespace=self.namespace,
                                                                                  body=patch_body,
                                                                                  plural=self.crd_plural_name,
                                                                                  version=self.crd_version,
                                                                                  name=self.name)
            self._fields_to_update = set()  # Clear after successful update
            return response
        except ApiException:
            logger.exception(f'Failed to update {self.__class__.__name__} {self.name}.')
            raise
github monasca / monasca-docker / job-cleanup / kubernetes.py View on Github external
def new(self, path, value):
        return dpath.util.new(self, path, value)