text:
package draco18s.decay.instability.symbols;

import net.minecraft.block.Block;

import com.xcompwiz.mystcraft.api.internals.BlockDescriptor;
import com.xcompwiz.mystcraft.api.symbol.IAgeController;
import com.xcompwiz.mystcraft.api.symbol.IAgeSymbol;

import draco18s.decay.instability.effects.EffectWormDecay;

public class SymbolWorm implements IAgeSymbol
{
    //boolean unstable = false;

    @Override
    public float getRarity()
    {
        return 2;
    }

    @Override
    public void registerLogic(IAgeController controller, long seed)
    {
        BlockDescriptor blockDescriptor = BlockDescriptor.popBlockOfType(controller, "STRUCTURE");
        EffectWormDecay feature;

        if (blockDescriptor != null)
        {
            //System.out.println("Worm tube material: " + blockDescriptor.id);
            feature = new EffectWormDecay(-1, blockDescriptor.id, blockDescriptor.metadata);
            double x = (double)blockDescriptor.getInstability(250);
            int inst = (int)(10 + 7.7 * x + 0.026 * x * x + 0.0003 * x * x * x);
            //-20.+8.0x+0.038 x^2+0.0002 x^3
            System.out.println("Worm instability amount: " + inst);
            controller.addInstability(inst);
            //unstable = true;
        }
        else
        {
            feature = new EffectWormDecay(1, Block.cobblestone.blockID, 0);
            controller.addInstability(-70);
        }

        controller.registerInterface(feature);
    }

    @Override
    public int instabilityModifier(int count)
    {
        count--;
        return count * count * 3;
    }

    @Override
    public String identifier()
    {
        return "DecayWorm";
    }

    @Override
    public String displayName()
    {
        return "Worms";
    }

    @Override
    public String[] getDescriptorWords()
    {
        String[] str = {"Chaos", "Motion", "Form", "Flow"};
        return str;
    }
}


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

namespace UserLogs
{
    class UserLogs
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();

            var namesIps = new SortedDictionary<string, Dictionary<string, int>>();

            while (input != "end")
            {
                FillDictionary(input, namesIps);

                input = Console.ReadLine();
            }

