http://en.wikipedia.org/wiki/Binomial_coefficient
 http://rosettacode.org/wiki/Evaluate_binomial_coefficients#Ruby
551252
def binomial_coefficient(k)
	    (0...k).inject(1) {|m,i| (m * (degree - i)) / (i + 1) }
	end
465456
def step5(self):
        
        self.j = self.k
        if self.b[self.k] == "e":
            a = self.m()
            if a > 1 or (a == 1 and not self.cvc(self.k - 1)):
                self.k = self.k - 1
        if self.b[self.k] == "l" and self.doublec(self.k) and self.m() > 1:
            self.k = self.k - 1
666728
def binary_operator(op):
    
    # When combining a Factor with a NumericalExpression, we use this
    # attrgetter instance to defer to the commuted implementation of the
    # NumericalExpression operator.
    commuted_method_getter = attrgetter(method_name_for_op(op, commute=True))

    @with_doc("Binary Operator: '%s'" % op)
    @with_name(method_name_for_op(op))
    @coerce_numbers_to_my_dtype
    def binary_operator(self, other):
        # This can't be hoisted up a scope because the types returned by
        # binop_return_type aren't defined when the top-level function is
        # invoked in the class body of Factor.
        return_type = binop_return_type(op)
        if isinstance(self, NumExprFactor):
            self_expr, other_expr, new_inputs = self.build_binary_op(
                op, other,
            )
            return return_type(
                "({left}) {op} ({right})".format(
                    left=self_expr,
                    op=op,
                    right=other_expr,
                ),
                new_inputs,
                dtype=binop_return_dtype(op, self.dtype, other.dtype),
            )
        elif isinstance(other, NumExprFactor):
            # NumericalExpression overrides ops to correctly handle merging of
            # inputs.  Look up and call the appropriate reflected operator with
            # ourself as the input.
            return commuted_method_getter(other)(self)
        elif isinstance(other, Term):
            if self is other:
                return return_type(
                    "x_0 {op} x_0".format(op=op),
                    (self,),
                    dtype=binop_return_dtype(op, self.dtype, other.dtype),
                )
            return return_type(
                "x_0 {op} x_1".format(op=op),
                (self, other),
                dtype=binop_return_dtype(op, self.dtype, other.dtype),
            )
        elif isinstance(other, Number):
            return return_type(
                "x_0 {op} ({constant})".format(op=op, constant=other),
                binds=(self,),
                # .dtype access is safe here because coerce_numbers_to_my_dtype
                # will convert any input numbers to numpy equivalents.
                dtype=binop_return_dtype(op, self.dtype, other.dtype)
            )
        raise BadBinaryOperator(op, self, other)

    return binary_operator
410216
def **(n)
      if @expr.nil?
        expr = nil
      elsif /^[A-Za-z_]+$/o =~ @expr
        expr = @expr+'^'+n.to_s
      else
        expr = '('+@expr+')^'+n.to_s+''
      end
      self.class.new( @value**n, expr, @unit**n )
    end
1288972
def result(_binding_or_hash=TOPLEVEL_BINDING)
      _arg = _binding_or_hash
      if _arg.is_a?(Hash)
        _b = binding()
        eval _arg.collect{|k,v| "#{k} = _arg[#{k.inspect}]; "}.join, _b
      elsif _arg.is_a?(Binding)
        _b = _arg
      elsif _arg.nil?
        _b = binding()
      else
        raise ArgumentError.new("#{self.class.name}#result(): argument should be Binding or Hash but passed #{_arg.class.name} object.")
      end
      return eval(@src, _b, (@filename || '(erubis'))
    end
