text:
Getting Started
===============

**"Hello World" - TFUtils style**

We will take our first steps with TFUtils by training the cononical *MNIST*
network and saving the results to a MongoDB database (The following assumes
you have successfully completed the installation process).

Configuring MongoDB
~~~~~~~~~~~~~~~~~~~

Before we can begin training MNIST, we must locate a running instance of
MongoDB and determine the port it is listening to (by default, MongoDB
is set to listen on port ``27017``).

To verify that an instance of MongoDB is running on your machine, type

.. code-block:: bash

    $ps aux | grep mongod

which should produce an output resembling

.. code-block:: bash

    root      8030  0.3  0.8 13326208376 1165680 ? Sl   Aug07 170:37 /usr/bin/mongod -f /etc/mongod.conf

Look for the lines:

::

    ...
    # network interfaces
    net:
      port: 29101
    ...

in the mongod configuration file (``/etc/mongod.conf`` above) to determine the port,

These tests show basic procedures for training, validating, and extracting features from
models.

Note about MongoDB:

The tests require a MongoDB instance to be available on the port defined by "testport" in
the code below. This db can either be local to where you run these tests (and therefore
on 'localhost' by default) or it can be running somewhere else and then by ssh-tunneled on
the relevant port to the host where you run these tests. [That is, before testing, you'd run

.. code-block:: bash

         ssh -f -N -L  [testport]:localhost:[testport] [username]@mongohost.xx.xx

on the machine where you're running these tests. ``[mongohost]`` is the where the mongodb
instance is running.

Specifying an Experiment
~~~~~~~~~~~~~~~~~~~~~~~~

Now that we have a database ready to store our training results, let's specify
how they will be saved. Critically, any experiment executed by
TFUtils can be uniquely identified by the following 5-tuple:

+--------------+------------------------------------------+
| ``host``     | Hostname where database connection lives |
+--------------+------------------------------------------+
| ``port``     | Port where database connection lives     |
+--------------+------------------------------------------+
| ``dbname``   | Name of database for storage             |
+--------------+------------+-----------------------------+
| ``collname`` | Name of the database collection          |
+--------------+------------+-----------------------------+
| ``exp_id``   | Experiment id descriptor                 |
+--------------+------------------------------------------+

The variables host/port/dbname/coll/exp_id control the location of the saved
data for the run, in order of increasing specificity.

.. note::
  When choosing these, consider that:

        1.  If a given host/port/dbname/coll/exp_id already has saved checkpoints,
            then any new call to start training with these same location variables
            will start to train from the most recent saved checkpoint.  If you mistakenly
            try to start training a new model with different variable names, or structure,
            from that existing checkpoint, an error will be raised, as the model will be
            incompatiable with the saved variables.

        2.  When choosing what dbname, coll, and exp_id, to use, keep in mind that mongodb
            queries only operate over a single collection.  So if you want to analyze
            results from a bunch of experiments together using mongod queries, you should
            put them all in the same collection, but with different exp_ids.  If, on the
            other hand, you never expect to analyze data from two experiments together,
            you can put them in different collections or different databases.  Choosing
            between putting two experiments in two collections in the same database
            or in two totally different databases will depend on how you want to organize
            your results and is really a matter of preference.

With this in mind, let us specify our ``save_params``:

.. code-block:: python

    from tfutils import model, utils
    from tfutils.tests import mnist_data as data

    host = 'localhost'
    port = 27017  # default mongoDB port
    dbname = 'tfutils_database'
    collname = 'into_collection'
    exp_id = 'hello_world_training'

    params = {}
    params['save_params'] = {'host': host,
                             'port': port,
                             'dbname': dbname,
                             'collname': collname,
                             'exp_id': exp_id,
                             'save_valid_freq': 20,
                             'save_filters_freq': 200,
                             'cache_filters_freq': 100,
                             }

Defining a Model
~~~~~~~~~~~~~~~~

.. code-block:: python

    params['model_params'] = {'func': model.mnist_tfutils}

    params['loss_params'] = {'targets': ['labels'],
                             'loss_per_case_func': tf.nn.sparse_softmax_cross_entropy_with_logits,
                             'agg_func': tf.reduce_mean})

    params['optimizer_params'] = {'optimizer_class': tf.train.MomentumOptimizer,
                                  'optimizer_kwargs':{'momentum': 0.9}})

    params['train_params'] = {'data_params': {'func': data.build_data,
                                              'batch_size': 100,
                                              'group': 'train'},
                              'num_steps': 500
                              }
    params['learning_rate_params'] = {'learning_rate': 0.05,
                                      'decay_steps': num_batches_per_epoch,
                                      'decay_rate': 0.95,
                                      'staircase': True}

Including Validation
~~~~~~~~~~~~~~~~~~~~

.. code-block:: python

    params['validation_params'] = {'valid0': {'data_params': {'func': data.build_data,
                                                              'batch_size': 100,
                                                              'group': 'test'},
                                              'num_steps': 10,
                                              'agg_func': utils.mean_dict}}

Train!
~~~~~~

.. code-block:: python

    base.train_from_params(**params)


text:
package org.apache.ignite.jdbc;

import java.sql.ResultSet;
import org.junit.Test;

import static org.apache.ignite.IgniteJdbcDriver.CFG_URL_PREFIX;

/**
 * Test for Jdbc driver query without class on client
 */
