Solve the entire F2L. (Generator)
767862
def solve(self):
        
        for i in range(4):
            for slot in ["FR", "RB", "BL", "LF"]:
                solver = F2LPairSolver(self.cube, slot)
                if not solver.is_solved():
                    yield tuple([self.cube[slot[i]].colour for i in range(2)]), solver.solve()
                    break
949648
def generator(self, t):
        """"""
        return np.power(-np.log(t), self.theta)
371693
private void _symmetricTql2 ()
  {
    // This is derived from the Algol procedures tql2, by
    // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
    // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
    // Fortran subroutine in EISPACK.
    for (int i = 1; i < m_nDim; i++)
      m_aEVe[i - 1] = m_aEVe[i];
    m_aEVe[m_nDim - 1] = 0.0;

    double f = 0.0;
    double tst1 = 0.0;
    for (int l = 0; l < m_nDim; l++)
    {
      // Find small subdiagonal element
      tst1 = Math.max (tst1, MathHelper.abs (m_aEVd[l]) + MathHelper.abs (m_aEVe[l]));
      int m = l;
      while (m < m_nDim)
      {
        if (MathHelper.abs (m_aEVe[m]) <= EPSILON * tst1)
          break;
        m++;
      }

      // If m == l, d[l] is an eigenvalue,
      // otherwise, iterate.

      if (m > l)
      {
        do
        {
          // Compute implicit shift
          double g = m_aEVd[l];
          double p = (m_aEVd[l + 1] - g) / (2.0 * m_aEVe[l]);
          double r = MathHelper.hypot (p, 1.0);
          if (p < 0)
          {
            r = -r;
          }
          m_aEVd[l] = m_aEVe[l] / (p + r);
          m_aEVd[l + 1] = m_aEVe[l] * (p + r);
          final double dl1 = m_aEVd[l + 1];
          double h = g - m_aEVd[l];
          for (int i = l + 2; i < m_nDim; i++)
          {
            m_aEVd[i] -= h;
          }
          f += h;

          // Implicit QL transformation.
          p = m_aEVd[m];
          double c = 1.0;
          double c2 = c;
          double c3 = c;
          final double el1 = m_aEVe[l + 1];
          double s = 0.0;
          double s2 = 0.0;
          for (int i = m - 1; i >= l; i--)
          {
            c3 = c2;
            c2 = c;
            s2 = s;
            g = c * m_aEVe[i];
            h = c * p;
            r = MathHelper.hypot (p, m_aEVe[i]);
            m_aEVe[i + 1] = s * r;
            s = m_aEVe[i] / r;
            c = p / r;
            p = c * m_aEVd[i] - s * g;
            m_aEVd[i + 1] = h + s * (c * g + s * m_aEVd[i]);

            // Accumulate transformation.

            for (int k = 0; k < m_nDim; k++)
            {
              h = m_aEigenVector[k][i + 1];
              m_aEigenVector[k][i + 1] = s * m_aEigenVector[k][i] + c * h;
              m_aEigenVector[k][i] = c * m_aEigenVector[k][i] - s * h;
            }
          }
          p = -s * s2 * c3 * el1 * m_aEVe[l] / dl1;
          m_aEVe[l] = s * p;
          m_aEVd[l] = c * p;

          // Check for convergence.

        } while (MathHelper.abs (m_aEVe[l]) > EPSILON * tst1);
      }
      m_aEVd[l] = m_aEVd[l] + f;
      m_aEVe[l] = 0.0;
    }

    // Sort eigenvalues and corresponding vectors.
    for (int i = 0; i < m_nDim - 1; i++)
    {
      int k = i;
      double p = m_aEVd[i];
      for (int j = i + 1; j < m_nDim; j++)
      {
        if (m_aEVd[j] < p)
        {
          k = j;
          p = m_aEVd[j];
        }
      }
      if (k != i)
      {
        m_aEVd[k] = m_aEVd[i];
        m_aEVd[i] = p;
        for (int j = 0; j < m_nDim; j++)
        {
          p = m_aEigenVector[j][i];
          m_aEigenVector[j][i] = m_aEigenVector[j][k];
          m_aEigenVector[j][k] = p;
        }
      }
    }
  }
