Build a basic values object used in every create method.

       All our resources contain a same subset of value. Instead of
       redoing this code everytime, this method ensures it is done only at
       one place.
967803
def common_values_dict():
    
    now = datetime.datetime.utcnow().isoformat()
    etag = utils.gen_etag()
    values = {
        'id': utils.gen_uuid(),
        'created_at': now,
        'updated_at': now,
        'etag': etag
    }

    return values
349610
def new(self, *args, **kwargs) -> str:
        
        args = list(args)

        data = [self.prefix]

        for part in self._part_names:
            value = kwargs.pop(part, None)
            if value is None:
                if args:
                    value = args.pop(0)
                else:
                    raise ValueError(f"Value for '{part}' is not passed!")

            if value is not None and not isinstance(value, str):
                value = str(value)

            if not value:
                raise ValueError(f"Value for part {part} can't be empty!'")
            elif self.sep in value:
                raise ValueError(f"Symbol defined as separator can't be used in values of parts")

            data.append(value)

        if args or kwargs:
            raise TypeError('Too many arguments is passed!')

        callback_data = self.sep.join(data)
        if len(callback_data) > 64:
            raise ValueError('Resulted callback data is too long!')

        return callback_data
107628
def set(self, instance, value, **kw):  # noqa
        
        ref = []

        # The value is an UID
        if api.is_uid(value):
            ref.append(api.get_object_by_uid(value))

        # The value is already an object
        if api.is_at_content(value):
            ref.append(value)

        # The value is a dictionary
        # -> handle it like a catalog query
        if u.is_dict(value):
            results = api.search(portal_type=self.allowed_types, **value)
            ref = map(api.get_object, results)

        # The value is a list
        if u.is_list(value):
            for item in value:
                # uid
                if api.is_uid(item):
                    ref.append(api.get_object_by_uid(item))
                    continue

                # object
                if api.is_at_content(item):
                    ref.append(api.get_object(item))
                    continue

                # path
                if api.is_path(item):
                    ref.append(api.get_object_by_path(item))
                    continue

                # dict (catalog query)
                if u.is_dict(item):
                    # If there is UID of objects, just use it.
                    uid = item.get('uid', None)
                    if uid:
                        obj = api.get_object_by_uid(uid)
                        ref.append(obj)
                    else:
                        results = api.search(portal_type=self.allowed_types, **item)
                        objs = map(api.get_object, results)
                        ref.extend(objs)
                    continue

                # Plain string
                # -> do a catalog query for title
                if isinstance(item, basestring):
                    results = api.search(portal_type=self.allowed_types, title=item)
                    objs = map(api.get_object, results)
                    ref.extend(objs)
                    continue

        # The value is a physical path
        if api.is_path(value):
            ref.append(api.get_object_by_path(value))

        # Handle non multi valued fields
        if not self.multi_valued:
            if len(ref) > 1:
                raise ValueError("Multiple values given for single valued "
                                 "field {}".format(repr(self.field)))
            else:
                ref = ref[0]
        return self._set(instance, ref, **kw)
394689
def render_create(self, value, system, common_kw):
        
        kw = self._get_create_update_kwargs(value, common_kw)
        return JHTTPCreated(**kw)
439618
def init(cls, *args, **kwargs):
        """"""
        instance = cls()
        instance._values.update(dict(*args, **kwargs))
        return instance
1062339
public Client createWithValues(Object... varValues) {
        serviceFactory.setBus(getBus());
        checkResources(false);
        ClassResourceInfo cri = null;
        try {
            Endpoint ep = createEndpoint();
            if (getServiceClass() != null) {
                for (ClassResourceInfo info : serviceFactory.getClassResourceInfo()) {
                    if (info.getServiceClass().isAssignableFrom(getServiceClass())
                        || getServiceClass().isAssignableFrom(info.getServiceClass())) {
                        cri = info;
                        break;
                    }
                }
                if (cri == null) {
                    // can not happen in the reality
                    throw new RuntimeException("Service class " + getServiceClass().getName()
                                               + " is not recognized");
                }
            } else {
                cri = serviceFactory.getClassResourceInfo().get(0);
            }

            boolean isRoot = cri.getURITemplate() != null;
            ClientProxyImpl proxyImpl = null;
            ClientState actualState = getActualState();
            proxyImpl = createClientProxy(cri, isRoot, actualState, varValues);
            initClient(proxyImpl, ep, actualState == null);

            final Class<?> serviceClass = cri.getServiceClass();
            ClassLoader theLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {

                @Override
                public ClassLoader run() {
                    return proxyLoader == null ? serviceClass.getClassLoader() : proxyLoader;
                }
            });
            Class<?>[] ifaces = new Class[]{Client.class, InvocationHandlerAware.class, cri.getServiceClass()};
            Client actualClient = (Client)ProxyHelper.getProxy(theLoader, ifaces, proxyImpl);
            proxyImpl.setProxyClient(actualClient);
            notifyLifecycleManager(actualClient);
            this.getServiceFactory().sendEvent(FactoryBeanListener.Event.CLIENT_CREATED, actualClient, ep);
            return actualClient;
        } catch (IllegalArgumentException ex) {
            String message = ex.getLocalizedMessage();
            if (cri != null) {
                String expected = cri.getServiceClass().getSimpleName();
                if ((expected + " is not an interface").equals(message)) {
                    message += "; make sure CGLIB is on the classpath";
                }
            }
            LOG.severe(ex.getClass().getName() + " : " + message);
            throw ex;
        } catch (Exception ex) {
            LOG.severe(ex.getClass().getName() + " : " + ex.getLocalizedMessage());
            throw new RuntimeException(ex);
        }

    }