public class JdbcPojoQuerySelfTest extends AbstractJdbcPojoQuerySelfTest {
    /** URL. */
    private static final String URL = CFG_URL_PREFIX + "cache=default@modules/clients/src/test/config/jdbc-bin-config.xml";

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testJdbcQueryTask2() throws Exception {
        stmt.execute("select * from JdbcTestObject");

        ResultSet rs = stmt.getResultSet();

        assertResultSet(rs);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testJdbcQueryTask1() throws Exception {
        ResultSet rs = stmt.executeQuery("select * from JdbcTestObject");

        assertResultSet(rs);

    }

    /** {@inheritDoc} */
    @Override protected String getURL() {
        return URL;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ImageBrowser.Data
{
    public interface IDataSource<T> where T : BindableSchemaBase
    {
        Task<IEnumerable<T>> LoadData();

        Task<IEnumerable<T>> Refresh();
    }
}


text:
/

public class TDataSet extends TDBXReader {
	public TDataSet(TParams params, TJSONObject value) {
		super(params, value);
	}

	/**
	 *  Returns a TDataSet created by the information contained in the JSONObject
	 *
	 * @param value a TJSONObject that contains the parameters for create the TDataSet
	 * @return return the TDataSet object created
	 * @throws DBXException
	 */

	public static TDataSet createFrom(TJSONObject value) throws DBXException{
		TParams params = TParams.CreateParametersFromMetadata(value
				.getJSONArray("table"));
		TDataSet dst = new TDataSet(params, value);
		return dst;
	}
}


text:
using System;
using System.Web;
using System.Web.UI;
namespace IPR
{
    public partial class Employee
    {
    }
}


text:
@interface RMStoreKeychainPersistence_Extend : RMStoreKeychainPersistence

- (void)setPurchasedProductOfIdentifier:(NSString *)productIdentifier;

@end

@interface RMStore (Extend)

@property (nonatomic, strong) RMStoreKeychainPersistence_Extend *transactionPersistorKeychain;

+ (void)removeTransactions;

+ (BOOL)consumeProductOfIdentifier:(NSString *)productIdentifier;

+ (NSInteger)countProductOfdentifier:(NSString *)productIdentifier;

+ (BOOL)isPurchasedProductOfIdentifier:(NSString *)productIdentifier;

+ (void)setPurchasedProductOfIdentifier:(NSString *)productIdentifier;

+ (NSSet *)purchasedProductIdentifiers;

+ (BOOL)containsProductWithId:(NSString *)productId price:(float *)price localizedPrice:(NSString **)localizedPrice;

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView9"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/soon"
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textSize="36sp"
        android:textStyle="normal|bold" />

    <TextView
        android:id="@+id/textView10"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="200dp"
        android:text="@string/wait"
        android:textAlignment="center"
        android:textSize="20sp" />

    <ImageButton
        android:id="@+id/fb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="15dp"
        android:background="@drawable/fb" />

</LinearLayout>


text:
"""
Type-annotates the private botocore APIs that we're currently relying on.
"""
from typing import Any, Dict, Optional

import botocore.client
import botocore.credentials
import botocore.endpoint
import botocore.hooks
import botocore.model
import botocore.signers

class BotocoreEndpointPrivate(botocore.endpoint.Endpoint):
    _event_emitter: botocore.hooks.HierarchicalEmitter

class BotocoreRequestSignerPrivate(botocore.signers.RequestSigner):
    _credentials: botocore.credentials.Credentials

class BotocoreBaseClientPrivate(botocore.client.BaseClient):
    _endpoint: BotocoreEndpointPrivate
    _request_signer: BotocoreRequestSignerPrivate
    _service_model: botocore.model.ServiceModel

    def _resolve_endpoint_ruleset(
        self,
        operation_model: botocore.model.OperationModel,
        params: Dict[str, Any],
        request_context: Dict[str, Any],
        ignore_signing_region: bool = ...,
    ):
        raise NotImplementedError

    def _convert_to_request_dict(
        self,
        api_params: Dict[str, Any],
        operation_model: botocore.model.OperationModel,
        *,
        endpoint_url: str = ...,  # added in botocore 1.28
        context: Optional[Dict[str, Any]] = ...,
        headers: Optional[Dict[str, Any]] = ...,
        set_user_agent_header: bool = ...,
    ) -> Dict[str, Any]:
        raise NotImplementedError


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Alternaria: an identification manual 572 (2007)

#### Original name
Alternaria solidaccana E.G. Simmons

### Remarks
null


text:
"""RFCN Box Predictor."""
import tensorflow as tf
from object_detection.core import box_predictor
from object_detection.utils import ops

slim = tf.contrib.slim

BOX_ENCODINGS = box_predictor.BOX_ENCODINGS
CLASS_PREDICTIONS_WITH_BACKGROUND = (
    box_predictor.CLASS_PREDICTIONS_WITH_BACKGROUND)
MASK_PREDICTIONS = box_predictor.MASK_PREDICTIONS

class RfcnBoxPredictor(box_predictor.BoxPredictor):
  """RFCN Box Predictor.

  Applies a position sensitive ROI pooling on position sensitive feature maps to
  predict classes and refined locations. See https://arxiv.org/abs/1605.06409
  for details.

  This is used for the second stage of the RFCN meta architecture. Notice that
  locations are *not* shared across classes, thus for each anchor, a separate
  prediction is made for each class.
  """

  def __init__(self,
               is_training,
               num_classes,
               conv_hyperparams_fn,
               num_spatial_bins,
               depth,
               crop_size,
               box_code_size):
    """Constructor.

    Args:
      is_training: Indicates whether the BoxPredictor is in training mode.
      num_classes: number of classes.  Note that num_classes *does not*
        include the background category, so if groundtruth labels take values
        in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the
        assigned classification targets can range from {0,... K}).
      conv_hyperparams_fn: A function to construct tf-slim arg_scope with
        hyperparameters for convolutional layers.
      num_spatial_bins: A list of two integers `[spatial_bins_y,
        spatial_bins_x]`.
      depth: Target depth to reduce the input feature maps to.
      crop_size: A list of two integers `[crop_height, crop_width]`.
      box_code_size: Size of encoding for each box.
    """
    super(RfcnBoxPredictor, self).__init__(is_training, num_classes)
    self._conv_hyperparams_fn = conv_hyperparams_fn
    self._num_spatial_bins = num_spatial_bins
    self._depth = depth
    self._crop_size = crop_size
    self._box_code_size = box_code_size

  @property
  def num_classes(self):
    return self._num_classes

  def _predict(self, image_features, num_predictions_per_location,
               proposal_boxes):
    """Computes encoded object locations and corresponding confidences.

    Args:
      image_features: A list of float tensors of shape [batch_size, height_i,
      width_i, channels_i] containing features for a batch of images.
      num_predictions_per_location: A list of integers representing the number
        of box predictions to be made per spatial location for each feature map.
        Currently, this must be set to [1], or an error will be raised.
      proposal_boxes: A float tensor of shape [batch_size, num_proposals,
        box_code_size].

    Returns:
      box_encodings: A list of float tensors of shape
        [batch_size, num_anchors_i, q, code_size] representing the location of
        the objects, where q is 1 or the number of classes. Each entry in the
        list corresponds to a feature map in the input `image_features` list.
      class_predictions_with_background: A list of float tensors of shape
        [batch_size, num_anchors_i, num_classes + 1] representing the class
        predictions for the proposals. Each entry in the list corresponds to a
        feature map in the input `image_features` list.

    Raises:
      ValueError: if num_predictions_per_location is not 1 or if
        len(image_features) is not 1.
    """
    if (len(num_predictions_per_location) != 1 or
        num_predictions_per_location[0] != 1):
      raise ValueError('Currently RfcnBoxPredictor only supports '
                       'predicting a single box per class per location.')
    if len(image_features) != 1:
      raise ValueError('length of `image_features` must be 1. Found {}'.
                       format(len(image_features)))
    image_feature = image_features[0]
    num_predictions_per_location = num_predictions_per_location[0]
    batch_size = tf.shape(proposal_boxes)[0]
    num_boxes = tf.shape(proposal_boxes)[1]
    net = image_feature
    with slim.arg_scope(self._conv_hyperparams_fn()):
      net = slim.conv2d(net, self._depth, [1, 1], scope='reduce_depth')
      # Location predictions.
      location_feature_map_depth = (self._num_spatial_bins[0] *
                                    self._num_spatial_bins[1] *
                                    self.num_classes *
                                    self._box_code_size)
      location_feature_map = slim.conv2d(net, location_feature_map_depth,
                                         [1, 1], activation_fn=None,
                                         scope='refined_locations')
      box_encodings = ops.batch_position_sensitive_crop_regions(
          location_feature_map,
          boxes=proposal_boxes,
          crop_size=self._crop_size,
          num_spatial_bins=self._num_spatial_bins,
          global_pool=True)
      box_encodings = tf.squeeze(box_encodings, axis=[2, 3])
      box_encodings = tf.reshape(box_encodings,
                                 [batch_size * num_boxes, 1, self.num_classes,
                                  self._box_code_size])

      # Class predictions.
      total_classes = self.num_classes + 1  # Account for background class.
      class_feature_map_depth = (self._num_spatial_bins[0] *
                                 self._num_spatial_bins[1] *
                                 total_classes)
      class_feature_map = slim.conv2d(net, class_feature_map_depth, [1, 1],
                                      activation_fn=None,
                                      scope='class_predictions')
      class_predictions_with_background = (
          ops.batch_position_sensitive_crop_regions(
              class_feature_map,
              boxes=proposal_boxes,
              crop_size=self._crop_size,
              num_spatial_bins=self._num_spatial_bins,
              global_pool=True))
      class_predictions_with_background = tf.squeeze(
          class_predictions_with_background, axis=[2, 3])
      class_predictions_with_background = tf.reshape(
          class_predictions_with_background,
          [batch_size * num_boxes, 1, total_classes])

    return {BOX_ENCODINGS: [box_encodings],
            CLASS_PREDICTIONS_WITH_BACKGROUND:
            [class_predictions_with_background]}


text:
package org.backbone.orm.parser;

import org.backbone.orm.search.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.HashMap;

/**
 * @author bianliang (05/14/2017)
 */
public class SQLParameter<T extends Serializable> extends HashMap implements Serializable {

    private static final Logger LOG = LoggerFactory.getLogger(SQLParameter.class);

    private String selectClause;
    private String tableName;
    private String whereClause;
    private String orderByClause;
    private String limitClause;

    private Class<T> resultType;
    private Query<T> query;

    public SQLParameter(Query<T> query) {
        super();
        this.query = query;
    }

    public String getSQL() {
        StringBuffer sql =  new StringBuffer("select ")
                .append(selectClause)
                .append(" from ")
                .append(tableName)
                .append(whereClause);
        if (orderByClause != null) sql.append(orderByClause);
        if (limitClause != null) sql.append(limitClause);

        LOG.debug("Preparing to execute sql statement is:{}", sql);
        return sql.toString();
    }

    public Class<T> getResultType() {
        return resultType;
    }

    public void setResultType(Class<T> resultType) {
        this.resultType = resultType;
    }

    public Query<T> getQuery() {
        return query;
    }

    public void setQuery(Query<T> query) {
        this.query = query;
    }

    public String getSelectClause() {
        return selectClause;
    }

    public void setSelectClause(String selectClause) {
        this.selectClause = selectClause;
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public String getWhereClause() {
        return whereClause;
    }

    public void setWhereClause(String whereClause) {
        this.whereClause = whereClause;
    }

    public String getOrderByClause() {
        return orderByClause;
    }

    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    public String getLimitClause() {
        return limitClause;
    }

    public void setLimitClause(String limitClause) {
        this.limitClause = limitClause;
    }

    @Override
    public String toString() {
        return "SQLParameter:" + getSQL();
    }
}


text:
import uuid
from datetime import datetime, timedelta

from flask import current_app
from notifications_utils.letter_timings import (
    CANCELLABLE_JOB_LETTER_STATUSES,
    letter_can_be_cancelled,
)
from sqlalchemy import and_, asc, desc, func

from app import db
from app.dao.dao_utils import autocommit
from app.dao.templates_dao import dao_get_template_by_id
from app.models import (
    JOB_STATUS_CANCELLED,
    JOB_STATUS_FINISHED,
    JOB_STATUS_PENDING,
    JOB_STATUS_SCHEDULED,
    LETTER_TYPE,
    NOTIFICATION_CANCELLED,
    NOTIFICATION_CREATED,
    FactNotificationStatus,
    Job,
    Notification,
    ServiceDataRetention,
    Template,
)
from app.utils import midnight_n_days_ago

def dao_get_notification_outcomes_for_job(service_id, job_id):
    notification_statuses = (
        db.session.query(func.count(Notification.status).label("count"), Notification.status)
        .filter(Notification.service_id == service_id, Notification.job_id == job_id)
        .group_by(Notification.status)
        .all()
    )

    if not notification_statuses:
        notification_statuses = (
            db.session.query(
                FactNotificationStatus.notification_count.label("count"),
                FactNotificationStatus.notification_status.label("status"),
            )
            .filter(FactNotificationStatus.service_id == service_id, FactNotificationStatus.job_id == job_id)
            .all()
        )
    return notification_statuses

def dao_get_job_by_service_id_and_job_id(service_id, job_id):
    return Job.query.filter_by(service_id=service_id, id=job_id).one()

def dao_get_jobs_by_service_id(
    service_id,
    *,
    limit_days=None,
    page=1,
    page_size=50,
    statuses=None,
    contact_list_id=None,
):
    query_filter = [
        Job.service_id == service_id,
        Job.original_file_name != current_app.config["TEST_MESSAGE_FILENAME"],
        Job.original_file_name != current_app.config["ONE_OFF_MESSAGE_FILENAME"],
    ]
    if limit_days is not None:
        query_filter.append(Job.created_at >= midnight_n_days_ago(limit_days))
    if statuses is not None and statuses != [""]:
        query_filter.append(Job.job_status.in_(statuses))
    if contact_list_id is not None:
        query_filter.append(Job.contact_list_id == contact_list_id)
    return (
        Job.query.filter(*query_filter)
        .order_by(Job.processing_started.desc(), Job.created_at.desc())
        .paginate(page=page, per_page=page_size)
    )

def dao_get_scheduled_job_stats(
    service_id,
):
    return (
        db.session.query(
            func.count(Job.id),
            func.min(Job.scheduled_for),
        )
        .filter(
            Job.service_id == service_id,
            Job.job_status == JOB_STATUS_SCHEDULED,
        )
        .one()
    )

def dao_get_job_by_id(job_id):
    return Job.query.filter_by(id=job_id).one()

def dao_archive_job(job):
    job.archived = True
    db.session.add(job)
    db.session.commit()

def dao_set_scheduled_jobs_to_pending():
    """
    Sets all past scheduled jobs to pending, and then returns them for further processing.

    this is used in the run_scheduled_jobs task, so we put a FOR UPDATE lock on the job table for the duration of
    the transaction so that if the task is run more than once concurrently, one task will block the other select
    from completing until it commits.
    """
    jobs = (
        Job.query.filter(Job.job_status == JOB_STATUS_SCHEDULED, Job.scheduled_for < datetime.utcnow())
        .order_by(asc(Job.scheduled_for))
        .with_for_update()
        .all()
    )

    for job in jobs:
        job.job_status = JOB_STATUS_PENDING

    db.session.add_all(jobs)
    db.session.commit()

    return jobs

def dao_get_future_scheduled_job_by_id_and_service_id(job_id, service_id):
    return Job.query.filter(
        Job.service_id == service_id,
        Job.id == job_id,
        Job.job_status == JOB_STATUS_SCHEDULED,
        Job.scheduled_for > datetime.utcnow(),
    ).one()

def dao_create_job(job):
    if not job.id:
        job.id = uuid.uuid4()
    db.session.add(job)
    db.session.commit()

def dao_update_job(job):
    db.session.add(job)
    db.session.commit()

def dao_get_jobs_older_than_data_retention(notification_types):
    flexible_data_retention = ServiceDataRetention.query.filter(
        ServiceDataRetention.notification_type.in_(notification_types)
    ).all()
    jobs = []
    today = datetime.utcnow().date()
    for f in flexible_data_retention:
        end_date = today - timedelta(days=f.days_of_retention)

        jobs.extend(
            Job.query.join(Template)
            .filter(
                func.coalesce(Job.scheduled_for, Job.created_at) < end_date,
                Job.archived == False,  # noqa
                Template.template_type == f.notification_type,
                Job.service_id == f.service_id,
            )
            .order_by(desc(Job.created_at))
            .all()
        )

    end_date = today - timedelta(days=7)
    for notification_type in notification_types:
        services_with_data_retention = [
            x.service_id for x in flexible_data_retention if x.notification_type == notification_type
        ]
        jobs.extend(
            Job.query.join(Template)
            .filter(
                func.coalesce(Job.scheduled_for, Job.created_at) < end_date,
                Job.archived == False,  # noqa
                Template.template_type == notification_type,
                Job.service_id.notin_(services_with_data_retention),
            )
            .order_by(desc(Job.created_at))
            .all()
        )

    return jobs

@autocommit
def dao_cancel_letter_job(job):
    number_of_notifications_cancelled = Notification.query.filter(Notification.job_id == job.id).update(
        {"status": NOTIFICATION_CANCELLED, "updated_at": datetime.utcnow(), "billable_units": 0}
    )
    job.job_status = JOB_STATUS_CANCELLED
    dao_update_job(job)
    return number_of_notifications_cancelled

def can_letter_job_be_cancelled(job):
    template = dao_get_template_by_id(job.template_id)
    if template.template_type != LETTER_TYPE:
        return False, "Only letter jobs can be cancelled through this endpoint. This is not a letter job."

    notifications = Notification.query.filter(Notification.job_id == job.id).all()
    count_notifications = len(notifications)
    if job.job_status != JOB_STATUS_FINISHED or count_notifications != job.notification_count:
        return False, "We are still processing these letters, please try again in a minute."
    count_cancellable_notifications = len([n for n in notifications if n.status in CANCELLABLE_JOB_LETTER_STATUSES])
    if count_cancellable_notifications != job.notification_count or not letter_can_be_cancelled(
        NOTIFICATION_CREATED, job.created_at
    ):
        return False, "It's too late to cancel sending, these letters have already been sent."

    return True, None

def find_jobs_with_missing_rows():
    # Jobs can be a maximum of 100,000 rows. It typically takes 10 minutes to create all those notifications.
    # Using 20 minutes as a condition seems reasonable.
    ten_minutes_ago = datetime.utcnow() - timedelta(minutes=20)
    yesterday = datetime.utcnow() - timedelta(days=1)
    jobs_with_rows_missing = (
        db.session.query(Job)
        .filter(
            Job.job_status == JOB_STATUS_FINISHED,
            Job.processing_finished < ten_minutes_ago,
            Job.processing_finished > yesterday,
            Job.id == Notification.job_id,
        )
        .group_by(Job)
        .having(func.count(Notification.id) != Job.notification_count)
    )

    return jobs_with_rows_missing.all()

def find_missing_row_for_job(job_id, job_size):
    expected_row_numbers = db.session.query(func.generate_series(0, job_size - 1).label("row")).subquery()

    query = (
        db.session.query(Notification.job_row_number, expected_row_numbers.c.row.label("missing_row"))
        .outerjoin(
            Notification, and_(expected_row_numbers.c.row == Notification.job_row_number, Notification.job_id == job_id)
        )
        .filter(Notification.job_row_number == None)  # noqa
    )
    return query.all()


text:
#ifndef YASM_LINEMAP_H
#define YASM_LINEMAP_H

/** Create a new line mapping repository.
 * \return New repository.
 */
yasm_linemap *yasm_linemap_create(void);

/** Clean up any memory allocated for a repository.
 * \param linemap       line mapping repository
 */
void yasm_linemap_destroy(yasm_linemap *linemap);

/** Get the current line position in a repository.
 * \param linemap       line mapping repository
 * \return Current virtual line.
 */
unsigned long yasm_linemap_get_current(yasm_linemap *linemap);

/** Get bytecode and source line information, if any, for a virtual line.
 * \param linemap       line mapping repository
 * \param line          virtual line
 * \param bcp           pointer to return bytecode into
 * \param sourcep       pointer to return source code line pointer into
 * \return Zero if source line information available for line, nonzero if not.
 * \note If source line information is not available, bcp and sourcep targets
 * are set to NULL.
 */
int yasm_linemap_get_source(yasm_linemap *linemap, unsigned long line,
                            /*@null@*/ yasm_bytecode **bcp,
                            const char **sourcep);

/** Add bytecode and source line information to the current virtual line.
 * \attention Deletes any existing bytecode and source line information for
 *            the current virtual line.
 * \param linemap       line mapping repository
 * \param bc            bytecode (if any)
 * \param source        source code line
 * \note The source code line pointer is NOT kept, it is strdup'ed.
 */
void yasm_linemap_add_source(yasm_linemap *linemap,
                             /*@null@*/ yasm_bytecode *bc,
                             const char *source);

/** Go to the next line (increments the current virtual line).
 * \param linemap       line mapping repository
 * \return The current (new) virtual line.
 */
unsigned long yasm_linemap_goto_next(yasm_linemap *linemap);

/** Set a new file/line physical association starting point at the current
 * virtual line.  line_inc indicates how much the "real" line is incremented
 * by for each virtual line increment (0 is perfectly legal).
 * \param linemap       line mapping repository
 * \param filename      physical file name (if NULL, not changed)
 * \param file_line     physical line number
 * \param line_inc      line increment
 */
void yasm_linemap_set(yasm_linemap *linemap, /*@null@*/ const char *filename,
                      unsigned long file_line, unsigned long line_inc);

/** Poke a single file/line association, restoring the original physical
 * association starting point.  Caution: increments the current virtual line
 * twice.
 * \param linemap       line mapping repository
 * \param filename      physical file name (if NULL, not changed)
 * \param file_line     physical line number
 * \return The virtual line number of the poked association.
 */
unsigned long yasm_linemap_poke(yasm_linemap *linemap,
                                /*@null@*/ const char *filename,
                                unsigned long file_line);

/** Look up the associated physical file and line for a virtual line.
 * \param linemap       line mapping repository
 * \param line          virtual line
 * \param filename      physical file name (output)
 * \param file_line     physical line number (output)
 */
void yasm_linemap_lookup(yasm_linemap *linemap, unsigned long line,
                         /*@out@*/ const char **filename,
                         /*@out@*/ unsigned long *file_line);

/** Traverses all filenames used in a linemap, calling a function on each
 * filename.
 * \param linemap       line mapping repository
 * \param d             data pointer passed to func on each call
 * \param func          function
 * \return Stops early (and returns func's return value) if func returns a
 *         nonzero value; otherwise 0.
 */
int yasm_linemap_traverse_filenames
    (yasm_linemap *linemap, /*@null@*/ void *d,
     int (*func) (const char *filename, void *d));

#endif


text:
package store

import (
	"context"

	basemetrics "k8s.io/component-base/metrics"

	"k8s.io/kube-state-metrics/v2/pkg/metric"
	generator "k8s.io/kube-state-metrics/v2/pkg/metric_generator"

	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/watch"
	clientset "k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/cache"
)

var (
	descPersistentVolumeClaimAnnotationsName     = "kube_persistentvolumeclaim_annotations"
	descPersistentVolumeClaimAnnotationsHelp     = "Kubernetes annotations converted to Prometheus labels."
	descPersistentVolumeClaimLabelsName          = "kube_persistentvolumeclaim_labels"
	descPersistentVolumeClaimLabelsHelp          = "Kubernetes labels converted to Prometheus labels."
	descPersistentVolumeClaimLabelsDefaultLabels = []string{"namespace", "persistentvolumeclaim"}
)

func persistentVolumeClaimMetricFamilies(allowAnnotationsList, allowLabelsList []string) []generator.FamilyGenerator {
	return []generator.FamilyGenerator{
		*generator.NewFamilyGeneratorWithStability(
			descPersistentVolumeClaimLabelsName,
			descPersistentVolumeClaimLabelsHelp,
			metric.Gauge,
			basemetrics.STABLE,
			"",
			wrapPersistentVolumeClaimFunc(func(p *v1.PersistentVolumeClaim) *metric.Family {
				labelKeys, labelValues := createPrometheusLabelKeysValues("label", p.Labels, allowLabelsList)
				return &metric.Family{
					Metrics: []*metric.Metric{
						{
							LabelKeys:   labelKeys,
							LabelValues: labelValues,
							Value:       1,
						},
					},
				}
			}),
		),
		*generator.NewFamilyGenerator(
			descPersistentVolumeClaimAnnotationsName,
			descPersistentVolumeClaimAnnotationsHelp,
			metric.Gauge,
			"",
			wrapPersistentVolumeClaimFunc(func(p *v1.PersistentVolumeClaim) *metric.Family {
				annotationKeys, annotationValues := createPrometheusLabelKeysValues("annotation", p.Annotations, allowAnnotationsList)
				return &metric.Family{
					Metrics: []*metric.Metric{
						{
							LabelKeys:   annotationKeys,
							LabelValues: annotationValues,
							Value:       1,
						},
					},
				}
			}),
		),
		*generator.NewFamilyGeneratorWithStability(
			"kube_persistentvolumeclaim_info",
			"Information about persistent volume claim.",
			metric.Gauge,
			basemetrics.STABLE,
			"",
			wrapPersistentVolumeClaimFunc(func(p *v1.PersistentVolumeClaim) *metric.Family {
				storageClassName := getPersistentVolumeClaimClass(p)
				volumeName := p.Spec.VolumeName
				return &metric.Family{
					Metrics: []*metric.Metric{
						{
							LabelKeys:   []string{"storageclass", "volumename"},
							LabelValues: []string{storageClassName, volumeName},
							Value:       1,
						},
					},
				}
			}),
		),
		*generator.NewFamilyGeneratorWithStability(
			"kube_persistentvolumeclaim_status_phase",
			"The phase the persistent volume claim is currently in.",
			metric.Gauge,
			basemetrics.STABLE,
			"",
			wrapPersistentVolumeClaimFunc(func(p *v1.PersistentVolumeClaim) *metric.Family {
				phase := p.Status.Phase

				if phase == "" {
					return &metric.Family{
						Metrics: []*metric.Metric{},
					}
				}

				// Set current phase to 1, others to 0 if it is set.
				ms := []*metric.Metric{
					{
						LabelValues: []string{string(v1.ClaimLost)},
						Value:       boolFloat64(phase == v1.ClaimLost),
					},
					{
						LabelValues: []string{string(v1.ClaimBound)},
						Value:       boolFloat64(phase == v1.ClaimBound),
					},
					{
						LabelValues: []string{string(v1.ClaimPending)},
						Value:       boolFloat64(phase == v1.ClaimPending),
					},
				}

				for _, m := range ms {
					m.LabelKeys = []string{"phase"}
				}

				return &metric.Family{
					Metrics: ms,
				}
			}),
		),
		*generator.NewFamilyGeneratorWithStability(
			"kube_persistentvolumeclaim_resource_requests_storage_bytes",
			"The capacity of storage requested by the persistent volume claim.",
			metric.Gauge,
			basemetrics.STABLE,
			"",
			wrapPersistentVolumeClaimFunc(func(p *v1.PersistentVolumeClaim) *metric.Family {
				ms := []*metric.Metric{}

				if storage, ok := p.Spec.Resources.Requests[v1.ResourceStorage]; ok {
					ms = append(ms, &metric.Metric{
						Value: float64(storage.Value()),
					})
				}

				return &metric.Family{
					Metrics: ms,
				}
			}),
		),
		*generator.NewFamilyGeneratorWithStability(
			"kube_persistentvolumeclaim_access_mode",
			"The access mode(s) specified by the persistent volume claim.",
			metric.Gauge,
			basemetrics.STABLE,
			"",
			wrapPersistentVolumeClaimFunc(func(p *v1.PersistentVolumeClaim) *metric.Family {
				ms := make([]*metric.Metric, len(p.Spec.AccessModes))

				for i, mode := range p.Spec.AccessModes {
					ms[i] = &metric.Metric{
						LabelKeys:   []string{"access_mode"},
						LabelValues: []string{string(mode)},
						Value:       1,
					}
				}

				return &metric.Family{
					Metrics: ms,
				}
			}),
		),
		*generator.NewFamilyGenerator(
			"kube_persistentvolumeclaim_status_condition",
			"Information about status of different conditions of persistent volume claim.",
			metric.Gauge,
			"",
			wrapPersistentVolumeClaimFunc(func(p *v1.PersistentVolumeClaim) *metric.Family {
				ms := make([]*metric.Metric, len(p.Status.Conditions)*len(conditionStatuses))

				for i, c := range p.Status.Conditions {
					conditionMetrics := addConditionMetrics(c.Status)

					for j, m := range conditionMetrics {
						metric := m

						metric.LabelKeys = []string{"condition", "status"}
						metric.LabelValues = append([]string{string(c.Type)}, metric.LabelValues...)

						ms[i*len(conditionStatuses)+j] = metric
					}
				}

				return &metric.Family{
					Metrics: ms,
				}
			}),
		),
		*generator.NewFamilyGenerator(
			"kube_persistentvolumeclaim_created",
			"Unix creation timestamp",
			metric.Gauge,
			"",
			wrapPersistentVolumeClaimFunc(func(p *v1.PersistentVolumeClaim) *metric.Family {
				ms := []*metric.Metric{}

				if !p.CreationTimestamp.IsZero() {
					ms = append(ms, &metric.Metric{
						LabelKeys:   []string{},
						LabelValues: []string{},
						Value:       float64(p.CreationTimestamp.Unix()),
					})
				}

				return &metric.Family{
					Metrics: ms,
				}
			}),
		),
	}
}

func wrapPersistentVolumeClaimFunc(f func(*v1.PersistentVolumeClaim) *metric.Family) func(interface{}) *metric.Family {
	return func(obj interface{}) *metric.Family {
		persistentVolumeClaim := obj.(*v1.PersistentVolumeClaim)

		metricFamily := f(persistentVolumeClaim)

		for _, m := range metricFamily.Metrics {
			m.LabelKeys, m.LabelValues = mergeKeyValues(descPersistentVolumeClaimLabelsDefaultLabels, []string{persistentVolumeClaim.Namespace, persistentVolumeClaim.Name}, m.LabelKeys, m.LabelValues)
		}

		return metricFamily
	}
}

func createPersistentVolumeClaimListWatch(kubeClient clientset.Interface, ns string, fieldSelector string) cache.ListerWatcher {
	return &cache.ListWatch{
		ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) {
			opts.FieldSelector = fieldSelector
			return kubeClient.CoreV1().PersistentVolumeClaims(ns).List(context.TODO(), opts)
		},
		WatchFunc: func(opts metav1.ListOptions) (watch.Interface, error) {
			opts.FieldSelector = fieldSelector
			return kubeClient.CoreV1().PersistentVolumeClaims(ns).Watch(context.TODO(), opts)
		},
	}
}

// getPersistentVolumeClaimClass returns StorageClassName. If no storage class was
// requested, it returns "".
func getPersistentVolumeClaimClass(claim *v1.PersistentVolumeClaim) string {
	// Use beta annotation first
	if class, found := claim.Annotations[v1.BetaStorageClassAnnotation]; found {
		return class
	}

	if claim.Spec.StorageClassName != nil {
		return *claim.Spec.StorageClassName
	}

	// Special non-empty string to indicate absence of storage class.
	return "<none>"
}


text:
#include "hd/periph.hh"

/*************** Class LightSensor Definition ***************/

periph::LightSensor::LightSensor(uint16_t config_value)
{
    //Initialize I2C communication
    comm::i2c::init();
    //Configure Light Sensor as I2C slave prior to communication
    comm::i2c::setSlave(LIGHT_SENSOR_I2C_ADDR);
    //Sends specified configuration to OPT3001 I2C Interface
    comm::i2c::write16(CONFIG_REG, config_value);
}

uint16_t periph::LightSensor::readRegister(uint8_t regAddr)
{
    //Configure Light Sensor as I2C slave prior to communication
    comm::i2c::setSlave(LIGHT_SENSOR_I2C_ADDR);
    //Gets the content from the specified register (2 bytes)
    return comm::i2c::read16(regAddr);
}

uint64_t periph::LightSensor::read(void)
{
    //Reads the result register raw value
    uint16_t sensorVal = readRegister(RESULT_REG);

    //Lux value exponent corresponds to the 4 MSBs from sensorVal
    uint8_t exponent = (sensorVal >> 12) & 0x0F;
    assert(exponent >= 0 && exponent <= 11);

    //Lux fraction value corresponds to the 12 LSBs from sensorVal
    uint16_t fraction = sensorVal & 0x0FFF;

    uint64_t result;

    /* Decreasing the exponent by 6 allows to approximate the
     * 0.01 factor in the formula LSB_Size = 0.01 * 2^E[3:0].
     * (2^-6 = 0.015625). This allows to approximate the
     * lux reading (lux = LSB_Size * R[11:0]) by only shifting
     * the fraction shiftedExp times.
     */
    int shiftedExp = exponent - 6;

    if (shiftedExp < 0)
    {
        result = fraction >> -shiftedExp;
    }
    else
    {
        result = fraction << shiftedExp;
    }

    return result;
}


text:
""" Unit test file for the InitCommand class.
"""

import os
import sys
import unittest
from io import StringIO

from snapshot_dbg_cli import cli_run
from snapshot_dbg_cli import data_formatter
from snapshot_dbg_cli.cli_services import CliServices
from snapshot_dbg_cli.gcloud_cli_service import GcloudCliService
from snapshot_dbg_cli.firebase_types import DatabaseGetResponse
from snapshot_dbg_cli.firebase_types import DatabaseGetStatus
from snapshot_dbg_cli.firebase_types import DatabaseInstance
from snapshot_dbg_cli.firebase_types import DatabaseCreateResponse
from snapshot_dbg_cli.firebase_types import DatabaseCreateStatus
from snapshot_dbg_cli.firebase_types import FirebaseProject
from snapshot_dbg_cli.firebase_types import FirebaseProjectGetResponse
from snapshot_dbg_cli.firebase_types import FirebaseProjectStatus
from snapshot_dbg_cli.firebase_management_rest_service import FirebaseManagementRestService
from snapshot_dbg_cli.permissions_rest_service import PermissionsRestService
from snapshot_dbg_cli.snapshot_debugger_rtdb_service import SnapshotDebuggerRtdbService
from snapshot_dbg_cli.user_output import UserOutput

from snapshot_dbg_cli.exceptions import SilentlyExitError

from unittest.mock import call
from unittest.mock import MagicMock
from unittest.mock import patch

TEST_PROJECT_ID = 'cli-test-project'

def build_firebase_project(defaut_rtdb_name=None):
  project_data = {'resources': {}}

  if defaut_rtdb_name is not None:
    project_data['resources']['realtimeDatabaseInstance'] = defaut_rtdb_name

  return FirebaseProject(project_data)

def build_database_instance(db_name, db_type):
  return DatabaseInstance({
      'name': f'projects/1111111111/locations/us-central1/instances/{db_name}',
      'project': 'projects/1111111111',
      'databaseUrl': f'https://{db_name}.firebaseio.com',
      'type': db_type,
      'state': 'ACTIVE'
  })

class InitCommandTests(unittest.TestCase):
  """ Contains the unit tests for the GetSnapshot class.
  """

  def setUp(self):
    self.cli_services = MagicMock(spec=CliServices)

    self.data_formatter = data_formatter.DataFormatter()
    self.cli_services.data_formatter = self.data_formatter

    # By wrapping a real UserOutput instance, we can test the method calls etc,
    # and it will still perform the actual stdout/stderr output which we can
    # also check when desired.
    self.user_output_mock = MagicMock(
        wraps=UserOutput(
            is_debug_enabled=False,
            data_formatter=data_formatter.DataFormatter()))
    self.cli_services.user_output = self.user_output_mock

    self.cli_services.project_id = TEST_PROJECT_ID

    self.gcloud_service_mock = MagicMock(spec=GcloudCliService)
    self.cli_services.gcloud_service = self.gcloud_service_mock

    self.permissions_service_mock = MagicMock(spec=PermissionsRestService)
    self.cli_services.permissions_service = self.permissions_service_mock

    self.firebase_management_service_mock = MagicMock(
        spec=FirebaseManagementRestService)
    self.cli_services.firebase_management_service = \
        self.firebase_management_service_mock

    self.rtdb_service_mock = MagicMock(spec=SnapshotDebuggerRtdbService)
    self.cli_services.get_snapshot_debugger_rtdb_service = MagicMock(
        return_value=self.rtdb_service_mock)

    self.cli_services.get_snapshot_debugger_default_database_id = MagicMock(
        return_value=f'{TEST_PROJECT_ID}-cdbg')
    self.cli_services.get_firebase_default_rtdb_id = MagicMock(
        return_value=f'{TEST_PROJECT_ID}-default-rtdb')

    # Install a default happy path set of responses to mimic a project that is
    # already fully configured to minimize duplicating uninteresting parts of
    # the tests. The tests will override these defaults when appropriate.
    self.gcloud_service_mock.is_api_enabled = MagicMock(return_value=True)

    self.firebase_management_service_mock.project_get = MagicMock(
        return_value=FirebaseProjectGetResponse(FirebaseProjectStatus.ENABLED,
                                                build_firebase_project()))

    self.firebase_management_service_mock.rtdb_instance_get = MagicMock(
        return_value=DatabaseGetResponse(
            status=DatabaseGetStatus.EXISTS,
            database_instance=build_database_instance(TEST_PROJECT_ID,
                                                      'USER_DATABASE')))

    self.rtdb_service_mock.get_schema_version = MagicMock(return_value='1')

  def run_cmd(self, testargs, expected_exception=None):
    args = ['cli-test', 'init'] + testargs

    # We patch os.environ as some cli arguments can come from environment
    # variables, and if they happen to be set in the terminal running the tests
    # it will affect things.
    # We patch the sleep to speed the tests up as the init command has a sleep,
    # which slows the tests down.
    with patch.object(sys, 'argv', args), \
         patch.dict(os.environ, {}, clear=True), \
         patch('time.sleep', return_value=None), \
         patch('sys.stdout', new_callable=StringIO) as out, \
         patch('sys.stderr', new_callable=StringIO) as err:
      if expected_exception is not None:
        with self.assertRaises(expected_exception):
          cli_run.run(self.cli_services)
      else:
        cli_run.run(self.cli_services)

    return out, err

  def test_only_default_location_allowed(self):
    testargs = ['--location=us-west1']

    out, err = self.run_cmd(testargs, expected_exception=SilentlyExitError)

    self.assertEqual(
        "ERROR: Currently the only supported location is 'us-central1'\n",
        err.getvalue())
    self.assertEqual('', out.getvalue())

    # Ensure the test had not progressed at all, that check should be done
    # first.
    self.permissions_service_mock.check_required_permissions.assert_not_called()
    self.gcloud_service_mock.is_api_enabled.assert_not_called()
    self.firebase_management_service_mock.project_get.assert_not_called()
    self.firebase_management_service_mock.rtdb_instance_get.assert_not_called()
    self.cli_services.get_snapshot_debugger_rtdb_service.assert_not_called()
    self.rtdb_service_mock.get_schema_version.assert_not_called()

  def test_permissions_check_done_as_expected(self):
    testargs = []

    self.permissions_service_mock.check_required_permissions = MagicMock(
        side_effect=SilentlyExitError())

    self.run_cmd(testargs, expected_exception=SilentlyExitError)

    self.permissions_service_mock.check_required_permissions.assert_called_once(
    )

    # The permissions check should be first, and we put a side effect for it to
    # error out, so none of these methods should have been called.
    self.firebase_management_service_mock.project_get.assert_not_called()
    self.gcloud_service_mock.is_api_enabled.assert_not_called()
    self.firebase_management_service_mock.rtdb_instance_get.assert_not_called()
    self.cli_services.get_snapshot_debugger_rtdb_service.assert_not_called()
    self.rtdb_service_mock.get_schema_version.assert_not_called()

  def test_firebase_management_api_not_enabled(self):
    """Tests the situation where the Firebase Management API is not enabled.

    If this API (firebase.googleapis.com) is not enabled, that means the project
    likely has not been enabled for Firebase. The init command should emit a
    message instructing the user how to enable Firebase on their project while
    also providing the exact link to use.
    """
    testargs = []
    self.gcloud_service_mock.is_api_enabled = MagicMock(return_value=False)

    out, err = self.run_cmd(testargs, expected_exception=SilentlyExitError)

    # Verify the outputted text contains the expected migrate project
    # instructions for enabling a project for Firebase.
    self.permissions_service_mock.check_required_permissions.assert_called_once(
    )
    self.gcloud_service_mock.is_api_enabled.assert_called_once_with(
        'firebase.googleapis.com')
    self.assertIn(
        'Your Google Cloud project must be enabled for Firebase resources',
        err.getvalue())
    self.assertIn('Point your browser to the following URL:', err.getvalue())
    self.assertIn(
        'https://console.firebase.google.com/?dlAction=MigrateCloudProject'
        '&cloudProjectNumber=cli-test-project', err.getvalue())
    self.assertEqual('', out.getvalue())

    # Ensure the command exited before progressing any further
    self.firebase_management_service_mock.rtdb_instance_get.assert_not_called()
    self.cli_services.get_snapshot_debugger_rtdb_service.assert_not_called()
    self.rtdb_service_mock.get_schema_version.assert_not_called()

  def test_project_not_firebase_enabled(self):
    """Tests the situation where the project is not enabled for Firebase.

    This is the situation where the
      - Firebase Management API is enabled (firebase.googleapis.com)
      - The API was used to query the project state.
      - The response indicates the project is not enabled for Firebase

    This is a bit of a corner case situation, since if the Firebase Management
    API is enabled for the project, it would be expected that the project was
    enabled for Firebase.

    In this case the user must enable the project for Firebase, which means they
    need to follow the migration instructions that are emitted when the
    Firebase Management API is found to be disabled. However for the migration
    instructions to work the Firebase Management API must first be disabled.

    Therefore in this case the instructions emitted should be to disable the
    API, and to then rerun the init command, which will detect the API is
    disabled and emit the migration instructions.
    """
    testargs = []
    self.gcloud_service_mock.is_api_enabled = MagicMock(return_value=True)
    self.firebase_management_service_mock.project_get = MagicMock(
        return_value=FirebaseProjectGetResponse(
            status=FirebaseProjectStatus.NOT_ENABLED))

    out, err = self.run_cmd(testargs, expected_exception=SilentlyExitError)

    # Verify the outputted text contains the expected messaging about
    # disabling the API and rerunning the init command.
    # instructions for enabling a project for Firebase.
    self.permissions_service_mock.check_required_permissions.assert_called_once(
    )
    self.gcloud_service_mock.is_api_enabled.assert_called_once_with(
        'firebase.googleapis.com')
    self.firebase_management_service_mock.project_get.assert_called_once()
    self.assertIn('Your project is not yet enabled for Firebase',
                  err.getvalue())
    self.assertIn('Disable the Firebase Management API', err.getvalue())
    self.assertIn(
        'https://console.developers.google.com/apis/'
        'api/firebase.googleapis.com?project=cli-test-project', err.getvalue())
    self.assertIn('Rerun the init command', err.getvalue())
    self.assertEqual('', out.getvalue())

    # Ensure the command exited before progressing any further
    self.cli_services.get_snapshot_debugger_rtdb_service.assert_not_called()
    self.rtdb_service_mock.get_schema_version.assert_not_called()

  def test_rtdb_management_api_gets_enabled_when_not_enabled(self):
    testargs = []

    # Returns True for the first check, firebase.googleapis.com
    # Returns False for the second check, firebasedatabase.googleapis.com
    self.gcloud_service_mock.is_api_enabled = MagicMock(
        side_effect=[True, False])

    self.firebase_management_service_mock.project_get = MagicMock(
        return_value=FirebaseProjectGetResponse(
            status=FirebaseProjectStatus.ENABLED))

    self.run_cmd(testargs)

    self.gcloud_service_mock.is_api_enabled.assert_has_calls([
        call('firebase.googleapis.com'),
        call('firebasedatabase.googleapis.com')
    ])
    self.gcloud_service_mock.enable_api.assert_called_once_with(
        'firebasedatabase.googleapis.com')

  def test_rtdb_management_api_does_not_get_enabled_when_already_enabled(self):
    testargs = []

    self.gcloud_service_mock.is_api_enabled = MagicMock(return_value=True)

    self.run_cmd(testargs)

    self.gcloud_service_mock.is_api_enabled.assert_has_calls([
        call('firebase.googleapis.com'),
        call('firebasedatabase.googleapis.com')
    ])
    self.gcloud_service_mock.enable_api.assert_not_called()

  def test_use_rtdb_database_and_id_mutually_exclusive(self):
    testargs = ['--use-default-rtdb', '--database-id=foo']

    out, err = self.run_cmd(testargs, expected_exception=SystemExit)

    self.assertIn(
        'init: error: argument --database-id: not allowed '
        'with argument --use-default-rtdb', err.getvalue())
    self.assertEqual('', out.getvalue())

  def test_db_created_when_it_doesnt_exist(self):
    # Testdata: (test_name, testargs, db_type, expected_db_name)
    # The db_type doesn't actually enter into this test, but we are setting it
    # nonetheless to the value it would have in practise.
    testcases = [
        ('Default', [], 'USER_DATABASE', 'cli-test-project-cdbg'),
        ('Use Default RTDB', ['--use-default-rtdb'], 'DEFAULT_DATABASE',
         'cli-test-project-default-rtdb'),
        ('Custom', ['--database-id=custom-database-name'], 'USER_DATABASE',
         'custom-database-name'),
    ]

    self.firebase_management_service_mock.rtdb_instance_get = MagicMock(
        return_value=DatabaseGetResponse(
            status=DatabaseGetStatus.DOES_NOT_EXIST))

    for test_name, testargs, db_type, expected_database_name in testcases:
      with self.subTest(test_name):
        self.firebase_management_service_mock.rtdb_instance_get.reset_mock()
        database_instance = build_database_instance(expected_database_name,
                                                    db_type)

        self.firebase_management_service_mock.rtdb_instance_create = MagicMock(
            return_value=DatabaseCreateResponse(
                status=DatabaseCreateStatus.SUCCESS,
                database_instance=database_instance))

        self.run_cmd(testargs)

        service_mock = self.firebase_management_service_mock
        service_mock.rtdb_instance_get.assert_called_once_with(
            expected_database_name)
        service_mock.rtdb_instance_create.assert_called_once_with(
            database_id=expected_database_name, location='us-central1')

  def test_handles_db_create_fails_precondition_as_expected(self):
    # Testdata: (test_name, testargs, db_type, expected_db_name)
    # The db_type doesn't actually enter into this test, but we are setting it
    # nonetheless to the value it would have in practise.
    testcases = [
        ('Default', [], 'cli-test-project-cdbg'),
        ('Use Default RTDB', ['--use-default-rtdb'],
         'cli-test-project-default-rtdb'),
        ('Custom', ['--database-id=custom-database-name'],
         'custom-database-name'),
    ]

    self.firebase_management_service_mock.rtdb_instance_get = MagicMock(
        return_value=DatabaseGetResponse(
            status=DatabaseGetStatus.DOES_NOT_EXIST))

    for test_name, testargs, expected_database_name in testcases:
      with self.subTest(test_name):
        self.firebase_management_service_mock.rtdb_instance_get.reset_mock()

        self.firebase_management_service_mock.rtdb_instance_create = MagicMock(
            return_value=DatabaseCreateResponse(
                status=DatabaseCreateStatus.FAILED_PRECONDITION))

        out, err = self.run_cmd(testargs, expected_exception=SilentlyExitError)

        service_mock = self.firebase_management_service_mock
        service_mock.rtdb_instance_get.assert_called_once_with(
            expected_database_name)
        service_mock.rtdb_instance_create.assert_called_once_with(
            database_id=expected_database_name, location='us-central1')

        project_billing_link = ('https://console.firebase.google.com/project/'
                                'cli-test-project/usage/details')

        self.assertIn(
            (f"Database '{expected_database_name}' could not be created on "
             "project 'cli-test-project'"), err.getvalue())

        self.assertIn(
            f'Please check your billing plan at {project_billing_link}',
            err.getvalue())
        self.assertIn(('Read about the billing plans at '
                       'https://firebase.google.com/pricing'), err.getvalue())
        self.assertIn(f"Visit {project_billing_link} and click 'Modify plan'",
                      err.getvalue())
        self.assertEqual('', out.getvalue())

  def test_db_not_created_when_it_exists(self):
    # Testdata: (test_name, testargs, db_type, expected_db_name)
    # The db_type doesn't actually enter into this test, but we are setting it
    # nonetheless to the value it would have in practise.
    testcases = [
        ('Default', [], 'USER_DATABASE', 'cli-test-project-cdbg'),
        ('Use Default RTDB', ['--use-default-rtdb'], 'DEFAULT_DATABASE',
         'cli-test-project-default-rtdb'),
        ('Custom', ['--database-id=custom-database-name'], 'USER_DATABASE',
         'custom-database-name'),
    ]

    for test_name, testargs, db_type, expected_database_name in testcases:
      with self.subTest(test_name):
        self.firebase_management_service_mock.rtdb_instance_get.reset_mock()
        database_instance = build_database_instance(expected_database_name,
                                                    db_type)

        self.firebase_management_service_mock.rtdb_instance_get = MagicMock(
            return_value=DatabaseGetResponse(
                status=DatabaseGetStatus.EXISTS,
                database_instance=database_instance))

        self.run_cmd(testargs)

        service_mock = self.firebase_management_service_mock
        service_mock.rtdb_instance_get.assert_called_once_with(
            expected_database_name)
        service_mock.rtdb_instance_create.assert_not_called()

  def test_correct_db_url_is_used(self):
    # Testdata: (test_name, testargs, db_type, expected_db_name)
    # The db_type doesn't actually enter into this test, but we are setting it
    # nonetheless to the value it would have in practise.
    testcases = [
        ('Default', [], 'USER_DATABASE', 'cli-test-project-cdbg'),
        ('Use Default RTDB', ['--use-default-rtdb'], 'DEFAULT_DATABASE',
         'cli-test-project-default-rtdb'),
        ('Custom', ['--database-id=custom-database-name'], 'USER_DATABASE',
         'custom-database-name'),
    ]

    for test_name, testargs, db_type, expected_database_name in testcases:
      with self.subTest(test_name):
        self.cli_services.get_snapshot_debugger_rtdb_service.reset_mock()
        database_instance = build_database_instance(expected_database_name,
                                                    db_type)

        self.firebase_management_service_mock.rtdb_instance_get = MagicMock(
            return_value=DatabaseGetResponse(
                status=DatabaseGetStatus.EXISTS,
                database_instance=database_instance))

        expected_url = f'https://{expected_database_name}.firebaseio.com'
        self.assertEqual(expected_url, database_instance.database_url)

        self.run_cmd(testargs)

        get_service_mock = self.cli_services.get_snapshot_debugger_rtdb_service
        get_service_mock.assert_called_once_with(database_url=expected_url)

  def test_db_not_initialized_when_already_initialized(self):
    # By returning a value here, that indicates the database has been
    # initialized
    self.rtdb_service_mock.get_schema_version = MagicMock(return_value='1')

    self.run_cmd(testargs=[])

    self.rtdb_service_mock.set_schema_version.assert_not_called()

  def test_db_initialized_when_not_yet_initialized(self):
    # By returning None here, that indicates the database has not been
    # initialized
    self.rtdb_service_mock.get_schema_version = MagicMock(return_value=None)

    self.run_cmd(testargs=[])

    self.rtdb_service_mock.set_schema_version.assert_called_once_with('1')

  def test_db_info_output_after_successful_run(self):
    database_instance = DatabaseInstance({
        'name': ('projects/1111111111/locations/us-central1/instances'
                 '/cli-test-project-cdbg'),
        'project': 'projects/1111111111',
        'databaseUrl': 'https://cli-test-project-cdbg.firebaseio.com',
        'type': 'USER_DATABASE',
        'state': 'ACTIVE'
    })

    self.firebase_management_service_mock.rtdb_instance_get = MagicMock(
        return_value=DatabaseGetResponse(
            status=DatabaseGetStatus.EXISTS,
            database_instance=database_instance))

    out, err = self.run_cmd(testargs=[])

    self.assertIn("Project 'cli-test-project' is successfully configured",
                  err.getvalue())
    self.assertIn(
        ('name:         projects/1111111111/locations/us-central1/instances/'
         'cli-test-project-cdbg'), err.getvalue())
    self.assertIn('project:      projects/1111111111', err.getvalue())
    self.assertIn('database url: https://cli-test-project-cdbg.firebaseio.com',
                  err.getvalue())
    self.assertIn('type:         USER_DATABASE', err.getvalue())
    self.assertIn('state:        ACTIVE', err.getvalue())
    self.assertEqual('', out.getvalue())


text:
package io.crnk.data.jpa.internal.query.backend.criteria;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.From;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.MapJoin;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection;

import io.crnk.core.engine.internal.utils.PreconditionUtil;
import io.crnk.core.queryspec.Direction;
import io.crnk.core.queryspec.FilterOperator;
import io.crnk.data.jpa.internal.query.JoinRegistry;
import io.crnk.data.jpa.internal.query.MetaComputedAttribute;
import io.crnk.data.jpa.internal.query.QueryUtil;
import io.crnk.data.jpa.internal.query.backend.JpaQueryBackend;
import io.crnk.data.jpa.query.criteria.JpaCriteriaExpressionFactory;
import io.crnk.meta.model.MetaAttribute;
import io.crnk.meta.model.MetaAttributePath;
import io.crnk.meta.model.MetaDataObject;

public class JpaCriteriaQueryBackend<T> implements JpaQueryBackend<From<?, ?>, Order, Predicate, Expression<?>> {

	private final String parentKey;
	protected CriteriaBuilder cb;

	private CriteriaQuery<T> criteriaQuery;

	private JoinRegistry<From<?, ?>, Expression<?>> joinHelper;

	private From<T, T> root;

	private Root<?> parentFrom;

	private JpaCriteriaQueryImpl<T> queryImpl;

	@SuppressWarnings({"unchecked", "rawtypes"})
	public JpaCriteriaQueryBackend(JpaCriteriaQueryImpl<T> query, EntityManager em, Class<T> clazz, MetaDataObject parentMeta,
								   MetaAttribute parentAttr, String parentKey, boolean parentIdSelection) {
		this.queryImpl = query;
		this.parentKey = parentKey;

		cb = em.getCriteriaBuilder();
		criteriaQuery = (CriteriaQuery<T>) cb.createQuery();

		if (parentMeta != null) {
			parentFrom = criteriaQuery.from(parentMeta.getImplementationClass());
			root = parentFrom.join(parentAttr.getName());
			joinHelper = new JoinRegistry<>(this, query);
			joinHelper.putJoin(new MetaAttributePath(), root);

			if (parentIdSelection) {
				Expression<?> parentIdExpr = getParentIdExpression(parentAttr, parentKey);
				criteriaQuery.multiselect((List) Arrays.asList(parentIdExpr, root));
			} else {
				criteriaQuery.select(root);
			}
		} else {
			root = criteriaQuery.from(clazz);
			joinHelper = new JoinRegistry<>(this, query);
			joinHelper.putJoin(new MetaAttributePath(), root);
			criteriaQuery.select(root);
		}
	}

	private Expression<?> getParentIdExpression(MetaAttribute parentAttr, String parentKey) {
		MetaDataObject parentEntity = parentAttr.getParent();
		return parentFrom.get(parentKey);
	}

	@Override
	public Expression<?> getAttribute(MetaAttributePath attrPath) {
		return joinHelper.getEntityAttribute(attrPath);
	}

	@Override
	public Expression<?> getAttribute(MetaAttributePath attrPath, JoinType defaultJoinType) {
		return joinHelper.getEntityAttribute(attrPath, defaultJoinType);
	}

	@Override
	public void addPredicate(Predicate predicate) {
		Predicate restriction = criteriaQuery.getRestriction();
		if (restriction != null) {
			criteriaQuery.where(restriction, predicate);
		} else {
			criteriaQuery.where(predicate);
		}
	}

	@Override
	public From<?, ?> getRoot() {
		return root;
	}

	@Override
	public void setOrder(List<Order> list) {
		criteriaQuery.orderBy(list);
	}

	@Override
	public List<Order> getOrderList() {
		java.util.List<Order> orderedList = criteriaQuery.getOrderList();
		if (orderedList != null) {
			return new ArrayList<>(criteriaQuery.getOrderList());
		} else {
			return new ArrayList<>();
		}
	}

	@Override
	public Order newSort(Expression<?> expr, Direction dir) {
		if (dir == Direction.ASC) {
			return cb.asc(expr);
		} else {
			return cb.desc(expr);
		}
	}

	@Override
	public void distinct() {
		criteriaQuery.distinct(true);
	}

	public CriteriaQuery<T> getCriteriaQuery() {
		return criteriaQuery;
	}

	@Override
	public void addParentPredicate(MetaAttribute primaryKeyAttr) {
		List<?> parentIds = queryImpl.getParentIds();
		Path<Object> parentIdPath = parentFrom.get(parentKey);
		addPredicate(parentIdPath.in(new ArrayList<Object>(parentIds)));
	}

	@Override
	public boolean hasManyRootsFetchesOrJoins() {
		return QueryUtil.hasManyRootsFetchesOrJoins(criteriaQuery);
	}

	@Override
	public void addSelection(Expression<?> expression, String name) {
		Selection<?> selection = criteriaQuery.getSelection();

		List<Selection<?>> newSelection = new ArrayList<>();
		if (selection != null) {
			if (selection.isCompoundSelection()) {
				newSelection.addAll(selection.getCompoundSelectionItems());
			} else {
				newSelection.add(selection);
			}
		}
		newSelection.add(expression);
		criteriaQuery.multiselect(newSelection);
	}

	@Override
	public Expression<?> getExpression(Order order) {
		return order.getExpression();
	}

	@Override
	public boolean containsRelation(Expression<?> expression) {
		return QueryUtil.containsRelation(expression);
	}

	public Predicate ilike(Expression<String> expr, String val) {
		return cb.like(cb.lower(expr), val.toLowerCase());
	}

	private Predicate negateIfNeeded(Predicate p, FilterOperator fc) {
		if (fc.equals(FilterOperator.NEQ)) {
			return cb.not(p);
		}
		return p;
	}

	@Override
	public Predicate buildPredicate(FilterOperator operator, MetaAttributePath attrPath, Object value) {
		Expression<?> attr = getAttribute(attrPath);
		return buildPredicate(operator, attr, value);
	}

	@SuppressWarnings({"rawtypes"})
	public Predicate buildPredicate(FilterOperator operator, Expression<?> expressionObj, Object value) {
		Expression expression = expressionObj;

		expression = handleConversions(expression, operator);

		return handle(expression, operator, value);

	}

	@SuppressWarnings({"rawtypes", "unchecked"})
	private Predicate handle(Expression expression, FilterOperator operator, Object value) {
		if (operator == FilterOperator.EQ || operator == FilterOperator.NEQ) {
			return handleEquals(expression, operator, value);
		}

		if (value instanceof Collection) {
			// map collection to OR statement (expect for EQUALS where a IN is used)
			List<Predicate> pred = new ArrayList();
			for (Object element : (Collection) value) {
				pred.add(handle(expression, operator, element));
			}
			return or(pred);
		}

		if (operator == FilterOperator.LIKE) {
			return ilike(expression, value.toString());
		} else if (operator == FilterOperator.GT) {
			return cb.greaterThan(expression, (Comparable) value);
		} else if (operator == FilterOperator.LT) {
			return cb.lessThan(expression, (Comparable) value);
		} else if (operator == FilterOperator.GE) {
			return cb.greaterThanOrEqualTo(expression, (Comparable) value);
		} else {
			PreconditionUtil.verify(operator == FilterOperator.LE, "unexpected operator %s", operator);
			return cb.lessThanOrEqualTo(expression, (Comparable) value);
		}
	}

	@SuppressWarnings({"rawtypes", "unchecked"})
	private Predicate handleEquals(Expression<?> expression, FilterOperator operator, Object value) {
		if (value instanceof List) {
			Predicate p = expression.in(((List<?>) value).toArray());
			return negateIfNeeded(p, operator);
		} else if (Collection.class.isAssignableFrom(expression.getJavaType())) {
			Predicate p = cb.literal(value).in(expression);
			return negateIfNeeded(p, operator);
		} else if (expression instanceof MapJoin) {
			Predicate p = cb.literal(value).in(((MapJoin) expression).value());
			return negateIfNeeded(p, operator);
		} else if (value == null) {
			return negateIfNeeded(cb.isNull(expression), operator);
		}
		return negateIfNeeded(cb.equal(expression, value), operator);
	}

	private Expression<?> handleConversions(Expression<?> expression, FilterOperator operator) {
		// convert to String for LIKE operators
		if (expression.getJavaType() != String.class && (operator == FilterOperator.LIKE)) {
			return expression.as(String.class);
		} else {
			return expression;
		}
	}

	@Override
	public Predicate and(List<Predicate> predicates) {
		return cb.and(predicates.toArray(new Predicate[predicates.size()]));
	}

	@Override
	public Predicate not(Predicate predicate) {
		return cb.not(predicate);
	}

	@Override
	public Predicate or(List<Predicate> predicates) {
		return cb.or(predicates.toArray(new Predicate[predicates.size()]));
	}

	@Override
	public Expression<?> joinMapValue(Expression<?> currentCriteriaPath, MetaAttribute pathElement, Object key) {
		MapJoin<Object, Object, Object> mapJoin = ((From<?, ?>) currentCriteriaPath).joinMap(pathElement.getName(),
				JoinType.LEFT);
		Predicate mapJoinCondition = cb.equal(mapJoin.key(), key);
		Predicate nullCondition = cb.isNull(mapJoin.key());
		addPredicate(cb.or(mapJoinCondition, nullCondition));
		return mapJoin;
	}

	@Override
	public From joinMapRelation(From currentCriteriaPath, MetaAttribute pathElement, Object key) {
		MapJoin<Object, Object, Object> mapJoin = ((From<?, ?>) currentCriteriaPath).joinMap(pathElement.getName(),
				JoinType.LEFT);
		Predicate mapJoinCondition = cb.equal(mapJoin.key(), key);
		Predicate nullCondition = cb.isNull(mapJoin.key());
		addPredicate(cb.or(mapJoinCondition, nullCondition));
		return mapJoin;
	}

	@Override
	public Class<?> getJavaElementType(Expression<?> currentCriteriaPath) {
		return currentCriteriaPath.getJavaType();
	}

	@Override
	@SuppressWarnings({"rawtypes", "unchecked"})
	public Expression<?> getAttribute(Expression<?> currentCriteriaPath, MetaAttribute pathElement) {
		if (pathElement instanceof MetaComputedAttribute) {
			MetaComputedAttribute projAttr = (MetaComputedAttribute) pathElement;
			JpaCriteriaExpressionFactory expressionFactory = (JpaCriteriaExpressionFactory<?>) queryImpl.getComputedAttrs()
					.get(projAttr);

			From from = (From) currentCriteriaPath;
			return expressionFactory.getExpression(from, getCriteriaQuery());
		} else {
			return ((Path<?>) currentCriteriaPath).get(pathElement.getName());
		}
	}

	@SuppressWarnings({"unchecked", "rawtypes"})
	@Override
	public Expression<?> joinSubType(Expression<?> currentCriteriaPath, Class<?> entityType) {
		return cb.treat((Path) currentCriteriaPath, entityType);
	}

	@SuppressWarnings("unchecked")
	@Override
	public From<?, ?> doJoin(MetaAttribute targetAttr, JoinType joinType, From<?, ?> parent) {
		if (targetAttr instanceof MetaComputedAttribute) {
			MetaComputedAttribute projAttr = (MetaComputedAttribute) targetAttr;
			@SuppressWarnings("rawtypes")
			JpaCriteriaExpressionFactory expressionFactory = (JpaCriteriaExpressionFactory<?>) queryImpl.getComputedAttrs()
					.get(projAttr);

			return (From<?, ?>) expressionFactory.getExpression(parent, getCriteriaQuery());
		} else {
			return parent.join(targetAttr.getName(), joinType);
		}
	}

	public CriteriaBuilder getCriteriaBuilder() {
		return cb;
	}
}


text:
class ChangeEventsDate < ActiveRecord::Migration
  def change
    change_column :events, :date, 'date USING CAST(date AS date)'
  end
end


text:
<!DOCTYPE html>

<title>Eat em Up</title>
<meta charset="utf-8">
<meta name="viewport"
	content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=0">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />

<link rel="stylesheet"
	href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css"></link>

<link rel="stylesheet" href="css/gameStyle.css" type="text/css"></link>
<link rel="stylesheet" href="css/loginStyle.css" type="text/css"></link>
<link rel="stylesheet" href="css/lobbyStyle.css" type="text/css"></link>
<link rel="stylesheet" href="css/selectStyle.css" type="text/css"></link>
<link rel="stylesheet" href="css/statsStyle.css" type="text/css"></link>
<link rel="stylesheet" href="css/generalStyle.css" type="text/css"></link>
<link rel="stylesheet" href="css/sponsorStyle.css" type="text/css"></link>
<link rel="stylesheet" href="css/loginSelectionStyle.css"
	type="text/css"></link>

EatEmUp

				<input id="fbLoginButton" type="image" src="img/fbLogin.png"></input>

				<input id="standardLoginButton" type="image"
					src="img/standardLogin.png"></input>

Sammle Punkte

					Close

Dieser Benutzer ist bereits eingeloggt!

Login

			<form id="loginForm">
				Benutzername: <input type="text"
					name="name" id="usernameField" value="" class="required" /> Passwort: <input type="password"
					name="password" id="passwordField" value="" class="required" />

				<input type="submit" data-theme="a" name="submit" id="loginButton"
					value="Login">
			</form>

					Close

Falsche Logindaten!

					Close

Dieser Benutzer ist bereits eingeloggt!

Auswahl

			Logout

				Willkommen, Stefan!

				Punkte: 0

							Code: XE43TZ

An Spiel
						teilnehmen

Spiel
						mitverfolgen

Highscore

Punkte
						einlösen

					Close

						Gib diesen Code an deine Freunde/Freundinnen weiter, um mehr
						Punkte zu bekommen

Dein Freund/Deine Freundin muss diesen Code bei der
								Registrierung angeben

Du bekommst 50% der Punkte, die deine
								Freunde/Freundinnen gewinnen, auf dein eigenes Konto
								gutgeschrieben

 	  Zurück

Lobby

Spielort: JKU Campus

Verfügbare Spieler:

Drück auf deinen Namen sobald du für das Spiel bereit bist

Das Spiel wird gestartet wenn alle Spieler bereit sind

Team Rot

Team Blau

			Abbrechen

Eat!

Team Rot

 Pkt.

Team Blau

 Pkt.

Gegner:

Berechne schnell das korrekte Ergebnis!

							<fieldset data-role="controlgroup">
								<input type="radio" name="radio-choice-2" id="answer-choice-0"
									value="choice-1" checked="checked" />
								 <input type="radio"
									name="radio-choice-2" id="answer-choice-1" value="choice-2" />

								<input type="radio"
									name="radio-choice-2" id="answer-choice-2" value="choice-3" />

								 <input type="radio"
									name="radio-choice-2" id="answer-choice-3" value="choice-4" />

							</fieldset>

						<input type="button" id="battleSubmitButton" value="Abschicken" />

								4 Sekunden übrig

					<form>

Battle gegen  !

									  Punkte

							<input type="button" data-theme="b" id="battleResultOK" value="OK" />

					</form>

			Abbrechen Wetten

Eat!

14:30

Team Rot

600 Pkt.

Team Blau

700 Pkt.

					Close
					<form>

								Verfügbare Punkte: 0

							<input type="radio" name="radio-choice-2" id="betTeamRed"
								value="choice-1" checked="checked" /> Sieg
								Team Rot <input type="radio" name="radio-choice-2"
								id="betTeamBlue" value="choice-1" checked="checked" /> Sieg Team Blau Einsatz:
							<input type="range" name="slider-1" id="slider-1" value="50"
								min="0" max="500" />

Quote: 1.50 : 1

							<button type="submit" data-theme="b" data-icon="check">Wette
								platzieren</button>

					</form>

Spielende

			Fertig

Team  hat gewonnen!

					Team Rot

					Team Blau

Einlösen

				Verfügbare Punkte: 0

Amazon Gutschein 5€

						Für 5000 Punkte

2x MTV EMA Tickets

						Für 50000 Punkte

Highscore

SpielerInnen Highscore

Top:


text:
/*
Swapping Counters
Problem 321

A horizontal row comprising of 2n + 1 squares has n red counters placed at one end and n blue counters at the other end, being separated by a single empty square in the centre. For example, when n = 3.

A counter can move from one square to the next (slide) or can jump over another counter (hop) as long as the square next to that counter is unoccupied.

Let M(n) represent the minimum number of moves/actions to completely reverse the positions of the coloured counters; that is, move all the red counters to the right and all the blue counters to the left.
It can be verified M(3) = 15, which also happens to be a triangle number.
If we create a sequence based on the values of n for which M(n) is a triangle number then the first five terms would be:
1, 3, 10, 22, and 63, and their sum would be 99.
Find the sum of the first forty terms of this sequence.
*/


text:
var path = require('path');
var rootPath = path.normalize(__dirname + '/../../');
var properties = require('../lib/envProperties');

module.exports = {
	//db: properties.MONGO_DOMAIN,
    rootPath: rootPath
};

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : properties.mysqlhost,
  user     : properties.mysqluser,
  password : properties.mysqlpassword,
  database : properties.mysqldatabase
  //port     : '/tmp/mysql.sock'
});
connection.connect( function(err) {
	if(err) {
		console.error('error connecting: ' + err.stack);
		return;
	}

	console.log('connected to mysql db as id ' + connection.threadId);
});


text: SELECT ASSERT({in:INTEGER:input} IS NULL);


text:
FOUNDATION_EXPORT double VKFloatingActionTextVersionNumber;
FOUNDATION_EXPORT const unsigned char VKFloatingActionTextVersionString[];


text:
layout: sidebar-right
title: "New coffee shop opens at Ipswich County Library"
date: 2020-02-11
author: hannah-foulstone
category: news
excerpt: "Enjoy a hot drink or a delicious pastry at Ipswich County Library with the opening of a new Coffeelink."
breadcrumb: news
featured-image: /images/featured/featured-coffeelink-launch.jpg
featured-alt: "L-R: Scott Barker, Maria Gasparova and Dilyana Nikolova at the opening of the new Coffeelink café at Ipswich County Library"
---

{% include /c/figure.html alt="S" src="/images/featured/featured-coffeelink-launch.jpg" caption="L-R: Scott Barker, Maria Gasparova and Dilyana Nikolova at the opening of the new Coffeelink café at Ipswich County Library" %}

Library users can now enjoy a hot drink or a delicious pastry while browsing books at [Ipswich County Library](/libraries/ipswich-county-library/) with the opening of a new Coffeelink café.

The coffee shop at the library on Northgate Street is open to the public as of 11 February.

Nikki Hulse, Business Development Manager at Suffolk Libraries said:

"We're very excited to welcome Coffeelink to Ipswich County Library and are proud to be working with such a well-loved and ethical local business. We hope library customers will enjoy this new service and that it'll also bring new people into the library too."

Azzouz El-Mahraoui, Company Director of Coffeelink, said:

"When Suffolk Libraries approached us to talk about a potential partnership, we were both delighted and honoured and we felt a real sense of privilege."

"We are so excited about the launch of our new venture and we are proud to support Suffolk Libraries. This initiative will help bring communities together in a relaxing central hub at the heart of Ipswich Library in Suffolk."

The new coffee shop will be available to customers at the following times:

* Monday to Friday - 9.30am to 4.30pm
* Saturday - 10am to 4pm


text:
title: Lesson 16
layout: post
author: nathan.davies
permalink: /lesson-16/
source-id: 1gEgOruTdec4gWUN6avfP4SECA57wmvBWInijO7a5sYI
published: true
---

14-6-17

Today, we advanced