1367406
def _solve_k_from_mu(data, k_array, nll, *args):
    
    # TODO: See if a root finder like fminbound would work with Decimal used in
    # logpmf method (will this work with arrays?)

    nll_array = np.zeros(len(k_array))

    for i in range(len(k_array)):
        nll_array[i] = nll(data, k_array[i], *args)

    min_nll_idx = np.argmin(nll_array)

    return k_array[min_nll_idx]
623243
void cffti() {
		if (n == 1)
			return;

		final int twon = 2 * n;
		final int fourn = 4 * n;
		double argh;
		int idot, ntry = 0, i, j;
		double argld;
		int i1, k1, l1, l2, ib;
		double fi;
		int ld, ii, nf, ip, nl, nq, nr;
		double arg;
		int ido, ipm;

		nl = n;
		nf = 0;
		j = 0;

		factorize_loop: while (true) {
			j++;
			if (j <= 4)
				ntry = factors[j - 1];
			else
				ntry += 2;
			do {
				nq = nl / ntry;
				nr = nl - ntry * nq;
				if (nr != 0)
					continue factorize_loop;
				nf++;
				wtable[nf + 1 + fourn] = ntry;
				nl = nq;
				if (ntry == 2 && nf != 1) {
					for (i = 2; i <= nf; i++) {
						ib = nf - i + 2;
						int idx = ib + fourn;
						wtable[idx + 1] = wtable[idx];
					}
					wtable[2 + fourn] = 2;
				}
			} while (nl != 1);
			break factorize_loop;
		}
		wtable[fourn] = n;
		wtable[1 + fourn] = nf;
		argh = TWO_PI / (double) n;
		i = 1;
		l1 = 1;
		for (k1 = 1; k1 <= nf; k1++) {
			ip = (int) wtable[k1 + 1 + fourn];
			ld = 0;
			l2 = l1 * ip;
			ido = n / l2;
			idot = ido + ido + 2;
			ipm = ip - 1;
			for (j = 1; j <= ipm; j++) {
				i1 = i;
				wtable[i - 1 + twon] = 1;
				wtable[i + twon] = 0;
				ld += l1;
				fi = 0;
				argld = ld * argh;
				for (ii = 4; ii <= idot; ii += 2) {
					i += 2;
					fi += 1;
					arg = fi * argld;
					int idx = i + twon;
					wtable[idx - 1] = Math.cos(arg);
					wtable[idx] = Math.sin(arg);
				}
				if (ip > 5) {
					int idx1 = i1 + twon;
					int idx2 = i + twon;
					wtable[idx1 - 1] = wtable[idx2 - 1];
					wtable[idx1] = wtable[idx2];
				}
			}
			l1 = l2;
		}

	}
898384
def _cho_solve_AATI(A, rho, b, c, lwr, check_finite=True):
    """"""

    N, M = A.shape
    if N >= M:
        x = (b - _cho_solve((c, lwr), b.dot(A).T,
            check_finite=check_finite).T.dot(A.T)) / rho
    else:
        x = _cho_solve((c, lwr), b.T, check_finite=check_finite).T
    return x
766162
private void tql2() {
    // This is derived from the Algol procedures tql2, by
    // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
    // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
    // Fortran subroutine in EISPACK.

    System.arraycopy(e, 1, e, 0, n - 1);
    e[n - 1] = 0.;

    double f = 0., tst1 = 0.;
    for(int l = 0; l < n; l++) {
      // Find small subdiagonal element
      tst1 = max(tst1, abs(d[l]) + abs(e[l]));
      int m = l;
      for(; m < n; ++m) {
        if(abs(e[m]) <= 0x1P-52 * tst1) {
          break;
        }
      }

      // If m == l, d[l] is an eigenvalue,
      // otherwise, iterate.
      if(m > l) {
        do {
          // Compute implicit shift
          f += tql2ComputeImplicitShift(l);
          // Implicit QL transformation.
          tql2ImplicitQL(l, m, d[l + 1]);
          // Check for convergence.
          // TODO: Iteration limit?
        }
        while(abs(e[l]) > 0x1P-52 * tst1);
      }
      d[l] += f;
      e[l] = 0.;
    }
  }