37371
def _process_monomial(self, monomial, n_vars):
        
        processed_monomial, coeff = separate_scalar_factor(monomial)
        # Are we substituting this moment?
        try:
            substitute = self.moment_substitutions[processed_monomial]
            if not isinstance(substitute, (int, float, complex)):
                result = []
                if not isinstance(substitute, Add):
                    args = [substitute]
                else:
                    args = substitute.args
                for arg in args:
                    if is_number_type(arg):
                        if iscomplex(arg):
                            result.append((0, coeff*complex(arg)))
                        else:
                            result.append((0, coeff*float(arg)))
                    else:
                        result += [(k, coeff*c2)
                                   for k, c2 in self._process_monomial(arg,
                                                                       n_vars)]
            else:
                result = [(0, coeff*substitute)]
        except KeyError:
            # Have we seen this monomial before?
            try:
                # If yes, then we improve sparsity by reusing the
                # previous variable to denote this entry in the matrix
                k = self.monomial_index[processed_monomial]
            except KeyError:
                # If no, it still may be possible that we have already seen its
                # conjugate. If the problem is real-valued, a monomial and its
                # conjugate should be equal (Hermiticity becomes symmetry)
                if not self.complex_matrix:
                    try:
                    # If we have seen the conjugate before, we just use the
                    # conjugate monomial instead
                        processed_monomial_adjoint = \
                              apply_substitutions(processed_monomial.adjoint(),
                                                  self.substitutions)
                        k = self.monomial_index[processed_monomial_adjoint]
                    except KeyError:
                        # Otherwise we define a new entry in the associated
                        # array recording the monomials, and add an entry in
                        # the moment matrix
                        k = n_vars + 1
                        self.monomial_index[processed_monomial] = k
                else:
                    k = n_vars + 1
                    self.monomial_index[processed_monomial] = k
            result = [(k, coeff)]
        return result
530907
protected String pbLhs(final Literal[] operands, final int[] coefficients) {
        assert operands.length == coefficients.length;
        final StringBuilder sb = new StringBuilder();
        final String mul = this.pbMul();
        final String add = this.pbAdd();
        for (int i = 0; i < operands.length - 1; i++) {
            if (coefficients[i] != 1) {
                sb.append(coefficients[i]).append(mul).append(operands[i]).append(add);
            } else {
                sb.append(operands[i]).append(add);
            }
        }
        if (operands.length > 0) {
            if (coefficients[operands.length - 1] != 1) {
                sb.append(coefficients[operands.length - 1]).append(mul).append(operands[operands.length - 1]);
            } else {
                sb.append(operands[operands.length - 1]);
            }
        }
        return sb.toString();
    }
615585
def determine_coefficient
      # Array of photon energies (in units of MeV).
      @energies = [
        0.001,
        0.0015,
        0.002,
        0.003,
        0.004,
        0.005,
        0.006,
        0.008,
        0.01,
        0.015,
        0.02,
        0.03,
        0.04,
        0.05,
        0.06,
        0.08,
        0.1,
        0.15,
        0.2,
        0.3,
        0.4,
        0.5,
        0.6,
        0.8,
        1.0,
        1.25,
        1.5,
        2.0,
        3.0,
        4.0,
        5.0,
        6.0,
        8.0,
        10.0,
        15.0,
        20.0
      ]
      # Array of mass attenuation coefficients for the above energies, for liquid water (in units of cm^2/g):
      @att_coeffs = [
        4078,
        1376,
        617.3,
        192.9,
        82.78,
        42.58,
        24.64,
        10.37,
        5.329,
        1.673,
        0.8096,
        0.3756,
        0.2683,
        0.2269,
        0.2059,
        0.1837,
        0.1707,
        0.1505,
        0.137,
        0.1186,
        0.1061,
        0.09687,
        0.08956,
        0.07865,
        0.07072,
        0.06323,
        0.05754,
        0.04942,
        0.03969,
        0.03403,
        0.03031,
        0.0277,
        0.02429,
        0.02219,
        0.01941,
        0.01813
      ]
      # Determine the coefficient:
      if @energy >= 20.0
        # When the energy is above 20, we use the coefficient for 20 MeV:
        @ac_water = @att_coeffs.last
      else
        if i = @energies.index(@energy)
          # When it exactly matches one of the listed energies, use its corresponding coefficient:
          @ac_water = @att_coeffs[i]
        else
          # When the given energy is between two of the listed values, interpolate:
          i_after = @energies.index {|x| x > @energy}
          if i_after
            e_high = @energies[i_after]
            e_low = @energies[i_after - 1]
            ac_high = @att_coeffs[i_after]
            ac_low = @att_coeffs[i_after - 1]
            @ac_water = (ac_high - ac_low ) / (e_high - e_low) * (@energy - e_low)
          else
            raise "Unexpected behaviour with index in the energy interpolation logic."
          end
        end
      end
    end