    Target for this lesson?
    To complete more Codecademy

    Did I reach my target?
     Yes

Lesson Review

How did I learn? What strategies were effective?

    Today, me and my partner found someone who is at a similar level to us so we have now formed a three. We started off the lesson by helping each other get to the same point. This only took five minutes. We then progressed as a three and gave each other small hints just to guide each other in the correct direction. We completed a lot of the work this lesson.

What limited my learning? Which habits do I need to work on?

    The only thing that limited my learning was the five minutes at the start of the lesson that I gave up to help my friend.

What will I change for next time? How will I improve my learning?

    Next time, I will try and make the most of the time I had as I didn't have much time this lesson.


text:
Clears all buffers for this stream and causes any buffered data to be written to the underlying device.

```csharp
public override void Flush()
```

## See Also

* class [WrappingStream](../WrappingStream.md)
* namespace [Faithlife.Utility](../../Faithlife.Utility.md)

<!-- DO NOT EDIT: generated by xmldocmd for Faithlife.Utility.dll -->


text:
cask "caption" do
  version "2.0.1"
  sha256 "bc3c2383ca3be4fb64adc5c8d97af2e372c163272132527db0b4ee5ab6a43605"

  url "https://github.com/gielcobben/caption/releases/download/v#{version}/caption-#{version}-mac.zip",
      verified: "github.com/gielcobben/caption/"
  name "Caption"
  desc "Finds and sets up subtitles automatically"
  homepage "https://getcaption.co/"

