Convert a possiblty time-dependent operator into the nested-list
    structure required by QuTiP
189406
def _time_dependent_to_qutip(
        op, full_space=None, time_symbol=symbols("t", real=True),
        convert_as='pyfunc'):
    """"""
    if full_space is None:
        full_space = op.space
    if time_symbol in op.free_symbols:
        op = op.expand()
        if isinstance(op, OperatorPlus):
            result = []
            for o in op.operands:
                if time_symbol not in o.free_symbols:
                    if len(result) == 0:
                        result.append(convert_to_qutip(o,
                                                       full_space=full_space))
                    else:
                        result[0] += convert_to_qutip(o, full_space=full_space)
            for o in op.operands:
                if time_symbol in o.free_symbols:
                    result.append(_time_dependent_to_qutip(o, full_space,
                                  time_symbol, convert_as))
            return result
        elif (
                isinstance(op, ScalarTimesOperator) and
                isinstance(op.coeff, ScalarValue)):
            if convert_as == 'pyfunc':
                func_no_args = lambdify(time_symbol, op.coeff.val)
                if {time_symbol, } == op.coeff.free_symbols:
                    def func(t, args):
                        # args are ignored for increased efficiency, since we
                        # know there are no free symbols except t
                        return func_no_args(t)
                else:
                    def func(t, args):
                        return func_no_args(t).subs(args)
                coeff = func
            elif convert_as == 'str':
                # a bit of a hack to replace imaginary unit
                # TODO: we can probably use one of the sympy code generation
                # routines, or lambdify with 'numexpr' to implement this in a
                # more robust way
                coeff = re.sub("I", "(1.0j)", str(op.coeff.val))
            else:
                raise ValueError(("Invalid value '%s' for `convert_as`, must "
                                  "be one of 'str', 'pyfunc'") % convert_as)
            return [convert_to_qutip(op.term, full_space), coeff]
        else:
            raise ValueError("op cannot be expressed in qutip. It must have "
                             "the structure op = sum_i f_i(t) * op_i")
    else:
        return convert_to_qutip(op, full_space=full_space)
