text:
// Copyright(c) 2021 Jounayd Id Salah
// Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http://opensource.org/licenses/MIT).
#include "render/pch.h"
#include "render/manager/coRenderManager.h"
#include "lang/result/coResult_f.h"

coResult coRenderManager::Init()
{
	return true;
	/*
	switch (gl3wInit())
	{
	case GL3W_OK: return true;
	case GL3W_ERROR_INIT: coERROR("gl3w: Failed to init."); return false;
	case GL3W_ERROR_LIBRARY_OPEN: coERROR("gl3w: Failed to open lib gl"); return false;
	case GL3W_ERROR_OPENGL_VERSION: return true;//coERROR("gl3w: Failed to retrieve OpenGL version."); return true;
	default: return false;
	}
	*/
}


text:
import numpy as np
from math import ceil, floor
import tensorflow as tf
from tensorflow.python.training import momentum
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.framework import ops

# Values for gate_gradients.
GATE_NONE = 0
GATE_OP = 1
GATE_GRAPH = 2

class YFOptimizer(object):
  def __init__(self, lr=0.1, mu=0.0, clip_thresh=None, beta=0.999, curv_win_width=20,
    mu_update_interval=1, zero_debias=True, delta_mu=0.0):
    '''
    clip thresh is the threshold value on ||lr * gradient||
    delta_mu can be place holder/variable/python scalar. They are used for additional
    momentum in situations such as asynchronous-parallel training. The default is 0.0
    for basic usage of the optimizer.
    Args:
      lr: python scalar. The initial value of learning rate, we use 1.0 in our paper.
      mu: python scalar. The initial value of momentum, we use 0.0 in our paper.
      clip_thresh: python scalar. The cliping threshold for tf.clip_by_global_norm.
        if None, no clipping will be carried out.
      beta: python scalar. The smoothing parameter for estimations.
      delta_mu: for extensions. Not necessary in the basic use.
    Other features:
      If you want to manually control the learning rates, self.lr_factor is
      an interface to the outside, it is an multiplier for the internal learning rate
      in YellowFin. It is helpful when you want to do additional hand tuning
      or some decaying scheme to the tuned learning rate in YellowFin.
      Example on using lr_factor can be found here:
      https://github.com/JianGoForIt/YellowFin/blob/master/char-rnn-tensorflow/train_YF.py#L140
    '''
    self._lr = lr
    self._mu = mu

    self._lr_var = tf.Variable(lr, dtype=tf.float32, name="YF_lr", trainable=False)
    self._mu_var = tf.Variable(mu, dtype=tf.float32, name="YF_mu", trainable=False)
    # for step scheme or decaying scheme for the learning rates
    self.lr_factor = tf.Variable(1.0, dtype=tf.float32, name="YF_lr_factor", trainable=False)
    if clip_thresh is not None:
      self._clip_thresh_var = tf.Variable(clip_thresh, dtype=tf.float32, name="YF_clip_thresh", trainable=False)
    else:
      self._clip_thresh_var = None

    # the underlying momentum optimizer
    self._optimizer = \
      tf.train.MomentumOptimizer(self._lr_var * self.lr_factor, self._mu_var + delta_mu)

    # moving average for statistics
    self._beta = beta
    self._moving_averager = None

    # for global step counting
    self._global_step = tf.Variable(0, trainable=False)

    # for conditional tuning
    self._do_tune = tf.greater(self._global_step, tf.constant(0) )

    self._zero_debias = zero_debias

    self._tvars = None

    # for curvature range
    self._curv_win_width = curv_win_width
    self._curv_win = None

  def curvature_range(self):
    # set up the curvature window
    self._curv_win = \
      tf.Variable(np.zeros( [self._curv_win_width, ] ), dtype=tf.float32, name="curv_win", trainable=False)
    self._curv_win = tf.scatter_update(self._curv_win,
      self._global_step % self._curv_win_width, self._grad_norm_squared)
    # note here the iterations start from iteration 0
    valid_window = tf.slice(self._curv_win, tf.constant( [0, ] ),
      tf.expand_dims(tf.minimum(tf.constant(self._curv_win_width), self._global_step + 1), dim=0) )
    self._h_min_t = tf.reduce_min(valid_window)
    self._h_max_t = tf.reduce_max(valid_window)

    curv_range_ops = []
    with tf.control_dependencies([self._h_min_t, self._h_max_t] ):
      avg_op = self._moving_averager.apply([self._h_min_t, self._h_max_t] )
      with tf.control_dependencies([avg_op] ):
        self._h_min = tf.identity(self._moving_averager.average(self._h_min_t) )
        self._h_max = tf.identity(self._moving_averager.average(self._h_max_t) )
    curv_range_ops.append(avg_op)
    return curv_range_ops

  def grad_variance(self):
    grad_var_ops = []
    tensor_to_avg = []
    for t, g in zip(self._tvars, self._grads):
      if isinstance(g, ops.IndexedSlices):
        tensor_to_avg.append(tf.reshape(tf.unsorted_segment_sum(g.values, g.indices, g.dense_shape[0] ), shape=t.get_shape() ) )
      else:
        tensor_to_avg.append(g)
    avg_op = self._moving_averager.apply(tensor_to_avg)
    grad_var_ops.append(avg_op)
    with tf.control_dependencies([avg_op] ):
      self._grad_avg = [self._moving_averager.average(val) for val in tensor_to_avg]
      self._grad_avg_squared = [tf.square(val) for val in self._grad_avg]
    self._grad_var = self._grad_norm_squared_avg - tf.add_n( [tf.reduce_sum(val) for val in self._grad_avg_squared] )
    return grad_var_ops

  def dist_to_opt(self):
    dist_to_opt_ops = []
    # running average of the norm of gradeint
    self._grad_norm = tf.sqrt(self._grad_norm_squared)
    avg_op = self._moving_averager.apply([self._grad_norm,] )
    dist_to_opt_ops.append(avg_op)
    with tf.control_dependencies([avg_op] ):
      self._grad_norm_avg = self._moving_averager.average(self._grad_norm)
      # single iteration distance estimation, note here self._grad_norm_avg is per variable
      self._dist_to_opt = self._grad_norm_avg / self._grad_norm_squared_avg
    # running average of distance
    avg_op = self._moving_averager.apply([self._dist_to_opt] )
    dist_to_opt_ops.append(avg_op)
    with tf.control_dependencies([avg_op]):
      self._dist_to_opt_avg = tf.identity(self._moving_averager.average(self._dist_to_opt) )
    return dist_to_opt_ops

  def after_apply(self):
    self._moving_averager = tf.train.ExponentialMovingAverage(decay=self._beta, zero_debias=self._zero_debias)
    assert self._grads != None and len(self._grads) > 0
    after_apply_ops = []

    # get per var g**2 and norm**2
    self._grad_squared = []
    self._grad_norm_squared = []
    for v, g in zip(self._tvars, self._grads):
      with ops.colocate_with(v):
        self._grad_squared.append(tf.square(g) )
    self._grad_norm_squared = [tf.reduce_sum(grad_squared) for grad_squared in self._grad_squared]

    # the following running average on squared norm of gradient is shared by grad_var and dist_to_opt
    avg_op = self._moving_averager.apply(self._grad_norm_squared)
    with tf.control_dependencies([avg_op] ):
      self._grad_norm_squared_avg = [self._moving_averager.average(val) for val in self._grad_norm_squared]
      self._grad_norm_squared = tf.add_n(self._grad_norm_squared)
      self._grad_norm_squared_avg = tf.add_n(self._grad_norm_squared_avg)
    after_apply_ops.append(avg_op)

    with tf.control_dependencies([avg_op] ):
      curv_range_ops = self.curvature_range()
      after_apply_ops += curv_range_ops
      grad_var_ops = self.grad_variance()
      after_apply_ops += grad_var_ops
      dist_to_opt_ops = self.dist_to_opt()
      after_apply_ops += dist_to_opt_ops

    return tf.group(*after_apply_ops)

  def get_lr_tensor(self):
    lr = (1.0 - tf.sqrt(self._mu) )**2 / self._h_min
    return lr

  def get_mu_tensor(self):
    const_fact = self._dist_to_opt_avg**2 * self._h_min**2 / 2 / self._grad_var
    coef = tf.Variable([-1.0, 3.0, 0.0, 1.0], dtype=tf.float32, name="cubic_solver_coef")
    coef = tf.scatter_update(coef, tf.constant(2), -(3 + const_fact) )
    roots = tf.py_func(np.roots, [coef], Tout=tf.complex64, stateful=False)

    # filter out the correct root
    root_idx = tf.logical_and(tf.logical_and(tf.greater(tf.real(roots), tf.constant(0.0) ),
      tf.less(tf.real(roots), tf.constant(1.0) ) ), tf.less(tf.abs(tf.imag(roots) ), 1e-5) )
    # in case there are two duplicated roots satisfying the above condition
    root = tf.reshape(tf.gather(tf.gather(roots, tf.where(root_idx) ), tf.constant(0) ), shape=[] )
    tf.assert_equal(tf.size(root), tf.constant(1) )

    dr = self._h_max / self._h_min
    mu = tf.maximum(tf.real(root)**2, ( (tf.sqrt(dr) - 1)/(tf.sqrt(dr) + 1) )**2)
    return mu

  def update_hyper_param(self):
    assign_hyper_ops = []
    self._mu = tf.identity(tf.cond(self._do_tune, lambda: self.get_mu_tensor(),
      lambda: self._mu_var) )
    with tf.control_dependencies([self._mu] ):
      self._lr = tf.identity(tf.cond(self._do_tune, lambda: self.get_lr_tensor(),
        lambda: self._lr_var) )

    with tf.control_dependencies([self._mu, self._lr] ):
      self._mu = self._beta * self._mu_var + (1 - self._beta) * self._mu
      self._lr = self._beta * self._lr_var + (1 - self._beta) * self._lr
      assign_hyper_ops.append(tf.assign(self._mu_var, self._mu) )
      assign_hyper_ops.append(tf.assign(self._lr_var, self._lr) )
    assign_hyper_op = tf.group(*assign_hyper_ops)
    return assign_hyper_op

  def apply_gradients(self, grads_tvars, global_step=None, name=None):
    self._grads, self._tvars = zip(*grads_tvars)

    with tf.variable_scope("apply_updates"):
      if self._clip_thresh_var is not None:
        self._grads_clip, self._grads_norm = tf.clip_by_global_norm(self._grads, self._clip_thresh_var)
        apply_grad_op = \
          self._optimizer.apply_gradients(zip(self._grads_clip, self._tvars) )
      else:
        apply_grad_op = \
          self._optimizer.apply_gradients(zip(self._grads, self._tvars) )

    with tf.variable_scope("after_apply"):
      after_apply_op = self.after_apply()

    with tf.variable_scope("update_hyper"):
      with tf.control_dependencies( [after_apply_op] ):
        update_hyper_op = self.update_hyper_param()

    with tf.control_dependencies([update_hyper_op] ):
      self._increment_global_step_op = tf.assign(self._global_step, self._global_step + 1)

    return tf.group(apply_grad_op, after_apply_op, update_hyper_op, self._increment_global_step_op)

  def minimize(self, loss, global_step=None, var_list=None,
               gate_gradients=GATE_OP, aggregation_method=None,
               colocate_gradients_with_ops=False, name=None,
               grad_loss=None):
    """Adapted from Tensorflow Optimizer base class member function:
    Add operations to minimize `loss` by updating `var_list`.
    This method simply combines calls `compute_gradients()` and
    `apply_gradients()`. If you want to process the gradient before applying
    them call `tf.gradients()` and `self.apply_gradients()` explicitly instead
    of using this function.
    """
    grads_and_vars = self._optimizer.compute_gradients(
        loss, var_list=var_list, gate_gradients=gate_gradients,
        aggregation_method=aggregation_method,
        colocate_gradients_with_ops=colocate_gradients_with_ops,
        grad_loss=grad_loss)

    vars_with_grad = [v for g, v in grads_and_vars if g is not None]
    if not vars_with_grad:
      raise ValueError(
          "No gradients provided for any variable, check your graph for ops"
          " that do not support gradients, between variables %s and loss %s." %
          ([str(v) for _, v in grads_and_vars], loss))
    for g, v in grads_and_vars:
      print("g ", g)
      print("v ", v)

    return self.apply_gradients(grads_and_vars)

  def compute_gradients(self, loss, var_list, gate_gradients=GATE_OP,
                        aggregation_method=None, colocate_gradients_with_ops=False,
                        name=None,grad_loss=None):

    return self._optimizer.compute_gradients(
      loss, var_list=var_list, gate_gradients=gate_gradients,
      aggregation_method=aggregation_method,
      colocate_gradients_with_ops=colocate_gradients_with_ops,
      grad_loss=grad_loss)

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Elcodi\Bundle\AttributeBundle\DependencyInjection;