            PrintUsersIpsCount(namesIps);

        }

        static void PrintUsersIpsCount(SortedDictionary<string, Dictionary<string, int>> namesIps)
        {
            foreach (var nameIps in namesIps)
            {
                string name = nameIps.Key;
                Dictionary<string, int> ipsCounts = nameIps.Value;

                Console.WriteLine($"{name}:");
                bool isFirstIp = true;
                foreach (var ipCounts in ipsCounts)
                {
                    int eachIpCnt = ipCounts.Value;
                    if (!isFirstIp)
                    {
                        Console.Write(", ");
                    }
                    Console.Write($"{ipCounts.Key} => {eachIpCnt}");
                    isFirstIp = false;
                }
                Console.WriteLine(".");
            }
        }

        static void FillDictionary(string input, SortedDictionary<string, Dictionary<string, int>> namesIps)
        {
            string username = input.Split('=').Last();
            string ipAdress = input.Split('=', ' ').Skip(1).First();

            if (!namesIps.ContainsKey(username))
            {
                namesIps[username] = new Dictionary<string, int>();
            }

            if (!namesIps[username].ContainsKey(ipAdress))
            {
                namesIps[username][ipAdress] = 0;
            }

            namesIps[username][ipAdress]++;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.appleframework.pay.reconciliation.dao;

import com.appleframework.pay.common.core.dao.BaseDao;
import com.appleframework.pay.reconciliation.entity.RpAccountCheckMistake;

/**
 * 对账差错dao接口
 *
 * http://www.appleframework.com
 *
 * @author  Cruise.Xu
 */
public interface RpAccountCheckMistakeDao extends BaseDao<RpAccountCheckMistake> {

}


text:
<?php

namespace IfRPGMaker\PersonnageBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Doctrine\DBAL\DriverManager;

/**
 * PersonnageRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PersonnageRepository extends EntityRepository
{
    public function getConnection()
    {
        return $this->_em->getConnection();
    }

    public function find($id)
    {
        $sql = "SELECT * FROM Personnage WHERE nom = ".$id;

        $query = $this->createQueryBuilder("p")
                ->where("p.nom = :nom")
                ->setParameter("nom", $id)
                ->getQuery();

       $res = $query->getResult();
        if (empty($res))
            $res = NULL;
        else
            $res = $res[0];
        return array("sql" => $sql, "entity"=> $res);
    }

    public function findByTaille($taille)
    {
        $sql = "SELECT * FROM Personnage WHERE taille = " .$taille;

        $query = $this->createQueryBuilder("p")
                ->where("p.taille = :taille")
                ->setParameter("taille", $taille)
                ->getQuery();

        $res = $query->getResult();
        return array("sql" => $sql, "entity"=> $res);
    }

    public function findAll()
    {
        $sql = "SELECT * FROM Personnage";

        $query = $this->createQueryBuilder("p")->getQuery();
        $res = $query->getResult();

        return array("sql" => $sql, "entities" => $res);
    }

    public function insert($entity) {
        $sql = "INSERT INTO Personnage (contenu) VALUES ('".$entity->getContenu()."')";
        $conn = $this->getConnection();

        $conn->insert('Personnage', array('contenu' => $entity->getContenu()));

        return array('sql' => $sql, 'id' => $conn->lastInsertId());
    }

    public function delete($entity) {
        $sql = "DELETE FROM Personnage WHERE id=".$entity->getId();

        $conn = $this->getConnection();
        $conn->delete('Personnage', array('id' => $entity->getId()));

        return $sql;
    }

    public function update($entity) {
        $sql = "UPDATE Personnage SET contenu='".$entity->getContenu()."' WHERE id =".$entity->getId();

        $conn = $this->getConnection();
        $conn->update('Personnage',
                array('contenu' => $entity->getContenu()),
                array('id' => $entity->getId())
                );

        return $sql;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<title>Python: module swf.geom</title>

<big><big>swf.geom</big></big>	index
geom.py

<big>Modules</big>

<tt>      </tt>

math

<big>Classes</big>

<tt>      </tt>

__builtin__.object

Matrix2

Matrix4

Vector2

Vector3

class Matrix2(__builtin__.object)

<tt>   </tt>
<tt>Matrix2
 </tt>

Methods defined here:

__init__(self, a=1.0, b=0.0, c=0.0, d=1.0, tx=0.0, ty=0.0)

append(self, a, b, c, d, tx, ty)

append_matrix(self, m)

multiply_point(self, vec)

prepend(self, a, b, c, d, tx, ty)

prepend_matrix(self, m)

rotate(self, angle)

scale(self, x, y)

translate(self, x, y)

Data descriptors defined here:

__dict__

<tt>dictionary for instance variables (if defined)</tt>

__weakref__

<tt>list of weak references to the object (if defined)</tt>

class Matrix4(__builtin__.object)

<tt>   </tt>
<tt>Matrix4
 </tt>

Methods defined here:

__init__(self, data=None)

clone(self)

det(self)

flatten(self)

identity(self)

lookAt(self, eye, center, up)

multiply(self, a, b)

multiplyScalar(self, s)

multiplyVec3(self, vec)

multiplyVector3(self, vec)

multiplyVector4(self, v)

Class methods defined here:

inverse(cls, m1) from __builtin__.type

rotationMatrix(cls, x, y, z, angle) from __builtin__.type

scaleMatrix(cls, x, y, z) from __builtin__.type

translationMatrix(cls, x, y, z) from __builtin__.type

Data descriptors defined here:

__dict__

<tt>dictionary for instance variables (if defined)</tt>

__weakref__

<tt>list of weak references to the object (if defined)</tt>

class Vector2(__builtin__.object)

<tt>   </tt>
Methods defined here:

__init__(self, x=0.0, y=0.0)

Data descriptors defined here:

__dict__

<tt>dictionary for instance variables (if defined)</tt>

__weakref__

<tt>list of weak references to the object (if defined)</tt>

class Vector3(__builtin__.object)

<tt>   </tt>
Methods defined here:

__init__(self, x=0, y=0, z=0)

addScalar(self, s)

clone(self)

cross(self, v1, v2)

distance(self, v)

distanceSq(self, v)

divScalar(self, s)

dot(self, v)

equals(self, v, e=None)

length(self)

lengthSq(self)

multScalar(self, s)

normalize(self)

set(self, x, y, z)

sub(self, a, b)

subScalar(self, s)

tostring(self)

Data descriptors defined here:

__dict__

<tt>dictionary for instance variables (if defined)</tt>

__weakref__

<tt>list of weak references to the object (if defined)</tt>

<big>Data</big>

<tt>      </tt>
SNAP = 0.001


text:
namespace terminalpp { namespace ui { namespace models {

// ==========================================================================
// SET_FILL
// ==========================================================================
void default_image_model::set_fill(terminalpp::element const &fill)
{
    fill_ = fill;
}

// ==========================================================================
// GET_FILL
// ==========================================================================
terminalpp::element default_image_model::get_fill() const
{
    return fill_;
}

// ==========================================================================
// GET_SIZE
// ==========================================================================
terminalpp::extent default_image_model::get_size() const
{
    return size_;
}

// ==========================================================================
// GET_CONTENT
// ==========================================================================
std::vector<terminalpp::string> const &default_image_model::get_content() const
{
    return content_;
}

// ==========================================================================
// SET_CONTENT
// ==========================================================================
void default_image_model::set_content(
    std::vector<terminalpp::string> const &content)
{
    content_ = content;

    auto longest_line = std::accumulate(
        content.begin(),
        content.end(),
        decltype(content[0].size()){},
        [](auto const &longest, auto const &line)
        {
            return std::max(longest, line.size());
        });

    size_.width  = longest_line;
    size_.height = content.size();
}

}}}


text:
FROM ubuntu:trusty

RUN locale-gen en_US.UTF-8
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8

RUN rm -vf /var/lib/apt/lists/*
RUN apt-get -y update

# system dependencies
RUN apt-get -y install\
        git\
        mysql-server\
        nginx\
        python-software-properties\
        software-properties-common\
        supervisor\
        curl

# for python 3.6
RUN add-apt-repository ppa:fkrull/deadsnakes
RUN apt-get -y update

# python requirement dependencies
RUN apt-get -y install\
        python3.6\
        # dependencies for ansible's dependency module "cryptography"
        build-essential\
        libpython3.6-dev\
        libssl-dev\
        libffi-dev

RUN curl https://bootstrap.pypa.io/get-pip.py | python3.6 -
RUN pip install virtualenv

ENV venvs=/root/.virtualenvs
ENV venv=$venvs/chaos
ENV chaosdir=/root/workspace/Chaos

RUN mkdir -p $chaosdir
RUN mkdir $venvs
RUN virtualenv $venv

ENV PATH="$venv/bin:$PATH"

WORKDIR $chaosdir

COPY requirements.txt .
RUN pip install -r requirements.txt
RUN rm requirements.txt

RUN rm /etc/nginx/sites-enabled/default

EXPOSE 80 8081


text:
require 'spec_helper'

describe Plan do
  #pending "add some examples to (or delete) #{__FILE__}"
  it "is valid with all field" do
    plan = Plan.new(
      area_tags:   ["okinawa"],
      cards:        [ Card.new(title: "test") ],
      description: "desc test",
      thumbnail:   "sumbnail test",
      tags:        ["a","b"],
      title:       "title test"
    )
    expect(plan).to be_valid
  end

  it "is invalid without a title" do
    expect(Plan.new(title: nil)).to have(1).errors_on(:title)
  end
end


text:
package org.multibit.hd.ui.views.wizards.credentials;

import com.google.common.base.Optional;
import com.google.common.eventbus.Subscribe;
import net.miginfocom.swing.MigLayout;
import org.multibit.hd.core.dto.BitcoinNetworkSummary;
import org.multibit.hd.core.dto.CoreMessageKey;
import org.multibit.hd.core.events.BitcoinNetworkChangedEvent;
import org.multibit.hd.core.events.WalletLoadEvent;
import org.multibit.hd.core.managers.WalletManager;
import org.multibit.hd.core.services.CoreServices;
import org.multibit.hd.hardware.core.HardwareWalletService;
import org.multibit.hd.ui.events.view.ViewEvents;
import org.multibit.hd.ui.languages.Languages;
import org.multibit.hd.ui.languages.MessageKey;
import org.multibit.hd.ui.views.components.LabelDecorator;
import org.multibit.hd.ui.views.components.Labels;
import org.multibit.hd.ui.views.components.Panels;
import org.multibit.hd.ui.views.components.panels.PanelDecorator;
import org.multibit.hd.ui.views.fonts.AwesomeIcon;
import org.multibit.hd.ui.views.themes.Themes;
import org.multibit.hd.ui.views.wizards.AbstractWizard;
import org.multibit.hd.ui.views.wizards.AbstractWizardPanelView;
import org.multibit.hd.ui.views.wizards.WizardButton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 *
View to provide the following to UI:

 *

 *
Show result of attempting to load a wallet

 *

 *
 * @since 0.0.1
 */
public class CredentialsLoadWalletReportPanelView extends AbstractWizardPanelView<CredentialsWizardModel, String> {

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

  // The status of whether the wallet loaded ok
  private JLabel walletLoadedStatusLabel;
  private boolean loadedOk = false;

  // The status of whether you are connected to the bitcoin network (i.e. at least one peer)
  private JLabel connectedStatusLabel;

  private boolean connected = false;

  // The status of synchronisation
  private JLabel synchronisationStatusLabel;

  // Alabel indicating that the wallet is ready to use
  private JLabel walletIsReadyToUseStatusLabel;

  private boolean startedSync = false;

  private WalletLoadEvent unprocessedWalletLoadEvent;

  /**
   * @param wizard    The wizard managing the states
   * @param panelName The panel name to filter events from components
   */
  public CredentialsLoadWalletReportPanelView(AbstractWizard<CredentialsWizardModel> wizard, String panelName) {

    super(wizard, panelName, AwesomeIcon.SUN_O, MessageKey.LOAD_WALLET_REPORT_TITLE);

  }

  @Override
  public void newPanelModel() {

    String model = "TODO replace with a proper model";
    setPanelModel(model);

    // No need to bind this to the wizard model
  }

  @Override
  public void initialiseContent(JPanel contentPanel) {

    contentPanel.setLayout(
            new MigLayout(
                    Panels.migXYLayout(),
                    "[][][]", // Column constraints
                    "[20]10[20]10[20]10[20]10" // Row constraints
            ));

    // Apply the theme
    contentPanel.setBackground(Themes.currentTheme.detailPanelBackground());

    // Initialise wallet load status to loading
    walletLoadedStatusLabel = Labels.newCoreStatusLabel(Optional.of(CoreMessageKey.WALLET_LOADING), new Object[0], Optional.<Boolean>absent());
    walletLoadedStatusLabel.setVisible(true);

    // Initialise connected status to invisible
    connectedStatusLabel = Labels.newCoreStatusLabel(Optional.<CoreMessageKey>absent(), new Object[0], Optional.<Boolean>absent());
    connectedStatusLabel.setVisible(false);

    // Initialise synchronisation status to invisible
    synchronisationStatusLabel = Labels.newCoreStatusLabel(Optional.<CoreMessageKey>absent(), new Object[0], Optional.<Boolean>absent());
    synchronisationStatusLabel.setVisible(false);

    // Initialise wallet is ready to use status to invisible
    walletIsReadyToUseStatusLabel = Labels.newCoreStatusLabel(Optional.<CoreMessageKey>absent(), new Object[0], Optional.<Boolean>absent());
    walletIsReadyToUseStatusLabel.setVisible(false);

    contentPanel.add(walletLoadedStatusLabel, "wrap");
    contentPanel.add(connectedStatusLabel, "wrap");
    contentPanel.add(synchronisationStatusLabel, "wrap");
    contentPanel.add(walletIsReadyToUseStatusLabel, "wrap");

  }

  @Override
  protected void initialiseButtons(AbstractWizard<CredentialsWizardModel> wizard) {

    Optional<HardwareWalletService> hardwareWalletService = CoreServices.getCurrentHardwareWalletService();

    if (hardwareWalletService.isPresent() && hardwareWalletService.get().getContext().getFeatures().isPresent()) {
      // The hardware wallet is connected but there may be an issue with the current wallet
      // so we provide a Restore button to allow the user to choose an earlier backup
      PanelDecorator.addExitRestoreFinish(this, wizard);
    } else {
      // There is no hardware wallet or there is a problem with connection
      // so we provide a Previous button to allow the user to return to either
      // the password screen (soft) or the device unlock (hard) to rectify it
      // We also require the Restore button here to force a wallet switch operation
      // which would not occur simply through Previous
      PanelDecorator.addExitRestorePreviousFinish(this, wizard);
    }

    if (getPreviousButton() != null) {
      getPreviousButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
          // Clear any 'password failed' before moving back
          walletLoadedStatusLabel.setText("");
          walletLoadedStatusLabel.setIcon(null);
        }
      });
    }
  }

  @Override
  public void fireInitialStateViewEvents() {
    // Disable the previous button - it is enabled once the wallet fails loads
    ViewEvents.fireWizardButtonEnabledEvent(getPanelName(), WizardButton.PREVIOUS, false);

    // Disable the finish button - it is enabled once the wallet loads
    ViewEvents.fireWizardButtonEnabledEvent(getPanelName(), WizardButton.FINISH, false);
  }

  @Override
  public void updateFromComponentModels(Optional componentModel) {
    // Do nothing - panel model is updated via an action and wizard model is not applicable
  }

  @Override
  public boolean beforeShow() {
    return true;
  }

  @Override
  public void afterShow() {
    SwingUtilities.invokeLater(
            new Runnable() {
              @Override
              public void run() {

                registerDefaultButton(getFinishButton());

                if (unprocessedWalletLoadEvent != null) {
                  onWalletLoadEvent(unprocessedWalletLoadEvent);
                }
              }
            });
  }

  @Subscribe
  public void onWalletLoadEvent(final WalletLoadEvent walletLoadEvent) {
    SwingUtilities.invokeLater(
            new Runnable() {
              @Override
              public void run() {

                log.debug("Saw a wallet load event {}", walletLoadEvent);

                // Ensure the wallet balance is propagated out
                if (WalletManager.INSTANCE.getCurrentWalletBalance().isPresent()) {
                  ViewEvents.fireBalanceChangedEvent(
                          WalletManager.INSTANCE.getCurrentWalletBalance().get(),
                          WalletManager.INSTANCE.getCurrentWalletBalanceWithUnconfirmed().get(),
                          null,
                          Optional.<String>absent());
                }

                if (isInitialised()) {
                  unprocessedWalletLoadEvent = null;
                  if (walletLoadEvent.isWalletLoadWasSuccessful() || walletLoadEvent.getBackupLoaded().isPresent()) {
                    // Wallet loaded ok or rolling backup loaded
                    loadedOk = true;

                    if (walletLoadEvent.getBackupLoaded().isPresent()) {
                      // Indicate backup wallet was loaded with a cross
                      LabelDecorator.applyWrappingLabel(walletLoadedStatusLabel, Languages.safeText(CoreMessageKey.BACKUP_WALLET_WAS_LOADED));
                      LabelDecorator.applyStatusLabel(walletLoadedStatusLabel, Optional.of(Boolean.FALSE));
                    } else {
                      LabelDecorator.applyWrappingLabel(walletLoadedStatusLabel, Languages.safeText(CoreMessageKey.WALLET_LOADED_OK));
                      LabelDecorator.applyStatusLabel(walletLoadedStatusLabel, Optional.of(Boolean.TRUE));
                    }

                    // Enable the finish button
                    ViewEvents.fireWizardButtonEnabledEvent(getPanelName(), WizardButton.FINISH, true);

                    // Disable previous button - this is only there to enable bad password recovery
                    ViewEvents.fireWizardButtonEnabledEvent(getPanelName(), WizardButton.PREVIOUS, false);

                    // Indicate connecting
                    if (!connected) {
                      connectedStatusLabel.setVisible(true);
                      LabelDecorator.applyWrappingLabel(connectedStatusLabel, Languages.safeText(CoreMessageKey.CONNECTING_TO_BITCOIN_NETWORK));
                    }

                  } else {
                    // Wallet failed to load
                    if (walletLoadEvent.getWalletLoadMessageKey() != null) {
                      // Specific
                      LabelDecorator.applyWrappingLabel(walletLoadedStatusLabel, Languages.safeText(walletLoadEvent.getWalletLoadMessageKey()));
                    } else {
                      LabelDecorator.applyWrappingLabel(walletLoadedStatusLabel, Languages.safeText(CoreMessageKey.WALLET_FAILED_TO_LOAD));
                    }
                    LabelDecorator.applyStatusLabel(walletLoadedStatusLabel, Optional.of(Boolean.FALSE));

                    // Disable the finish button
                    ViewEvents.fireWizardButtonEnabledEvent(getPanelName(), WizardButton.FINISH, false);

                    // Enable previous button
                    ViewEvents.fireWizardButtonEnabledEvent(getPanelName(), WizardButton.PREVIOUS, true);

                    // Set focus to previous button since it's the most likely action from here
                    getPreviousButton().requestFocusInWindow();

                  }

                } else {
                  unprocessedWalletLoadEvent = walletLoadEvent;
                }
              }
            });
  }

  @Subscribe
  public void onBitcoinChangeEvent(final BitcoinNetworkChangedEvent bitcoinNetworkChangedEvent) {

    if (!isInitialised()) {
      return;
    }
    SwingUtilities.invokeLater(
            new Runnable() {
              @Override
              public void run() {

                // Extremely high volume
                log.trace("Saw a Bitcoin network changed event {}", bitcoinNetworkChangedEvent);
                BitcoinNetworkSummary summary = bitcoinNetworkChangedEvent.getSummary();

                switch (summary.getStatus()) {
                  case NOT_CONNECTED:
                    startedSync = false;
                    break;

                  case CONNECTING:
                    startedSync = false;
                    connectedStatusLabel.setVisible(true);
                    LabelDecorator.applyWrappingLabel(connectedStatusLabel, Languages.safeText(CoreMessageKey.CONNECTING_TO_BITCOIN_NETWORK));
                    break;

                  case CONNECTED:
                    connectedStatusLabel.setVisible(true);
                    LabelDecorator.applyWrappingLabel(connectedStatusLabel, Languages.safeText(CoreMessageKey.CONNECTED_TO_BITCOIN_NETWORK));
                    LabelDecorator.applyStatusLabel(connectedStatusLabel, Optional.of(Boolean.TRUE));

                    if (!startedSync) {
                      synchronisationStatusLabel.setVisible(true);
                      LabelDecorator.applyWrappingLabel(synchronisationStatusLabel, Languages.safeText(CoreMessageKey.PREPARING_TO_SYNCHRONISE));
                    }
                    break;

                  case DOWNLOADING_BLOCKCHAIN:
                    startedSync = true;
                    synchronisationStatusLabel.setVisible(true);
                    LabelDecorator.applyWrappingLabel(synchronisationStatusLabel, Languages.safeText(CoreMessageKey.SYNCHRONISING));
                    break;

                  case SYNCHRONIZED:
                    startedSync = true;
                    synchronisationStatusLabel.setVisible(true);
                    LabelDecorator.applyWrappingLabel(synchronisationStatusLabel, Languages.safeText(CoreMessageKey.SYNCHRONISED));
                    LabelDecorator.applyStatusLabel(synchronisationStatusLabel, Optional.of(Boolean.TRUE));

                    if (loadedOk) {
                      // Wallet is ready to use
                      walletIsReadyToUseStatusLabel.setVisible(true);
                      LabelDecorator.applyWrappingLabel(walletIsReadyToUseStatusLabel, Languages.safeText(CoreMessageKey.WALLET_IS_READY_TO_USE));
                      LabelDecorator.applyStatusLabel(walletIsReadyToUseStatusLabel, Optional.of(Boolean.TRUE));
                    }
                    break;

                  default:

                }

              }
            });
  }
}