  app "Caption.app"
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="lang">fr</string>
    <string name="connection_error">Vérifiez votre connexion internet</string>
    <string name="noborder">Ce pays n\'a pas de frontière</string>
    <string name="borderletter">F</string>
    <string name="regionletter">R</string>
</resources>


text:
<?php

namespace pgb_liv\php_ms\Utility\Digest;

use pgb_liv\php_ms\Core\Protein;

/**
 * Generic interface for all digestion algorithms
 *
 * @author Andrew Collins
 */
interface DigestInterface
{

    /**
     * Digest the protein and produce peptides matching the enzyme rules.
     *
     * @param Protein $protein
     *            Must contain a protein sequence
     * @return array
     */
    public function digest(Protein $protein);

    /**
     * Returns the name of this enzyme
     *
     * @return string
     */
    public function getName();

    /**
     * Set the maximum number of missed cleavages the algorithm should produce.
     * By default no missed cleavages are produced.
     *
     * @param int $maxMissedCleavage
     *            Maximum number of cleavages to account for
     */
    public function setMaxMissedCleavage($maxMissedCleavage);

    /**
     * Gets the maximum missed cleavage count value
     *
     * @return int max missed cleavage count
     */
    public function getMaxMissedCleavage();

    /**
     * Sets whether n-terminal methionine excision should be performed.
     * When enabled any methionine at the n-terminus of a protein will be removed.
     * Both the excised and non-excised peptide will be returned after
     * digestion. Defaults to true.
     *
     * @param bool $isNmeEnabled
     *            Set true to enable n-terminal methionine excision
     */
    public function setNmeEnabled($isNmeEnabled);