use Symfony\Component\Config\Definition\ConfigurationInterface;

use Elcodi\Bundle\CoreBundle\DependencyInjection\Abstracts\AbstractExtension;
use Elcodi\Bundle\CoreBundle\DependencyInjection\Interfaces\EntitiesOverridableExtensionInterface;

/**
 * This is the class that loads and manages your bundle configuration.
 */
class ElcodiAttributeExtension extends AbstractExtension implements EntitiesOverridableExtensionInterface
{
    /**
     * @var string
     *
     * Extension name
     */
    const EXTENSION_NAME = 'elcodi_attribute';

    /**
     * Get the Config file location.
     *
     * @return string Config file location
     */
    public function getConfigFilesLocation()
    {
        return __DIR__ . '/../Resources/config';
    }

    /**
     * Return a new Configuration instance.
     *
     * If object returned by this method is an instance of
     * ConfigurationInterface, extension will use the Configuration to read all
     * bundle config definitions.
     *
     * Also will call getParametrizationValues method to load some config values
     * to internal parameters.
     *
     * @return ConfigurationInterface Configuration file
     */
    protected function getConfigurationInstance()
    {
        return new Configuration(static::EXTENSION_NAME);
    }

    /**
     * Load Parametrization definition.
     *
     * return array(
     *      'parameter1' => $config['parameter1'],
     *      'parameter2' => $config['parameter2'],
     *      ...
     * );
     *
     * @param array $config Bundles config values
     *
     * @return array Parametrization values
     */
    protected function getParametrizationValues(array $config)
    {
        return [
            'elcodi.entity.attribute.class' => $config['mapping']['attribute']['class'],
            'elcodi.entity.attribute.mapping_file' => $config['mapping']['attribute']['mapping_file'],
            'elcodi.entity.attribute.manager' => $config['mapping']['attribute']['manager'],
            'elcodi.entity.attribute.enabled' => $config['mapping']['attribute']['enabled'],

            'elcodi.entity.attribute_value.class' => $config['mapping']['value']['class'],
            'elcodi.entity.attribute_value.mapping_file' => $config['mapping']['value']['mapping_file'],
            'elcodi.entity.attribute_value.manager' => $config['mapping']['value']['manager'],
            'elcodi.entity.attribute_value.enabled' => $config['mapping']['value']['enabled'],
        ];
    }

    /**
     * Config files to load.
     *
     * @param array $config Configuration array
     *
     * @return array Config files
     */
    public function getConfigFiles(array $config)
    {
        return [
            'factories',
            'repositories',
            'objectManagers',
            'directors',
        ];
    }

    /**
     * Get entities overrides.
     *
     * Result must be an array with:
     * index: Original Interface
     * value: Parameter where class is defined.
     *
     * @return array Overrides definition
     */
    public function getEntitiesOverrides()
    {
        return [
            'Elcodi\Component\Attribute\Entity\Interfaces\AttributeInterface' => 'elcodi.entity.attribute.class',
            'Elcodi\Component\Attribute\Entity\Interfaces\ValueInterface' => 'elcodi.entity.attribute_value.class',
        ];
    }

    /**
     * Returns the extension alias, same value as extension name.
     *
     * @return string The alias
     */
    public function getAlias()
    {
        return static::EXTENSION_NAME;
    }
}


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>
#include <assert.h>
#include <exception>

#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_Array_InternalEnumerator_1_gen2953159047MethodDeclarations.h"

// System.Void System.Array/InternalEnumerator`1<UnityEngine.Material>::.ctor(System.Array)
#define InternalEnumerator_1__ctor_m1780005615(__this, ___array0, method) ((  void (*) (InternalEnumerator_1_t2652942783 *, Il2CppArray *, const MethodInfo*))InternalEnumerator_1__ctor_m2616641763_gshared)(__this, ___array0, method)
// System.Void System.Array/InternalEnumerator`1<UnityEngine.Material>::System.Collections.IEnumerator.Reset()
#define InternalEnumerator_1_System_Collections_IEnumerator_Reset_m1896767057(__this, method) ((  void (*) (InternalEnumerator_1_t2652942783 *, const MethodInfo*))InternalEnumerator_1_System_Collections_IEnumerator_Reset_m2224260061_gshared)(__this, method)
// System.Object System.Array/InternalEnumerator`1<UnityEngine.Material>::System.Collections.IEnumerator.get_Current()
#define InternalEnumerator_1_System_Collections_IEnumerator_get_Current_m4076284989(__this, method) ((  Il2CppObject * (*) (InternalEnumerator_1_t2652942783 *, const MethodInfo*))InternalEnumerator_1_System_Collections_IEnumerator_get_Current_m390763987_gshared)(__this, method)
// System.Void System.Array/InternalEnumerator`1<UnityEngine.Material>::Dispose()
#define InternalEnumerator_1_Dispose_m1921471366(__this, method) ((  void (*) (InternalEnumerator_1_t2652942783 *, const MethodInfo*))InternalEnumerator_1_Dispose_m2760671866_gshared)(__this, method)
// System.Boolean System.Array/InternalEnumerator`1<UnityEngine.Material>::MoveNext()
#define InternalEnumerator_1_MoveNext_m1948610749(__this, method) ((  bool (*) (InternalEnumerator_1_t2652942783 *, const MethodInfo*))InternalEnumerator_1_MoveNext_m3716548237_gshared)(__this, method)
// T System.Array/InternalEnumerator`1<UnityEngine.Material>::get_Current()
#define InternalEnumerator_1_get_Current_m1318997814(__this, method) ((  Material_t3870600107 * (*) (InternalEnumerator_1_t2652942783 *, const MethodInfo*))InternalEnumerator_1_get_Current_m2178852364_gshared)(__this, method)


text:
(function(module) {
  mifosX.models = _.extend(module, {
    LoggedInUser: function(data) {
      this.name = data.username;

      this.getHomePageIdentifier = function() {
        var role = _.first(data.selectedRoles || data.roles);
        return mifosX.models.roleMap[role.id];
      };
    }
  });
}(mifosX.models || {}));


text:
=============================================
Why PyMEL?
=============================================

.. _why_wrappers:

---------------------------------------------
The Nature of the Beast
---------------------------------------------

Rather than reinvent the wheel, Autodesk opted to provide "wrappers" around their pre-existing toolsets: the :term:`C++ API` and :term:`MEL`.  By wrapping them they provided an alternate python interface for each, but the core code that comprises the API and MEL remained largely the same.  The wrappers serve as a (hopefully) thin layer to communicate between python and the Maya code being wrapped. The nature of the wraps is slightly different for each.

``maya.OpenMaya``
	In the case of the C++ API, Autodesk went with an open source wrapper called `swig <http://www.swig.org/exec.html>`_ which generates python functions and classes from C++ counterparts. The python layer rests on top of C++, which remains the native execution language. During execution, swig marshals data back and forth between python and C++.

MEL itself is split into two components: commands, and everything else.

``maya.cmds``
	In the case of MEL commands, which are (effectively) written using the C++ API, Autodesk wrote the wrapping mechanism themselves such that MEL commands could also be registered and used in python as functions. The same command executed in MEL and python ultimately end up triggering the same underlying C++ API calls.

``maya.mel.eval``
	In order to allow execution of arbitrary MEL code such as procedures, Autodesk provided high level access to the MEL interpreter. This is as simple of a wrapper as you can get: evaluate a string representing a chunk of MEL code in the MEL interpreter and convert the result to a python object (string, float, int, and lists thereof).