text:
package hep.lcio.implementation.event;

import hep.lcio.event.Cluster;
import hep.lcio.event.ParticleID;
import hep.lcio.event.ReconstructedParticle;
import hep.lcio.event.Track;
import hep.lcio.event.Vertex ;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.List;

/**Implementation of ReconstructedParticle
 * @author gaede
 *
 */
public class IReconstructedParticle extends ILCObject implements ReconstructedParticle
{
   protected ParticleID particleIDUsed;
   protected List clusters;
   protected List particleIDs;
   protected List particles;
   protected List tracks;
   protected float[] covMatrix = new float[10];
   protected double[] momentum = new double[3];
   protected float[] referencePoint = new float[3];
   protected float charge;
   protected double energy;
   protected double mass;
   protected float goodnessOfPID;
   protected int type;
   protected Vertex startVertex;

   public float getGoodnessOfPID()
   {
      return goodnessOfPID;
   }

   public void setGoodnessOfPID(float goodnessOfPID)
   {
      checkAccess();
      this.goodnessOfPID = goodnessOfPID;
   }

   public void setCharge(float charge)
   {
      checkAccess();
      this.charge = charge;
   }

   public float getCharge()
   {
      return charge;
   }

   public void setClusters(List clusters)
   {
      checkAccess();
      this.clusters = clusters;
   }

   public List getClusters()
   {
      return clusters == null ? Collections.EMPTY_LIST : clusters;
   }

   public boolean isCompound()
   {
      return particles != null && !particles.isEmpty();
   }

   public void setCovMatrix(float[] cov)
   {
      if (cov.length != 10) throw new IllegalArgumentException();
      checkAccess();
      this.covMatrix = cov;
   }

   public float[] getCovMatrix()
   {
      return covMatrix;
   }

   public void setEnergy(float e)
   {
      checkAccess();
      this.energy = e;
   }

   public double getEnergy()
   {
      return energy;
   }

   public void setMass(float f)
   {
      mass = f;
   }

   public double getMass()
   {
      return mass;
   }

   public void setMomentum(float[] fs)
   {
      if (fs.length != 3) throw new IllegalArgumentException();
      checkAccess();
      setMomentum( momentum[0], momentum[1], momentum[2]) ;
   }
   public void setMomentum(double[] momentum)
   {
      checkAccess();
      if (momentum.length != 3)
         throw new IllegalArgumentException();
      this.momentum = momentum;
   }

   public void setMomentum(double px , double py, double pz){
      this.momentum[0] = px ;
      this.momentum[1] = py ;
      this.momentum[2] = pz ;
   }

   public double[] getMomentum()
   {
      return momentum;
   }

   public ParticleID getParticleIDUsed()
   {
      return particleIDUsed;
   }
   public void setParticleIDs(List ids)
   {
      checkAccess();
//      this.particleIDs = ids;
    //fg: add elmenets one by one to sort wrt. likelihood...
      ListIterator iter = ids.listIterator();
      while (iter.hasNext()) {
         ParticleID element = (ParticleID) iter.next();
         addParticleID(element) ;
      }

   }

   public List getParticleIDs()
   {
      return particleIDs == null ? Collections.EMPTY_LIST : particleIDs;
   }
   public void setParticles(List particles)
   {
      checkAccess();
      this.particles = particles;
   }
   public List getParticles()
   {
      return particles == null ? Collections.EMPTY_LIST : particles;
   }

   public void setReferencePoint(float[] fs)
   {
      if (fs.length != 3) throw new IllegalArgumentException();
      checkAccess();
      referencePoint = fs;
   }

   public float[] getReferencePoint()
   {
      return referencePoint;
   }

   public Vertex getStartVertex(){
	   return startVertex;
   }

   public void setStartVertex(Vertex vertex){
	   checkAccess();
	   this.startVertex = vertex;
   }

   public Vertex getEndVertex(){
	   if(getParticles().size() != 0)
		   return ((ReconstructedParticle)getParticles().get(0)).getStartVertex();
	   return null;
   }

   public void setTracks(List tracks)
   {
      checkAccess();
      this.tracks = tracks;
   }
   public List getTracks()
   {
      return tracks == null ? Collections.EMPTY_LIST : tracks;
   }

   public void setType(int type)
   {
      checkAccess();
      this.type = type;
   }

   public int getType()
   {
      return type;
   }

   public void addCluster(Cluster cluster)
   {
      if (clusters == null) clusters = new ArrayList();
      clusters.add(cluster);
   }
   public void addTrack(Track track)
   {
      if (tracks == null) tracks = new ArrayList();
      tracks.add(track);
   }
   public void addParticle(ReconstructedParticle particle)
   {
      if (particles == null) particles = new ArrayList();
      particles.add(particle);
   }

   public void addParticleID(ParticleID pid)
   {
      if (particleIDs ==  null) particleIDs = new ArrayList();

      //fg: insert pid sorted wrt. to likelihood
      ListIterator it = particleIDs.listIterator() ;
      while( it.hasNext() ) {
         ParticleID aPid = (ParticleID) it.next() ;
         if( aPid.getLikelihood() < pid.getLikelihood() ){
            particleIDs.add( it.nextIndex()-1  , pid ) ;
            return ;
         }
      }
      particleIDs.add(pid);
   }

}


text:
<?php

namespace Bolt\Session\Handler;

use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler;

/**
 * {@inheritdoc}
 *
 * Added lazy write support.
 *
 * @author Carson Full <carsonfull@gmail.com>
 */
class MemcachedHandler extends MemcachedSessionHandler implements LazyWriteHandlerInterface
{
    /** @var int Time to live in seconds */
    protected $ttl;
    /** @var string Key prefix for shared environments */
    protected $prefix;

    /**
     * {@inheritdoc}
     */
    public function __construct(\Memcached $memcached, array $options = [])
    {
        parent::__construct($memcached, $options);

        $this->ttl = isset($options['expiretime']) ? (int) $options['expiretime'] : 86400;
        $this->prefix = isset($options['prefix']) ? $options['prefix'] : 'sf2s';
    }

    /**
     * {@inheritdoc}
     */
    public function updateTimestamp($sessionId, $data)
    {
        $this->getMemcached()->touch($this->prefix . $sessionId, time() + $this->ttl);
    }
}


text:
import consts from './consts';
import {
    createElement,
    classNames,
    getParsedDate,
    isSameDate,
    isDateSmaller,
    isDateBigger,
    isDateBetween,
} from './utils';

import './datepickerCell.scss';

export default class DatepickerCell {
    constructor({type, date, dp, opts, body} = {}) {
        this.type = type;
        this.singleType = this.type.slice(0, -1); // days -> day etc.'`
        this.date = date;
        this.dp = dp;
        this.opts = opts;
        this.body = body;
        this.customData = false;

        this.init();
    }

    init() {
        let {range, onRenderCell} = this.opts;

        if (onRenderCell) {
            this.customData = onRenderCell({
                date: this.date,
                cellType: this.singleType,
                datepicker: this.dp,
            });
        }

        this._createElement();
        this._bindDatepickerEvents();
        this._handleInitialFocusStatus();
        if (this.dp.hasSelectedDates) {
            this._handleSelectedStatus();
            if (range) {
                this._handleRangeStatus();
            }
        }
    }

    _bindDatepickerEvents() {
        this.dp.on(consts.eventChangeSelectedDate, this.onChangeSelectedDate);
        this.dp.on(consts.eventChangeFocusDate, this.onChangeFocusDate);
    }

    unbindDatepickerEvents() {
        this.dp.off(consts.eventChangeSelectedDate, this.onChangeSelectedDate);
        this.dp.off(consts.eventChangeFocusDate, this.onChangeFocusDate);
    }

    _createElement() {
        let {year, month, date} = getParsedDate(this.date);
        let extraAttrs = this.customData?.attrs || {};

        this.$cell = createElement({
            className: this._getClassName(),
            attrs: {
                'data-year': year,
                'data-month': month,
                'data-date': date,
                ...extraAttrs,
            }
        });
    }

    _getClassName() {
        let currentDate = new Date();
        let {selectOtherMonths, selectOtherYears} = this.opts;
        let {minDate, maxDate} = this.dp;
        let {day} = getParsedDate(this.date);
        let isOutOfMinMaxRange = this._isOutOfMinMaxRange();
        let disabled = this.customData?.disabled;

        let classNameCommon = classNames(
            'air-datepicker-cell',
            `-${this.singleType}-`, // days -> day etc.'`
            {
                '-current-': isSameDate(currentDate, this.date, this.type),
                '-min-date-': minDate && isSameDate(minDate, this.date, this.type),
                '-max-date-': maxDate && isSameDate(maxDate, this.date, this.type),
            }
        );
        let classNameType = '';

        switch (this.type) {
            case consts.days:
                classNameType = classNames({
                    '-weekend-': this.dp.isWeekend(day),
                    '-other-month-': this.isOtherMonth,
                    '-disabled-': this.isOtherMonth && !selectOtherMonths || isOutOfMinMaxRange || disabled
                });
                break;
            case consts.months:
                classNameType = classNames({
                    '-disabled-': isOutOfMinMaxRange || disabled
                });
                break;
            case consts.years:
                classNameType = classNames({
                    '-other-decade-': this.isOtherDecade,
                    '-disabled-': isOutOfMinMaxRange || (this.isOtherDecade && !selectOtherYears) || disabled
                });
                break;
        }

        return classNames(classNameCommon, classNameType, this.customData?.classes);
    }

    _getHtml() {
        let {year, month, date} = getParsedDate(this.date);
        let {showOtherMonths, showOtherYears} = this.opts;

        if (this.customData?.html) {
            return this.customData.html;
        }

        switch (this.type) {
            case consts.days:
                return !showOtherMonths && this.isOtherMonth ? '' : date;
            case consts.months:
                return this.dp.locale[this.opts.monthsField][month];
            case consts.years:
                return !showOtherYears && this.isOtherDecade ? '' : year;
        }
    }