672882
private static function _getMorphed($n, $f1, $f2, $f5) {
        $n  = abs($n) % 100;
        $n1 = $n % 10;
        if ($n > 10 && $n < 20) return $f5;
        if ($n1 > 1 && $n1 < 5) return $f2;
        if ($n1 == 1) return $f1;

        return $f5;
    }
489243
def genCompleteTypes( compoundSig ):
    

    i     = 0
    start = 0
    end   = len(compoundSig)

    def find_end( idx, b, e ):
        depth = 1
        while idx < end:
            subc = compoundSig[idx]
            if subc == b:
                depth += 1
            elif subc == e:
                depth -= 1
                if depth == 0:
                    return idx
            idx += 1
    
    while i < end:
        c = compoundSig[i]
        
        if c == '(':
            x = find_end(i+1, '(', ')')
            yield compoundSig[i:x+1]
            i = x

        elif c == '{':
            x = find_end(i+1, '{', '}')
            yield compoundSig[i:x+1]
            i = x

        elif c == 'a':
            start = i
            g = genCompleteTypes( compoundSig[i+1:] )
            ct = six.next(g)
            i += len(ct)
            yield 'a' + ct
            
        else:
            yield c
        i += 1
886370
private double[][] solveL(double[][] X) {
    final int n = L.length, m = X[0].length;
    { // First iteration, simplified.
      final double[] X0 = X[0], L0 = L[0];
      for(int j = 0; j < m; j++) {
        X0[j] /= L0[0];
      }
    }
    for(int k = 1; k < n; k++) {
      final double[] Xk = X[k], Lk = L[k];
      final double iLkk = 1. / Lk[k];
      for(int j = 0; j < m; j++) {
        double Xkj = Xk[j];
        for(int i = 0; i < k; i++) {
          Xkj -= X[i][j] * Lk[i];
        }
        Xk[j] = Xkj * iLkk;
      }
    }
    return X;
  }
92704
def solve(self, solver_klass=None):
        
        case = self.case
        generators = case.online_generators

        logger.info("Solving OPF with unit de-commitment [%s]." % case.name)

        t0 = time()

        # 1. Begin at stage zero (N = 0), assuming all generators are on-line
        # with all limits in place. At most one generator shutdown per stage.
        i_stage = 0

        # Check for sum(p_min) > total load, decommit as necessary.
        online = [g for g in generators if not g.is_load]
        online_vload = [g for g in generators if g.is_load]

        # Total dispatchable load capacity.
        vload_capacity = sum([g.p_min for g in online_vload])
        # Total load capacity.
        load_capacity = sum([b.p_demand for b in case.buses]) - vload_capacity

        # Minimum total online generation capacity.
        p_min_tot = sum([g.p_min for g in online])

        # Shutdown the most expensive units until the minimum generation
        # capacity is less than the total load capacity.
        while p_min_tot > load_capacity:
            i_stage += 1
            logger.debug("De-commitment stage %d." % i_stage)

            # Find generator with the maximum average cost at Pmin.
            avg_pmin_cost = [g.total_cost(g.p_min) / g.p_min for g in online]
            # Select at random from maximal generators with equal cost.
            g_idx, _ = fair_max(avg_pmin_cost)
            generator = online[g_idx]

            logger.info("Shutting down generator [%s] to satisfy all "
                        "p_min limits." % generator.name)

            # Shut down most expensive unit.
            generator.online = False

            # Update minimum generation capacity for while loop.
            online = [g for g in case.online_generators if not g.is_load]
            p_min_tot = sum([g.p_min for g in online])

        # 2. Solve a normal OPF and save the solution as the current best.
        solution = super(UDOPF, self).solve(solver_klass)

        logger.debug("Initial system cost: $%.3f" % solution["f"])

        if not solution["converged"] == True:
            logger.error("Non-convergent UDOPF [%s]." %
                         solution["output"]["message"])
            return solution

        # 3. Go to the next stage, N = N + 1. Using the best solution from the
        # previous stage as the base case for this stage, ...

        # Best case so far. A list of the on-line status of all generators.
        overall_online = [g.online for g in case.generators]
        # The objective function value is the total system cost.
        overall_cost = solution["f"]

        # Best case for this stage.
        stage_online = overall_online
        stage_cost = overall_cost

        # Shutdown at most one generator per stage.
        while True:
            # 4. Form a candidate list of generators with minimum
            # generation limits binding.

            # Activate generators according to the stage best.
            for i, generator in enumerate(case.generators):
                generator.online = stage_online[i]

            # Get candidates for shutdown. Lagrangian multipliers are often
            # very small so we round to four decimal places.
            candidates = [g for g in case.online_generators if \
                          (round(g.mu_pmin, 4) > 0.0) and (g.p_min > 0.0)]

            if len(candidates) == 0:
                break

            # Assume no improvement during this stage.
            done = True

            i_stage += 1
            logger.debug("De-commitment stage %d." % i_stage)

            for candidate in candidates:
                # 5. For each generator on the candidate list, solve an OPF to
                # find the total system cost with the generator shut down.

                # Activate generators according to the stage best.
                for i, generator in enumerate(case.generators):
                    generator.online = stage_online[i]

                # Shutdown candidate generator.
                candidate.online = False

                logger.debug("Solving OPF with generator '%s' shutdown." %
                    candidate.name)

                # Run OPF.
                solution = super(UDOPF, self).solve(solver_klass)

                # Compare total system costs for improvement.
                if solution["converged"] == True \
                    and (solution["f"] < overall_cost):
                    logger.debug("System cost improvement: $%.3f ($%.3f)" %
                                 (stage_cost - solution["f"], solution["f"]))
                    # 6. Replace the current best solution with this one if
                    # it has a lower cost.
                    overall_online = [g.online for g in case.generators]
                    overall_cost = solution["f"]
                    best_candidate = candidate
                    # Check for further decommitment.
                    done = False
                else:
                    logger.debug("Candidate OPF failed [%s]." %
                                 solution["output"]["message"])

                # Reactivate the candidate before deactivating the next.