..
	(this is not completely accurate, as some of the older core commands bypass the API, but we'll ignore that for the sake of conceptual simplicity).

	====================== ==================================================
	                       Python Module
	====================== ==================================================
	API classes            ``maya.OpenMaya``, ``maya.OpenMayaAnim``, ...
	MEL commands           ``maya.cmds``
	MEL                    ``maya.mel``
	====================== ==================================================

So now that python is available in Maya all of our problems are solved, right?  Well, not quite.  Since these new modules are just wraps of the same underlying API and MEL code that we've had all along and neither were intended to eventually become "pythonified", the syntax that results from this layering of python over MEL and C++ tends to be awkward, especially to those familiar with python's idioms.

This syntactical awkwardness, particularly in ``maya.cmds``, was one of the initial inspirations behind PyMEL. Think of it this way: would you rather read a book that was translated from japanese into english by a software program like babelfish or by a  human who is fluent in both languages? That is a key difference between an automatic wrap like ``maya.cmds`` and a "restructured wrap" like PyMEL, which uses the maya python modules as building blocks to construct an intuitive, insightful, and pythonic API.

---------------------------------------------
The Paradigm Shift
---------------------------------------------

MEL is a procedural language, meaning it provides the ability to encapsulate code into reusable "procedures" ( aka "functions" ).  (This is probably old news to you, but bear with me, there's a mildly entertaining analogy coming up ). The term "procedural programming" is used primarily in the context of distinguishing a language from the newer, object-oriented paradigm.

Object-oriented programming adds organization by creating logical groupings of functions which are accessed from a common "object".  If you have used MEL extensively you know you can get pretty far with procedural programming alone, but there is often an exponential relationship between the complexity of a task and the amount of code it will take to complete in MEL.  In other words, progress breaks down once the task at hand becomes too complicated. Object-oriented code tends to be easier to read and write, provides the ability to easily create new data types and reuse code, and ultimately scales better to complex tasks.

To prove my point, here's a quick example that we'll cover in more depth later.

procedural::

	cmds.getAttr( cmds.listRelatives( cmds.ls(type='camera')[0], p=1 )[0] + '.translate' )[0][2]

object oriented::

	pymel.ls(type='camera')[0].getParent().translate.get().z

See how nicely that reads from left to right? Object oriented programming isn't necessarily about brevity, it's about legibility derived from structure.

A quick perusal of the more than three thousand MEL commands in the Maya documentation will give you an idea why object-oriented groupings are a good idea.  MEL is like a tool chest, a wardrobe, and a kitchen set all dumped into a bathtub -- everything in there is useful in the proper context, but you've really got to know what you're looking for to get anything done.  The shame of it is that Maya's great innovation is that it is itself inherently object-oriented -- every scene represents networks of nodes, each with its own unique abilities and those that it inherits from its super-classes.  Maya's API is object-oriented, too.  So how did MEL end up so crippled?

The original idea behind MEL and the API was to create a tiered relationship where complex tasks, or tasks where execution time is of great concern, were to be performed using the C++ API and bundled into easy-to-use MEL commands.  These commands were in turn to become the building blocks of more generalized tasks performed in MEL.  The API would be the toolset of the superuser -- with access to complex types and external libraries --  whereas the scope of MEL would be much more limited and thus more accessible to the average user.

The advent of python in Maya brought a common language to MEL and the API, and as a result, the clarity of this tiered structure has become muddied.  API classes, MEL commands, and MEL procedures can be used within the same python script, completely outside the context of a plugin.  Moreover, python manages to borrow the strengths of both languages: like C++, it is object-oriented and extensible through third party libraries and custom types, but like MEL, python is easy to learn, protects the user from certain daunting programming concepts, and compiles at runtime.  Having managed to provide an object-oriented design without a steep learning curve, python makes the simplicity of MEL seem like an unfortunate over-simplification.

So, on the one hand we have the C++ API, now easily accessible from within Python, object-oriented, but too cryptic and verbose for everyday tasks, and on the other hand, we have a host of thousands of MEL-commands-turned-python-functions, too valuable to do without, but woefully unorganized and "unpythonic". Which do we use?  How can they work together?  PyMEL bridges this gap by forging a new object-oriented API that's as powerful and easy to use as python is.

..
	When I began designing PyMEL, I started by sifting through every... single... MEL command and, if possible, associating it with a node type. This is the fundamental precept of object-oriented design -- group your functions around a common object.  It was the first step in the right direction.

	It has a hierarchy of classes that roughly mirror the nodes available in Maya. MEL, being by design a simple procedural language accessible to your average artist, had most of these concepts stripped from it.

	The primary reasons for PyMEL's existence are threefold:

	    1. to fix bugs in maya.cmds
	    2. to modify the behavior of maya.cmds to improve workflow and make it more pythonic ( like returning an empty list instead of None )
	    3. to provide a complete object-oriented design for working with nodes, attributes, and other maya structures

	If you're still not sure you're ready to make the jump to object-oriented programming, the first two points alone are reason enough to use pymel, but the object-oriented design is where PyMEL really shines.  PyMEL strikes a balance between the complicated yet powerful API, and straightforward but unruly MEL.

	Originally, the gap was intentional, but now we find ourselves asking "how can we bridge the gap?".  How can we use what

	Further emphasizing this tiered structure, MEL commands could be executed from the API, but the reverse, executing API from MEL, was neither possible nor desirable, except indirectly by calling registered commands.

	Through the use of classes and modules, python makes sure that everything is in its right place.

	..
		Only a few fundamental types are supported in MEL, and the ability to access the API from MEL was fundamentally prohibited, except through pre-compiled commands.  This hides the complexity of coding and compiling C++ code from the average scripter.
		Unlike Python, it cannot operate without an instance of Maya running.

		Fast-forward 10 years to the present.  Scripting languages like python and perl have become commonplace in VFX and animation studios for performing everyday pipeline tasks such as moving, manipulating, and parsing files, communicating with databases, and building standalone user interfaces.  Unlike MEL, these languages are not tied to any particular application and have benefitted from years of active development. In comparison, MEL seems downright antiquated and restrictive.

		So, as you well know, Autodesk has added python to Maya, but you may still be wondering what exactly that means. First and foremost, it means providing access to python's interpreter within Maya ( The interpreter is the software responsible for executing python code ). The second step is to provide modules with functions and classes for working with maya objects and user interfaces.

	============================= =============================
	MEL                           Python
	============================= =============================
	script (*.mel)                module (*.py)
	procedure                     function
	command                       builtin function
	============================= =============================

---------------------------------------
Glossary
---------------------------------------

.. glossary::

	MEL
		short for Maya Embedded Language, is a scripting language written for Maya, and with which much of Maya's functionality and user interface is built. It was designed to be concise, simple, and Maya-specific.

	C++ API
		provides deeper access to Maya's internals.  With the API you can create new node types and new MEL commands. Prior to the introduction of python in Maya, the API could only be used with C++.


text:
package org.apache.jackrabbit.oak.plugins.memory;

import javax.annotation.Nonnull;
import javax.jcr.PropertyType;

import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.plugins.value.Conversions.Converter;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Collections.singleton;

/**
 * Abstract base class for single valued {@code PropertyState} implementations.
 */
abstract class SinglePropertyState<T> extends EmptyPropertyState {

    /**
     * Create a new property state with the given {@code name}
     * @param name  The name of the property state.
     */
    protected SinglePropertyState(@Nonnull String name) {
        super(name);
    }

    /**
     * @return  {@code false}
     */
    @Override
    public boolean isArray() {
        return false;
    }

    /**
     * Create a converter for converting the value of this property to other types.
     * @return  A converter for the value of this property
     */
    public abstract Converter getConverter();

    @SuppressWarnings("unchecked")
    private <S> S  convertTo(Type<S> type) {
        switch (type.tag()) {
            case PropertyType.STRING: return (S) getConverter().toString();
            case PropertyType.BINARY: return (S) getConverter().toBinary();
            case PropertyType.LONG: return (S) (Long) getConverter().toLong();
            case PropertyType.DOUBLE: return (S) (Double) getConverter().toDouble();
            case PropertyType.DATE: return (S) getConverter().toDate();
            case PropertyType.BOOLEAN: return (S) (Boolean) getConverter().toBoolean();
            case PropertyType.NAME: return (S) getConverter().toString();
            case PropertyType.PATH: return (S) getConverter().toString();
            case PropertyType.REFERENCE: return (S) getConverter().toString();
            case PropertyType.WEAKREFERENCE: return (S) getConverter().toString();
            case PropertyType.URI: return (S) getConverter().toString();
            case PropertyType.DECIMAL: return (S) getConverter().toDecimal();
            default: throw new IllegalArgumentException("Unknown type:" + type);
        }
    }

    /**
     * The value of this property
     * @return  Value of this property
     */
    public abstract T getValue();

    /**
     * @throws IllegalArgumentException if {@code type} is not one of the
     * values defined in {@link Type}.
     */
    @SuppressWarnings("unchecked")
    @Nonnull
    @Override
    public <S> S getValue(Type<S> type) {
        if (type.isArray()) {
            if (getType() == type.getBaseType()) {
                return (S) singleton(getValue());
            }
            else {
                return (S) singleton(convertTo(type.getBaseType()));
            }
        }
        else {
            if (getType() == type) {
                return (S) getValue();
            }
            else {
                return convertTo(type);
            }
        }
    }

    /**
     * @throws IllegalArgumentException  if {@code type.isArray} is {@code true}
     * @throws IndexOutOfBoundsException  if {@code index != 0}
     */
    @Nonnull
    @Override
    public <S> S getValue(Type<S> type, int index) {
        checkArgument(!type.isArray(), "Type must not be an array type");
        if (index != 0) {
            throw new IndexOutOfBoundsException(String.valueOf(index));
        }
        return getValue(type);
    }

    /**
     * @return  {@code getString().length()}
     */
    @Override
    public long size() {
        return convertTo(Type.STRING).length();
    }

    /**
     * @return  {@code size}
     * @throws IndexOutOfBoundsException  if {@code index != 0}
     */
    @Override
    public long size(int index) {
        if (index != 0) {
            throw new IndexOutOfBoundsException(String.valueOf(index));
        }
        return size();
    }

    /**
     * @return {@code 1}
     */
    @Override
    public int count() {
        return 1;
    }
}


text:
package org.vitrivr.cineast.art.modules;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.vitrivr.cineast.art.modules.abstracts.AbstractVisualizationModule;
import org.vitrivr.cineast.art.modules.visualization.VisualizationResult;
import org.vitrivr.cineast.art.modules.visualization.VisualizationType;
import org.vitrivr.cineast.core.color.ColorConverter;
import org.vitrivr.cineast.core.color.RGBContainer;
import org.vitrivr.cineast.core.color.ReadableLabContainer;
import org.vitrivr.cineast.core.data.providers.primitive.PrimitiveTypeProvider;
import org.vitrivr.cineast.core.util.ArtUtil;
import org.vitrivr.cineast.core.util.web.ImageParser;

/**
 * Created by sein on 30.08.16.
 */
public class VisualizationMedianColorStripe extends AbstractVisualizationModule {
  public VisualizationMedianColorStripe() {
    super();
    tableNames.put("MedianColor", "features_MedianColor");
  }

  @Override
  public String getDisplayName() {
    return "VisualizationMedianColorStripe";
  }

  @Override
  protected String visualizeMulti(List<Map<String, PrimitiveTypeProvider>> featureData){
    BufferedImage image = new BufferedImage(featureData.size(), 1, BufferedImage.TYPE_INT_RGB);
    Graphics2D graph = image.createGraphics();
    int count = 0;
    for (Map<String, PrimitiveTypeProvider> feature : featureData) {
      float[] arr = feature.get("feature").getFloatArray();
      RGBContainer rgbContainer = ColorConverter.LabtoRGB(new ReadableLabContainer(arr[0], arr[1], arr[2]));
      graph.setColor(new Color(rgbContainer.toIntColor()));
      graph.fillRect(count, 0, 1, 1);
      count++;
    }
    graph.dispose();
    return ImageParser.BufferedImageToDataURL(image, "png");
  }

  @Override
  public String visualizeMultipleSegments(List<String> segmentIds){
    return visualizeMulti(ArtUtil.getFeatureData(selectors.get("MedianColor"), segmentIds));
  }

  @Override
  public String visualizeMultimediaobject(String multimediaobjectId) {
    return visualizeMulti(ArtUtil.getFeatureData(selectors.get("MedianColor"), multimediaobjectId));
  }

  @Override
  public List<VisualizationType> getVisualizations() {
    List<VisualizationType> types = new ArrayList<>();
    types.add(VisualizationType.VISUALIZATION_MULTIMEDIAOBJECT);
    return types;
  }

  @Override
  public VisualizationResult getResultType() {
    return VisualizationResult.IMAGE;
  }
}


text:
import time

from openerp.osv import fields, osv

class account_partner_reconcile_process(osv.osv_memory):
    _name = 'account.partner.reconcile.process'
    _description = 'Reconcilation Process partner by partner'

    def _get_to_reconcile(self, cr, uid, context=None):
        cr.execute("""
                  SELECT p_id FROM (SELECT l.partner_id as p_id, SUM(l.debit) AS debit, SUM(l.credit) AS credit
                                    FROM account_move_line AS l LEFT JOIN account_account a ON (l.account_id = a.id)
                                                                LEFT JOIN res_partner p ON (p.id = l.partner_id)
                                    WHERE a.reconcile = 't'
                                    AND l.reconcile_id IS NULL
                                    AND  (%s >  to_char(p.last_reconciliation_date, 'YYYY-MM-DD') OR  p.last_reconciliation_date IS NULL )
                                    AND  l.state <> 'draft'
                                    GROUP BY l.partner_id) AS tmp
                              WHERE debit > 0
                              AND credit > 0
                """,(time.strftime('%Y-%m-%d'),)
        )
        return len(map(lambda x: x[0], cr.fetchall())) - 1

    def _get_today_reconciled(self, cr, uid, context=None):
        cr.execute(
                "SELECT l.partner_id " \
                "FROM account_move_line AS l LEFT JOIN res_partner p ON (p.id = l.partner_id) " \
                "WHERE l.reconcile_id IS NULL " \
                "AND %s =  to_char(p.last_reconciliation_date, 'YYYY-MM-DD') " \
                "AND l.state <> 'draft' " \
                "GROUP BY l.partner_id ",(time.strftime('%Y-%m-%d'),)
        )
        return len(map(lambda x: x[0], cr.fetchall())) + 1

    def _get_partner(self, cr, uid, context=None):
        move_line_obj = self.pool.get('account.move.line')

        partner = move_line_obj.list_partners_to_reconcile(cr, uid, context=context)
        if not partner:
            return False
        return partner[0][0]

    def data_get(self, cr, uid, to_reconcile, today_reconciled, context=None):
        return {'progress': (100 / (float(to_reconcile + today_reconciled) or 1.0)) * today_reconciled}

    def default_get(self, cr, uid, fields, context=None):
        res = super(account_partner_reconcile_process, self).default_get(cr, uid, fields, context=context)
        if 'to_reconcile' in res and 'today_reconciled' in res:
            data = self.data_get(cr, uid, res['to_reconcile'], res['today_reconciled'], context)
            res.update(data)
        return res

    def next_partner(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        move_line_obj = self.pool.get('account.move.line')
        res_partner_obj = self.pool.get('res.partner')

        partner_id = move_line_obj.read(cr, uid, context['active_id'], ['partner_id'])['partner_id']
        if partner_id:
            res_partner_obj.write(cr, uid, partner_id[0], {'last_reconciliation_date': time.strftime('%Y-%m-%d')}, context)
        #TODO: we have to find a way to update the context of the current tab (we could open a new tab with the context but it's not really handy)
        #TODO: remove that comments when the client side dev is done
        return {'type': 'ir.actions.act_window_close'}

    _columns = {
        'to_reconcile': fields.float('Remaining Partners', readonly=True, help='This is the remaining partners for who you should check if there is something to reconcile or not. This figure already count the current partner as reconciled.'),
        'today_reconciled': fields.float('Partners Reconciled Today', readonly=True, help='This figure depicts the total number of partners that have gone throught the reconciliation process today. The current partner is counted as already processed.'),
        'progress': fields.float('Progress', readonly=True, help='Shows you the progress made today on the reconciliation process. Given by \nPartners Reconciled Today \ (Remaining Partners + Partners Reconciled Today)'),
        'next_partner_id': fields.many2one('res.partner', 'Next Partner to Reconcile', readonly=True, help='This field shows you the next partner that will be automatically chosen by the system to go through the reconciliation process, based on the latest day it have been reconciled.'), # TODO: remove the readonly=True when teh client side will allow to update the context of existing tab, so that the user can change this value if he doesn't want to follow openerp proposal
    }

    _defaults = {
        'to_reconcile': _get_to_reconcile,
        'today_reconciled': _get_today_reconciled,
        'next_partner_id': _get_partner,
    }

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


text:
from django.db import models
from django.conf import settings

class Comment(models.Model):

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
    )

    idea = models.ForeignKey(
        'Idea',
    )

    content = models.TextField()

    reaction = models.PositiveIntegerField(
        default=0,
    )

    created_at = models.DateTimeField(
        auto_now_add=True,
    )

    updated_at = models.DateTimeField(
        auto_now=True,
    )

    def __str__(self):
        return self.content


text:
package server

import (
	"fmt"
	"net"
	"testing"
	"time"

	"github.com/coreos/etcd/clientv3"
	"github.com/jive/postal/api"
	"github.com/stretchr/testify/assert"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

type sandboxedServerTest func(assert *assert.Assertions, client api.PostalClient)

func (srvTest sandboxedServerTest) execute(t *testing.T) {
	assert := assert.New(t)

	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"127.0.0.1:2379"},
		DialTimeout: 5 * time.Second,
	})
	assert.NoError(err)

	defer cli.Close()
	defer cli.KV.Delete(context.Background(), "/", clientv3.WithPrefix())

	serverAddr := "127.0.0.1:54321"

	lis, err := net.Listen("tcp", serverAddr)
	defer lis.Close()
	assert.NoError(err)

	grpcServer := grpc.NewServer()
	srv := PostalServer{etcd: cli}
	srv.Register(grpcServer)
	go grpcServer.Serve(lis)

	conn, err := grpc.Dial(serverAddr, grpc.WithInsecure())
	assert.NoError(err)
	defer conn.Close()
	client := api.NewPostalClient(conn)
	srvTest(assert, client)
}