    _isOutOfMinMaxRange() {
        let {minDate, maxDate} = this.dp;
        let {type, date: cellDate} = this;
        let {month, year, date} = getParsedDate(cellDate);
        let isDay = type === consts.days;
        let isYear = type === consts.years;

        //Since in months cells date is set to the first day of month we should change it value to from min or max dates
        //to be able to mark cell as disabled correctly
        //Same goes to year cells
        let cellMinDate = minDate
            ? new Date(year, isYear ? minDate.getMonth() : month, isDay ? date : minDate.getDate())
            : false;
        let cellMaxDate = maxDate
            ? new Date(year, isYear ? maxDate.getMonth() : month, isDay ? date : maxDate.getDate())
            : false;

        if (minDate && maxDate) {
            return isDateSmaller(cellMinDate, minDate) || isDateBigger(cellMaxDate, maxDate);
        }

        if (minDate) {
            return isDateSmaller(cellMinDate, minDate);
        }

        if (maxDate) {
            return isDateBigger(cellMaxDate, maxDate);
        }
    }

    destroy() {
        this.unbindDatepickerEvents();
    }

    focus = () => {
        this.$cell.classList.add('-focus-');
        this.focused = true;
    }

    removeFocus = () => {
        this.$cell.classList.remove('-focus-');
        this.focused = false;
    }

    select = () => {
        this.$cell.classList.add('-selected-');
        this.selected = true;
    }

    removeSelect = () => {
        this.$cell.classList.remove('-selected-', '-range-from-', '-range-to-');
        this.selected = false;
    }

    _handleRangeStatus() {
        let {rangeDateFrom, rangeDateTo} = this.dp;
        let classes = classNames({
            '-in-range-': rangeDateFrom && rangeDateTo && isDateBetween(this.date, rangeDateFrom, rangeDateTo),
            '-range-from-': rangeDateFrom && isSameDate(this.date, rangeDateFrom, this.type),
            '-range-to-': rangeDateTo && isSameDate(this.date, rangeDateTo, this.type)
        });

        this.$cell.classList.remove('-range-from-', '-range-to-', '-in-range-');

        if (classes) {
            this.$cell.classList.add(...classes.split(' '));
        }
    }

    _handleSelectedStatus() {
        let selected = this.dp._checkIfDateIsSelected(this.date, this.type);
        if (selected) {
            this.select();
        } else if (!selected && this.selected) {
            this.removeSelect();
        }
    }

    _handleInitialFocusStatus() {
        let datesAreSame = isSameDate(this.dp.focusDate, this.date, this.type);

        if (datesAreSame) {
            this.focus();
        }
    }

    get isDisabled() {
        return this.$cell.matches('.-disabled-');
    }

    get isOtherMonth() {
        return this.dp.isOtherMonth(this.date);
    }

    get isOtherDecade() {
        return this.dp.isOtherDecade(this.date);
    }

    onChangeSelectedDate = () => {
        if (this.isDisabled) return;

        this._handleSelectedStatus();
        if (this.opts.range) {
            this._handleRangeStatus();
        }
    }

    onChangeFocusDate = (date) => {
        if (!date) {
            if (this.focused) {
                this.removeFocus();
            }
            return;
        }

        let datesAreSame = isSameDate(date, this.date, this.type);

        if (datesAreSame) {
            this.focus();
        } else if (!datesAreSame && this.focused) {
            this.removeFocus();
        }

        if (this.opts.range) {
            this._handleRangeStatus();
        }
    }

    render = () => {
        this.$cell.innerHTML = this._getHtml();
        this.$cell.adpCell = this;

        return this.$cell;
    }
}


text:
import { RelationConfig } from '../../repo-populator';
import { RelationEmbeddedAbstract } from './embedded-abstract';

export abstract class RelationEmbeddedBelongsToAbstract extends RelationEmbeddedAbstract
{
  async embeddedBelongsTo(config: RelationConfig, docs)
  {
    config = this.normalizeConfig(config);

    // Since this is an embedded relation, we are looking up relations ids using
    // - a simple indexOf() rather than a DB query, cast ids to string to esnure objects
    // - are matched based on value rather than object reference
    const relationIds = this.getRelationIds(config, docs).map(id => String(id));
    const embeddedDocs = this.getEmebedRelations(config.docPathRelated, docs);

    var values = {};
    embeddedDocs.forEach(embeddedDoc => {
      // We must store the id as a primitive so we can use it as a object field name in our lookup values object
      // - complex types can not be used as object field names
      let id = String(embeddedDoc[config.pkey]);
      if (relationIds.indexOf(id) != -1) {
        // Group related docs by parent key
        values[id] = embeddedDoc;
      }
    });

    return this.populateValues(config, docs, values);
  }
}

export default RelationEmbeddedBelongsToAbstract;


text:
package org.apache.coyote.http11.upgrade;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

import org.apache.tomcat.util.net.SocketWrapper;

public class BioServletInputStream extends AbstractServletInputStream {

    private final InputStream inputStream;

    public BioServletInputStream(SocketWrapper<Socket> wrapper)
            throws IOException {
        inputStream = wrapper.getSocket().getInputStream();
    }

    @Override
    protected int doRead(boolean block, byte[] b, int off, int len)
            throws IOException {
        return inputStream.read(b, off, len);
    }

    @Override
    protected boolean doIsReady() {
        // Always returns true for BIO
        return true;
    }

    @Override
    protected void doClose() throws IOException {
        inputStream.close();
    }
}


text:
package tv.avfun.util;

import tv.ac.fun.AcApp;
import android.content.Context;

public class DensityUtil {
    public static int dip2px(Context context, float dipValue) {
        if(AcApp.density == 1f){
            AcApp.density  = context.getResources().getDisplayMetrics().density;
        }
        return (int) (dipValue * AcApp.density + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        if(AcApp.density == 1f){
            AcApp.density  = context.getResources().getDisplayMetrics().density;
        }
        return (int) (pxValue / AcApp.density + 0.5f);
    }

}


text:
package com.layer.atlas;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.layer.atlas.Atlas.Participant;
import com.layer.atlas.Atlas.Tools;
import com.layer.sdk.LayerClient;
import com.layer.sdk.changes.LayerChange;
import com.layer.sdk.changes.LayerChangeEvent;
import com.layer.sdk.exceptions.LayerException;
import com.layer.sdk.listeners.LayerAuthenticationListener;
import com.layer.sdk.listeners.LayerChangeEventListener;
import com.layer.sdk.messaging.Conversation;
import com.layer.sdk.messaging.LayerObject;
import com.layer.sdk.messaging.Message;
import com.layer.sdk.messaging.Message.RecipientStatus;

/**
 * @author Oleg Orlov
 * @since 14 May 2015
 */
public class AtlasConversationsList extends FrameLayout implements LayerChangeEventListener.MainThread {

    private static final String TAG = AtlasConversationsList.class.getSimpleName();
    private static final boolean debug = false;

    private ListView conversationsList;
    private BaseAdapter conversationsAdapter;

    private ArrayList<Conversation> conversations = new ArrayList<Conversation>();

    private LayerClient layerClient;

    private ConversationClickListener clickListener;
    private ConversationLongClickListener longClickListener;

    //styles
    private int titleTextColor;
    private int titleTextStyle;
    private Typeface titleTextTypeface;
    private int titleUnreadTextColor;
    private int titleUnreadTextStyle;
    private Typeface titleUnreadTextTypeface;
    private int subtitleTextColor;
    private int subtitleTextStyle;
    private Typeface subtitleTextTypeface;
    private int subtitleUnreadTextColor;
    private int subtitleUnreadTextStyle;
    private Typeface subtitleUnreadTextTypeface;
    private int cellBackgroundColor;
    private int cellUnreadBackgroundColor;
    private int dateTextColor;
    private int avatarTextColor;
    private int avatarBackgroundColor;

    // date
    private final DateFormat dateFormat;
    private final DateFormat timeFormat;

    public AtlasConversationsList(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        parseStyle(context, attrs, defStyle);
        this.dateFormat = android.text.format.DateFormat.getDateFormat(context);
        this.timeFormat = android.text.format.DateFormat.getTimeFormat(context);
    }