    /**
     * Tells whether n-terminal methionine excision will be performed or not.
     *
     * @return boolean true if NME is enabled, else false
     */
    public function isNmeEnabled();
}


text:
// <copyright file="Bug0019.cs" company="Meld contributors">
//  Copyright (c) Meld contributors. All rights reserved.
// </copyright>

namespace Meld.Tests.Bug
{
    using System.Linq;
    using Xunit;

    public class Bug0019
    {
        [Fact]
        public void CanReferenceDuplicateScript()
        {
            // arrange
            Support.Ensure.Loaded(); // NOTE (Cameron): This ensures that the assembly is loaded which affect the script manager (pre bug fix).
            var scriptManager = new ManifestResourceScriptManager();

            // act
            var scripts = scriptManager.GetSqlScripts("Duplicate");

            // assert
            Assert.True(scripts.Count() == 1);
        }
    }
}


text:
package test.enter;
//import my.*;
//;


text:
package org.apache.rya.rdftriplestore.provenance;

import org.apache.log4j.Logger;

/**
 * Provenance collector that logs queries
 */
public class LoggingProvenanceCollector implements ProvenanceCollector {

    private static final Logger log = Logger.getLogger(LoggingProvenanceCollector.class);

	/* (non-Javadoc)
	 * @see org.apache.rya.rdftriplestore.provenance.ProvenanceCollector#recordQuery(java.lang.String)
	 */
	public void recordQuery(String query) {
		log.debug("User entered query: " + query);
	}

}


text:
package org.apache.activeio.xnet;

import edu.emory.mathcs.backport.java.util.concurrent.Executor;

import org.apache.activeio.xnet.hba.IPAddressPermission;
import org.apache.geronimo.gbean.GBeanData;
import org.apache.geronimo.gbean.GBeanInfo;
import org.apache.geronimo.gbean.GBeanInfoBuilder;
import org.apache.geronimo.gbean.GBeanLifecycle;
import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory;
import org.apache.geronimo.kernel.GBeanAlreadyExistsException;
import org.apache.geronimo.kernel.GBeanNotFoundException;
import org.apache.geronimo.kernel.Kernel;
import org.apache.geronimo.kernel.jmx.JMXUtil;

import javax.management.ObjectName;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.net.SocketException;
import java.io.IOException;

public class StandardServiceStackGBean implements GBeanLifecycle {
    private final StandardServiceStack standardServiceStack;