127489
def assoc_indexed(cls, ops, kwargs):
    
    """
    from qnet.algebra.core.abstract_quantum_algebra import (
        ScalarTimesQuantumExpression)
    term, *ranges = ops

    if isinstance(term, cls):
        coeff = 1
    elif isinstance(term, ScalarTimesQuantumExpression):
        coeff = term.coeff
        term = term.term
        if not isinstance(term, cls):
            return ops, kwargs
    else:
        return ops, kwargs

    term = term.make_disjunct_indices(*ranges)
    combined_ranges = tuple(ranges) + term.ranges

    if coeff == 1:
        return cls.create(term.term, *combined_ranges)
    else:
        bound_symbols = set([r.index_symbol for r in combined_ranges])
        if len(coeff.free_symbols.intersection(bound_symbols)) == 0:
            return coeff * cls.create(term.term, *combined_ranges)
        else:
            return cls.create(coeff * term.term, *combined_ranges)
359006
def flatten_if(cond: Callable[[Union[T, ActualIterable[T]]], bool]):
    

    def inner(nested: ActualIterable[Union[T, ActualIterable[T]]]) -> ActualIterable[T]:
        for each in nested:
            if cond(each):
                yield from inner(each)
            else:
                yield each

    return inner
1250773
def inc(self, *args, **kwargs):
        '''  '''
        pairs = []
        if len(args) == 1:
            pairs.append((args[0], 1))
        elif len(args) == 2:
            pairs.append(args)
        elif len(kwargs) != 0:
            pairs.extend([(k, v) for k, v in kwargs.items()])
        else:
            raise UpdateException('Invalid arguments for set.  Requires either two positional arguments or at least one keyword argument')

        ret = self
        for qfield, value in pairs:
            ret = self._atomic_op('$inc', qfield, value)
        return ret
362917
def _transpose_dict_list(dict_list):
  """"""
  # 1. Unstack numpy arrays into list
  dict_list = utils.map_nested(np_to_list, dict_list, dict_only=True)

  # 2. Extract the sequence length (and ensure the length is constant for all
  # elements)
  length = {'value': None}  # dict because `nonlocal` is Python3 only
  def update_length(elem):
    if length['value'] is None:
      length['value'] = len(elem)
    elif length['value'] != len(elem):
      raise ValueError(
          'The length of all elements of one sequence should be the same. '
          'Got {} != {}'.format(length['value'], len(elem)))
    return elem
  utils.map_nested(update_length, dict_list, dict_only=True)

  # 3. Extract each individual elements
  return [
      utils.map_nested(lambda elem: elem[i], dict_list, dict_only=True)   # pylint: disable=cell-var-from-loop
      for i in range(length['value'])
  ]
907753
function convertFakeListsToProperLists(node) {
          var currentListNode, prevListNode, lastLevel = 1;

          function getText(node) {
            var txt = '';

            if (node.type === 3) {
              return node.value;
            }

            if ((node = node.firstChild)) {
              do {
                txt += getText(node);
              } while ((node = node.next));
            }

            return txt;
          }

          function trimListStart(node, regExp) {
            if (node.type === 3) {
              if (regExp.test(node.value)) {
                node.value = node.value.replace(regExp, '');
                return false;
              }
            }

            if ((node = node.firstChild)) {
              do {
                if (!trimListStart(node, regExp)) {
                  return false;
                }
              } while ((node = node.next));
            }

            return true;
          }

          function removeIgnoredNodes(node) {
            if (node._listIgnore) {
              node.remove();
              return;
            }

            if ((node = node.firstChild)) {
              do {
                removeIgnoredNodes(node);
              } while ((node = node.next));
            }
          }

          function convertParagraphToLi(paragraphNode, listName, start) {
            var level = paragraphNode._listLevel || lastLevel;

            // Handle list nesting
            if (level != lastLevel) {
              if (level < lastLevel) {
                // Move to parent list
                if (currentListNode) {
                  currentListNode = currentListNode.parent.parent;
                }
              } else {
                // Create new list
                prevListNode = currentListNode;
                currentListNode = null;
              }
            }

            if (!currentListNode || currentListNode.name != listName) {
              prevListNode = prevListNode || currentListNode;
              currentListNode = new Node(listName, 1);

              if (start > 1) {
                currentListNode.attr('start', '' + start);
              }

              paragraphNode.wrap(currentListNode);
            } else {
              currentListNode.append(paragraphNode);
            }

            paragraphNode.name = 'li';

            // Append list to previous list if it exists
            if (level > lastLevel && prevListNode) {
              prevListNode.lastChild.append(currentListNode);
            }

            lastLevel = level;

            // Remove start of list item "1. " or "&middot; " etc
            removeIgnoredNodes(paragraphNode);
            trimListStart(paragraphNode, /^\u00a0+/);
            trimListStart(paragraphNode, /^\s*([\u2022\u00b7\u00a7\u25CF]|\w+\.)/);
            trimListStart(paragraphNode, /^\u00a0+/);
          }

          // Build a list of all root level elements before we start
          // altering them in the loop below.
          var elements = [], child = node.firstChild;
          while (typeof child !== 'undefined' && child !== null) {
            elements.push(child);

            child = child.walk();
            if (child !== null) {
              while (typeof child !== 'undefined' && child.parent !== node) {
                child = child.walk();
              }
            }
          }

          for (var i = 0; i < elements.length; i++) {
            node = elements[i];

            if (node.name == 'p' && node.firstChild) {
              // Find first text node in paragraph
              var nodeText = getText(node);

              // Detect unordered lists look for bullets
              if (isBulletList(nodeText)) {
                convertParagraphToLi(node, 'ul');
                continue;
              }

              // Detect ordered lists 1., a. or ixv.
              if (isNumericList(nodeText)) {
                // Parse OL start number
                var matches = /([0-9]+)\./.exec(nodeText);
                var start = 1;
                if (matches) {
                  start = parseInt(matches[1], 10);
                }

                convertParagraphToLi(node, 'ol', start);
                continue;
              }

              // Convert paragraphs marked as lists but doesn't look like anything
              if (node._listLevel) {
                convertParagraphToLi(node, 'ul', 1);
                continue;
              }

              currentListNode = null;
            } else {
              // If the root level element isn't a p tag which can be
              // processed by convertParagraphToLi, it interrupts the
              // lists, causing a new list to start instead of having
              // elements from the next list inserted above this tag.
              prevListNode = currentListNode;
              currentListNode = null;
            }
          }
        }
1111049
def recenter(positions):
    '''
    '''
    (x0, y0, z0), (x1, y1, z1) = bounding_box(positions)
    dx = x1 - (x1 - x0) / 2.0
    dy = y1 - (y1 - y0) / 2.0
    dz = z1 - (z1 - z0) / 2.0
    result = []
    for x, y, z in positions:
        result.append((x - dx, y - dy, z - dz))
    return result
371106
def listify(p:OptListOrItem=None, q:OptListOrItem=None):
    ""
    if p is None: p=[]
    elif isinstance(p, str):          p = [p]
    elif not isinstance(p, Iterable): p = [p]
    #Rank 0 tensors in PyTorch are Iterable but don't have a length.
    else:
        try: a = len(p)
        except: p = [p]
    n = q if type(q)==int else len(p) if q is None else len(q)
    if len(p)==1: p = p * n
    assert len(p)==n, f'List len mismatch ({len(p)} vs {n})'
    return list(p)
1312115
function(time, key, val) {
		return {
			db: dbPrefix(key),
			col: colPrefix('gauges', key),
			data: {
				time: time,
				gauge: val
			},
		};
	}
567168
def w_state(qubits: Union[int, Qubits]) -> State:
    """"""
    N, qubits = qubits_count_tuple(qubits)
    ket = np.zeros(shape=[2] * N)
    for n in range(N):
        idx = np.zeros(shape=N, dtype=int)
        idx[n] += 1
        ket[tuple(idx)] = 1 / sqrt(N)
    return State(ket, qubits)
469610
function flattenList(list) {
  // Make a copy, so the original tensor is not modified.
  list = [].concat(list);

  // Note that i must be checked against the length of the list each time through the loop, as the
  // list is modified within the iterations.
  for (let i = 0; i < list.length; i++) {
    if (Array.isArray(list[i])) {
      // Replace the item with the flattened version of the item (using the ... operator).
      // Replace with the items and backtrack 1 position
      list.splice(i, 1, ...list[i]);

      // Decrement i to look at the element again; we'll keep looking at this i index, until
      // the most deeply nested item has been flattened.
      i--;
    }
  }

  return list;
}
732122
def apply_type_shim(cls, _context=None) -> Iterator:
    
    if cls.name in ["IntField", "SmallIntField"]:
        base_nodes = scoped_nodes.builtin_lookup("int")
    elif cls.name in ["CharField", "TextField"]:
        base_nodes = scoped_nodes.builtin_lookup("str")
    elif cls.name == "BooleanField":
        base_nodes = scoped_nodes.builtin_lookup("bool")
    elif cls.name == "FloatField":
        base_nodes = scoped_nodes.builtin_lookup("float")
    elif cls.name == "DecimalField":
        base_nodes = MANAGER.ast_from_module_name("decimal").lookup("Decimal")
    elif cls.name == "DatetimeField":
        base_nodes = MANAGER.ast_from_module_name("datetime").lookup("datetime")
    elif cls.name == "DateField":
        base_nodes = MANAGER.ast_from_module_name("datetime").lookup("date")
    elif cls.name == "ForeignKeyField":
        base_nodes = MANAGER.ast_from_module_name("tortoise.fields").lookup("BackwardFKRelation")
    elif cls.name == "ManyToManyField":
        base_nodes = MANAGER.ast_from_module_name("tortoise.fields").lookup(
            "ManyToManyRelationManager"
        )
    else:
        return iter([cls])

    return iter([cls] + base_nodes[1])
739802
def _generate_a_indptr(num_states, s_indices, out):
    
    idx = 0
    out[0] = 0
    for s in range(num_states-1):
        while(s_indices[idx] == s):
            idx += 1
        out[s+1] = idx
    out[num_states] = len(s_indices)
1319583
def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds):
    
    fmt = u("{%s}")
    pairs = []

    pfmt = u("%s: %s")

    if max_seq_items is False:
        nitems = len(seq)
    else:
        nitems = max_seq_items or options.display.max_seq_items or len(seq)

    for k, v in list(seq.items())[:nitems]:
        pairs.append(pfmt % (pprint_thing(k, _nest_lvl + 1, max_seq_items=max_seq_items, **kwds),
                             pprint_thing(v, _nest_lvl + 1, max_seq_items=max_seq_items, **kwds)))

    if nitems < len(seq):
        return fmt % (", ".join(pairs) + ", ...")
    else:
        return fmt % ", ".join(pairs)
54480
function(item, options) {
    return [
      {index:{_index: 'listening_' + moment(item._source.cdate).format('YYYYMM'), _type:options.type || item._type, _id: item._id}},
      item._source
    ];
  }
836817
def _flatten_nested_input(v):
    
    v = copy.deepcopy(v)
    if isinstance(v["type"], dict) and v["type"]["type"] == "array":
        v["type"] = v["type"]["items"]
    else:
        assert isinstance(v["type"], (list, tuple)), v
        new_type = None
        want_null = False
        for x in v["type"]:
            if isinstance(x, dict) and x["type"] == "array":
                new_type = x["items"]
            elif isinstance(x, six.string_types) and x == "null":
                want_null = True
            else:
                new_type = x
        if want_null:
            if not isinstance(new_type, (list, tuple)):
                new_type = [new_type] if new_type is not None else []
            for toadd in ["null", "string"]:
                if toadd not in new_type:
                    new_type.append(toadd)
        assert new_type, v
        v["type"] = new_type
    return v
1257079
def expect(qubits, meas):
    ""
    result = {}
    i = np.arange(len(qubits))
    meas = tuple(meas)

    def to_mask(n):
        return reduce(lambda acc, im: acc | (n & (1 << im[0])) << (im[1] - im[0]), enumerate(meas), 0)

    def to_key(k):
        return tuple(1 if k & (1 << i) else 0 for i in meas)

    mask = reduce(lambda acc, v: acc | (1 << v), meas, 0)

    cnt = defaultdict(float)
    for i, v in enumerate(qubits):
        p = v.real ** 2 + v.imag ** 2
        if p != 0.0:
            cnt[i & mask] += p
    return {to_key(k): v for k, v in cnt.items()}