    public AtlasConversationsList(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AtlasConversationsList(Context context) {
        super(context);
        this.dateFormat = android.text.format.DateFormat.getDateFormat(context);
        this.timeFormat = android.text.format.DateFormat.getTimeFormat(context);
    }

    public void init(final LayerClient layerClient, final Atlas.ParticipantProvider participantProvider) {
        if (layerClient == null) throw new IllegalArgumentException("LayerClient cannot be null");
        if (participantProvider == null) throw new IllegalArgumentException("ParticipantProvider cannot be null");
        if (conversationsList != null) throw new IllegalStateException("AtlasConversationList is already initialized!");

        this.layerClient = layerClient;

        // inflate children:
        LayoutInflater.from(getContext()).inflate(R.layout.atlas_conversations_list, this);

        this.conversationsList = (ListView) findViewById(R.id.atlas_conversations_view);
        this.conversationsList.setAdapter(conversationsAdapter = new BaseAdapter() {

            public View getView(int position, View convertView, ViewGroup parent) {
                if (convertView == null) {
                    convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.atlas_view_conversations_list_convert, parent, false);
                }

                Uri convId = conversations.get(position).getId();
                Conversation conv = layerClient.getConversation(convId);

                ArrayList<String> allButMe = new ArrayList<String>(conv.getParticipants());
                allButMe.remove(layerClient.getAuthenticatedUserId());

                TextView textTitle = (TextView) convertView.findViewById(R.id.atlas_conversation_view_convert_participant);
                String conversationTitle = Atlas.getTitle(conv, participantProvider, layerClient.getAuthenticatedUserId());
                textTitle.setText(conversationTitle);

                // avatar icons...
                TextView textInitials = (TextView) convertView.findViewById(R.id.atlas_view_conversations_list_convert_avatar_single_text);
                View avatarSingle = convertView.findViewById(R.id.atlas_view_conversations_list_convert_avatar_single);
                View avatarMulti = convertView.findViewById(R.id.atlas_view_conversations_list_convert_avatar_multi);
                if (allButMe.size() < 2) {
                    String conterpartyUserId = allButMe.get(0);
                    Atlas.Participant participant = participantProvider.getParticipant(conterpartyUserId);
                    textInitials.setText(participant == null ? null : Atlas.getInitials(participant));
                    textInitials.setTextColor(avatarTextColor);
                    ((GradientDrawable) textInitials.getBackground()).setColor(avatarBackgroundColor);
                    avatarSingle.setVisibility(View.VISIBLE);
                    avatarMulti.setVisibility(View.GONE);
                } else {
                    Participant leftParticipant = null;
                    Participant rightParticipant = null;
                    for (Iterator<String> itUserId = allButMe.iterator(); itUserId.hasNext();) {
                        String userId = itUserId.next();
                        Participant p = participantProvider.getParticipant(userId);
                        if (p == null) continue;

                        if (leftParticipant == null) {
                            leftParticipant = p;
                        } else {
                            rightParticipant = p;
                            break;
                        }
                    }

                    TextView textInitialsLeft = (TextView) convertView.findViewById(R.id.atlas_view_conversations_list_convert_avatar_multi_left);
                    textInitialsLeft.setText(leftParticipant == null ? "?" : Atlas.getInitials(leftParticipant));
                    textInitialsLeft.setTextColor(avatarTextColor);
                    ((GradientDrawable) textInitialsLeft.getBackground()).setColor(avatarBackgroundColor);

                    TextView textInitialsRight = (TextView) convertView.findViewById(R.id.atlas_view_conversations_list_convert_avatar_multi_right);
                    textInitialsRight.setText(rightParticipant == null ? "?" : Atlas.getInitials(rightParticipant));
                    textInitialsRight.setTextColor(avatarTextColor);
                    ((GradientDrawable) textInitialsRight.getBackground()).setColor(avatarBackgroundColor);

                    avatarSingle.setVisibility(View.GONE);
                    avatarMulti.setVisibility(View.VISIBLE);
                }

                TextView textLastMessage = (TextView) convertView.findViewById(R.id.atlas_conversation_view_last_message);
                TextView timeView = (TextView) convertView.findViewById(R.id.atlas_conversation_view_convert_time);
                if (conv.getLastMessage() != null ) {
                    Message last = conv.getLastMessage();
                    String lastMessageText = Atlas.Tools.toString(last);

                    textLastMessage.setText(lastMessageText);

                    Date sentAt = last.getSentAt();
                    if (sentAt == null) timeView.setText("...");
                    else                timeView.setText(formatTime(sentAt));

                    String userId = last.getSender().getUserId();                   // could be null for system messages
                    String myId = layerClient.getAuthenticatedUserId();
                    if ((userId != null) && !userId.equals(myId) && last.getRecipientStatus(myId) != RecipientStatus.READ) {
                        textTitle.setTextColor(titleUnreadTextColor);
                        textTitle.setTypeface(titleUnreadTextTypeface, titleUnreadTextStyle);
                        textLastMessage.setTypeface(subtitleUnreadTextTypeface, subtitleUnreadTextStyle);
                        textLastMessage.setTextColor(subtitleUnreadTextColor);
                        convertView.setBackgroundColor(cellUnreadBackgroundColor);
                    } else {
                        textTitle.setTextColor(titleTextColor);
                        textTitle.setTypeface(titleTextTypeface, titleTextStyle);
                        textLastMessage.setTypeface(subtitleTextTypeface, subtitleTextStyle);
                        textLastMessage.setTextColor(subtitleTextColor);
                        convertView.setBackgroundColor(cellBackgroundColor);
                    }
                } else {
                    timeView.setText("...");
                    textLastMessage.setText("");
                    textTitle.setTextColor(titleTextColor);
                    textTitle.setTypeface(titleTextTypeface, titleTextStyle);
                    textLastMessage.setTypeface(subtitleTextTypeface, subtitleTextStyle);
                    textLastMessage.setTextColor(subtitleTextColor);
                    convertView.setBackgroundColor(cellBackgroundColor);
                }
                timeView.setTextColor(dateTextColor);
                return convertView;
            }
            public long getItemId(int position) {
                return position;
            }
            public Object getItem(int position) {
                return conversations.get(position);
            }
            public int getCount() {
                return conversations.size();
            }
        });

        conversationsList.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Conversation conv = conversations.get(position);
                if (clickListener != null) clickListener.onItemClick(conv);
            }
        });
        conversationsList.setOnItemLongClickListener(new OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Conversation conv = conversations.get(position);
                if (longClickListener != null) longClickListener.onItemLongClick(conv);
                return true;
            }
        });

        // clean everything if deathenticated (client will explode on .getConversation())
        // and rebuilt everything back after successful authentication
        layerClient.registerAuthenticationListener(new LayerAuthenticationListener() {
            public void onDeauthenticated(LayerClient client) {
                if (debug) Log.w(TAG, "onDeauthenticated() ");
                updateValues();
            }
            public void onAuthenticated(LayerClient client, String userId) {
                updateValues();
            }
            public void onAuthenticationError(LayerClient client, LayerException exception) {}
            public void onAuthenticationChallenge(LayerClient client, String nonce) {}
        });

        applyStyle();

        updateValues();
    }

    public void updateValues() {
        if (conversationsAdapter == null) {                 // never initialized
            return;
        }

        conversations.clear();                              // always clean, rebuild if authenticated
        conversationsAdapter.notifyDataSetChanged();

        if (layerClient.isAuthenticated()) {

            List<Conversation> convs = layerClient.getConversations();
            if (debug) Log.d(TAG, "updateValues() conv: " + convs.size());
            for (Conversation conv : convs) {
                // no participants means we are removed from conversation (disconnected conversation)
                if (conv.getParticipants().size() == 0) continue;
                // only ourselves in participant list is possible to happen, but there is nothing to do with it
                // behave like conversation is disconnected
                if (conv.getParticipants().size() == 1
                        && conv.getParticipants().contains(layerClient.getAuthenticatedUserId())) continue;

                conversations.add(conv);
            }

            // the bigger .time the highest in the list
            Collections.sort(conversations, new Comparator<Conversation>() {
                public int compare(Conversation lhs, Conversation rhs) {
                    long leftSentAt = 0;
                    Message leftLastMessage = lhs.getLastMessage();
                    if (leftLastMessage != null && leftLastMessage.getSentAt() != null) {
                        leftSentAt = leftLastMessage.getSentAt().getTime();
                    }
                    long rightSentAt = 0;
                    Message rightLastMessage = rhs.getLastMessage();
                    if (rightLastMessage != null && rightLastMessage.getSentAt() != null) {
                        rightSentAt = rightLastMessage.getSentAt().getTime();
                    }
                    long result = rightSentAt - leftSentAt;
                    if (result == 0L) return 0;
                    return result < 0L ? -1 : 1;
                }
            });
        }
    }

    private void parseStyle(Context context, AttributeSet attrs, int defStyle) {
        TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.AtlasConversationList, R.attr.AtlasConversationList, defStyle);
        this.titleTextColor = ta.getColor(R.styleable.AtlasConversationList_cellTitleTextColor, context.getResources().getColor(R.color.atlas_text_black));
        this.titleTextStyle = ta.getInt(R.styleable.AtlasConversationList_cellTitleTextStyle, Typeface.NORMAL);
        String titleTextTypefaceName = ta.getString(R.styleable.AtlasConversationList_cellTitleTextTypeface);
        this.titleTextTypeface  = titleTextTypefaceName != null ? Typeface.create(titleTextTypefaceName, titleTextStyle) : null;

        this.titleUnreadTextColor = ta.getColor(R.styleable.AtlasConversationList_cellTitleUnreadTextColor, context.getResources().getColor(R.color.atlas_text_black));
        this.titleUnreadTextStyle = ta.getInt(R.styleable.AtlasConversationList_cellTitleUnreadTextStyle, Typeface.BOLD);
        String titleUnreadTextTypefaceName = ta.getString(R.styleable.AtlasConversationList_cellTitleUnreadTextTypeface);
        this.titleUnreadTextTypeface  = titleUnreadTextTypefaceName != null ? Typeface.create(titleUnreadTextTypefaceName, titleUnreadTextStyle) : null;

        this.subtitleTextColor = ta.getColor(R.styleable.AtlasConversationList_cellSubtitleTextColor, context.getResources().getColor(R.color.atlas_text_black));
        this.subtitleTextStyle = ta.getInt(R.styleable.AtlasConversationList_cellSubtitleTextStyle, Typeface.NORMAL);
        String subtitleTextTypefaceName = ta.getString(R.styleable.AtlasConversationList_cellSubtitleTextTypeface);
        this.subtitleTextTypeface  = subtitleTextTypefaceName != null ? Typeface.create(subtitleTextTypefaceName, subtitleTextStyle) : null;

        this.subtitleUnreadTextColor = ta.getColor(R.styleable.AtlasConversationList_cellSubtitleUnreadTextColor, context.getResources().getColor(R.color.atlas_text_black));
        this.subtitleUnreadTextStyle = ta.getInt(R.styleable.AtlasConversationList_cellSubtitleUnreadTextStyle, Typeface.NORMAL);
        String subtitleUnreadTextTypefaceName = ta.getString(R.styleable.AtlasConversationList_cellSubtitleUnreadTextTypeface);
        this.subtitleUnreadTextTypeface  = subtitleUnreadTextTypefaceName != null ? Typeface.create(subtitleUnreadTextTypefaceName, subtitleUnreadTextStyle) : null;

        this.cellBackgroundColor = ta.getColor(R.styleable.AtlasConversationList_cellBackgroundColor, Color.TRANSPARENT);
        this.cellUnreadBackgroundColor = ta.getColor(R.styleable.AtlasConversationList_cellUnreadBackgroundColor, Color.TRANSPARENT);
        this.dateTextColor = ta.getColor(R.styleable.AtlasConversationList_dateTextColor, context.getResources().getColor(R.color.atlas_text_black));
        this.avatarTextColor = ta.getColor(R.styleable.AtlasConversationList_avatarTextColor, context.getResources().getColor(R.color.atlas_text_black));
        this.avatarBackgroundColor = ta.getColor(R.styleable.AtlasConversationList_avatarBackgroundColor, context.getResources().getColor(R.color.atlas_shape_avatar_gray));
        ta.recycle();
    }

    private void applyStyle() {
        conversationsAdapter.notifyDataSetChanged();
    }

    public String formatTime(Date sentAt) {
        if (sentAt == null) sentAt = new Date();

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        long todayMidnight = cal.getTimeInMillis();
        long yesterMidnight = todayMidnight - Tools.TIME_HOURS_24;
        long weekAgoMidnight = todayMidnight - Tools.TIME_HOURS_24 * 7;

        String timeText = null;
        if (sentAt.getTime() > todayMidnight) {
            timeText = timeFormat.format(sentAt.getTime());
        } else if (sentAt.getTime() > yesterMidnight) {
            timeText = "Yesterday";
        } else if (sentAt.getTime() > weekAgoMidnight){
            cal.setTime(sentAt);
            timeText = Tools.TIME_WEEKDAYS_NAMES[cal.get(Calendar.DAY_OF_WEEK) - 1];
        } else {
            timeText = dateFormat.format(sentAt);
        }
        return timeText;
    }

    @Override
    public void onEventMainThread(LayerChangeEvent event) {
        for (LayerChange change : event.getChanges()) {
            if (change.getObjectType() == LayerObject.Type.CONVERSATION
                    || change.getObjectType() == LayerObject.Type.MESSAGE) {
                updateValues();
                return;
            }
        }
    }

    public ConversationClickListener getClickListener() {
        return clickListener;
    }

    public void setClickListener(ConversationClickListener clickListener) {
        this.clickListener = clickListener;
    }

    public ConversationLongClickListener getLongClickListener() {
        return longClickListener;
    }

    public void setLongClickListener(ConversationLongClickListener conversationLongClickListener) {
        this.longClickListener = conversationLongClickListener;
    }

    public interface ConversationClickListener {
        void onItemClick(Conversation conversation);
    }

    public interface ConversationLongClickListener {
        void onItemLongClick(Conversation conversation);
    }
}


text:
using namespace crunch3r;

Vector::Vector(std::initializer_list<float> seq){

    values = new float[4];
    size = seq.size() > VECTOR_MAX_SIZE ? VECTOR_MAX_SIZE : (unsigned int)seq.size();

    memset(values, 0, VECTOR_MEMORY);

    int i =0;
    for (float f: seq)
        if (i<VECTOR_MAX_SIZE)
            values[i++] = f;
}

Vector::Vector(const Vector& other) : Vector::Vector(other,other.getDimensions()){
}