102944
def append(name, value)
      
      if respond_to?(name)
        send("append_to_#{name}",value)
      elsif Configuration.setting_name_to_property(name)
        send("append_to_#{Configuration.setting_name_to_property(name)}",value)
      else

        # @note this will likely raise some errors if trying to append a booleans
        #   to fixnums, strings to booleans, symbols + arrays, etc. but that likely 
        #   means a new property should be defined so that the appending logic
        #   wil behave correctly.
  
        if build_settings[name].is_a?(Array)
          
          # Ensure that we are appending an array to the array; Array() does not
          # work in this case in the event we were to pass in a Hash.
          value = value.is_a?(Array) ? value : [ value ]
          build_settings[name] = build_settings[name] + value.compact
          
        else
          
          # Ensure we handle the cases where a nil value is present that we append
          # correctly to the value. We also need to try and leave intact boolean
          # values which may be stored
          
          value = "" unless value
          build_settings[name] = "" unless build_settings[name]
          
          build_settings[name] = build_settings[name] + value
        end
       
      end
    end
940566
def create(key, value, options = {})
      last = false
      @stack.each {|s| last = s.create(key, value, options) }
      last
    end
598020
public function build()
    {
        $value = $this->getValue();

        $this->uppercaseComparator();

        // Check for IS/IS NOT and set the value to NULL if it is.
        if ($this->isComparatorIsNotNullIsNull()) {
            $value = null;
        }

        // Check for IN/NOT IN and build a nice comma-separated list.
        if (!$this->isComparatorIsNotNullIsNull() && $this->isComparatorInNotIn() && is_array($value)) {
            $this->uppercaseComparator();
            $valueArray = [];
            foreach ($value as $valueItem) {
                if ($this->shouldQuoteValues()) {
                    $valueArray[] = $this->query->quote($valueItem);
                } else {
                    $valueArray[] = $valueItem;
                }
            }
            $value = '(' . implode(',', $valueArray) . ')';
        }

        // Now check if we need to still quote the value.
        if (!$this->isComparatorIsNotNullIsNull() && !$this->isComparatorInNotIn() && $this->shouldQuoteValues()) {
            $value = $this->query->quote($value);
        }

        // If we don't have IN/NOT IN, IS/NOT IS, and we shouldn't quote, we assume we're checking fields.
        if ($this->shouldCompareFields()) {
            $valueBuild = [
                $this->query->quoteIdentifier($this->getTableName()),
                '.',
                $this->query->quoteIdentifier($value),
            ];
            $value = implode($valueBuild);
        }

        $tableName = $this->getTableName();
        if ($this->getJoinTableName()) {
            $tableName = $this->getJoinTableName();
        }
        $tableName = $this->query->quoteIdentifier($tableName);

        $returnArray = [
            $tableName . '.' . $this->query->quoteIdentifier($this->getKey()),
            $this->getComparator(),
            $value,
        ];
        $returnString = implode(' ', $returnArray);

        return trim($returnString);
    }
81384
@SuppressWarnings("unchecked")
    protected void buildObject() {

        final Class<?> objectType = ClassUtility.findGenericClass(this.getClass(), OBJECT_EXCLUDED_CLASSES);

        // If not generic type is defined for Object, object field will remain null
        if (objectType != null) {
            Object keyPart = null;
            boolean found = false;
            for (int i = 0; !found && i < getListKeyPart().size(); i++) {
                keyPart = getListKeyPart().get(i);

                if (objectType.isAssignableFrom(keyPart.getClass())) {

                    this.object = (O) keyPart;
                    found = true;
                }
            }

            if (this.object == null) {
                // Build the current default object by reflection if it hadn't been provided into the key without any constructor parameters
                try {
                    this.object = (O) ClassUtility.buildGenericType(this.getClass(), OBJECT_EXCLUDED_CLASSES);
                } catch (final CoreException ce) {
                    LOGGER.log(UIMessages.CREATION_FAILURE, ce, this.getClass().getName());
                    throw new CoreRuntimeException(ce);
                }
            }
        }
    }