839899
def binary_operation_math(self, rule, left, right, **kwargs):
        
        return self.evaluate_binop_math(rule.operation, left, right, **kwargs)
550697
def calculable(self):
        """"""
        self._mode = ""
        if self.kwargs["T"] and self.kwargs["P"]:
            self._mode = "TP"
        elif self.kwargs["T"] and self.kwargs["rho"]:
            self._mode = "Trho"
        elif self.kwargs["T"] and self.kwargs["h"] is not None:
            self._mode = "Th"
        elif self.kwargs["T"] and self.kwargs["s"] is not None:
            self._mode = "Ts"
        elif self.kwargs["T"] and self.kwargs["u"] is not None:
            self._mode = "Tu"
        elif self.kwargs["P"] and self.kwargs["rho"]:
            self._mode = "Prho"
        elif self.kwargs["P"] and self.kwargs["h"] is not None:
            self._mode = "Ph"
        elif self.kwargs["P"] and self.kwargs["s"] is not None:
            self._mode = "Ps"
        elif self.kwargs["P"] and self.kwargs["u"] is not None:
            self._mode = "Pu"
        elif self.kwargs["rho"] and self.kwargs["h"] is not None:
            self._mode = "rhoh"
        elif self.kwargs["rho"] and self.kwargs["s"] is not None:
            self._mode = "rhos"
        elif self.kwargs["rho"] and self.kwargs["u"] is not None:
            self._mode = "rhou"
        elif self.kwargs["h"] is not None and self.kwargs["s"] is not None:
            self._mode = "hs"
        elif self.kwargs["h"] is not None and self.kwargs["u"] is not None:
            self._mode = "hu"
        elif self.kwargs["s"] is not None and self.kwargs["u"] is not None:
            self._mode = "su"
        elif self.kwargs["T"] and self.kwargs["x"] is not None:
            self._mode = "Tx"
        elif self.kwargs["P"] and self.kwargs["x"] is not None:
            self._mode = "Px"
        return bool(self._mode)
1283535
def _add_numeric_methods_binary(cls):
        

        def _make_evaluate_binop(op, step=False):
            """
            Parameters
            ----------
            op : callable that accepts 2 parms
                perform the binary op
            step : callable, optional, default to False
                op to apply to the step parm if not None
                if False, use the existing step
            """

            def _evaluate_numeric_binop(self, other):
                if isinstance(other, (ABCSeries, ABCDataFrame)):
                    return NotImplemented
                elif isinstance(other, ABCTimedeltaIndex):
                    # Defer to TimedeltaIndex implementation
                    return NotImplemented
                elif isinstance(other, (timedelta, np.timedelta64)):
                    # GH#19333 is_integer evaluated True on timedelta64,
                    # so we need to catch these explicitly
                    return op(self._int64index, other)
                elif is_timedelta64_dtype(other):
                    # Must be an np.ndarray; GH#22390
                    return op(self._int64index, other)

                other = self._validate_for_numeric_binop(other, op)
                attrs = self._get_attributes_dict()
                attrs = self._maybe_update_attributes(attrs)

                left, right = self, other

                try:
                    # apply if we have an override
                    if step:
                        with np.errstate(all='ignore'):
                            rstep = step(left._step, right)

                        # we don't have a representable op
                        # so return a base index
                        if not is_integer(rstep) or not rstep:
                            raise ValueError

                    else:
                        rstep = left._step

                    with np.errstate(all='ignore'):
                        rstart = op(left._start, right)
                        rstop = op(left._stop, right)

                    result = RangeIndex(rstart,
                                        rstop,
                                        rstep,
                                        **attrs)

                    # for compat with numpy / Int64Index
                    # even if we can represent as a RangeIndex, return
                    # as a Float64Index if we have float-like descriptors
                    if not all(is_integer(x) for x in
                               [rstart, rstop, rstep]):
                        result = result.astype('float64')

                    return result

                except (ValueError, TypeError, ZeroDivisionError):
                    # Defer to Int64Index implementation
                    return op(self._int64index, other)
                    # TODO: Do attrs get handled reliably?

            name = '__{name}__'.format(name=op.__name__)
            return compat.set_function_name(_evaluate_numeric_binop, name, cls)

        cls.__add__ = _make_evaluate_binop(operator.add)
        cls.__radd__ = _make_evaluate_binop(ops.radd)
        cls.__sub__ = _make_evaluate_binop(operator.sub)
        cls.__rsub__ = _make_evaluate_binop(ops.rsub)
        cls.__mul__ = _make_evaluate_binop(operator.mul, step=operator.mul)
        cls.__rmul__ = _make_evaluate_binop(ops.rmul, step=ops.rmul)
        cls.__truediv__ = _make_evaluate_binop(operator.truediv,
                                               step=operator.truediv)
        cls.__rtruediv__ = _make_evaluate_binop(ops.rtruediv,
                                                step=ops.rtruediv)