Vector::Vector(const Vector& other, unsigned int size){
    assert(VECTOR_MEMORY>=sizeof(float)*size);
    values = new float[4];
    memset(values, 0, VECTOR_MEMORY);
    memcpy(values, other.values, sizeof(float)*size);
    this->size = size;
}

Vector::Vector(float* values, unsigned int size){
    this->values = values;
    this->size = size;
}

bool Vector::operator==(const Vector other) const{
    ///TODO: float comparison
    return memcmp(values, other.values, VECTOR_MEMORY) == 0;
}

bool Vector::operator!=(const Vector other) const {
    ///TODO: float comparison
    return memcmp(values, other.values, VECTOR_MEMORY) != 0;
}

float& Vector::operator[](const unsigned int i){
    assert(i<VECTOR_MAX_SIZE);
    return values[i];
}

float Vector::operator[](const unsigned int i) const{
    assert(i<VECTOR_MAX_SIZE);
    return values[i];
}

#ifdef SSE
__m128 Vector::Load() const{
    return _mm_load_ps(values);
}
void Vector::Store(__m128 m){
    _mm_store_ps(values, m);
}
#endif

std::string& Vector::toString(){
    std::string *s = new std::string("(");

    for (int i=0;i<getDimensions();i++){
        s->append(std::to_string(values[i]));
        if (i == getDimensions() -1)
            s->append(")");
        else
            s->append(",");
    }

    return *s;
}

const Vector Vector::UP = {0,1,0,0};
const Vector Vector::RIGHT = {1,0,0,0};
const Vector Vector::FORWARD = {0,0,1,0};
const Vector Vector::ZERO = {0,0,0,0};
const Vector Vector::ONE = {1,1,1,1};


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.azureadexternalidentities.generated;

import com.azure.core.util.Context;

/** Samples for B2CTenants GetByResourceGroup. */
public final class B2CTenantsGetByResourceGroupSamples {
    /*
     * x-ms-original-file: specification/cpim/resource-manager/Microsoft.AzureActiveDirectory/stable/2021-04-01/examples/getTenant.json
     */
    /**
     * Sample code: Get tenant.
     *
     * @param manager Entry point to ExternalIdentitiesConfigurationManager.
     */
    public static void getTenant(
        com.azure.resourcemanager.azureadexternalidentities.ExternalIdentitiesConfigurationManager manager) {
        manager
            .b2CTenants()
            .getByResourceGroupWithResponse("contosoResourceGroup", "contoso.onmicrosoft.com", Context.NONE);
    }
}


text:
var checksCtrlr = require("bolt-internal-checks");

var express = require('express');

var apiAppUsersCtrlr = require('../controllers/api-app-users');

var router = express.Router();

//returns an array of app-user objects matching the specified criteria
router.get('/', apiAppUsersCtrlr.get);

//adds an app-user association to the database
router.post('/', checksCtrlr.forSystemApp, apiAppUsersCtrlr.post);

//deletes an array of app-user objects matching the specified criteria
router.delete('/', checksCtrlr.forSystemApp, checksCtrlr.forBulkDeleteCriterion, apiAppUsersCtrlr.delete);

module.exports = router;


