Creates new instance of the query state.
554288
function queryState(defaults, options) {
  options = options || {};
  var history = options.history || windowHistory(defaults, options);
  validateHistoryAPI(history);

  history.onChanged(updateQuery)

  var query = history.get() || Object.create(null);

  var api = {

    /**
     * Gets current state.
     *
     * @param {string?} keyName if present then value for this key is returned.
     * Otherwise the entire app state is returned.
     */
    get: getValue,

    /**
     * Merges current app state with new key/value.
     *
     * @param {string} key name
     * @param {string|number|date} value
     */
    set: setValue,

    /**
     * Removes value from the query string
     */
    unset: unsetValue,

    /**
     * Similar to `set()`, but only sets value if it was not set before.
     *
     * @param {string} key name
     * @param {string|number|date} value
     */
    setIfEmpty: setIfEmpty,

    /**
     * Releases all resources acquired by query state. After calling this method
     * no hash monitoring will happen and no more events will be fired.
     */
    dispose: dispose,

    onChange: onChange,
    offChange: offChange,

    getHistoryObject: getHistoryObject,
  }

  var eventBus = eventify({});

  return api;

  function onChange(callback, ctx) {
    eventBus.on('change', callback, ctx);
  }

  function offChange(callback, ctx) {
    eventBus.off('change', callback, ctx)
  }

  function getHistoryObject() {
    return history;
  }

  function dispose() {
    // dispose all history listeners
    history.dispose();

    // And remove our own listeners
    eventBus.off();
  }

  function getValue(keyName) {
    if (keyName === undefined) return query;

    return query[keyName];
  }

  function setValue(keyName, value) {
    var keyNameType = typeof keyName;

    if (keyNameType === 'object') {
      Object.keys(keyName).forEach(function(key) {
        query[key] = keyName[key];
      });
    } else if (keyNameType === 'string') {
      query[keyName] = value;
    }

    history.set(query);

    return api;
  }

  function unsetValue(keyName) {
    if (!(keyName in query)) return; // nothing to do

    delete query[keyName];
    history.set(query);

    return api;
  }

  function updateQuery(newAppState) {
    query = newAppState;
    eventBus.fire('change', query);
  }

  function setIfEmpty(keyName, value) {
    if (typeof keyName === 'object') {
      Object.keys(keyName).forEach(function(key) {
        // TODO: Can I remove code duplication? The main reason why I don't
        // want recursion here is to avoid spamming `history.set()`
        if (key in query) return; // key name is not empty

        query[key] = keyName[key];
      });
    }

    if (keyName in query) return; // key name is not empty
    query[keyName] = value;

    history.set(query);

    return api;
  }
}
933076
function() {
    var self = this;
    var fsm = self.filterStateModel;

    var newFilter = fsm.get("filterCollection").createNewFilter();
    fsm.set("activeFilterId", newFilter.cid);

    self.trigger("filter:new", newFilter.cid, newFilter);
  }
970100
function newInstance(extend) {
  return (initialValues = {}) => {
    const model = {};
    const publicAPI = {};
    extend(publicAPI, model, initialValues);
    return Object.freeze(publicAPI);
  };
}
524241
public static PreparedStatement newInstance(PreparedStatement stmt, Log statementLog, int queryStack) {
    InvocationHandler handler = new PreparedStatementLogger(stmt, statementLog, queryStack);
    ClassLoader cl = PreparedStatement.class.getClassLoader();
    return (PreparedStatement) Proxy.newProxyInstance(cl, new Class[]{PreparedStatement.class, CallableStatement.class}, handler);
  }
567812
private void initialize()
    {
        SqlStageExecution rootStage = stages.get(rootStageId);
        rootStage.addStateChangeListener(state -> {
            if (state == FINISHED) {
                queryStateMachine.transitionToFinishing();
            }
            else if (state == CANCELED) {
                // output stage was canceled
                queryStateMachine.transitionToCanceled();
            }
        });

        for (SqlStageExecution stage : stages.values()) {
            stage.addStateChangeListener(state -> {
                if (queryStateMachine.isDone()) {
                    return;
                }
                if (state == FAILED) {
                    queryStateMachine.transitionToFailed(stage.getStageInfo().getFailureCause().toException());
                }
                else if (state == ABORTED) {
                    // this should never happen, since abort can only be triggered in query clean up after the query is finished
                    queryStateMachine.transitionToFailed(new PrestoException(GENERIC_INTERNAL_ERROR, "Query stage was aborted"));
                }
                else if (state == FINISHED) {
                    List<SqlStageExecution> nextStagesToSchedule = getStagesReadyForExecution();
                    if (!nextStagesToSchedule.isEmpty()) {
                        startScheduling(nextStagesToSchedule);
                    }
                }
                else if (queryStateMachine.getQueryState() == QueryState.STARTING) {
                    // if the stage has at least one task, we are running
                    if (stage.hasTasks()) {
                        queryStateMachine.transitionToRunning();
                    }
                }
            });
        }

        // when query is done or any time a stage completes, attempt to transition query to "final query info ready"
        queryStateMachine.addStateChangeListener(newState -> {
            if (newState.isDone()) {
                queryStateMachine.updateQueryInfo(Optional.ofNullable(getStageInfo()));
            }
        });
        for (SqlStageExecution stage : stages.values()) {
            stage.addFinalStageInfoListener(status -> queryStateMachine.updateQueryInfo(Optional.ofNullable(getStageInfo())));
        }
    }