func TestSrvNetwork(t *testing.T) {
	test := sandboxedServerTest(func(assert *assert.Assertions, client api.PostalClient) {
		// Add sme networks to the server
		networkCount := 5
		networks := map[string]*api.Network{}
		for i := 0; i < networkCount; i++ {
			cidr := fmt.Sprintf("10.%d.0.0/16", i)
			resp, err := client.NetworkAdd(context.TODO(), &api.NetworkAddRequest{
				Annotations: map[string]string{
					"foo":      "bar",
					"netCount": string(i),
				},
				Cidr: cidr,
			})
			assert.NoError(err)
			assert.Equal(cidr, resp.Network.Cidr)
			assert.Equal("bar", resp.Network.Annotations["foo"])
			assert.Equal(string(i), resp.Network.Annotations["netCount"])
			networks[resp.Network.ID] = resp.Network
		}
		assert.Equal(networkCount, len(networks))

		// Assert the server knows about the networks added
		resp, err := client.NetworkRange(context.TODO(), &api.NetworkRangeRequest{})
		assert.NoError(err)
		assert.Equal(networkCount, len(resp.Networks))

		for k, v := range networks {
			resp, err = client.NetworkRange(context.TODO(), &api.NetworkRangeRequest{ID: k})
			assert.NoError(err)
			assert.Equal(1, len(resp.Networks))
			assert.Equal(v.ID, resp.Networks[0].ID)
			assert.Equal(v.Cidr, resp.Networks[0].Cidr)
			assert.Equal(v.Annotations, resp.Networks[0].Annotations)
		}

		// Assert errors return when bogus data is used
		resp, err = client.NetworkRange(context.TODO(), &api.NetworkRangeRequest{ID: "foobar"})
		assert.Error(err)

	})

	test.execute(t)
}

func TestSrvPool(t *testing.T) {
	test := sandboxedServerTest(func(assert *assert.Assertions, client api.PostalClient) {
		networkResp, networkErr := client.NetworkAdd(context.TODO(), &api.NetworkAddRequest{
			Annotations: map[string]string{},
			Cidr:        "10.0.0.0/16",
		})
		assert.NoError(networkErr)

		poolCount := 5
		pools := map[string]*api.Pool{}
		poolMax := uint64(10)
		for i := 0; i < poolCount; i++ {
			resp, err := client.PoolAdd(context.TODO(), &api.PoolAddRequest{
				NetworkID:   networkResp.Network.ID,
				Annotations: map[string]string{},
				Maximum:     poolMax,
				Type:        api.Pool_DYNAMIC,
			})

			assert.NoError(err)
			assert.Equal(networkResp.Network.ID, resp.Pool.ID.NetworkID)
			assert.Equal(poolMax, resp.Pool.MaximumAddresses)
			assert.Equal(api.Pool_DYNAMIC, resp.Pool.Type)
			pools[resp.Pool.ID.ID] = resp.Pool
		}
		assert.Equal(poolCount, len(pools))

		resp, err := client.PoolRange(context.TODO(), &api.PoolRangeRequest{
			ID: &api.Pool_PoolID{
				NetworkID: networkResp.Network.ID,
			},
		})
		assert.NoError(err)
		assert.Equal(int32(poolCount), resp.Size_)
		assert.Equal(poolCount, len(resp.Pools))

		for k, v := range pools {
			resp, err = client.PoolRange(context.TODO(), &api.PoolRangeRequest{
				ID: &api.Pool_PoolID{
					NetworkID: networkResp.Network.ID,
					ID:        k,
				},
			})
			assert.NoError(err)
			assert.Equal(int32(1), resp.Size_)
			assert.Equal(1, len(resp.Pools))
			assert.Equal(v.ID.NetworkID, resp.Pools[0].ID.NetworkID)
			assert.Equal(v.ID.ID, resp.Pools[0].ID.ID)
			assert.Equal(v.MaximumAddresses, resp.Pools[0].MaximumAddresses)
			assert.Equal(v.Type, resp.Pools[0].Type)
		}

		resp, err = client.PoolRange(context.TODO(), &api.PoolRangeRequest{
			ID: &api.Pool_PoolID{
				NetworkID: networkResp.Network.ID,
				ID:        "foo",
			},
		})
		assert.Error(err)

		resp, err = client.PoolRange(context.TODO(), &api.PoolRangeRequest{
			ID: &api.Pool_PoolID{
				NetworkID: "foo",
			},
		})
		assert.Error(err)
	})
	test.execute(t)
}

func TestSrvMultiplePools(t *testing.T) {
	test := sandboxedServerTest(func(assert *assert.Assertions, client api.PostalClient) {
		_, networkCidr, _ := net.ParseCIDR("10.0.0.0/16")
		networkResp, networkErr := client.NetworkAdd(context.TODO(), &api.NetworkAddRequest{
			Annotations: map[string]string{},
			Cidr:        networkCidr.String(),
		})
		assert.NoError(networkErr)

		poolResp, poolErr := client.PoolAdd(context.TODO(), &api.PoolAddRequest{
			NetworkID:   networkResp.Network.ID,
			Annotations: map[string]string{},
			Maximum:     3,
			Type:        api.Pool_FIXED,
		})
		assert.NoError(poolErr)

		allocResp, allocErr := client.AllocateAddress(context.TODO(), &api.AllocateAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "10.0.0.1",
		})
		assert.NoError(allocErr)
		allocatedAddr := net.ParseIP(allocResp.Binding.Address)
		assert.False(allocatedAddr.IsUnspecified())
		assert.True(networkCidr.Contains(allocatedAddr))

		_, allocErr = client.AllocateAddress(context.TODO(), &api.AllocateAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "10.0.0.1",
		})
		assert.Error(allocErr)

		bindingRngResp, err := client.BindingRange(context.TODO(), &api.BindingRangeRequest{
			NetworkID: poolResp.Pool.ID.NetworkID,
			Filters:   map[string]string{"_address": allocResp.Binding.Address},
		})
		assert.NoError(err)
		assert.Len(bindingRngResp.Bindings, 1)

	})
	test.execute(t)
}