text:
"""Interface for binaries built around predictor.

To use: subclass PredictorRunnerBase, implement the InputGenerator and RunBatch
functions, and call Run().

To run on TPU, set:
  --device_type=tpu
  --xla_device=tpu
  --tf_master=url/to/tpu/server
  --inference_threads=num_tpu_cores
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import concurrent.futures
import itertools
import os
import re
import threading
import time

from absl import flags
from REDACTED.tensorflow_models.mlperf.models.rough.transformer_lingvo.lingvo import compat as tf
from REDACTED.tensorflow_models.mlperf.models.rough.transformer_lingvo.lingvo.core import predictor
from REDACTED.tensorflow_models.mlperf.models.rough.transformer_lingvo.lingvo.core import py_utils
import six
from six.moves import range

flags.DEFINE_string(
    'checkpoint', None, 'Either a checkpoint file to load,'
    ' or a directory containing multiple checkpoints, where'
    ' the latest checkpoint will be loaded.')
flags.DEFINE_string(
    'inference_graph', None, 'Path to an inference graph. '
    'If not specified, will be inferred from the checkpoint path.')
flags.DEFINE_string(
    'inference_subgraph_name', '', 'The name of the inference subgraph to use. '
    'Defaults to the default subgraph.')
flags.DEFINE_enum('device_type', 'gpu', ['cpu', 'gpu', 'tpu'], 'Device type.')
flags.DEFINE_string('tf_master', 'local', 'tf_master for predictor session.')
flags.DEFINE_integer('inference_threads', '1', 'Number of inference threads.')
flags.DEFINE_integer('batch_size', 64, 'Batch size.')
flags.DEFINE_integer(
    'prediction_step_interval', 3000, 'Number of steps between outputs. '
    'Only meaningful if FLAGS.checkpoint is a directory.')

flags.DEFINE_integer('max_inputs', 0, 'Only process the first n inputs.')
flags.DEFINE_list(
    'input_id_filter', [],
    'If not empty, only process the input ids in the given list.')
flags.DEFINE_string(
    'output_dir', None, 'Output directory. '
    'If FLAGS.checkpoint is a directory, a subdirectory will be created '
    'for each checkpoint evaluated.')
flags.DEFINE_integer(
    'output_num_shards', 1, 'Each replica generates one shard of output '
    'according to --output_shard_id.')
flags.DEFINE_integer(
    'output_shard_id', 0,
    'The output shard id in range [0, output_num_shards - 1].')

FLAGS = flags.FLAGS

_RETRY_SLEEP_SECONDS = 10

class PredictorRunnerBase(object):
  """Manages state for running predictor.

  Abstract class. Subclasses should override `InputGenerator` and `RunBatch`.
  Call `Subclass().Run()` in `main()` function to run.
  """

  def __init__(self,
               checkpoint,
               output_dir=None,
               inference_graph=None,
               inference_subgraph_name='',
               device_type='cpu',
               output_num_shards=1,
               output_shard_id=0,
               max_inputs=0,
               input_id_filter=None,
               tf_master='local',
               inference_threads=1,
               batch_size=64,
               prediction_step_interval=3000):
    """Constructor.

    Args:
      checkpoint: Either a checkpoint file to load, or a directory containing
        multiple checkpoints, where the latest checkpoint will be loaded.
      output_dir: Output directory. If `checkpoint` is a directory, a
        subdirectory will be created for each checkpoint evaluated.
      inference_graph: Path to an inference graph. If not specified, will be
        inferred from the checkpoint path.
      inference_subgraph_name: The name of the inference subgraph to use.
        Defaults to the default subgraph.
      device_type: Device type, either cpu, gpu, or tpu.
      output_num_shards: Each replica generates one shard of output according to
        `output_shard_id`.
      output_shard_id: The output shard id in range `[0, output_num_shards -
        1]`.
      max_inputs: Only process the first n inputs. 0 means process all inputs.
      input_id_filter: If not empty, only process the input ids in the given
        list.
      tf_master: tf_master for predictor session.
      inference_threads: Number of inference threads.
      batch_size: Batch size.
      prediction_step_interval: Number of steps between outputs. Only meaningful
        if `checkpoint` is a directory.
    """
    self._checkpoint = checkpoint
    self._output_dir = output_dir
    self._output_num_shards = output_num_shards
    self._output_shard_id = output_shard_id
    self._max_inputs = max_inputs
    input_id_filter = input_id_filter or []
    self._input_id_filter = [str(x) for x in input_id_filter]
    self._batch_size = batch_size
    self._prediction_step_interval = prediction_step_interval

    if device_type == 'tpu' and FLAGS.xla_device != 'tpu':
      raise ValueError('xla_device=tpu should be set with device_type=tpu!')

    if tf.io.gfile.isdir(self._checkpoint):
      initial_checkpoint = tf.train.latest_checkpoint(self._checkpoint)
      while (not initial_checkpoint or
             not tf.io.gfile.exists(initial_checkpoint + '.index')):
        tf.logging.log_first_n(tf.logging.INFO,
                                    'Waiting for checkpoint to be available.',
                                    10)
        time.sleep(_RETRY_SLEEP_SECONDS)
        initial_checkpoint = tf.train.latest_checkpoint(self._checkpoint)
    else:
      initial_checkpoint = self._checkpoint
      if not tf.io.gfile.exists(initial_checkpoint + '.index'):
        raise ValueError('Could not find checkpoint %s' % initial_checkpoint)

    # Use saved inference graph.
    if inference_graph:
      self._inference_graph = inference_graph
    else:
      checkpoint_dir = self._checkpoint
      if not tf.io.gfile.isdir(checkpoint_dir):
        checkpoint_dir = os.path.dirname(checkpoint_dir)
      logdir = os.path.dirname(checkpoint_dir)
      inference_graph_filename = 'inference.pbtxt'
      if device_type == 'tpu':
        inference_graph_filename = 'inference_tpu.pbtxt'
      self._inference_graph = os.path.join(logdir, 'inference_graphs',
                                           inference_graph_filename)
    self._predictor = predictor.Predictor(
        inference_graph=self._inference_graph,
        subgraph_name=inference_subgraph_name,
        checkpoint=initial_checkpoint,
        device_type=device_type,
        tf_master=tf_master)
    self._threadpool = concurrent.futures.ThreadPoolExecutor(inference_threads)
    self._locks = [threading.Lock() for _ in range(inference_threads)]

  @classmethod
  def FromFlags(cls, **kwargs):
    """Constructs an instance of this class from FLAGS."""
    return cls(
        checkpoint=FLAGS.checkpoint,
        output_dir=FLAGS.output_dir,
        inference_graph=FLAGS.inference_graph,
        inference_subgraph_name=FLAGS.inference_subgraph_name,
        device_type=FLAGS.device_type,
        output_num_shards=FLAGS.output_num_shards,
        output_shard_id=FLAGS.output_shard_id,
        max_inputs=FLAGS.max_inputs,
        input_id_filter=FLAGS.input_id_filter,
        tf_master=FLAGS.tf_master,
        inference_threads=FLAGS.inference_threads,
        batch_size=FLAGS.batch_size,
        prediction_step_interval=FLAGS.prediction_step_interval,
        **kwargs)

  def _ShouldProcessInputId(self, input_id):
    if self._max_inputs > 0 and input_id >= self._max_inputs:
      return False
    if self._input_id_filter and str(input_id) not in self._input_id_filter:
      return False
    return input_id % self._output_num_shards == self._output_shard_id

  def _OutputFilename(self, output_dir, name):
    assert self._output_shard_id >= 0
    assert self._output_shard_id < self._output_num_shards
    return '%s-%.5d-of-%.5d' % (os.path.join(
        output_dir, name), self._output_shard_id, self._output_num_shards)

  def InputGenerator(self):
    """Generator that yields the next input.

    Must yield in a deterministic order or raise an exception when
    self._output_num_shards > 1.
    """
    raise NotImplementedError('Abstract method.')

  def RunBatch(self, output_dir, batch):
    """Runs predictor on a single batch of data.

    Args:
      output_dir: the output directory.
      batch: a list of (input_id, element) pairs, where element is yielded from
        InputGenerator and input_id is a unique counter starting from 0.
    """
    raise NotImplementedError('Abstract method.')

  def _PredictOneCheckpoint(self, checkpoint, output_dir):
    """Runs predictor."""
    tf.logging.info('Processing checkpoint %s.', checkpoint)
    self._predictor.Load(checkpoint)

    def LockedRunBatch(batch, batch_id):
      """TPU inference runs the i-th batch on the i%num_cores-th core.

      Make sure that core is available before scheduling the next batch on it.

      Args:
        batch: The input to be passed to RunBatch.
        batch_id: The id of this batch, which determins which core it runs on.
      """
      with self._locks[batch_id % len(self._locks)]:
        self.RunBatch(output_dir, batch)

    batch_id = 0
    batch = []
    futures = []
    # Iterate through the input and process it one batch at a time.
    it = self.InputGenerator()
    if self._max_inputs > 0:
      it = itertools.islice(it, self._max_inputs)
    for next_id, element in enumerate(it):
      if self._ShouldProcessInputId(next_id):
        batch.append((next_id, element))
        if len(batch) == self._batch_size:
          futures.append(
              self._threadpool.submit(LockedRunBatch, batch, batch_id))
          batch_id += 1
          batch = []
    # Last batch.
    if batch:
      futures.append(self._threadpool.submit(LockedRunBatch, batch, batch_id))
    # Wait for completion.
    for f in futures:
      f.result()

  def _PredictContinuously(self):
    """Waits for new checkpoints and runs predictor continuously."""
    prev_step = -1000000
    while True:
      # TODO(jonathanasdf): how to determine when training finished?
      path = tf.train.latest_checkpoint(self._checkpoint)
      step_str = re.search(r'ckpt-(\d{8})', six.ensure_str(path)).group(1)
      step = int(step_str)
      if step - prev_step >= self._prediction_step_interval:
        if not self._output_dir:
          raise ValueError(
              'output_dir must be specified for _PredictContinuously.')
        output_dir = os.path.join(self._output_dir, 'step_' + step_str)
        tf.io.gfile.makedirs(output_dir)
        self._PredictOneCheckpoint(path, output_dir)
        prev_step = step
        tf.logging.info('Waiting for next checkpoint...')
      time.sleep(_RETRY_SLEEP_SECONDS)

  @py_utils.RetryOnTransientTfError()
  def Run(self):
    """Monitor checkpoints and runs predictor."""
    if self._output_dir:
      tf.io.gfile.makedirs(self._output_dir)
    if tf.io.gfile.isdir(self._checkpoint):
      self._PredictContinuously()
    else:
      self._PredictOneCheckpoint(self._checkpoint, self._output_dir)


text:
namespace GuessMyNumber.Messages
{
    /// <summary>
    /// Answer to Enquirer if a try was too small
    /// </summary>
    public class TryTooSmall
    {
        public int Number { get; private set; }

        public TryTooSmall(int number)
        {
            Number = number;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Vita.Data.Model;
using Vita.Entities;
using Vita.Entities.Model;
using Vita.Entities.Utilities;

namespace Vita.Data.Linq.Translation.Expressions {
  public class TableFilterExpression: SqlExpression {
    public TableExpression Table;
    public DbTableFilter Filter;
    public List<ColumnExpression> Columns;

    public TableFilterExpression(TableExpression table, EntityFilter filter)  : base(SqlExpressionType.TableFilter, typeof(bool)) {
      Table = table;
      Filter = new DbTableFilter() { EntityFilter = filter };
      // Retrieve columns
      Columns = new List<ColumnExpression>();
      foreach(var member in filter.Members) {
        var col = table.TableInfo.Columns.FirstOrDefault(c => c.Member == member);
        // that should never happen, but just in case
        Util.Check(col != null, "Error processing filter, column for member {0} not found. Entity: {1}.",
            member.MemberName, table.TableInfo.Entity.Name);
        Filter.Columns.Add(col);
        Columns.Add(new ColumnExpression(table, col));
      }
    }

    public override Expression Mutate(System.Collections.Generic.IList<Expression> newOperands) {
      throw new Exception("Mutate not implemented for TableFilterExpression");
      /*
      if (newOperands != null && newOperands.Count > 0)
        Table = (TableExpression) newOperands[0];
      return this;
      */
    }

  }
}


text:
class Part < ActiveRecord::Base
  unloadable

  has_and_belongs_to_many :pages, :uniq => true

  acts_as_attachable

  default_scope order(:part_type)

  scope :global, where(:is_global => true)

  liquid_methods :name, :attachments, :title

  after_commit :touch_pages

  validates_uniqueness_of :name
  validates_presence_of :name, :part_type, :content_type
  validates_format_of :name, :with => /^(?!\d+$)[a-z0-9\-_]*$/

 [:content, :header, :footer, :sidebar].each do |name, params|
    src = <<-END_SRC
    def is_#{name}_type?
      self.part_type.strip.downcase == "#{name.to_s}"
    end
    END_SRC
    class_eval src, __FILE__, __LINE__
  end

  def copy_from(arg)
    part = arg.is_a?(Part) ? arg : Part.find_by_id(arg)
    self.attributes = part.attributes.dup.except("id", "name", "created_at", "updated_at") if part
    self
  end

private
  def touch_pages
    pages.each{|p| p.touch} if pages
  end

end


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IRandomNumberGenerator.cs" company="">
//
// </copyright>
// <summary>
//   The RandomNumberGenerator interface.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace AutoPoco.Util
{
    /// <summary>
    ///     The RandomNumberGenerator interface.
    /// </summary>
    public interface IRandomNumberGenerator
    {
        #region Public Methods and Operators

        /// <summary>
        /// Gets the next random number.
        /// </summary>
        /// <returns>
        /// The <see cref="int"/>.
        /// </returns>
        int Next();

        /// <summary>
        /// Gets the next random number between zero and the given max value.
        /// </summary>
        /// <param name="maxValue">
        /// The max value.
        /// </param>
        /// <returns>
        /// The <see cref="int"/>.
        /// </returns>
        int Next(int maxValue);

        /// <summary>
        /// Gets the next random number between the min value and the given max value.
        /// </summary>
        /// <param name="minValue">
        /// The min value.
        /// </param>
        /// <param name="maxValue">
        /// The max value.
        /// </param>
        /// <returns>
        /// The <see cref="int"/>.
        /// </returns>
        int Next(int minValue, int maxValue);

        /// <summary>
        /// The next double.
        /// </summary>
        /// <returns>
        /// The <see cref="double"/>.
        /// </returns>
        double NextDouble();

        #endregion

        /// <summary>
        /// Fills the buffer with a collection of random bytes.
        /// </summary>
        /// <param name="buffer">The buffer.</param>
        void NextBytes(byte[] buffer);
    }
}


text:
 /**
 * Provides A+ v1.1 compliant promises.
 * @module uP
 * @name microPromise
 * @main uP
 */

// commented out by npm-component: var task = require('microtask'); // nextTick shim

(function(root){
    "use strict"

    try {root = global} catch(e){ try {root = window} catch(e){} };

    var slice = Array.prototype.slice,
        isArray = Array.isArray;

    var uP = function microPromise(proto){
        // object mixin
        if(proto && typeof proto === 'object'){
            for(var key in uP.prototype) proto[key] = uP.prototype[key];
            proto._tuple = [];
            return proto;
        }

        if(!(this instanceof microPromise))
            return new microPromise(proto);

        this._tuple = [];

        // resolver callback
        if(typeof proto === 'function') {
            proto(this.resolve,this.reject,this.progress,this.timeout);
        }
    }

    /**
     * Attaches callback,errback,notify handlers and returns a promise
     *
     * Example: catch fulfillment or rejection
     *      var p = uP();
     *      p.then(function(value){
     *          console.log("received:", value);
     *      },function(error){
     *          console.log("failed with:", error);
     *      });
     *      p.fulfill('hello world!'); // => 'received: hello world!'
     *
     * Example: chainable then clauses
     *      p.then(function(v){
     *          console.log('v is:', v);
     *          if(v > 10) throw new RangeError('to large!');
     *          return v*2;
     *      }).then(function(v){
     *          // gets v*2 from above
     *          console.log('v is:', v)
     *      },function(e){
     *          console.log('error2:', e);
     *      });
     *      p.fulfill(142); // => v is: 142, error2: [RangeError:'to large']
     *
     * Example: undefined callbacks are ignored
     *      p.then(function(v){
     *          if(v < 0) throw v;
     *          return v;
     *      }).then(undefined,function(e){
     *          e = -e;
     *          return e;
     *      }).then(function(value){
     *          console.log('we got:', value);
     *      });
     *      p.fulfill(-5); // => we got: 5
     *
     * @param {Function} onFulfill callback
     * @param {Function} onReject errback
     * @param {Function} onNotify callback
     * @return {Object} a decendant promise
     * @api public
     */
    uP.prototype.then = function(f,r,n){
        var p = new uP();

        this._tuple[this._tuple.length] = [p,f,r,n];

        if(this._state) task(resolver,[this._tuple,this._state,this._value,this._opaque]);

        return p;
    }
    /**
     * Same semantic as `then` but spreads array value into separate arguments
     *
     * Example: Multiple fulfillment values
     *      p = uP();
     *      p.fulfill([1,2,3])
     *      p.spread(function(a,b,c){
     *          console.log(a,b,c); // => '1 2 3'
     *      });
     *
     * @param {Function} onFulfill callback
     * @param {Function} onReject errback
     * @param {Function} onNotify callback
     * @return {Object} a decendant promise
     * @api public
     */
    uP.prototype.spread = function(f,r,n){
        function s(v,a){
            if(!Array.isArray(v)) v = [v];
            return f.apply(f,v.concat(a));
        }

        return this.then(s,r,n);
    }
    /**
     * Same as `then` but terminates a promise chain and calls onerror / throws error on unhandled Errors
     *
     * Example: capture error with done
     *      p.then(function(v){
     *          console.log('v is:', v);
     *          if(v > 10) throw new RangeError('to large!');
     *          return v*2;
     *      }).done(function(v){
     *          // gets v*2 from above
     *          console.log('v is:', v)
     *      });
     *      p.fulfill(142); // => v is: 142, throws [RangeError:'to large']
     * Example: use onerror handler
     *      p.onerror = function(error){ console.log("Sorry:",error) };
     *      p.then(function(v){
     *          console.log('v is:', v);
     *          if(v > 10) throw new RangeError('to large!');
     *          return v*2;
     *      }).done(function(v){
     *          // gets v*2 from above
     *          console.log('v is:', v)
     *      });
     *      p.fulfill(142); // => v is: 142, "Sorry: [RangeError:'to large']"
     *
     * @param {Function} onFulfill callback
     * @param {Function} onReject errback
     * @param {Function} onNotify callback
     * @api public
     */
    uP.prototype.done = function(f,r,n){

        if(typeof r !== 'function') r = handleError;

        var self = this, p = this.then(f,r,n);

        function handleError(e){
            task(function(){
                if(typeof self.onerror === 'function'){
                    self.onerror(e);
                } else {
                    throw e;
                }
            });
        }
    }

    /**
     * Fulfills a promise with a `value`
     *
     *  Example: fulfillment
     *      p = uP();
     *      p.fulfill(123);
     *
     *  Example: multiple fulfillment values in array
     *      p = uP();
     *      p.fulfill([1,2,3]);
     *      p.resolved; // => [1,2,3]
     *
     *  Example: Pass through opaque arguments (experimental)
     *      p = uP();
     *      p.fulfill("hello","world");
     *      p.then(function(x,o){
     *          console.log(x,o[0]); // => "hello world"
     *          o.push("!");
     *          return "bye bye";
     *      }).then(function(x,o){
     *          console.log(x,o.join('')); // => "bye bye world!"
     *      })
     *
     * @param {Object} value
     * @return {Object} promise
     * @api public
     */
    uP.prototype.fulfill = function(x,o){
        if(!this._state){
            task(resolver,[this._tuple,this._state = 1,this._value = x, this._opaque = o]);
        }

        return this;
    }

    /**
     * Resolves a promise with a `value` yielded from another promise
     *
     *  Example: resolve literal value
     *      p = uP();
     *      p.resolve(123); // fulfills promise with 123
     *
     *  Example: resolve value from another pending promise
     *      p1 = uP();
     *      p2 = uP();
     *      p1.resolve(p2);
     *      p2.fulfill(123) // => p2._value = 123
     *
     * @param {Object} value
     * @return {Object} promise
     * @api public
     */
    uP.prototype.resolve = function(x,o){
        var then, z = 0, p = this, z = 0;

        if(!this._state){
            if(x === p) p.reject(new TypeError("x === p"));

            if(x && (typeof x === 'object' || typeof x === 'function')){
                try { then = x.then } catch(e){ p.reject(e) }
            }

            if(typeof then !== 'function'){
                task(resolver,[this._tuple,this._state = 1,this._value = x, this._opaque = o])
            } else if(!z){
                try {
                    then.apply(x,[function(y){
                        if(!z++) p.resolve(y,o);
                    },function(r){
                        if(!z++) p.reject(r);
                    }]);
                } catch(e) {
                    if(!z++) p.reject(e);
                }
            }
        }

        return this;
    }

    /**
     * Rejects promise with a `reason`
     *
     *  Example:
     *      p = uP();
     *      p.then(function(ok){
     *         console.log("ok:",ok);
     *      }, function(error){
     *         console.log("error:",error);
     *      });
     *      p.reject('some error'); // outputs => 'error: some error'
     *
     * @param {Object} reason
     * @return {Object} promise
     * @api public
     */
    uP.prototype.reject = function(x,o){
        if(!this._state){
            task(resolver,[this._tuple,this._state = 2,this._value = x, this._opaque = o]);
        }

        return this;
    }

    /**
     * Notifies attached handlers
     *
     *  Example:
     *      p = uP();
     *      p.then(function(ok){
     *         console.log("ok:",ok);
     *      }, function(error){
     *         console.log("error:",error);
     *      }, function(notify){
     *         console.log(notify);
     *      });
     *      p.progress("almost done"); // optputs => 'almost done'
     *      p.reject('some error'); // outputs => 'error: some error'
     *
     * @param {Object} arguments
     * @api public
     */
    uP.prototype.progress = function(){
        var args = slice.call(arguments), fn;
        for(var i = 0, l = this._tuple.length; i < l; i++){
            if(typeof (fn = this._tuple[i][3]) === 'function')
                fn.apply(this,arguments);
        }
    }

    /**
     * Timeout a pending promise and invoke callback function on timeout.
     * Without a callback it throws a RangeError('exceeded timeout').
     *
     * Example: timeout & abort()
     *      var p = Promise();
     *      p.attach({abort:function(msg){console.log('Aborted:',msg)}});
     *      p.timeout(5000);
     *      // ... after 5 secs ... => Aborted: |RangeError: 'exceeded timeout']
     *
     * Example: cancel timeout
     *      p.timeout(5000);
     *      p.timeout(null); // timeout cancelled
     *
     * @param {Number} time timeout value in ms or null to clear timeout
     * @param {Function} callback optional timeout function callback
     * @throws {RangeError} If exceeded timeout
     * @return {Object} promise
     * @api public
     */
    uP.prototype.timeout = function(msec,func){
        var p = this;

        if(msec === null) {
            clearTimeout(p._timer);
            p._timer = null;
        } else if(!p._timer){
            p._timer = setTimeout(onTimeout,msec);
        }

        function onTimeout(){
            var e = RangeError("exceeded timeout");
            if(!p._state) {
                if(typeof func === 'function') func(p);
                else if(typeof p.onerror === 'function') p.onerror(e);
                else throw e;
            }
        }

        return this;
    }

    /**
     * Wraps a `proto` into a promise
     *
     * Example: wrap an Array
     *      p = Promise();
     *      c = p.wrap(Array);
     *      c(1,2,3); // => calls constructor and fulfills promise
     *      p.resolved; // => [1,2,3]
     *
     * @param {Object} proto
     * @return {Object} promise
     * @api public
     */
    uP.prototype.wrap = function(proto){
        var p = this;

        return function(){
            var args = slice.call(arguments), ret;

            if(proto instanceof microPromise){
                proto.fulfill(args).then(p.fulfill,p.reject);
            } else if(typeof proto === 'function'){
                try{
                    ret = proto.apply(p,args);
                    p.resolve(ret);
                } catch(err) {
                    p.reject(err);
                }
            }

            return p;
        }
    }
    /**
     * Deferres a task and fulfills with return value.
     * The process may also return a promise itself which to wait on.
     *
     * Example: Make readFileSync async
     *      fs = require('fs');
     *      var asyncReadFile = uP().defer(fs.readFileSync,'./index.js','utf-8');
     *      asyncReadFile.then(function(data){
     *          console.log(data)
     *      },function(error){
     *          console.log("Read error:", error);
     *      });
     *
     * @return {Object} promise
     * @api public
     */
    uP.prototype.defer = function(){
        var args = slice.call(arguments),
            proc = args.shift(),
            p = this;

        if(typeof proc === 'function'){
            task(enclose,args);
        }

        function enclose(){
            try { p.resolve(proc.apply(p,args)) } catch(err) { p.reject(err) }
        }

        return this;
    }
    /**
     * Adapted for nodejs style functions expecting a callback.
     *
     * Example: make readFile async
     *      fs = require('fs');
     *      var asyncReadFile = uP.async(fs.readFile,'./index.js','utf-8');
     *      asyncReadFile.then(function(data){
     *          console.log(data);
     *      },function(error){
     *          console.log("Read error:", error);
     *      });
     *
     * @return {Object} promise
     * @api public
     */
    uP.prototype.async = function(){
        var p = this,
            args = slice.call(arguments);

        function callback(err,ret){ if(!err) p.fulfill(ret); else p.reject(ret); }

        args[args.length] = callback;

        return this.defer.apply(this,args);
    }

    /**
     * Joins promises and collects results into an array.
     * If any of the promises are rejected the chain is also rejected.
     *
     * Example: join with two promises
     *      a = uP();
     *      b = uP();
     *      c = uP();
     *      a.join([b,c]).spread(function(a,b,c){
     *          console.log(a,b,c);
     *      },function(err){
     *          console.log('error=',err);
     *      });
     *      b.fulfill('world');
     *      a.fulfill('hello');
     *      c.fulfill('!'); // => 'hello world !''
     *
     * @param {Array} promises
     * @return {Object} promise
     * @api public
     */
    uP.prototype.join = function(j){
        var p = this,
            y = [],
            u = new uP().resolve(p).then(function(v){y[0] = v});

        if(arguments.length > 1) {
            j = slice.call(arguments);
        }

        if(!isArray(j)) j = [j];

        function collect(i){
            j[i].done(function(v){
                y[i+1] = v;
            },u.reject);

            return function(){return j[i]}
        }

        for(var i = 0; i < j.length; i++){
            u = u.then(collect(i));
        }

        return u.then(function(){return y});
    }

    /* Resolver function, yields back a promised value to handlers */
    function resolver(tuple,state,value,opaque){
        var t, p, h, x = value;

        while(t = tuple.shift()) {
            p = t[0];
            h = t[state];

            if(typeof h === 'function') {
                try {
                    x = h(value,opaque);
                    p.resolve(x,opaque);
                } catch(e) {
                    p.reject(e);
                }
            } else {
                p._state = state;
                p._value = x;
                p._opaque = opaque;
                task(resolver,[p._tuple, p._state, p._value, p._opaque]);
            }
        }
    }

    /* expose this module */
    if(module && module.exports) module.exports = uP;
    else if(typeof define ==='function' && define.amd) define(uP);
    else root.uP = uP;
}(this));


text:
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /app
COPY . .
RUN dotnet publish -c Release -o out Server

FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS runtime
ENV COMPlus_ReadyToRun 0
WORKDIR /app
COPY --from=build /app/out ./

EXPOSE 8080

ENTRYPOINT ["dotnet", "Server.dll", "--urls=http://*:8080"]


text:
Phase current

Maximum current that goes into motor's phase wires.

Increasing this value improves acceleration, but results in increased motor heating and stresses bike dropouts.

Common and relatively safe value is 2 x Battery current.


text:
module.exports = {
    setUp: function (callback) {
        this.foo = 'bar';
        callback();
    },
    tearDown: function (callback) {
        // clean up
        callback();
    },
    'Extend Test': function (test) {
            var extend = require('../src/utils/extend');
        var oldObj = {
            first:function () {
                console.log('first');
            },
            prop: 'Property On Base'
        };
        var extendObj = {
            second: function () {
                console.log('second');
            }
        };
        var newObj = extend(oldObj, extendObj);

        test.equal(typeof newObj.second, 'function');
        test.equal(typeof newObj.prop, 'string');
        test.done();
    }
};


text:
#ifndef ALINOUS_COMPILE_SQL_FUNCTIONS_COUNT_H_
#define ALINOUS_COMPILE_SQL_FUNCTIONS_COUNT_H_
namespace alinous {namespace runtime {namespace variant {
class VariantValue;}}}

namespace alinous {namespace db {namespace trx {namespace scan {
class ScanResultRecord;}}}}

namespace alinous {namespace runtime {namespace engine {
class ScriptMachine;}}}

namespace alinous {namespace compile {namespace expression {
class FunctionArguments;}}}

namespace alinous {namespace compile {namespace sql {namespace functions {
class ISQLFunctionBody;}}}}

namespace alinous {namespace db {namespace table {
class DatabaseException;}}}

namespace alinous {namespace system {
class AlinousException;}}

namespace java {namespace lang {
class IObject;
}}

namespace alinous {
class ThreadContext;
}

namespace alinous {namespace compile {namespace sql {namespace functions {

using namespace ::alinous;
using namespace ::java::lang;
using ::java::util::Iterator;
using ::alinous::compile::expression::FunctionArguments;
using ::alinous::db::table::DatabaseException;
using ::alinous::db::trx::scan::ScanResultRecord;
using ::alinous::runtime::engine::ScriptMachine;
using ::alinous::runtime::variant::VariantValue;
using ::alinous::system::AlinousException;

class Count final : public ISQLFunctionBody, public virtual IObject {
public:
	Count(const Count& base) = default;
public:
	Count(ThreadContext* ctx) throw() ;
	void __construct_impl(ThreadContext* ctx) throw() ;
	virtual ~Count() throw();
	virtual void __releaseRegerences(bool prepare, ThreadContext* ctx) throw();
public:
	String* getName(ThreadContext* ctx) throw()  final;
	VariantValue* resolveSQLExpression(ScanResultRecord* record, ScriptMachine* machine, FunctionArguments* args, bool debug, ThreadContext* ctx) final;
public:
	static bool __init_done;
	static bool __init_static_variables();
public:
	static void __cleanUp(ThreadContext* ctx);
};

}}}}

#endif /* end of ALINOUS_COMPILE_SQL_FUNCTIONS_COUNT_H_ */