212526
def _init_values(self, context=None):
        
        if context is None:
            context = self.env.context
        # Get basic fields (no relational ones)
        basic_fields = []
        for field_name in self._columns:
            field = self._columns[field_name]
            if not getattr(field, 'relation', False):
                basic_fields.append(field_name)
        # Fetch values from the server
        if self.ids:
            rows = self.__class__.read(
                self.ids, basic_fields, context=context, load='_classic_write')
            ids_fetched = set()
            for row in rows:
                ids_fetched.add(row['id'])
                for field_name in row:
                    if field_name == 'id':
                        continue
                    self._values[field_name][row['id']] = row[field_name]
            ids_in_error = set(self.ids) - ids_fetched
            if ids_in_error:
                raise ValueError(
                    "There is no '{model}' record with IDs {ids}.".format(
                        model=self._name, ids=list(ids_in_error)))
        # No ID: fields filled with default values
        else:
            default_get = self.__class__.default_get(
                list(self._columns), context=context)
            for field_name in self._columns:
                self._values[field_name][None] = default_get.get(
                    field_name, False)
1072710
def build_inside(input_method, input_args=None, substitutions=None):
    
    def process_keyvals(keyvals):
        """ ["key=val", "x=y"] -> {"key": "val", "x": "y"} """
        keyvals = keyvals or []
        processed_keyvals = {}
        for arg in keyvals:
            key, value = arg.split("=", 1)
            processed_keyvals[key] = value
        return processed_keyvals

    main = __name__.split('.', 1)[0]
    log_encoding = get_logging_encoding(main)
    logger.info("log encoding: %s", log_encoding)

    if not input_method:
        raise RuntimeError("No input method specified!")

    logger.debug("getting build json from input %s", input_method)

    cleaned_input_args = process_keyvals(input_args)
    cleaned_input_args['substitutions'] = process_keyvals(substitutions)

    input_runner = InputPluginsRunner([{'name': input_method,
                                        'args': cleaned_input_args}])
    build_json = input_runner.run()[input_method]

    if isinstance(build_json, Exception):
        raise RuntimeError("Input plugin raised exception: {}".format(build_json))
    logger.debug("build json: %s", build_json)
    if not build_json:
        raise RuntimeError("No valid build json!")
    if not isinstance(build_json, dict):
        raise RuntimeError("Input plugin did not return valid build json: {}".format(build_json))

    dbw = DockerBuildWorkflow(**build_json)
    try:
        build_result = dbw.build_docker_image()
    except Exception as e:
        logger.error('image build failed: %s', e)
        raise
    else:
        if not build_result or build_result.is_failed():
            raise RuntimeError("no image built")
        else:
            logger.info("build has finished successfully \\o/")
1235200
def build(self, **values: Any) -> str:
        """"""
        converted_values = {
            key: self._converters[key].to_url(value)
            for key, value in values.items()
            if key in self._converters
        }
        result = self._builder.format(**converted_values).split('|', 1)[1]
        query_string = urlencode(
            {
                key: value
                for key, value in values.items()
                if key not in self._converters and key not in self.defaults
            },
            doseq=True,
        )
        if query_string:
            result = "{}?{}".format(result, query_string)
        return result
587872
public static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
      Value.Builder... rest) {
    ArrayValue.Builder arrayValue = ArrayValue.newBuilder();
    arrayValue.addValues(value1);
    arrayValue.addValues(value2);
    for (Value.Builder builder : rest) {
      arrayValue.addValues(builder);
    }
    return Value.newBuilder().setArrayValue(arrayValue);
  }
1044201
public T value(Object... values) {
        if (values == null || values.length == 0) {
            return (T) this;
        }
        if (this.value == null) {
            this.value = new ArrayList<Object>(values.length);
        }
        if (this.value instanceof List) {
            ((List) this.value).addAll(Arrays.asList(values));
        }
        return (T) this;
    }
139869
def append(self, value):
        

        # We inline this checks to prevent method invocation each time
        if self.children is None:
            self._parse_children()

        self.children.append(self._make_value(value))

        if self._native is not None:
            self._native.append(self.children[-1].native)

        self._mutated = True
980858
def create_for_block(
            cls, i=None, name=None, cname=None, version=None, **kwargs):
        

        if cname is None:
            cname = name or 'values_block_{idx}'.format(idx=i)
        if name is None:
            name = cname

        # prior to 0.10.1, we named values blocks like: values_block_0 an the
        # name values_0
        try:
            if version[0] == 0 and version[1] <= 10 and version[2] == 0:
                m = re.search(r"values_block_(\d+)", name)
                if m:
                    name = "values_{group}".format(group=m.groups()[0])
        except IndexError:
            pass

        return cls(name=name, cname=cname, **kwargs)