6688
def unit_str
      rv = @numerator_units.sort.join("*")
      if @denominator_units.any?
        rv << "/"
        rv << @denominator_units.sort.join("*")
      end
      rv
    end
1063787
def overview_html_hash(evaluation, less)
      data = [@overview[:scores].group_by { |a| a }.map do |k, vs|
        { 'key': k, 'value': vs.length, 'main': false }
      end]
      { data: data, type: :simplebars, aux1: 10, aux2: '',
        title: 'Overall GeneValidator Score Evaluation', footer: '',
        xtitle: 'Validation Score', ytitle: 'Number of Queries',
        less: less, evaluation: evaluation }
    end
79347
def K(self):
        """"""
        K1 = np.float_power(pi, 0.5 * self.n_min * self.n_min)
        K1 /= (
            np.float_power(2, 0.5 * self.n_min * self._n_max)
            * self._mgamma(0.5 * self._n_max, self.n_min)
            * self._mgamma(0.5 * self.n_min, self.n_min)
        )

        K2 = np.float_power(
            2, self.alpha * self.size + 0.5 * self.size * (self.size + 1)
        )
        for i in xrange(self.size):
            K2 *= gamma(self.alpha + i + 1)
        return K1 * K2
144922
def _arith_method_SERIES(cls, op, special):
    
    str_rep = _get_opstr(op, cls)
    op_name = _get_op_name(op, special)
    eval_kwargs = _gen_eval_kwargs(op_name)
    fill_zeros = _gen_fill_zeros(op_name)
    construct_result = (_construct_divmod_result
                        if op in [divmod, rdivmod] else _construct_result)

    def na_op(x, y):
        import pandas.core.computation.expressions as expressions
        try:
            result = expressions.evaluate(op, str_rep, x, y, **eval_kwargs)
        except TypeError:
            result = masked_arith_op(x, y, op)

        result = missing.fill_zeros(result, x, y, op_name, fill_zeros)
        return result

    def safe_na_op(lvalues, rvalues):
        """
        return the result of evaluating na_op on the passed in values

        try coercion to object type if the native types are not compatible

        Parameters
        ----------
        lvalues : array-like
        rvalues : array-like

        Raises
        ------
        TypeError: invalid operation
        """
        try:
            with np.errstate(all='ignore'):
                return na_op(lvalues, rvalues)
        except Exception:
            if is_object_dtype(lvalues):
                return libalgos.arrmap_object(lvalues,
                                              lambda x: op(x, rvalues))
            raise

    def wrapper(left, right):
        if isinstance(right, ABCDataFrame):
            return NotImplemented

        left, right = _align_method_SERIES(left, right)
        res_name = get_op_result_name(left, right)
        right = maybe_upcast_for_op(right)

        if is_categorical_dtype(left):
            raise TypeError("{typ} cannot perform the operation "
                            "{op}".format(typ=type(left).__name__, op=str_rep))

        elif is_datetime64_dtype(left) or is_datetime64tz_dtype(left):
            # Give dispatch_to_index_op a chance for tests like
            # test_dt64_series_add_intlike, which the index dispatching handles
            # specifically.
            result = dispatch_to_index_op(op, left, right, pd.DatetimeIndex)
            return construct_result(left, result,
                                    index=left.index, name=res_name,
                                    dtype=result.dtype)

        elif (is_extension_array_dtype(left) or
                (is_extension_array_dtype(right) and not is_scalar(right))):
            # GH#22378 disallow scalar to exclude e.g. "category", "Int64"
            return dispatch_to_extension_op(op, left, right)

        elif is_timedelta64_dtype(left):
            result = dispatch_to_index_op(op, left, right, pd.TimedeltaIndex)
            return construct_result(left, result,
                                    index=left.index, name=res_name)

        elif is_timedelta64_dtype(right):
            # We should only get here with non-scalar or timedelta64('NaT')
            #  values for right
            # Note: we cannot use dispatch_to_index_op because
            #  that may incorrectly raise TypeError when we
            #  should get NullFrequencyError
            result = op(pd.Index(left), right)
            return construct_result(left, result,
                                    index=left.index, name=res_name,
                                    dtype=result.dtype)

        lvalues = left.values
        rvalues = right
        if isinstance(rvalues, ABCSeries):
            rvalues = rvalues.values

        result = safe_na_op(lvalues, rvalues)
        return construct_result(left, result,
                                index=left.index, name=res_name, dtype=None)

    wrapper.__name__ = op_name
    return wrapper