#                candidate.online = True

            if done:
                # Decommits at this stage did not help.
                break
            else:
                # 7. If any of the candidate solutions produced an improvement,
                # return to step 3.

                # Shutting something else down helps, so let's keep going.
                logger.info("Shutting down generator '%s'.",
                            best_candidate.name)

                stage_online = overall_online
                stage_cost = overall_cost

        # 8. Use the best overall solution as the final solution.
        for i, generator in enumerate(case.generators):
            generator.online = overall_online[i]

        # One final solve using the best case to ensure all results are
        # up-to-date.
        solution = super(UDOPF, self).solve(solver_klass)

        logger.debug("UDOPF system cost: $%.3f" % solution["f"])

        # Compute elapsed time and log it.
        elapsed = time() - t0

        plural = "" if i_stage == 1 else "s"
        logger.info("Unit decommitment OPF solved in %.3fs (%d decommitment "
                    "stage%s)." % (elapsed, i_stage, plural))

        return solution
1233595
def solve_full(z, Fval, DPhival, G, A):    
    M, N=G.shape
    P, N=A.shape

    """"""
    m=M    

    """Primal variable"""
    x=z[0:N]

    """Multiplier for equality constraints"""
    nu=z[N:N+P]

    """Multiplier for inequality constraints"""
    l=z[N+P:N+P+M]

    """Slacks"""
    s=z[N+P+M:]

    """Dual infeasibility"""
    rd = Fval[0:N]
    
    """Primal infeasibility"""
    rp1 = Fval[N:N+P]
    rp2 = Fval[N+P:N+P+M]

    """Centrality"""
    rc = Fval[N+P+M:]

    """Sigma matrix"""
    SIG = np.diag(l/s)

    """Condensed system"""
    if issparse(DPhival):
        if not issparse(A):
            A = csr_matrix(A)        
        H = DPhival + mydot(G.T, mydot(SIG, G))
        J = bmat([[H, A.T], [A, None]])
    else:
        if issparse(A):
            A = A.toarray()
        J = np.zeros((N+P, N+P))
        J[0:N, 0:N] = DPhival + mydot(G.T, mydot(SIG, G))            
        J[0:N, N:] = A.T
        J[N:, 0:N] = A

    b1 = -rd - mydot(G.T, mydot(SIG, rp2)) + mydot(G.T, rc/s)
    b2 = -rp1
    b = np.hstack((b1, b2))

    """Prepare iterative solve via MINRES"""
    sign = np.zeros(N+P)
    sign[0:N/2] = 1.0
    sign[N/2:] = -1.0
    S = diags(sign, 0)
    J_new = mydot(S, csr_matrix(J))
    b_new = mydot(S, b)

    dJ_new = np.abs(J_new.diagonal())
    dPc = np.ones(J_new.shape[0])
    ind = (dJ_new > 0.0)
    dPc[ind] = 1.0/dJ_new[ind]
    Pc = diags(dPc, 0)    
    dxnu, info = minres(J_new, b_new, tol=1e-8, M=Pc)
    
    # dxnu = solve(J, b)
    dx = dxnu[0:N]
    dnu = dxnu[N:]

    """Obtain search directions for l and s"""
    ds = -rp2 - mydot(G, dx)
    dl = -mydot(SIG, ds) - rc/s

    dz = np.hstack((dx, dnu, dl, ds))
    return dz