    public StandardServiceStackGBean(String name, int port, String host, IPAddressPermission[] allowHosts, String[] logOnSuccess, String[] logOnFailure, Executor executor, ServerService server) throws UnknownHostException {
        standardServiceStack = new StandardServiceStack(name, port, host, allowHosts, logOnSuccess, logOnFailure, executor, server);
    }

    public String getName() {
        return standardServiceStack.getName();
    }

    public InetAddress getAddress() {
        return standardServiceStack.getAddress();
    }

    public InetSocketAddress getFullAddress() {
        return standardServiceStack.getFullAddress();
    }

    public String getHost() {
        return standardServiceStack.getHost();
    }

    public int getPort() {
        return standardServiceStack.getPort();
    }

    public int getSoTimeout() throws IOException {
        return standardServiceStack.getSoTimeout();
    }

    public void setSoTimeout(int timeout) throws SocketException {
        standardServiceStack.setSoTimeout(timeout);
    }

    public String[] getLogOnSuccess() {
        return standardServiceStack.getLogOnSuccess();
    }

    public String[] getLogOnFailure() {
        return standardServiceStack.getLogOnFailure();
    }

    public IPAddressPermission[] getAllowHosts() {
        return standardServiceStack.getAllowHosts();
    }

    public void setAllowHosts(IPAddressPermission[] allowHosts) {
        standardServiceStack.setAllowHosts(allowHosts);
    }