func TestSrvFixedPool(t *testing.T) {
	test := sandboxedServerTest(func(assert *assert.Assertions, client api.PostalClient) {
		_, networkCidr, _ := net.ParseCIDR("10.0.0.0/16")
		networkResp, networkErr := client.NetworkAdd(context.TODO(), &api.NetworkAddRequest{
			Annotations: map[string]string{},
			Cidr:        networkCidr.String(),
		})
		assert.NoError(networkErr)

		poolResp, poolErr := client.PoolAdd(context.TODO(), &api.PoolAddRequest{
			NetworkID:   networkResp.Network.ID,
			Annotations: map[string]string{},
			Maximum:     3,
			Type:        api.Pool_FIXED,
		})
		assert.NoError(poolErr)

		// Allocated: 1
		// Bound:     0
		allocResp, allocErr := client.AllocateAddress(context.TODO(), &api.AllocateAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "10.0.0.1",
		})
		assert.NoError(allocErr)
		allocatedAddr := net.ParseIP(allocResp.Binding.Address)
		allocatedBinding := allocResp.Binding.ID
		assert.False(allocatedAddr.IsUnspecified())
		assert.True(networkCidr.Contains(allocatedAddr))

		// Allocated: 0
		// Bound:     1
		bindResp, bindErr := client.BindAddress(context.TODO(), &api.BindAddressRequest{
			PoolID: poolResp.Pool.ID,
		})
		assert.NoError(bindErr)
		assert.Equal(allocResp.Binding.AllocateTime, bindResp.Binding.AllocateTime)
		boundAddr := net.ParseIP(bindResp.Binding.Address)
		assert.Equal(allocatedAddr, boundAddr)

		// Allocated: 0
		// Bound:     1
		// Attempting to bind already bound address should error
		bindResp, bindErr = client.BindAddress(context.TODO(), &api.BindAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: boundAddr.String(),
		})
		assert.Error(bindErr)

		// Allocated: 0
		// Bound:     1
		// Attempting to bind any address with none allocated should error
		bindResp, bindErr = client.BindAddress(context.TODO(), &api.BindAddressRequest{
			PoolID: poolResp.Pool.ID,
		})
		assert.Error(bindErr)

		// Allocated: 1
		// Bound:     1
		allocResp, allocErr = client.AllocateAddress(context.TODO(), &api.AllocateAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "10.0.0.2",
		})
		assert.NoError(allocErr)

		// Allocated: 2
		// Bound:     1
		allocResp, allocErr = client.AllocateAddress(context.TODO(), &api.AllocateAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "10.0.0.3",
		})
		assert.NoError(allocErr)

		// Allocated: 1
		// Bound:     2
		bindResp, bindErr = client.BindAddress(context.TODO(), &api.BindAddressRequest{
			PoolID: poolResp.Pool.ID,
		})
		assert.NoError(bindErr)

		// Allocated: 2 ** over maximum should error
		// Bound:     2
		allocResp, allocErr = client.AllocateAddress(context.TODO(), &api.AllocateAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "10.0.0.4",
		})
		assert.Error(allocErr)

		bindingRngResp, err := client.BindingRange(context.TODO(), &api.BindingRangeRequest{
			NetworkID: poolResp.Pool.ID.NetworkID,
			Filters:   map[string]string{"_id": allocatedBinding},
		})
		assert.NoError(err)
		assert.Len(bindingRngResp.Bindings, 1)

		// Allocated: 0
		// Bound:     3
		bindResp, bindErr = client.BindAddress(context.TODO(), &api.BindAddressRequest{
			PoolID: poolResp.Pool.ID,
		})
		assert.NoError(bindErr)

		// Allocated: 1
		// Bound:     2
		_, err = client.ReleaseAddress(context.TODO(), &api.ReleaseAddressRequest{
			PoolID:    poolResp.Pool.ID,
			BindingID: bindingRngResp.Bindings[0].ID,
		})
		assert.NoError(err)

		// Allocated: 1
		// Bound:     2
		// Attempting to release non bound address should error
		_, err = client.ReleaseAddress(context.TODO(), &api.ReleaseAddressRequest{
			BindingID: bindingRngResp.Bindings[0].ID,
		})
		assert.Error(err)

		// Allocated: 0
		// Bound:     3
		bindResp, bindErr = client.BindAddress(context.TODO(), &api.BindAddressRequest{
			PoolID: poolResp.Pool.ID,
		})
		assert.NoError(bindErr)
		boundAddr = net.ParseIP(bindResp.Binding.Address)
		assert.Equal(allocatedAddr, boundAddr)

		// Allocated: 0
		// Bound:     2
		// Hard release expires the binding immediately
		_, err = client.ReleaseAddress(context.TODO(), &api.ReleaseAddressRequest{
			PoolID:    poolResp.Pool.ID,
			BindingID: bindingRngResp.Bindings[0].ID,
			Hard:      true,
		})
		assert.NoError(err)

		// Allocated: 0
		// Bound:     2
		// Since we previouslly force released, there should be no allocated address to bind.
		_, err = client.BindAddress(context.TODO(), &api.BindAddressRequest{
			PoolID: poolResp.Pool.ID,
		})
		assert.Error(err)

		// Allocated: 1
		// Bound:     2
		allocResp, allocErr = client.AllocateAddress(context.TODO(), &api.AllocateAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "10.0.0.5",
		})
		assert.NoError(allocErr)
		newAllocatedAddr := net.ParseIP(allocResp.Binding.Address)
		assert.NotEqual(allocatedAddr, newAllocatedAddr)
	})

	test.execute(t)
}

func TestSrvBulkAllocate(t *testing.T) {
	test := sandboxedServerTest(func(assert *assert.Assertions, client api.PostalClient) {
		_, networkCidr, _ := net.ParseCIDR("10.0.0.0/16")
		networkResp, networkErr := client.NetworkAdd(context.TODO(), &api.NetworkAddRequest{
			Annotations: map[string]string{},
			Cidr:        networkCidr.String(),
		})
		assert.NoError(networkErr)

		poolResp, poolErr := client.PoolAdd(context.TODO(), &api.PoolAddRequest{
			NetworkID:   networkResp.Network.ID,
			Annotations: map[string]string{},
			Maximum:     10000,
			Type:        api.Pool_DYNAMIC,
		})
		assert.NoError(poolErr)

		allocResp, allocErr := client.BulkAllocateAddress(context.TODO(), &api.BulkAllocateAddressRequest{
			PoolID: poolResp.Pool.ID,
			Cidr:   "10.0.255.0/24",
		})
		assert.NoError(allocErr)
		assert.Equal(0, len(allocResp.GetErrors()))
		assert.Equal(256, len(allocResp.GetBindings()))

		_, allocErr = client.BulkAllocateAddress(context.TODO(), &api.BulkAllocateAddressRequest{
			PoolID: poolResp.Pool.ID,
		})
		assert.Error(allocErr)

		allocResp, allocErr = client.BulkAllocateAddress(context.TODO(), &api.BulkAllocateAddressRequest{
			PoolID: poolResp.Pool.ID,
			Cidr:   "10.0.254.0/23",
		})
		assert.NoError(allocErr)
		assert.Equal(256, len(allocResp.GetErrors()))
		assert.Equal(256, len(allocResp.GetBindings()))

		allocResp, allocErr = client.BulkAllocateAddress(context.TODO(), &api.BulkAllocateAddressRequest{
			PoolID: poolResp.Pool.ID,
			Cidr:   "10.0.0.0/26",
		})
		assert.NoError(allocErr)
		assert.Equal(0, len(allocResp.GetErrors()))
		assert.Equal(64, len(allocResp.GetBindings()))

	})

	test.execute(t)
}

func TestAllocateReleaseAllocate(t *testing.T) {
	test := sandboxedServerTest(func(assert *assert.Assertions, client api.PostalClient) {
		_, networkCidr, _ := net.ParseCIDR("10.0.0.0/16")
		networkResp, networkErr := client.NetworkAdd(context.TODO(), &api.NetworkAddRequest{
			Annotations: map[string]string{},
			Cidr:        networkCidr.String(),
		})
		assert.NoError(networkErr)

		poolResp, poolErr := client.PoolAdd(context.TODO(), &api.PoolAddRequest{
			NetworkID:   networkResp.Network.ID,
			Annotations: map[string]string{},
			Maximum:     10000,
			Type:        api.Pool_FIXED,
		})
		assert.NoError(poolErr)

		_, err := client.AllocateAddress(context.TODO(), &api.AllocateAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "10.0.0.1",
		})
		assert.NoError(err)

		_, err = client.AllocateAddress(context.TODO(), &api.AllocateAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "10.0.0.2",
		})
		assert.NoError(err)

		_, err = client.AllocateAddress(context.TODO(), &api.AllocateAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "10.0.0.3",
		})
		assert.NoError(err)

		resp1, err1 := client.BindAddress(context.TODO(), &api.BindAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "",
		})

		resp2, err2 := client.BindAddress(context.TODO(), &api.BindAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "",
		})

		resp3, err3 := client.BindAddress(context.TODO(), &api.BindAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "",
		})

		assert.NoError(err1)
		assert.NoError(err2)
		assert.NoError(err3)
		assert.NotEqual(resp1.Binding.Address, resp2.Binding.Address)
		assert.NotEqual(resp1.Binding.Address, resp3.Binding.Address)

		_, err1 = client.ReleaseAddress(context.TODO(), &api.ReleaseAddressRequest{
			PoolID:    poolResp.Pool.ID,
			BindingID: resp1.Binding.ID,
		})
		assert.NoError(err1)

		_, err2 = client.ReleaseAddress(context.TODO(), &api.ReleaseAddressRequest{
			PoolID:    poolResp.Pool.ID,
			BindingID: resp2.Binding.ID,
		})
		assert.NoError(err2)

		_, err3 = client.ReleaseAddress(context.TODO(), &api.ReleaseAddressRequest{
			PoolID:    poolResp.Pool.ID,
			BindingID: resp3.Binding.ID,
		})
		assert.NoError(err3)

		resp1, err1 = client.BindAddress(context.TODO(), &api.BindAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "",
		})

		resp2, err2 = client.BindAddress(context.TODO(), &api.BindAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "",
		})

		resp3, err3 = client.BindAddress(context.TODO(), &api.BindAddressRequest{
			PoolID:  poolResp.Pool.ID,
			Address: "",
		})

		assert.NoError(err1)
		assert.NoError(err2)
		assert.NoError(err3)
		assert.NotEqual(resp1.Binding.Address, resp2.Binding.Address)
		assert.NotEqual(resp1.Binding.Address, resp3.Binding.Address)
	})

	test.execute(t)
}