788966
def _generate_net(cls, flatterm: FlatTerm, final_label: T) -> _State[T]:
        """"""
        # Capture the last sequence wildcard for every level of operation nesting on a stack
        # Used to add backtracking edges in case the "match" fails later
        last_wildcards = [None]
        # Generate a fail state for every level of nesting to backtrack to a sequence wildcard in a parent Expression
        # in case no match can be found
        fail_states = [None]
        operand_counts = [0]
        root = state = _State()
        states = {root.id: root}

        for term in flatterm:
            if operand_counts[-1] >= 0:
                operand_counts[-1] += 1

            # For wildcards, generate a chain of #min_count Wildcard edges
            # If the wildcard is unbounded (fixed_size = False),
            # add a wildcard self loop at the end
            if isinstance(term, Wildcard):
                # Generate a chain of #min_count Wildcard edges
                for _ in range(term.min_count):
                    state = cls._create_child_state(state, Wildcard)
                    states[state.id] = state
                # If it is a sequence wildcard, add a self loop
                if not term.fixed_size:
                    state[Wildcard] = state
                    last_wildcards[-1] = state
                    operand_counts[-1] = -1
            else:
                state = cls._create_child_state(state, term)
                states[state.id] = state
                if is_operation(term):
                    fail_state = None
                    if last_wildcards[-1] or fail_states[-1]:
                        last_fail_state = (
                            fail_states[-1]
                            if not isinstance(fail_states[-1], list) else fail_states[-1][operand_counts[-1]]
                        )
                        if term.arity.fixed_size:
                            fail_state = _State()
                            states[fail_state.id] = fail_state
                            new_fail_states = [fail_state]
                            for _ in range(term.arity.min_count):
                                new_fail_state = _State()
                                states[new_fail_state.id] = new_fail_state
                                fail_state[Wildcard] = new_fail_state
                                fail_state = new_fail_state
                                new_fail_states.append(new_fail_state)
                            fail_state[OPERATION_END] = last_wildcards[-1] or last_fail_state
                            fail_state = new_fail_states
                        else:
                            fail_state = _State()
                            states[fail_state.id] = fail_state
                            fail_state[OPERATION_END] = last_wildcards[-1] or last_fail_state
                            fail_state[Wildcard] = fail_state
                    fail_states.append(fail_state)
                    last_wildcards.append(None)
                    operand_counts.append(0)
                elif term == OPERATION_END:
                    fail_states.pop()
                    last_wildcards.pop()
                    operand_counts.pop()

            if last_wildcards[-1] != state:
                if last_wildcards[-1]:
                    state[EPSILON] = last_wildcards[-1]
                elif fail_states[-1]:
                    last_fail_state = (
                        fail_states[-1]
                        if not isinstance(fail_states[-1], list) else fail_states[-1][operand_counts[-1]]
                    )
                    state[EPSILON] = last_fail_state

        state.payload = [final_label]

        return cls._convert_nfa_to_dfa(root, states)