    public void doStart() throws Exception {
        standardServiceStack.doStart();
    }

    public void doStop() throws Exception {
        standardServiceStack.doStop();
    }

    public void doFail() {
        standardServiceStack.doFail();
    }

    public static final GBeanInfo GBEAN_INFO;

    static {
        GBeanInfoBuilder infoFactory = new GBeanInfoBuilder("ActiveIO Connector", StandardServiceStackGBean.class);

        infoFactory.addAttribute("name", String.class, true);
        infoFactory.addAttribute("port", int.class, true, true);
        infoFactory.addAttribute("soTimeout", int.class, true);
        infoFactory.addAttribute("host", String.class, true, true);
        infoFactory.addAttribute("fullAddress", InetSocketAddress.class, false);
        infoFactory.addAttribute("allowHosts", IPAddressPermission[].class, true);
        infoFactory.addAttribute("logOnSuccess", String[].class, true);
        infoFactory.addAttribute("logOnFailure", String[].class, true);

        infoFactory.addReference("Executor", Executor.class, NameFactory.GERONIMO_SERVICE);
        infoFactory.addReference("Server", ServerService.class, NameFactory.GERONIMO_SERVICE);

        infoFactory.setConstructor(new String[]{
            "name",
            "port",
            "host",
            "allowHosts",
            "logOnSuccess",
            "logOnFailure",
            "Executor",
            "Server"});

        GBEAN_INFO = infoFactory.getBeanInfo();
    }