func TestConcurrentBind(t *testing.T) {
	test := sandboxedServerTest(func(assert *assert.Assertions, client api.PostalClient) {
		_, networkCidr, _ := net.ParseCIDR("10.0.0.0/16")
		networkResp, networkErr := client.NetworkAdd(context.TODO(), &api.NetworkAddRequest{
			Annotations: map[string]string{},
			Cidr:        networkCidr.String(),
		})
		assert.NoError(networkErr)

		poolResp, poolErr := client.PoolAdd(context.TODO(), &api.PoolAddRequest{
			NetworkID:   networkResp.Network.ID,
			Annotations: map[string]string{},
			Maximum:     250,
			Type:        api.Pool_FIXED,
		})
		assert.NoError(poolErr)

		_, bulkErr := client.BulkAllocateAddress(context.TODO(), &api.BulkAllocateAddressRequest{
			PoolID: poolResp.Pool.ID,
			Cidr:   "10.0.10.0/25",
		})
		assert.NoError(bulkErr)

		addrChan := make(chan string)

		for i := 0; i < 20; i++ {
			go func() {
				resp, err := client.BindAddress(context.TODO(), &api.BindAddressRequest{
					PoolID: poolResp.Pool.ID,
				})
				assert.NoError(err)
				addrChan <- resp.Binding.Address
			}()
		}

		addresses := map[string]struct{}{}

		for i := 0; i < 20; i++ {
			addr := <-addrChan
			if _, ok := addresses[addr]; ok {
				assert.Fail("duplicate address found: " + addr)
			} else {
				addresses[addr] = struct{}{}
			}
		}
	})

	test.execute(t)
}


text:
CREATE TABLE [dbo].[Merchant]
(
[MerchantID] [bigint] NOT NULL,
[MerchantName] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NOT NULL,
[FK_MerchantType] [bigint] NOT NULL,
[MerchantSystemType] [char] (3) COLLATE Chinese_PRC_CI_AS NULL,
[Domain] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL,
[LogoURL] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL,
[ContactName] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL,
[Tel] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL,
[Landline] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL,
[Email] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL,
[QQ] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL,
[FK_PassType] [bigint] NOT NULL,
[PassNumber] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL,
[Address] [nvarchar] (200) COLLATE Chinese_PRC_CI_AS NULL,
[OtherContact] [nvarchar] (500) COLLATE Chinese_PRC_CI_AS NULL,
[MerchantRemark] [nvarchar] (500) COLLATE Chinese_PRC_CI_AS NULL,
[RegisterTime] [datetime] NULL,
[MerchantState] [char] (1) COLLATE Chinese_PRC_CI_AS NULL,
[Remark] [varchar] (1000) COLLATE Chinese_PRC_CI_AS NULL,
[RecordState] [char] (1) COLLATE Chinese_PRC_CI_AS NOT NULL,
[CreateTime] [datetime] NOT NULL,
[CreaterID] [bigint] NOT NULL,
[CreaterName] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL,
[UpdateTime] [datetime] NOT NULL,
[UpdaterID] [bigint] NOT NULL,
[UpdaterName] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
ALTER TABLE [dbo].[Merchant] ADD
CONSTRAINT [PK_MERCHANT] PRIMARY KEY CLUSTERED  ([MerchantID]) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IX_MerchantName] ON [dbo].[Merchant] ([MerchantName]) ON [PRIMARY]

GO
EXEC sp_addextendedproperty N'MS_Description', '商户表', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', NULL, NULL
GO

EXEC sp_addextendedproperty N'MS_Description', '地址', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'Address'
GO

EXEC sp_addextendedproperty N'MS_Description', '联系人', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'ContactName'
GO

EXEC sp_addextendedproperty N'MS_Description', '创建者ID', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'CreaterID'
GO

EXEC sp_addextendedproperty N'MS_Description', '创建者名', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'CreaterName'
GO

EXEC sp_addextendedproperty N'MS_Description', '创建时间', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'CreateTime'
GO

EXEC sp_addextendedproperty N'MS_Description', '绑定的域名', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'Domain'
GO

EXEC sp_addextendedproperty N'MS_Description', '电子邮件', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'Email'
GO

EXEC sp_addextendedproperty N'MS_Description', '商户类型(参见字典库)', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'FK_MerchantType'
GO

EXEC sp_addextendedproperty N'MS_Description', '证件类型(参见字典库)', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'FK_PassType'
GO

EXEC sp_addextendedproperty N'MS_Description', '固话', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'Landline'
GO

EXEC sp_addextendedproperty N'MS_Description', 'logo图片地址', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'LogoURL'
GO

EXEC sp_addextendedproperty N'MS_Description', '商户ID', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'MerchantID'
GO

EXEC sp_addextendedproperty N'MS_Description', '商户名', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'MerchantName'
GO

EXEC sp_addextendedproperty N'MS_Description', '商户备注信息', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'MerchantRemark'
GO

EXEC sp_addextendedproperty N'MS_Description', '商户状态(MerchantStateEnum)', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'MerchantState'
GO

EXEC sp_addextendedproperty N'MS_Description', '商户系统类型(MerchantSystemTypeEnum)', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'MerchantSystemType'
GO

EXEC sp_addextendedproperty N'MS_Description', '其它联系信息', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'OtherContact'
GO

EXEC sp_addextendedproperty N'MS_Description', '证件号', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'PassNumber'
GO

EXEC sp_addextendedproperty N'MS_Description', 'qq', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'QQ'
GO

EXEC sp_addextendedproperty N'MS_Description', '记录状态(RecordStateEnum)', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'RecordState'
GO

EXEC sp_addextendedproperty N'MS_Description', '注册时间', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'RegisterTime'
GO

EXEC sp_addextendedproperty N'MS_Description', '备注', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'Remark'
GO

EXEC sp_addextendedproperty N'MS_Description', '手机', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'Tel'
GO

EXEC sp_addextendedproperty N'MS_Description', '更新人ID', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'UpdaterID'
GO

EXEC sp_addextendedproperty N'MS_Description', '更新人名', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'UpdaterName'
GO

EXEC sp_addextendedproperty N'MS_Description', '更新时间', 'SCHEMA', N'dbo', 'TABLE', N'Merchant', 'COLUMN', N'UpdateTime'
GO


text:
package com.hp.ov.sdk.storage;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.hp.ov.sdk.dto.Property;
import com.hp.ov.sdk.dto.ResourceCollection;
import com.hp.ov.sdk.dto.fcsans.DeviceManagerResponse;
import com.hp.ov.sdk.dto.fcsans.SanProviderResponse;
import com.hp.ov.sdk.exceptions.SDKResourceNotFoundException;
import com.hp.ov.sdk.oneview.BasicResource;
import com.hp.ov.sdk.oneview.CreateResource;
import com.hp.ov.sdk.rest.client.storage.FcSanProviderClient;

public class FcSanProviderResource extends BasicResource implements CreateResource {

    private static FcSanProviderResource instance;

    private FcSanProviderClient client;

    public FcSanProviderResource() {
        client = oneViewClient.fcSanProvider();
    }

    public static FcSanProviderResource getInstance() {
        if (instance == null) {
            instance = new FcSanProviderResource();
        }
        return instance;
    }

    @Override
    public Map<String, String> getResourceProperties(String id) {
        return getResourceProperties(client.getById(id));
    }

    @Override
    public String findByName(String name) {
        SanProviderResponse provider = (SanProviderResponse) getResource(client.getByName(name));
        return provider == null ? "" : provider.getResourceId();
    }

    @Override
    public String findById(String id) {
        try {
            return client.getById(id).getName();
        } catch (final SDKResourceNotFoundException ex) {
            return "";
        }
    }

    @Override
    public int count() {
        return getCount(client.getAll());
    }

    @Override
    public void create() {
        SanProviderResponse sanProvider = (SanProviderResponse) getResource(client.getByName(resourceProperties.get("provider")));
        client.addSanManager(sanProvider.getResourceId(), builder());
    }

    public void createSynergy() {
        ResourceCollection<SanProviderResponse> sanProviders = client.getAll();

        for(SanProviderResponse sanProvider : sanProviders.getMembers())
        {
            if (sanProvider.getName().equals(resourceProperties.get("type"))) {
                client.addSanManager(sanProvider.getResourceId(), builderSynergy());
            }
        }
    }

    @Override
    public DeviceManagerResponse builder() {
        SanProviderResponse sanProvider = (SanProviderResponse) getResource(client.getByName(resourceProperties.get("provider")));

        DeviceManagerResponse deviceManagerResponseDto = new DeviceManagerResponse();
        List<Property> connectionInfo = new ArrayList<>();
        Object portValue = "";
        for (Property property : sanProvider.getDefaultConnectionInfo()) {
            if (property.getDisplayName().contains("Port")) {
                portValue = property.getValue();
            }
        }

        Property host = new Property();
        host.setName(resourceProperties.get("hostname"));
        host.setValue(resourceProperties.get("name"));

        Property port = new Property();
        port.setName(resourceProperties.get("port"));
        port.setValue(portValue);

        Property user = new Property();
        user.setName("Username");
        user.setValue(resourceProperties.get("user"));

        Property password = new Property();
        password.setName("Password");
        password.setValue(resourceProperties.get("password"));

        Property useSsl = new Property();
        useSsl.setName(resourceProperties.get("use_ssl"));
        useSsl.setValue(resourceProperties.get("use_ssl_value"));

        connectionInfo.add(host);
        connectionInfo.add(port);
        connectionInfo.add(user);
        connectionInfo.add(password);
        connectionInfo.add(useSsl);

        deviceManagerResponseDto.setConnectionInfo(connectionInfo);

        return deviceManagerResponseDto;
    }
    public DeviceManagerResponse builderSynergy() {

        DeviceManagerResponse deviceManagerResponseDtoSynergy = new DeviceManagerResponse();
        List<Property> connectionInfo = new ArrayList<>();

        Property host = new Property();

        host.setName("Host");
        host.setValue(resourceProperties.get("name"));

        Property port = new Property();
        port.setName("SnmpPort");
        port.setValue(Integer.valueOf(resourceProperties.get("snmpPort")));

        Property user = new Property();
        user.setName("snmpUserName");
        user.setValue(resourceProperties.get("snmpUserName"));

        Property authLevel = new Property();
        authLevel.setName("snmpAuthLevel");
        authLevel.setValue(resourceProperties.get("securityLevel"));

        Property authProtocol = new Property();
        authProtocol.setName("snmpAuthProtocol");
        authProtocol.setValue(resourceProperties.get("authProtocol"));

        Property password = new Property();
        password.setName("snmpAuthString");
        password.setValue(resourceProperties.get("password"));

        connectionInfo.add(host);
        connectionInfo.add(port);
        connectionInfo.add(user);
        connectionInfo.add(authLevel);
        connectionInfo.add(authProtocol);
        connectionInfo.add(password);

        deviceManagerResponseDtoSynergy.setConnectionInfo(connectionInfo);

        return deviceManagerResponseDtoSynergy;
    }
}