223557
def optimize(self, x0, f=None, df=None, f_df=None):
        
        # Based on the documentation of DIRECT, it does not seem we can pass through an initial point x0
        try:
            from DIRECT import solve
            def DIRECT_f_wrapper(f):
                def g(x, user_data):
                    return f(np.array([x])), 0
                return g
            lB = np.asarray(self.bounds)[:,0]
            uB = np.asarray(self.bounds)[:,1]
            x,_,_ = solve(DIRECT_f_wrapper(f),lB,uB, maxT=self.maxiter)
            return np.atleast_2d(x), f(np.atleast_2d(x))
        except ImportError:
            print("Cannot find DIRECT library, please install it to use this option.")
            raise
1352973
def solve(self):
        """"""
        self._initialize()
        while self._outer_error_is_decreasing() and self._outer_iters < MAX_OUTERS:
            print('* Starting outer iteration {0:03d}. Current err = {1:12.5E}'
                  ''.format(self._outer_iters, self._last_outer_error))
            self._iterate_to_update_x_transforms()
            self._update_y_transform()
            self._outer_iters += 1
10617
function f1(d, m, r) {
    const t = m + d;
    const I = (t << r) | (t >>> (32 - r));
    return ((sBox[0][I >>> 24] ^ sBox[1][(I >>> 16) & 255]) - sBox[2][(I >>> 8) & 255]) + sBox[3][I & 255];
  }
220110
def from_fsm(f):
	'''
		
	'''
	# Make sure the supplied alphabet is kosher. It must contain only single-
	# character strings or `fsm.anything_else`.
	for symbol in f.alphabet:
		if symbol == fsm.anything_else:
			continue
		if isinstance(symbol, str) and len(symbol) == 1:
			continue
		raise Exception("Symbol " + repr(symbol) + " cannot be used in a regular expression")

	# We need a new state not already used
	outside = object()

	# The set of strings that would be accepted by this FSM if you started
	# at state i is represented by the regex R_i.
	# If state i has a sole transition "a" to state j, then we know R_i = a R_j.
	# If state i is final, then the empty string is also accepted by this regex.
	# And so on...

	# From this we can build a set of simultaneous equations in len(f.states)
	# variables. This system is easily solved for all variables, but we only
	# need one: R_a, where a is the starting state.

	# The first thing we need to do is organise the states into order of depth,
	# so that when we perform our back-substitutions, we can start with the
	# last (deepest) state and therefore finish with R_a.
	states = [f.initial]
	i = 0
	while i < len(states):
		current = states[i]
		if current in f.map:
			for symbol in sorted(f.map[current], key=fsm.key):
				next = f.map[current][symbol]
				if next not in states:
					states.append(next)
		i += 1

	# Our system of equations is represented like so:
	brz = {}
	for a in f.states:
		brz[a] = {}
		for b in f.states | {outside}:
			brz[a][b] = nothing

	# Populate it with some initial data.
	for a in f.map:
		for symbol in f.map[a]:
			b = f.map[a][symbol]
			if symbol == fsm.anything_else:
				brz[a][b] |= ~charclass(f.alphabet - {fsm.anything_else})
			else:
				brz[a][b] |= charclass({symbol})
		if a in f.finals:
			brz[a][outside] |= emptystring

	# Now perform our back-substitution
	for i in reversed(range(len(states))):
		a = states[i]

		# Before the equation for R_a can be substituted into the other
		# equations, we need to resolve the self-transition (if any).
		# e.g.    R_a = 0 R_a |   1 R_b |   2 R_c
		# becomes R_a =         0*1 R_b | 0*2 R_c
		loop = brz[a][a] * star # i.e. "0*"
		del brz[a][a]

		for right in brz[a]:
			brz[a][right] = loop + brz[a][right]

		# Note: even if we're down to our final equation, the above step still
		# needs to be performed before anything is returned.

		# Now we can substitute this equation into all of the previous ones.
		for j in range(i):
			b = states[j]

			# e.g. substituting R_a =  0*1 R_b |      0*2 R_c
			# into              R_b =    3 R_a |        4 R_c | 5 R_d
			# yields            R_b = 30*1 R_b | (30*2|4) R_c | 5 R_d
			univ = brz[b][a] # i.e. "3"
			del brz[b][a]

			for right in brz[a]:
				brz[b][right] |= univ + brz[a][right]

	return brz[f.initial][outside].reduce()