    public static GBeanInfo getGBeanInfo() {
        return GBEAN_INFO;
    }

    public static ObjectName addGBean(Kernel kernel, String name, int port, String host, InetAddress[] allowHosts, String[] logOnSuccess, String[] logOnFailure, ObjectName executor, ObjectName server) throws GBeanAlreadyExistsException, GBeanNotFoundException {
        ClassLoader classLoader = StandardServiceStack.class.getClassLoader();
        ObjectName SERVICE_NAME = JMXUtil.getObjectName("activeio:type=StandardServiceStack,name=" + name);

        GBeanData gbean = new GBeanData(SERVICE_NAME, StandardServiceStackGBean.GBEAN_INFO);

        gbean.setAttribute("name", name);
        gbean.setAttribute("port", new Integer(port));
        gbean.setAttribute("host", host);
        gbean.setAttribute("allowHosts", allowHosts);
        gbean.setAttribute("logOnSuccess", logOnSuccess);
        gbean.setAttribute("logOnFailure", logOnFailure);

        gbean.setReferencePattern("Executor", executor);
        gbean.setReferencePattern("Server", server);

        kernel.loadGBean(gbean, classLoader);
        kernel.startGBean(SERVICE_NAME);
        return SERVICE_NAME;
    }
}


text:
import tvm.testing
from pytest import ExitCode

def pytest_configure(config):
    print("enabled targets:", "; ".join(map(lambda x: x[0], tvm.testing.enabled_targets())))
    print("pytest marker:", config.option.markexpr)

def pytest_sessionfinish(session, exitstatus):
    # Don't exit with an error if we select a subset of tests that doesn't
    # include anything
    if session.config.option.markexpr != "":
        if exitstatus == ExitCode.NO_TESTS_COLLECTED:
            session.exitstatus = ExitCode.OK


text:
<?php

declare(strict_types=1);

namespace App\Service;

use App\Classes\AcademicYear;

class AcademicYearFactory
{
    public function __construct(protected Config $config)
    {
    }

    public function create(int $year): AcademicYear
    {
        $title = $this->config->get('academic_year_crosses_calendar_year_boundaries') ?
            sprintf("%d - %d", $year, $year + 1) : (string) $year;
        return new AcademicYear($year, $title);
    }
}