text:
<mvc:View
	controllerName="sap.m.sample.PlanningCalendarDnD.Page"
	xmlns:mvc="sap.ui.core.mvc"
	xmlns:core="sap.ui.core"
	xmlns:unified="sap.ui.unified"
	xmlns="sap.m">
	<VBox class="sapUiSmallMargin">
		<PlanningCalendar
				id="PC1"
				startDate="{path: '/startDate'}"
				rows="{path: '/people'}"
				appointmentsVisualization="Filled"
				appointmentSelect="handleAppointmentSelect">
			<toolbarContent>
				<Title text="Title" titleStyle="H4"/>
				<ToolbarSpacer/>
				<Label text="Logged in as" />
				<Select
						id="userRole"
						change="handleRoleChange"
						selectedKey="admin"
						width="230px">
					<items>
						<core:Item key="admin" text="Admin" />
						<core:Item key="manager" text="Manager" />
						<core:Item key="donna" text="Donna Moore" />
					</items>
				</Select>
			</toolbarContent>
			<rows>
				<PlanningCalendarRow
						icon="{pic}"
						title="{name}"
						text="{role}"
						enableAppointmentsDragAndDrop="{path:'name', formatter:'.canModifyAppointments'}"
						enableAppointmentsResize="{path:'name', formatter:'.canModifyAppointments'}"
						enableAppointmentsCreate="{path:'name', formatter:'.canModifyAppointments'}"
						appointmentDrop="handleAppointmentDrop"
						appointmentDragEnter="handleAppointmentDragEnter"
						appointmentResize="handleAppointmentResize"
						appointmentCreate="handleAppointmentCreate"
						appointments="{path : 'appointments', templateShareable: 'true'}">
					<appointments>
						<unified:CalendarAppointment
								startDate="{start}"
								endDate="{end}"
								icon="{pic}"
								title="{title}"
								text="{info}"
								type="{type}"
								tentative="{tentative}">
						</unified:CalendarAppointment>
					</appointments>
				</PlanningCalendarRow>
			</rows>
		</PlanningCalendar>
	</VBox>
</mvc:View>


text:
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html;charset=utf-8">
  <title>rx.py</title>
  <link rel="stylesheet" href="pycco.css">
<meta name="thumbnail" content="https://avatars0.githubusercontent.com/u/23156192?v=3&s=200" />
	<link rel="shortcut icon" href="favicon.png" type="image/png">

      rx.py

            This is ttv1 code (Timm tools, version 1).

        #

   home | discuss | report bug

   <gcse:search></gcse:search>

<form style="margin-left: 20px;" id="searchbox_009630129455493240085:aja5uvdnjeo" action="">
   <input value="009630129455493240085:aja5uvdnjeo" name="cx" type="hidden"/>
   <input value="FORID:11" name="cof" type="hidden"/>
   <input id="q" style=""  name="q" size="25" type="text"/>
   <button class="btn">Search</button>
</form>

Run some some experiments, setting some globals,
the un-doing those changes once the experiment fails.

Example:

 class silly:
   X=1
   Y=min
 class solly:
   Z=22
   B="love"
 def f1():
   return 3>1

 # begin experiments
 for _ in rx(solly, Z=[20,30], B=["love","hate"]):
   for _ in rx(  silly, X=[2,3], Y=[max,f1]):
     # insert your experiment here
     assert silly.X != 1
     assert solly.Z != 22

 # afterwards, we are back to the old values.
 assert silly.X == 1
 assert solly.Z == 22

Programmer's Guide

In the following,  klass is some with attributes k.v1,k.v2,.. etc
which we want to (temporarily) set
to something else (and the something else comes from
the values in the dictionary **d).

Note that the
values in d can be lists or a single items

import itertools,sys,random

        #

def rx(klass,**d):
  lst = [[(k,v) for v in

        #

Ensure k's value is something we can iterate over.

          (vs if type(vs)==list else [vs])]
           for k,vs in d.items()]

        #

Generate all combinations.

  combos = list( itertools.product(*lst) )

        #

Run over the combinations.

  for settings in combos:
    now = {k:v for k,v in settings}

        #

Cache the old settings.

    saved = {k:getattr(klass,k) for k in now}

        #

Impose the temp settings.

    for k in now:
      setattr(klass,k,now[k])

        #

Let something do something with the temp settings.

    yield now

        #

Reset to old.

    for k in saved:
      setattr(klass,k,saved[k])

        #

def rx1(lst):
  d   = {key:val for d in lst for key,val in d.items()}
  tmp = []
  for k,v in d.items():
    i = 1
    key = k[:i]
    while key in tmp and len(key) < len(k):
      i += 1
      key = k[:i]
    if   v==True       : v="1"
    elif v==False      : v="0"
    elif type(v)==float: v= "%g" % v
    elif type(v)==int  : v=v
    elif v.__class__.__name__ == 'function': v=v.__name__
    tmp += ["%s%s" % (key,v)]
  return ':'.join(tmp)

        #

def say(*lst):
  print(*lst, sep=' ', end='', file=sys.stdout, flush=True)

        #

def watch(src,seed=1,every=10,klass="__all__",repeats=20):
  random.seed(seed)
  n = 0
  for _ in range(repeats):
    for one in src(klass):
      n += 1
      if (n % every) == 0 : say("",n)
      yield one

        #

def dominates(pop,objs=None,betters=None):
  betters = betters or [min for _ in pop[0]]
  if objs==None:
    objs= lambda z: z[1:]
  doms={}
  for i,one in enumerate( pop):
    doms[i] = 0
  for i,xs in enumerate(pop):
      for j,ys in enumerate(pop):
        if cdom1(objs(xs),objs(ys),betters):
          doms[i] += 1
  return sorted([( doms[i] ,xs) for i,xs in enumerate(pop)],reverse=True)

        #

def cdom1(x, y, betters):
  "many objective"

        #

  def w(better):
    return -1 if better == min else 1

        #

  def expLoss(w,x1,y1,n):
    return -1*2.71828**( w*(x1 - y1) / n )

        #

Copyleft

Copyright © 2016,2017 Tim Menzies tim@menzies.us, MIT license v2.

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject
to the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Share and enjoy.

Discussion

Please enable JavaScript to view the comments powered by Disqus.


text:
@interface STCreationTop : NSObject

// Drawing Methods
+ (void)drawCanvas1WithFrame: (CGRect)frame;

@end


text:
====================
Alignment statistics
====================

This section brings together various alignment statistics.

.. Bamstats
.. ========

.. The following list presents links to the results of the :term:`bamstats` tool.

.. .. report:: Mapping.BamReport
..    :render: user

..    bamstats results

.. FastQC
.. ======

.. The following list presents links to the results of the :term:`fastqc` tool.
.. The fastqc tool is run over aligned reads only.

.. .. report:: Mapping.FastQCReport
..    :render: user

..    fastqc results

Picard metrics
==============