416122
def _scalar_binary_op(self, other, binop, result):
        '''
        
        '''
        template = 'map({arr}, |z: {type}| z {binop} {other}{suffix})'
        weld_type = result._weld_type.__str__()
        result.weldobj.weld_code = template.format(arr = result.weldobj.weld_code,
                                                  type =  weld_type,
                                                  binop = binop,
                                                  other = str(other),
                                                  suffix = DTYPE_SUFFIXES[weld_type])
        return result
331170
def _convert(self, chain_id, residue_id, from_scheme, to_scheme):
        ''''''

        # There are 12 valid combinations but rather than write them all out explicitly, we will use recursion, sacrificing speed for brevity
        if from_scheme == 'rosetta':
            atom_id = self.rosetta_to_atom_sequence_maps.get(chain_id, {})[residue_id]
            if to_scheme == 'atom':
                return atom_id
            else:
                return self._convert(chain_id, atom_id, 'atom', to_scheme)
        if from_scheme == 'atom':
            if to_scheme == 'rosetta':
                return self.atom_to_rosetta_sequence_maps.get(chain_id, {})[residue_id]
            else:
                seqres_id = self.atom_to_seqres_sequence_maps.get(chain_id, {})[residue_id]
                if to_scheme == 'seqres':
                    return seqres_id
                return self.convert(chain_id, seqres_id, 'seqres', to_scheme)
        if from_scheme == 'seqres':
            if to_scheme == 'uniparc':
                return self.seqres_to_uniparc_sequence_maps.get(chain_id, {})[residue_id]
            else:
                atom_id = self.seqres_to_atom_sequence_maps.get(chain_id, {})[residue_id]
                if to_scheme == 'atom':
                    return atom_id
                return self.convert(chain_id, atom_id, 'atom', to_scheme)
        if from_scheme == 'uniparc':
            seqres_id = self.uniparc_to_seqres_sequence_maps.get(chain_id, {})[residue_id]
            if to_scheme == 'seqres':
                return seqres_id
            else:
                return self._convert(chain_id, seqres_id, 'seqres', to_scheme)

        raise Exception("We should never reach this line.")