215095
public Query createQuery( Constraint constraint ) {
        if (constraint instanceof And) {
            return createQuery((And) constraint);
        }
        if (constraint instanceof Or) {
            return createQuery((Or) constraint);
        }
        if (constraint instanceof Not) {
            return createQuery((Not) constraint);
        }
        if (constraint instanceof SetCriteria) {
            return createQuery((SetCriteria) constraint);
        }
        if (constraint instanceof PropertyExistence) {
            return createQuery((PropertyExistence) constraint);
        }
        if (constraint instanceof Between) {
            return createQuery((Between) constraint);
        }
        if (constraint instanceof Relike) {
            return createQuery((Relike) constraint);
        }
        if (constraint instanceof Comparison) {
            return createQuery((Comparison) constraint);
        }
        if (constraint instanceof FullTextSearch) {
            return createQuery((FullTextSearch) constraint);
        }
        // Should not get here ...
        throw new LuceneIndexException(
                "Unexpected Constraint instance: class=" + (constraint != null ? constraint.getClass() : "null")
                + " and instance=" + constraint);
    }
185736
private AbstractState createState(CopycatServer.State state) {
    switch (state) {
      case INACTIVE:
        return new InactiveState(this);
      case RESERVE:
        return new ReserveState(this);
      case PASSIVE:
        return new PassiveState(this);
      case FOLLOWER:
        return new FollowerState(this);
      case CANDIDATE:
        return new CandidateState(this);
      case LEADER:
        return new LeaderState(this);
      default:
        throw new AssertionError();
    }
  }
634469
def get_or_create(cls, **kwargs):
        '''
        
        '''
        session = Session()
        instance = session.query(cls).filter_by(**kwargs).first()
        session.close()

        if not instance:
            self = cls(**kwargs)
            self.save()
        else:
            self = instance

        return self
311761
public function newQuery()
    {
        $builder = $this->newElicitBuilder(
            $this->newBaseQueryBuilder()
        );

        // Once we have the query builders, we will set the model instances so the
        // builder can easily access any information it may need from the model
        // while it is constructing and executing various queries against it.
        $builder->setModel($this);

        return $builder;
    }
236217
@PublicEvolving
	public QueryableStateStream<KEY, T> asQueryableState(String queryableStateName) {
		ValueStateDescriptor<T> valueStateDescriptor = new ValueStateDescriptor<T>(
				UUID.randomUUID().toString(),
				getType());

		return asQueryableState(queryableStateName, valueStateDescriptor);
	}
1199970
protected function createQuery()
    {
        if (!$this->queryCreated) {
            $this->setBaseQuery();
            if (!isset($this->showInactiveUsers)) {
                $this->filter('u.uIsActive', 1);
            }
            if (!$this->showInvalidatedUsers) {
                $this->filter('u.uIsValidated', 0, '!=');
            }
            $this->setupAttributeFilters("left join UserSearchIndexAttributes on (UserSearchIndexAttributes.uID = u.uID)");
            $this->queryCreated = 1;
        }
    }
1155437
private void createNewState(AbstractBaseDTNode<I, D> newNode) {
        TTTTransition<I, D> newTreeTrans = newNode.getIncoming().choose();
        assert newTreeTrans != null;

        TTTState<I, D> newState = createState(newTreeTrans);
        link(newNode, newState);
        initializeState(newState);
    }
557516
public Object getStateOrCreate(long txid, StateInitializer init) {
        if(_curr.containsKey(txid)) {
            return _curr.get(txid);
        } else {
            getState(txid, init);
            return null;
        }
    }
266107
def query=(new_query)
      if new_query && !new_query.respond_to?(:to_str)
        raise TypeError, "Can't convert #{new_query.class} into String."
      end
      @query = new_query ? new_query.to_str : nil

      # Reset dependent values
      remove_instance_variable(:@normalized_query) if defined?(@normalized_query)
      remove_composite_values
    end
742085
public static void addSetupQuery(State state, String query) {
    state.setProp(SETUP_QUERIES, state.getProp(SETUP_QUERIES, "") + ";" + query);
  }
694728
private Query createQuery(PriorityQueue<Object[]> q)
   {
      BooleanQuery query = new BooleanQuery();
      Object cur;
      int qterms = 0;
      float bestScore = 0;

      while (((cur = q.pop()) != null))
      {
         Object[] ar = (Object[])cur;
         TermQuery tq = new JcrTermQuery(new Term((String)ar[1], (String)ar[0]));

         if (boost)
         {
            if (qterms == 0)
            {
               bestScore = ((Float)ar[2]).floatValue();
            }
            float myScore = ((Float)ar[2]).floatValue();

            tq.setBoost(myScore / bestScore);
         }

         try
         {
            query.add(tq, BooleanClause.Occur.SHOULD);
         }
         catch (BooleanQuery.TooManyClauses ignore)
         {
            break;
         }

         qterms++;
         if (maxQueryTerms > 0 && qterms >= maxQueryTerms)
         {
            break;
         }
      }

      return query;
   }
905491
@Override
    public final Query createQuery(String query)
    {
        checkClosed();
        checkTransactionNeeded();
        return getPersistenceDelegator().createQuery(query);
    }