The following table present an overview of the alignments in the
BAM files for each :term:`track`. See the
`Picard metrics <http://picard.sourceforge.net/picard-metric-definitions.shtml#AlignmentSummaryMetrics>`_
for a definition of the field contents.
(note: PF=pass filter, reads that pass the vendor's filter criteria).

.. report:: Mapping.PicardSummary
   :render: table

   Alignments summary

.. report:: Mapping.PicardSummary
   :render: interleaved-bar-plot
   :slices: PCT_PF_READS_ALIGNED,STRAND_BALANCE
   :layout: row
   :split-at: 10

   Percentage quantities

.. report:: Mapping.PicardSummary
   :render: interleaved-bar-plot
   :slices: PF_READS_ALIGNED,PF_HQ_ALIGNED_READS
   :layout: row
   :split-at: 10

   Percentage quantities

The following plots show the distribution of base quality scores in
reads. Note that if the bam-files have been stripped of sequence and
quality information the plots below will contain meaningless values.

.. report:: Mapping.AlignmentQualityByCycle
   :render: line-plot
   :as-lines:
   :yrange: 0,
   :layout: row

   mean quality score by cycle

.. report:: Mapping.AlignmentQualityDistribution
   :render: line-plot
   :as-lines:
   :yrange: 0,
   :layout: row

   quality score distribution

The following table presents an overview of the insert size metrics
for each :term:`track`.  See the
`Picard metrics <http://picard.sourceforge.net/picard-metric-definitions.shtml#InsertSizeMetrics>`_
for a definition of the field contents.
(note: only applicable for paired-end data).

.. report:: Mapping.PicardInsertSizeMetrics
   :render: table

   Insert size summary

.. report:: Mapping.PicardInsertSizeHistogram
   :render: line-plot
   :as-lines:

   Insert size distribution

Coverages
=========

The following base coverage summaries are computed from bigwig files.
This report might be empty if no bigwig files have been computed.

.. report:: Mapping.BigwigSummary
   :render: table
   :force:

   Coverage summary computed from bigwig files.


text:
<?php

namespace Sinergi\Config\Path;

use Exception;

class PathNotFoundException extends Exception
{
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2017 Snow Volf (Artem Zhiganov).
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~       http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~  Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="ru.SnowVolf.translate.ui.activity.LanguageListActivity">
    <include layout="@layout/app_bar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/include2" />
    <FrameLayout
        android:id="@+id/lang_list_container"
        android:layout_width="0dp"
        android:layout_height="0dp">

    </FrameLayout>
</android.support.design.widget.CoordinatorLayout>


text:
// Copyright 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

package com.google.appengine.tools.pipeline;

/**
 *
 * @author rudominer@google.com (Mitch Rudominer)
 *
 */
public class MiscPipelineTest extends PipelineTest {

  public void testImmediateChild() throws Exception {
    PipelineService service = PipelineServiceFactory.newPipelineService();
    String pipelineId = service.startNewPipeline(new Returns5FromChildJob());
    Integer five = (Integer) waitForJobToComplete(pipelineId);
    assertEquals(5, five.intValue());
  }

  private static class Returns5FromChildJob extends Job0<Integer> {
    @Override
    public Value<Integer> run() {
      return futureCall(new IdentityJob(), immediate(5));
    }
  }

  private static class IdentityJob extends Job1<Integer, Integer> {
    @Override
    public Value<Integer> run(Integer param1) {
      return immediate(param1);
    }
  }

}


text:
package com.orientechnologies.orient.core.record.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.db.record.ODatabaseRecordInternal;
import com.orientechnologies.orient.core.db.record.ORecordElement;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.record.ORecordAbstract;
import com.orientechnologies.orient.core.serialization.OMemoryStream;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializerFactory;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializerRaw;

/**
 * The rawest representation of a record. It's schema less. Use this if you need to store Strings or byte[] without matter about the
 * content. Useful also to store multimedia contents and binary files. The object can be reused across calls to the database by
 * using the reset() at every re-use.
 */
@SuppressWarnings({ "unchecked" })
public class ORecordBytes extends ORecordAbstract {
  private static final long   serialVersionUID = 1L;

  public static final byte    RECORD_TYPE      = 'b';
  private static final byte[] EMPTY_SOURCE     = new byte[] {};

  public ORecordBytes() {
    setup();
  }

  public ORecordBytes(final ODatabaseRecordInternal iDatabase) {
    setup();
    ODatabaseRecordThreadLocal.INSTANCE.set(iDatabase);
  }

  public ORecordBytes(final ODatabaseRecordInternal iDatabase, final byte[] iSource) {
    this(iSource);
    ODatabaseRecordThreadLocal.INSTANCE.set(iDatabase);
  }

  public ORecordBytes(final byte[] iSource) {
    super(iSource);
    _dirty = true;
    _contentChanged = true;
    setup();
  }

  public ORecordBytes(final ORID iRecordId) {
    _recordId = (ORecordId) iRecordId;
    setup();
  }

  public ORecordBytes reset(final byte[] iSource) {
    reset();
    _source = iSource;
    return this;
  }

  public ORecordBytes copy() {
    return (ORecordBytes) copyTo(new ORecordBytes());
  }

  @Override
  public ORecordBytes fromStream(final byte[] iRecordBuffer) {
    _source = iRecordBuffer;
    _status = ORecordElement.STATUS.LOADED;
    return this;
  }

  @Override
  public byte[] toStream() {
    return _source;
  }

  public byte getRecordType() {
    return RECORD_TYPE;
  }

  @Override
  protected void setup() {
    super.setup();
    _recordFormat = ORecordSerializerFactory.instance().getFormat(ORecordSerializerRaw.NAME);
  }

  /**
   * Reads the input stream in memory. This is less efficient than {@link #fromInputStream(InputStream, int)} because allocation is
   * made multiple times. If you already know the input size use {@link #fromInputStream(InputStream, int)}.
   *
   * @param in
   *          Input Stream, use buffered input stream wrapper to speed up reading
   * @return Buffer read from the stream. It's also the internal buffer size in bytes
   * @throws IOException
   */
  public int fromInputStream(final InputStream in) throws IOException {
    final OMemoryStream out = new OMemoryStream();
    try {
      final byte[] buffer = new byte[OMemoryStream.DEF_SIZE];
      int readBytesCount;
      while (true) {
        readBytesCount = in.read(buffer, 0, buffer.length);
        if (readBytesCount == -1) {
          break;
        }
        out.write(buffer, 0, readBytesCount);
      }
      out.flush();
      _source = out.toByteArray();
    } finally {
      out.close();
    }
    _size = _source.length;
    return _size;
  }

  /**
   * Reads the input stream in memory specifying the maximum bytes to read. This is more efficient than
   * {@link #fromInputStream(InputStream)} because allocation is made only once.
   *
   * @param in
   *          Input Stream, use buffered input stream wrapper to speed up reading
   * @param maxSize
   *          Maximum size to read
   * @return Buffer count of bytes that are read from the stream. It's also the internal buffer size in bytes
   * @throws IOException
   *           if an I/O error occurs.
   */
  public int fromInputStream(final InputStream in, final int maxSize) throws IOException {
    final byte[] buffer = new byte[maxSize];
    int totalBytesCount = 0;
    int readBytesCount;
    while (totalBytesCount < maxSize) {
      readBytesCount = in.read(buffer, totalBytesCount, buffer.length - totalBytesCount);
      if (readBytesCount == -1) {
        break;
      }
      totalBytesCount += readBytesCount;
    }

    if (totalBytesCount == 0) {
      _source = EMPTY_SOURCE;
      _size = 0;
    } else if (totalBytesCount == maxSize) {
      _source = buffer;
      _size = maxSize;
    } else {
      _source = Arrays.copyOf(buffer, totalBytesCount);
      _size = totalBytesCount;
    }
    return _size;
  }

  public void toOutputStream(final OutputStream out) throws IOException {
    checkForLoading();

    if (_source.length > 0) {
      out.write(_source);
    }
  }
}


text:
cask "airtool" do
  version "2.2.1,7"
  sha256 "e9e1031e5369e89664c9a3923643577ea9991ec8c9b8c33d0ede1d31372127bc"

  url "https://www.intuitibits.com/downloads/Airtool_#{version.before_comma}.pkg"
  name "Airtool"
  homepage "https://www.intuitibits.com/products/airtool/"

  livecheck do
    url "https://www.intuitibits.com/appcasts/com.intuitibits.airtool#{version.major}cast.xml"
    strategy :sparkle
  end

  auto_updates true

  pkg "Airtool_#{version.before_comma}.pkg"

  uninstall_preflight do
    set_ownership "/Library/Application Support/Airtool #{version.major}"
  end

  uninstall pkgutil:    [
    "com.intuitibits.airtool-helper.pkg",
    "com.intuitibits.airtool#{version.major}.pkg",
  ],
            launchctl:  "com.intuitibits.airtool#{version.major}.airtool-bpf",
            login_item: "Airtool",
            delete:     "/Library/Application Support/Airtool #{version.major}"
end


text:
require 'test_helper'

module Furious
  class TagTest < Minitest::Test
    def test_new_fails_when_no_gemspec_given
      error = assert_raises(ArgumentError) do
        Tag.new(nil)
      end
      assert_equal error.message, 'No gemspec file given'
    end

    def test_tag_creates_git_tag
      subject.expects(:system).with('git tag v1.0 && git push origin v1.0').returns(true)
      subject.tag
    end

    def test_tag_raises_on_failure
      subject.stub(:system, false) do
        error = assert_raises { subject.tag }
        assert_equal error.message, 'Failed to tag v1.0'
      end
    end

    private

    def subject
      @subject ||= Tag.new('test/fixtures/dummy.gemspec')
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_selected="true"><shape>
            <solid android:color="#FF2EA3FE" />

            <corners android:bottomLeftRadius="@dimen/button_conner_radius" android:bottomRightRadius="@dimen/button_conner_radius" android:topLeftRadius="@dimen/button_conner_radius" android:topRightRadius="@dimen/button_conner_radius" />

            <stroke android:width="1dp" android:color="#FF2EA3FE" />
        </shape></item>
    <item android:state_pressed="true"><shape>
            <solid android:color="#FF2EA3FE" />

            <corners android:bottomLeftRadius="@dimen/button_conner_radius" android:bottomRightRadius="@dimen/button_conner_radius" android:topLeftRadius="@dimen/button_conner_radius" android:topRightRadius="@dimen/button_conner_radius" />

            <stroke android:width="1dp" android:color="#FF2EA3FE" />
        </shape></item>
    <item><shape>
            <solid android:color="@android:color/transparent" />

            <corners android:bottomLeftRadius="@dimen/button_conner_radius" android:bottomRightRadius="@dimen/button_conner_radius" android:topLeftRadius="@dimen/button_conner_radius" android:topRightRadius="@dimen/button_conner_radius" />

            <stroke android:width="1dp" android:color="#FF2EA3FE" />
        </shape></item>

</selector>


text:
require_relative 'base.rb'

module CodecovApi
  module Objects
    class FolderTotals < Base
      protected

      def valid_methods
        [:files, :lines, :hits, :misses, :coverage]
      end

      def root_element
        @data['commit']['folder_totals']
      end
    end
  end
end


text:
package com.intellij.psi.html;

import com.intellij.html.embedding.HtmlEmbeddedContentSupport;
import com.intellij.ide.highlighter.HtmlFileType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.testFramework.ExtensionTestUtil;
import com.intellij.testFramework.LightIdeaTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileNotFoundException;

public class HtmlParseTest extends LightIdeaTestCase {
  private static final String BASE_PATH = "/xml/tests/testData/psi/old/html/";

  public void testSimpleParse() throws Exception {
    String result = getTreeTextByText("");
    assertResult("simple.txt",result);

    result = getTreeTextByText("
");
    assertResult("SingleTag.txt",result);

    result = getTreeTextByText("

");
    assertResult("TwoSingleTags.txt",result);

    result = getTreeTextByText("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\"\n" +
                               "        \"http://www.w3.org/TR/html4/frameset.dtd\">");
    assertResult("DocumentWithDocType.txt",result);

    result = getTreeTextByText("<!doctype html public \"-//W3C//DTD HTML 4.01 Frameset//EN\"\n" +
                               "        \"http://www.w3.org/TR/html4/frameset.dtd\">");
    assertResult("DocumentWithDocType2.txt",result);

    result = getTreeTextByText("""
                                 <tag>
                                     <subtag>
                                         Value
                                     </subtag>
                                     <emptyTag attr=""/>
                                 </tag>""");
    assertResult("Tags.txt",result);

    result = getTreeTextByText("""

""");
    assertResult("AttributeWithoutValue.txt",result);

    result = getTreeTextByText("""

""");
    assertResult("AttributeWithoutQuotes.txt",result);

    result = getTreeTextByText("
c
a
");
    assertResult("TagAfterNonClosedTag.txt",result);

    result = getTreeTextByText("
AAAABBBCCC
");
    assertResult("OptionalEndTagInBlockTag.txt",result);

    result = getTreeTextByText("");
    assertResult("OptionalEndTagEndedByBlockTag.txt",result);

    result = getTreeTextByText("""

PROHIBITED -\s
                                 Static variable in class ssh2.ChannelOpenException

The administrator does not permit this channel to be opened

QQQ - cipher.WWW.
cipher API.
QQQ() -\s
                                 Constructor for class sshtools.QQ

""");
    assertResult("OptionalEndTagEndedByBlockTag2.txt",result);

    result = getTreeTextByText("");
    assertResult("DifferentCaseInTagStartAndEnd.txt",result);

    result = getTreeTextByText("

");
    assertResult("ManyPs.txt",result);

    result = getTreeTextByText("""

                                 """);
    assertResult("ManyAs.txt",result);

    result = getTreeTextByText("<FRAMESET rows=50,* ></FRAMESET>");
    assertResult("ComplexUnquotedAttr.txt",result);

    result = getTreeTextByText("

");
    assertResult("ComplexPs.txt",result);

    result = getTreeTextByText("""

Footnotes

                                 <ADDRESS>
                                 Mon Apr 12 20:58:12 EST 2004, Gerwin Klein
                                 </ADDRESS>

                                 """);
    assertResult("BRHR.txt",result);

    result = getTreeTextByText("""

Introduction

Design goals

Installing and Running JFlex

""");
    assertResult("List.txt",result);

    result = getTreeTextByText("""

Copyright

                                 """);
    assertResult("WronglyBalancedOutOfChain.txt",result);

    result = getTreeTextByText("""

Changes to build 3075

Import Eclipse projects

Now you can import Eclipse projects into IDEA.

J2ME Support

                                     Features enhancing work with CSS:

aaa

                                 """);
    assertResult("BadBadBR.txt",result);

    @NonNls String s = """
      <?>
      <?style tt = font courier>

      <?page break>
      <?experiment> ... <?/experiment>
      """;
    result = getTreeTextByText(s);
    assertResult("ToleratingHtmlPIs.txt",result);

    s = " ";
    result = getTreeTextByText(s);
    assertResult("CharEntityRef.txt",result);

    s = "  ";
    result = getTreeTextByText(s);
    assertResult("CharRef.txt",result);

    s = "


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

#if !NO_PERF
using System;

namespace System.Reactive.Linq.ObservableImpl
{
    class Cast<TSource, TResult> : Producer<TResult> /* Could optimize further by deriving from Select<TResult> and providing Omega<TResult2>. We're not doing this (yet) for debuggability. */
    {
        private readonly IObservable<TSource> _source;

        public Cast(IObservable<TSource> source)
        {
            _source = source;
        }

        protected override IDisposable Run(IObserver<TResult> observer, IDisposable cancel, Action<IDisposable> setSink)
        {
            var sink = new _(observer, cancel);
            setSink(sink);
            return _source.SubscribeSafe(sink);
        }

        class _ : Sink<TResult>, IObserver<TSource>
        {
            public _(IObserver<TResult> observer, IDisposable cancel)
                : base(observer, cancel)
            {
            }

            public void OnNext(TSource value)
            {
                var result = default(TResult);
                try
                {
                    result = (TResult)(object)value;
                }
                catch (Exception exception)
                {
                    base._observer.OnError(exception);
                    base.Dispose();
                    return;
                }

                base._observer.OnNext(result);
            }

            public void OnError(Exception error)
            {
                base._observer.OnError(error);
                base.Dispose();
            }

            public void OnCompleted()
            {
                base._observer.OnCompleted();
                base.Dispose();
            }
        }
    }
}
#endif