text:
module Field::Style
  CHOICES = {
    "single" => "Single value – optional",
    "single-required" => "Single value – required",
    "multiple" => "Multiple values – optional",
    "multiple-required" => "Multiple values – at least one"
    # TODO: uncomment once ordering behavior is supported
    # "multiple-ordered" => "Multiple ordered values – optional",
    # "multiple-ordered-required" => "Multiple ordered values – at least one"
  }.freeze

  def style_choices
    CHOICES.select do |key, _name|
      key =~ /single/ || allows_multiple?
    end
  end

  # TODO: test
  def style=(key)
    return if key.blank?

    self.required = !!(key =~ /required/)
    self.multiple = !!(key =~ /multiple/)
    self.ordered = !!(key =~ /ordered/)
  end

  def style
    key = []
    key << (multiple? ? "multiple" : "single")
    key << "ordered" if multiple? && ordered?
    key << "required" if required?
    key.join("-")
  end
end

redpajama_set_name: RedPajamaGithub


text:
#include "OpenGLRenderer.h"
#include "../../../SyntopiaCore/GLEngine/Sphere.h"
#include "../../../SyntopiaCore/GLEngine/Box.h"
#include "../../../SyntopiaCore/GLEngine/Grid.h"
#include "../../../SyntopiaCore/GLEngine/Dot.h"
#include "../../../SyntopiaCore/GLEngine/Line.h"
#include "../../../SyntopiaCore/GLEngine/Mesh.h"
#include "../../../SyntopiaCore/GLEngine/Triangle.h"
#include "../../../SyntopiaCore/Math/Vector3.h"

using namespace SyntopiaCore::GLEngine;
using namespace SyntopiaCore::Math;

#include "../../../SyntopiaCore/Logging/Logging.h"

using namespace SyntopiaCore::Logging;

namespace StructureSynth {
	namespace Model {
		namespace Rendering {

			void OpenGLRenderer::drawBox(SyntopiaCore::Math::Vector3f base,
				SyntopiaCore::Math::Vector3f dir1 ,
				SyntopiaCore::Math::Vector3f dir2,
				SyntopiaCore::Math::Vector3f dir3, PrimitiveClass* classID) {
					Object3D* o =new Box( base, dir1, dir2, dir3);
					o->setPrimitiveClass(classID);
					o->setColor(rgb, alpha);

					engine->addObject(o);
			};

			void OpenGLRenderer::drawMesh(  SyntopiaCore::Math::Vector3f startBase,
										SyntopiaCore::Math::Vector3f startDir1,
										SyntopiaCore::Math::Vector3f startDir2,
										SyntopiaCore::Math::Vector3f endBase,
										SyntopiaCore::Math::Vector3f endDir1,
										SyntopiaCore::Math::Vector3f endDir2,
										PrimitiveClass* classID) {
					Mesh* o =new Mesh( startBase, startDir1, startDir2, endBase, endDir1, endDir2);
					o->setPrimitiveClass(classID);
					o->setPreviousColor(rgb, alpha);
					o->setColor(oldRgb, oldAlpha);

					engine->addObject(o);
			};

			void OpenGLRenderer::drawGrid(SyntopiaCore::Math::Vector3f base,
				SyntopiaCore::Math::Vector3f dir1 ,
				SyntopiaCore::Math::Vector3f dir2,
				SyntopiaCore::Math::Vector3f dir3,
				PrimitiveClass* classID) {
					Object3D* o = new Grid( base, dir1, dir2, dir3);
					o->setPrimitiveClass(classID);
					o->setColor(rgb, alpha);
					engine->addObject(o);
			};

			void OpenGLRenderer::drawLine(SyntopiaCore::Math::Vector3f from, SyntopiaCore::Math::Vector3f to, PrimitiveClass* classID) {
					Object3D* o = new Line( from, to);
					o->setPrimitiveClass(classID);
					o->setColor(rgb, alpha);
					engine->addObject(o);
			};

			void OpenGLRenderer::drawTriangle(SyntopiaCore::Math::Vector3f p1,
										 SyntopiaCore::Math::Vector3f p2,
									     SyntopiaCore::Math::Vector3f p3,
										PrimitiveClass* classID) {
				   Object3D* o = new Triangle(p1, p2,p3);
				   o->setPrimitiveClass(classID);
				   o->setColor(rgb, alpha);
				   engine->addObject(o);
			}

			void OpenGLRenderer::drawDot(SyntopiaCore::Math::Vector3f v, PrimitiveClass* classID) {
					Object3D* o = new Dot(v);
					o->setPrimitiveClass(classID);
					o->setColor(rgb, alpha);
					engine->addObject(o);
			};

			void OpenGLRenderer::drawSphere(SyntopiaCore::Math::Vector3f center, float radius, PrimitiveClass* classID) {
				Object3D* o = new Sphere( center, radius);
				o->setPrimitiveClass(classID);
				o->setColor(rgb, alpha);
				engine->addObject(o);
			};

			void OpenGLRenderer::begin() {
				engine->clearWorld();
				engine->setBackgroundColor(0,0,0);
				rgb = Vector3f(1,0,0);
				alpha = 1;
			};

			void OpenGLRenderer::end() {
				INFO(QString("Build done. Created %1 objects.").arg(engine->objectCount()));
				engine->requireRedraw();
			};

			void OpenGLRenderer::setBackgroundColor(SyntopiaCore::Math::Vector3f rgb) {
				engine->setBackgroundColor(rgb.x(),rgb.y(),rgb.z());
			}

			void OpenGLRenderer::callCommand(const QString& /*renderClass*/, const QString& /*command*/) {
			}

			void OpenGLRenderer::setTranslation(SyntopiaCore::Math::Vector3f translation) {
				engine->setTranslation(translation);
			};

			void OpenGLRenderer::setScale(double scale) {
				engine->setScale(scale);
			};

			void OpenGLRenderer::setRotation(SyntopiaCore::Math::Matrix4f rotation) {
				engine->setRotation(rotation);
			};

			void OpenGLRenderer::setPivot(SyntopiaCore::Math::Vector3f pivot) {
				engine->setPivot(pivot);
			};

			void OpenGLRenderer::setPerspectiveAngle(double angle) {
				engine->setPerspectiveAngle(angle);
			}

		}
	}
}


text:
namespace content {
class WebUI;
}

class ChromeCustomizeThemesHandler;

// This WebUI uses mojo for the color picker element.
class ProfileCustomizationUI
    : public ui::MojoWebUIController,
      public customize_themes::mojom::CustomizeThemesHandlerFactory {
 public:
  explicit ProfileCustomizationUI(content::WebUI* web_ui);
  ~ProfileCustomizationUI() override;

  ProfileCustomizationUI(const ProfileCustomizationUI&) = delete;
  ProfileCustomizationUI& operator=(const ProfileCustomizationUI&) = delete;

  // Initializes the ProfileCustomizationUI.
  void Initialize(base::OnceClosure done_closure);

  // Instantiates the implementor of the
  // customize_themes::mojom::CustomizeThemesHandlerFactory mojo interface
  // passing the pending receiver that will be internally bound.
  void BindInterface(mojo::PendingReceiver<
                     customize_themes::mojom::CustomizeThemesHandlerFactory>
                         pending_receiver);

 private:
  // customize_themes::mojom::CustomizeThemesHandlerFactory:
  void CreateCustomizeThemesHandler(
      mojo::PendingRemote<customize_themes::mojom::CustomizeThemesClient>
          pending_client,
      mojo::PendingReceiver<customize_themes::mojom::CustomizeThemesHandler>
          pending_handler) override;

  std::unique_ptr<ChromeCustomizeThemesHandler> customize_themes_handler_;
  mojo::Receiver<customize_themes::mojom::CustomizeThemesHandlerFactory>
      customize_themes_factory_receiver_;

  WEB_UI_CONTROLLER_TYPE_DECL();
};

#endif  // CHROME_BROWSER_UI_WEBUI_SIGNIN_PROFILE_CUSTOMIZATION_UI_H_


text:
#include <aws/route53resolver/model/GetResolverRulePolicyRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Route53Resolver::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GetResolverRulePolicyRequest::GetResolverRulePolicyRequest() :
    m_arnHasBeenSet(false)
{
}

Aws::String GetResolverRulePolicyRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_arnHasBeenSet)
  {
   payload.WithString("Arn", m_arn);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection GetResolverRulePolicyRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "Route53Resolver.GetResolverRulePolicy"));
  return headers;

}


text:
package edu.drexel.cis.dragon.nlp.ontology;

import edu.drexel.cis.dragon.nlp.Word;

public abstract interface Vocabulary
{
  public abstract boolean isPhrase(String paramString);

  public abstract boolean isPhrase(Word paramWord1, Word paramWord2);

  public abstract boolean isStartingWord(Word paramWord);

  public abstract Word findPhrase(Word paramWord);

  public abstract int getPhraseNum();

  public abstract String getPhrase(int paramInt);

  public abstract int maxPhraseLength();

  public abstract int minPhraseLength();

  public abstract void setAdjectivePhraseOption(boolean paramBoolean);

  public abstract boolean getAdjectivePhraseOption();

  public abstract void setNPPOption(boolean paramBoolean);

  public abstract boolean getNPPOption();

  public abstract void setCoordinateOption(boolean paramBoolean);

  public abstract boolean getCoordinateOption();

  public abstract void setLemmaOption(boolean paramBoolean);

  public abstract boolean getLemmaOption();
}

/* Location:           C:\dragontoolikt\dragontool.jar
 * Qualified Name:     dragon.nlp.ontology.Vocabulary
 * JD-Core Version:    0.6.2
 */


text:
package io.hascalator
package typeclasses

import Prelude._

/** The `Bounded` class is used to name the upper and lower limits of a type. `Ord` is not a superclass of Bounded
  * since types that are not totally ordered may also have upper and lower bounds.
  *
  * @tparam A the type for the instance
  * @author Carlo Micieli
  * @since 0.0.1
  */
trait Bounded[A] extends Any {
  /** Returns the lower limit for the type
    * @return the lower limit
    */
  def minBound: A

  /** Returns the upper limit for the type
    * @return the upper limit
    */
  def maxBound: A
}

object Bounded {
  def apply[A](implicit b: Bounded[A]): Bounded[A] = b

  private def newInstance[A](min: => A)(max: => A): Bounded[A] = new Bounded[A] {
    override def minBound: A = min
    override def maxBound: A = max
  }

  implicit val bool2Bounded: Bounded[Boolean] = newInstance(false)(true)
  implicit val char2Bounded: Bounded[Char] = newInstance(scala.Char.MinValue)(scala.Char.MaxValue)
  implicit val short2Bounded: Bounded[Short] = newInstance(scala.Short.MinValue)(scala.Short.MaxValue)
  implicit val int2Bounded: Bounded[Int] = newInstance(scala.Int.MinValue)(scala.Int.MaxValue)
  implicit val long2Bounded: Bounded[Long] = newInstance(scala.Long.MinValue)(scala.Long.MaxValue)
  implicit val float2Bounded: Bounded[Float] = newInstance(scala.Float.MinValue)(scala.Float.MaxValue)
  implicit val double2Bounded: Bounded[Double] = newInstance(scala.Double.MinValue)(scala.Double.MaxValue)
}


text:
<?php

namespace Insulin\Sugar\Versions\Tests;

use Insulin\Sugar\Tests\SugarTest;

class Sugar7Test extends SugarTest
{
    /**
     * {@inheritdoc}
     */
    protected static $version = '7';
}


text:
<?php
namespace Chamilo\Core\Rights\Editor\Table\LocationEntity;

use Chamilo\Libraries\Format\Table\Extension\DataClassTable\DataClassTableDataProvider;

abstract class LocationEntityTableDataProvider extends DataClassTableDataProvider
{

    public function retrieve_data($condition, $offset, $count, $order_property = null)
    {
        $condition = $condition[$this->get_table()->get_type()];
        $selected_entity = $this->get_component()->get_selected_entity();
        return $selected_entity->retrieve_entity_items($condition, $offset, $count, $order_property);
    }

    public function count_data($condition)
    {
        $selected_entity = $this->get_component()->get_selected_entity();
        $condition = $condition[$this->get_table()->get_type()];
        return $selected_entity->count_entity_items($condition);
    }
}


text:
class OneserviceController < ApplicationController

  respond_to :html, :js
  include Packable
  include OneappsHelper
  def show

  end

  def overview
    if current_user_verify
      serviceid = params["servicekey"]
      @assembly=GetAssembly.perform(serviceid,force_api[:email],force_api[:api_key])
    else
      redirect_to signin_path
    end
  end

  def metrics
    if current_user_verify
      serviceid = params["servicekey"]
      assembly=GetAssembly.perform(serviceid,force_api[:email],force_api[:api_key])
      if assembly.class != Megam::Error
        @appname = assembly.name + "." + assembly.components[0][0].inputs[:domain]
      else
        @appname = nil
      end
    else
      redirect_to signin_path
    end
  end

  def logs
    if current_user_verify
      @com_books = []
      @socketURL = Rails.configuration.socket_url
      appid = params["servicekey"]
      assembly=GetAssembly.perform(appid,force_api[:email],force_api[:api_key])
      if assembly.class != Megam::Error
        @appname = assembly.name + "." + assembly.components[0][0].inputs[:domain]
      else
        @appname = nil
      end
      assembly.components.each do |com|
        if com != nil
          com.each do |c|
            com_type = c.tosca_type.split(".")
            @com_books << c.name + "-" + com_type[2]
          end
        end
      end
    else
      redirect_to signin_path
    end
  end

  def runtime
    if current_user_verify
      serviceid = params["servicekey"]
      assembly=GetAssembly.perform(serviceid,force_api[:email],force_api[:api_key])
      if assembly.class != Megam::Error
        @appname = assembly.name + "." + assembly.components[0][0].inputs[:domain]
      else
        @appname = nil
      end
    else
      redirect_to signin_path
    end
  end

  def services
    serviceid = params["servicekey"]
  end

  def lcservice
    @id = params[:id]
    @name = params[:name]
    @command = params[:command]
    respond_to do |format|
      format.js {
        respond_with(@id, @name, @command, :layout => !request.xhr? )
      }
    end
  end

  def service_request
    if current_user_verify
      logger.debug "--> service:Build_request, #{params}"
      options = {:app_id => "#{params[:service_id]}", :app_name => "#{params[:service_name]}", :action => "#{params[:command]}"}
      defnd_result =  CreateAppRequests.perform(options, force_api[:email], force_api[:api_key])
      if params[:command] == "stop"
        @res_msg = "Service #{params[:command]}ped successfully"
      else
        @res_msg = "Service #{params[:command]}ed successfully"
      end
      @err_msg = nil
      if defnd_result.class == Megam::Error
        @res_msg = nil
        @err_msg= ActionController::Base.helpers.link_to 'Contact support ', "http://support.megam.co/"
        respond_to do |format|
          format.js {
            respond_with(@res_msg, @err_msg, :layout => !request.xhr? )
          }
        end
      end
    else
      redirect_to signin_path
    end
  end

end


text:
from base import BaseCommand

class TemperatureCommand(BaseCommand):

    def __init__(self, arguments=None):
        super(TemperatureCommand, self).__init__(arguments)

        for key in self.arguments:
            if key in ['temperature', 'box']:
                try:
                    self.arguments[key] = int(self.arguments[key])
                except ValueError:
                    self.logger.error("TemperatureCommand failed on parsing argument '{}'={} as integer"
                                      .format(key, self.arguments[key]))

        args = {'timeout': None}
        args.update(self.arguments)

        if not all(key in args for key in ['box', 'temperature']):
            self.logger.error("TemperatureCommand has incomplete arguments: '{}'".format(args))
            self.arguments = None
        else:
            self.arguments = args

    def execute(self, boxmanager):
        if not self.arguments:
            return False

        box = boxmanager.get_box(self.arguments['box'])
        if not box:
            self.logger.error("Box '{}' not found!".format(self.arguments['box']))
            return False

        box.set_air_temperature(self.arguments['temperature'])
        return True

    def __str__(self):
        return "TemperatureCommand()"


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

  <com.ppamorim.calculator.core.view.PaperButton
      android:id="@+id/calculate"
      android:layout_width="160dp"
      android:layout_height="54dp"
      android:layout_gravity="center_horizontal"
      widget:paper_text_color="@color/white"
      widget:paper_color="@color/actionbar"
      widget:paper_text="@string/calculate"/>

  <TextView
      android:id="@+id/text_result"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:gravity="center_horizontal"
      android:padding="16dp"
      android:textSize="14sp"
      android:textColor="@color/actionbar"
      android:text="@string/result"/>

  <com.ppamorim.calculator.core.view.FloatingEditText
      android:id="@+id/edittext_result"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:inputType="none"
      android:focusable="false"
      widget:floating_edit_text_highlighted_color="@color/actionbar"
      style="@style/edit_text_calculate"/>

</LinearLayout>


text:
function Scroller(stage) {

	this.main_bg = new Background_main();
	stage.addChild(this.main_bg);

	this.rocksDownMid = new RocksDownMid();
	stage.addChild(this.rocksDownMid);

	this.rocksDownSmall = new RocksDownSmall();
	stage.addChild(this.rocksDownSmall);

	this.rocksUpBig = new RocksUpBig();
	stage.addChild(this.rocksUpBig);

	this.rocksUpSmall = new RocksUpSmall();
	stage.addChild(this.rocksUpSmall);

	this.stars = new Stars();
	stage.addChild(this.stars);

	this.sun = new Sun();
	stage.addChild(this.sun);

	this.saturnus = new Saturnus();
	stage.addChild(this.saturnus);

	this.meteroits = new Meteroits();
	stage.addChild(this.meteroits);

	this.mapBuilder = new MapBuilder(this.meteroits);

	this.viewportX = 0;
}

Scroller.prototype.setViewportX = function (viewportX) {
	this.viewportX = viewportX;
	this.main_bg.setViewportX(viewportX);
	this.rocksDownMid.setViewportX(viewportX);
	this.rocksUpBig.setViewportX(viewportX);
	this.rocksDownSmall.setViewportX(viewportX);
	this.rocksUpSmall.setViewportX(viewportX);
	this.stars.setViewportX(viewportX);
	this.sun.setViewportX(viewportX);
	this.saturnus.setViewportX(viewportX);
	this.meteroits.setViewportX(viewportX);

};
Scroller.prototype.getViewportX = function () {
	return this.viewportX;
};

Scroller.prototype.moveViewportXBy = function(units) {
	var newViewportX = this.viewportX + units;
	this.setViewportX(newViewportX);
};


text:
require 'socket'
require 'ipaddr'
require 'pp'

def sh(cmd, ignore_exit_code = false, retry_count = 1, delay = 1, bg = false)
    puts cmd
    if bg then
        # Run command in background
        Process.detach(spawn(cmd))
        return
    end

    r = ""
    retry_count.times { |i|
        r = `#{cmd}`.chomp
        puts r
        break if $?.to_i == 0
        exit -1 if !ignore_exit_code and i == retry_count - 1
        sleep delay
        puts "#{i}/#{retry_count}: Retry: #{cmd}"
    }
    return r
end

def error(msg); puts msg; exit -1 end

# Return interface IP address, mask and gateway information
def get_intf_ip(intf)
    prefix = sh("ip addr show dev #{intf}|\grep -w inet | " +
                "\grep -v dynamic | awk '{print $2}'")
    error("Cannot retrieve #{intf}'s IP address") if prefix !~ /(.*)\/(\d+)$/
    ip = $1; prefix_len = $2
    mask = IPAddr.new(prefix).inspect.split("/")[1].chomp.chomp(">")
    gw = sh(%{netstat -rn |\grep "^0.0.0.0" | awk '{print $2}'})

    return ip, mask, gw, prefix_len
end

def sh_container(container_id, cmd, ignore = false)
    pid = sh(%{docker inspect -f {{.State.Pid}} #{container_id}})
    sh(%{echo #{cmd} | nsenter -n -t #{pid} sh})
end


text:
+++
Title = "devopsdays Porto Alegre 2020"
Type = "welcome"
Description = "devopsdays Porto Alegre 2020"
aliases = [
    "/events/2020-porto-alegre/",
    "/events/2020-porto-alegre/location/",
    "/events/2020-porto-alegre/propose/",
    "/events/2020-porto-alegre/registration/",
    "/events/2020-porto-alegre/sponsor/",
    "/events/2020-porto-alegre/program/",
    "/events/2020-porto-alegre/speakers/"
]
+++

    {{< event_logo >}}

      Informação importante devido ao coronavirus (COVID-19)

    O DevOpsDays Porto Alegre é um evento comunitário, e pensando no bem estar de todos, optamos por cancelar a edição de 2020, que aconteceria nos dias 22 e 23 de maio, não é uma decisão fácil, mas necessária. Para todos aqueles que já adquiriram ingresso, o mesmo será válido para a próxima edição, que por coincidência será o de comemoração de 5 anos. Será um evento incrível e por isso
    gostaríamos que todos que já possuem ingresso pudessem participar. Entendemos que essa decisão pode gerar algum contratempo, por isso e caso seja preciso, poderemos fazer o reembolso do ingresso, descontado as custas da plataforma que gerencia os tickets, para isso, envie um e-mail para porto-alegre@devopsdays.org com o seu número de inscrição, nome, e-mail e cpf e informe seu desejo de reembolso.

    Gostaríamos de agradecer também aos patrocinadores que optaram por manter a parceria para o ano que vem, MUITO OBRIGADO á Adentro, Interop, Azion, Globo e Southsystem que confiam no evento e serão parceiros fundamentais para o evento de 2021!

    Estamos planejando algumas ações durante o ano e com certeza vocês serão informados, obviamente tudo será feito de forma remota, pois neste momento precisamos nos cuidarmos, e cuidar de quem amamos.

    Até ano que vem ;)

    DevOpsDays Porto Alegre

    Contact

    {{< event_link page="contact" text="Get in touch with the organizers" >}}

{{< event_twitter >}}


text:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;

namespace Styx.Requests
{
    public sealed class RegexRequestParser : IRequestParser
    {
        private const string Pattern = @"^(?<method>[^\s]+)\s(?<path>[^\s]+)\sHTTP\/1\.1\r\n" + // request line
                                       @"((?<field_name>[^:\r\n]+):\s(?<field_value>[^\r\n]*)\r\n)+" + //headers
                                       @"\r\n" + //newline
                                       @"(?<body>.+)?";

        private static readonly Regex Regex = new Regex(Pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);

        public IRequest Parse(string requestString)
        {
            var match = Regex.Match(requestString);
            if (!match.Success)
                throw new HttpParseException();

            var method = match.Groups["method"].Value;
            var path = match.Groups["path"].Value;
            var body = match.Groups["body"].Value;

            var headers = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
            var fields = match.Groups["field_name"].Captures;
            var values = match.Groups["field_value"].Captures;
            for (var i = 0; i < fields.Count; i++)
            {
                var name = fields[i].ToString();
                var value = values[i].ToString();
                headers[name] = value;
            }

            return new Request(method, path, body, headers);
        }
    }
}


text:
Advanced |webapp2| |gae| Example
--------------------------------

.. seo-description::

   An advanced tutorial where we create a Google App Engine app
   where users can log in with Facebook, Twitter and OpenID and post statuses.

In this tutorial we will create a |gae|_ |webapp2|_ application
that will be able to log **users** in with Facebook, Twitter and |openid|_
and we will use the :class:`.Credentials` of an **authenticated user** to
post tweets and Facebook statuses on the **user's** behalf.

You can download all the source files we are about to create
`here <https://github.com/peterhudec/authomatic/tree/master/examples/gae/credentials>`__.

First create the :doc:`/reference/config` dictionary where you set up all the providers you want to use.
Yo will need the ``consumer_key`` and ``consumer_secret`` which you can get
`here <https://developers.facebook.com/apps>`__ for Facebook and
`here <https://dev.twitter.com/apps>`__ for Twitter.

.. note::

   Facebook and other |oauth2| providers require a **redirect URI**
   which should be the URL of the *login request handler*
   which we will create in this tutorial and whose walue in our case will be
   ``http://[hostname]:[port]/login/fb`` for Facebook.

.. literalinclude:: ../../../examples/gae/credentials/config-template.py
   :language: python

Create the ``main.py`` module and import what's needed.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 1-9

Make an instance of the :class:`.Authomatic` class and pass
the :doc:`/reference/config` together with a random secret string
used for session and CSRF token generation to it's constructor.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 12

Create a simple request handler which accepts ``GET`` and ``POST`` HTTP methods and
receives the ``provider_name`` URL variable.
Log the **user** in by calling the :meth:`.Authomatic.login` method.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 14, 15, 18

If there is :attr:`.LoginResult.user`, the *login procedure* was successful
and we can welcome the **user**.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 20-23

Save the **user's** name and ID to cookies so we can use them in other handlers.
We use cookies only for simplicity of the example,
in real app you will probably use some *User* datamodel.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 26-27

If the **user** has logged in with Facebook or Twitter, **he/she** gave us :class:`.Credentials`.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 29

You can serialize the :class:`.Credentials` into a lightweight URL-safe string.
Store also the serialized credentials to a cookie.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 31-32

Store also the possible error message to a cookie.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 34-35

Redirect the **user** to the *Home* handler which we are going to create next.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 37

The *Home* handler only needs a ``GET`` method.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 40-41

Create links to the *Login* handler.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 43-44

Retrieve the stored values from cookies.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 47-50

Handle possible errors.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 52-53

If there is no error, there must be a **user** ID.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 54-55

Let's look at what we can do with the :class:`.Credentials`.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 57

We can deserialize them.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 59

They know the **provider** name which we defined in the :doc:`/reference/config`.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 61-65

:class:`.Credentials` issued by |oauth2|_ providers have limited lifetime.
We can test whether they are still valid.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 67

Whether they expire soon.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 68

The remaining number of seconds till they expire.

.. note::

   If the number is negative, the :class:`.Credentials` will never expire.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 69

Their expiration date.

.. note::

   If :class:`.Credentials` will never expire it returns ``None``.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 70

We can refresh the :class:`.Credentials` without the **user** while they are valid.
If they are expired we only can get new :class:`.Credentials` by repeating the *login procedure*
with :meth:`.Authomatic.login`.

Inform the **user** about **his/her** :class:`.Credentials` and create links to
*Refresh*, *Action* and *Logout* handlers, which we are going to create next.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 72-97

Create the *Refresh* handler, retrieve the serialized :class:`.Credentials` from
the cookie, deserialize them and get their expiration date.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 100-106

Refresh the :class:`.Credentials` with the :meth:`.Credentials.refresh` method.
It returns a :class:`.Response object`, but only if the :class:`.Credentials` support refreshment.
Otherwise the method returns ``None``.

.. note::

   Only |oauth2| :class:`.Credentials` support refreshment but it also depends on the **provider's**
   implementation, e.g. Facebook allows you to refresh :class:`.Credentials` only if you requested the
   ``offline_access`` scope in the :doc:`/reference/config`.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 108-131

The most interesting things will happen in the *Action* handler.
Let's first create a method for ``GET`` requests which will accept the ``provider_name`` URL variable.
Inside create a simple HTML form which submits to this handler's ``POST`` method.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 134-148

In the ``POST`` method, retrieve the message from POST parameters and the values from cookies.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 150-152, 154-156

Let's first post a status to the **user's** Facebook timeline by accessing the
`Facebook Graph API <http://developers.facebook.com/docs/reference/api/>`_ endpoint.

.. note::

   You need to include the ``"publish_stream"`` scope in the ``"fb"`` section of the config
   to be able to post to the **user's** timeline.

Prepare the URL.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 158, 160

Access the **protected resource** of the **user** by calling the :meth:`.Authomatic.access` method.
You must pass it the :class:`.Credentials` (normal or serialized) and the URL.
The URL can contain query string parameters, but
you can also pass them to the method as a dictionary.
The method returns a :class:`.Response` object.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 163-165

Parse the :class:`.Response`. The :attr:`.Response.data` is a data structure (list or dictionary)
parsed from the :attr:`.Response.content` which usually is JSON.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 168-178

Do the same with Twitter.

.. note::

   You need to set the *Application Type* of your `Twitter app <https://dev.twitter.com/apps>`_
   to *Read and Write* to be able to post tweets on the **user's** behalf.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 180-203

Let the **user** repeat the action.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 206-211

The *Logout* handler is pretty simple. We just need to delete all those cookies we set
and redirect the **user** to the *Home* handler.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 214-215, 217-219, 222

Finally create routes to all those handlers,

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 226-230

and instantiate the |webapp2| WSGI application.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python
   :lines: 233

Don't forget to create the ``app.yaml`` file.

.. literalinclude:: ../../../examples/gae/credentials/app.yaml
   :language: yaml

That's it. Now just run the application.

.. code-block:: bash

   $ python dev_appserver.py [path to the root folder of this app]

.. include:: twitter-localhost.rst

And here is the complete app. Remember that you can download all the files we just created from
`GitHub <https://github.com/peterhudec/authomatic/tree/master/examples/gae/credentials>`_.

.. literalinclude:: ../../../examples/gae/credentials/main.py
   :language: python


text:
package championpicker.game;

import championpicker.champ.Champ;

import java.util.ArrayList;
import java.util.List;

public class Team {

    boolean firstPick;
    private List<Champ> picks, bans;

    public Team(boolean firstPick) {
        this.firstPick = firstPick;
        picks = new ArrayList<Champ>();
        bans = new ArrayList<Champ>();
    }

    public void addPick(Champ champ) {
        picks.add(champ);
    }

    public void addBan(Champ champ) {
        bans.add(champ);
    }

    public List<Champ> getPicks() {
        return picks;
    }

    public List<Champ> getBans() {
        return bans;
    }

    public boolean isFirstPick() {
        return firstPick;
    }

    public String toString() {
        return "picks: " + picks + "  bans: " + bans;
    }
}


text:
package bootswatchplus.common;

import java.util.ArrayList;
import java.util.List;

/**
 * Representation of a Menu, container of menuItems and subMenus.
 */
public class Menu {

  // ---- Member Variables --------------------------------------------------

  private String id;

  private List<MenuItem> menuItems;
  private List<Menu> subMenus;

  // ---- Constructors ------------------------------------------------------

  public Menu(String id) {
    this.id = id;
    this.menuItems = new ArrayList<>();
    this.subMenus = new ArrayList<>();
  }

  public Menu(String id, String[][] items) {
    this(id);

    for (String[] item : items) {
      MenuItem mi = new MenuItem(item);
      this.menuItems.add(mi);
    }
  }

  // ---- Other methods -----------------------------------------------------

  public void addMenuItem(MenuItem mi) {
    this.menuItems.add(mi);
  }

  public void addSubMenu(Menu m) {
    this.subMenus.add(m);
  }

  public void removeMenuItem(String menuItemId) {
    int index = indexOfMenuItem(menuItemId);
    if (index != -1) {
      this.menuItems.remove(index);
    }
  }

  public Menu getSubMenu(String subMenuId) {
    for (Menu m : subMenus) {
      if (m.getId().equals(subMenuId)) {
        return m;
      }
    }
    return null;
  }

  public String getId() {
    return id;
  }

  public List<MenuItem> getMenuItems() {
    return menuItems;
  }

  public List<Menu> getSubMenus() {
    return subMenus;
  }

  // ---- Bean Properties ---------------------------------------------------

  /**
   * Returns the index of the MenuItem with the specified identifier within
   * the internal list.
   *
   * Note: I have tried to override the equals method of the MenuItem to
   * match String objects, but although the equals method would return "true"
   * the list.remove method would not remove the item of the given string,
   * therefore I decided to iterate myself manually. Java bug anyone?
   */
  private int indexOfMenuItem(String menuItemId) {
    for (int i = 0; i < this.menuItems.size(); i++) {
      if (this.menuItems.get(i).getId().equals(menuItemId)) {
        return i;
      }
    }
    return -1;
  }
}


text:
 /**
  * This method counts the occurrences of Foo.
  *
  * When no more Foo ({@link http://example.com/my/bar}) are given this
  * function will add one as there must always be one Foo.
  *
  * @return integer Indicates the number of items.
  */
 function count()
 {
     <...>
 }

  /**
  * @link http://www.phpdoc.org/docs/latest/references/phpdoc/tags/link.html Documentation of Foo.
  *
  * @example example1.php Counting in action.
  * @example http://example.com/example2.phps Counting in action by a 3rd party.
  * @example "My Own Example.php" My counting.
  * @return integer Indicates the number of items.
  */
 function count()
 {
     <...>
 }


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
	<item android:state_enabled="false"  android:drawable="@drawable/segment_grey" />
	<item android:state_focused="true" android:state_checked="true" android:state_pressed="false" android:drawable="@drawable/segment_grey_focus" />
	<item android:state_focused="true" android:state_checked="false" android:state_pressed="false" android:drawable="@drawable/segment_white_focus" />

	<item android:state_pressed="true"  android:drawable="@drawable/segment_grey_press" />
	<item android:state_checked="false"  android:drawable="@drawable/segment_white" />
	<item android:drawable="@drawable/segment_grey" /> 	<!-- default  -->
</selector><!-- From: file:/Users/Breeze/Downloads/Products/Android/IntelliJ/trunk/moxtrasdk/products/ConversationSDK/src/main/res/drawable/segment_button.xml -->


text:
Photos

On the day if you take any photos or video, it would be great if you could send us a copy. If Instagramming etc, use hashtag #belanddylan.


text:
using System;
using System.Collections.Generic;
using Tracker.Data.Entities;
using Tracker.Data.Mapping;

namespace Tracker.Data
{
    public partial class TrackerContext
    {
    }
}


text:
package org.wso2.siddhi.performance;

import org.wso2.siddhi.core.ExecutionPlanRuntime;
import org.wso2.siddhi.core.SiddhiManager;
import org.wso2.siddhi.core.event.Event;
import org.wso2.siddhi.core.stream.input.InputHandler;
import org.wso2.siddhi.core.stream.output.StreamCallback;

public class SimpleFilterSingleQueryPerformance {

    public static void main(String[] args) throws InterruptedException {
        SiddhiManager siddhiManager = new SiddhiManager();

        String executionPlan = "" +
                "define stream cseEventStream (symbol string, price float, volume long, timestamp long);" +
                "" +
                "@info(name = 'query1') " +
                "from cseEventStream[700 > price] " +
                "select * " +
                "insert into outputStream ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);
        executionPlanRuntime.addCallback("outputStream", new StreamCallback() {
            public int eventCount = 0;
            public int timeSpent = 0;
            long startTime = System.currentTimeMillis();

            @Override
            public void receive(Event[] events) {
                for (Event event : events) {
                    eventCount++;
                    timeSpent += (System.currentTimeMillis() - (Long) event.getData(3));
                    if (eventCount % 1000000 == 0) {
                        System.out.println("Throughput : " + (eventCount * 1000) / ((System.currentTimeMillis()) - startTime));
                        System.out.println("Time spent :  " + (timeSpent * 1.0 / eventCount));
                        startTime = System.currentTimeMillis();
                        eventCount = 0;
                        timeSpent = 0;
                    }
                }
            }
        });

        InputHandler inputHandler = executionPlanRuntime.getInputHandler("cseEventStream");
        executionPlanRuntime.start();
        while (true) {
            inputHandler.send(new Object[]{"WSO2", 55.6f, 100, System.currentTimeMillis()});
            inputHandler.send(new Object[]{"IBM", 75.6f, 100, System.currentTimeMillis()});
            inputHandler.send(new Object[]{"WSO2", 100f, 80, System.currentTimeMillis()});
            inputHandler.send(new Object[]{"IBM", 75.6f, 100, System.currentTimeMillis()});
            inputHandler.send(new Object[]{"WSO2", 55.6f, 100, System.currentTimeMillis()});
            inputHandler.send(new Object[]{"IBM", 75.6f, 100, System.currentTimeMillis()});
            inputHandler.send(new Object[]{"WSO2", 100f, 80, System.currentTimeMillis()});
            inputHandler.send(new Object[]{"IBM", 75.6f, 100, System.currentTimeMillis()});
        }

    }
}


text:
/* eslint no-console:0 */
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb

console.log('Hello World from Webpacker')

require("trix")
require("@rails/actiontext")
require('awesomplete')

import Trix from 'trix'

Trix.config.attachments.preview.caption = { name: false, size: false }


text:
package at.fhjoanneum.ippr.eventlogger.services;

import javax.xml.transform.stream.StreamResult;
import java.util.Map;

public interface GenerateOWLService {

  StreamResult generateOWL(final String processModelName, final Map<String, String> petriNets) throws Exception;
}


text:
"use strict";

$(function() {
    fetchLocale().then(translate).then(function() {
        setMenu(false)
    }).then(function() {
        return new Promise(function(resolve, reject) {
            setTimeout(resolve, 1000)
        })
    }).then(redraw).then(populateGroups).then(function() {
        if (group === undefined) {
            addGroupPopup()
            $('#run').prop('disabled', true)
            setMenu(true)
        }
    }).then(nothing)
    $('#mask').hide()
    $('#popup').hide()

    $('#groups').change(function() {
        reloadGroup().then(setColors).then(drawGroup).then(updateGroupDisplay)
    })
})

const redraw = function() {
    return new Promise(function(resolve, reject) {
        SIZE = Math.min($('#center').width(), $('#center').height() - $('h1').eq(0).height() - $('#run').height()) - 10

        canvas = $('#wheel')
        canvas[0].width = SIZE
        canvas[0].height = SIZE
        wheel = canvas[0].getContext('2d')

        wheel.clearRect(0, 0, SIZE, SIZE)
        wheel.beginPath()
        wheel.arc(SIZE / 2, SIZE / 2, SIZE / 2 - 50, 0, 2 * Math.PI, false)
        wheel.fill()
        resolve()
    })
}

$('#proportional').change(function() {
    group.proportional = $(this).is(':checked')
    updateGroupDisplay()
    updateGroup().then(reloadGroup).then(drawGroup)
})

$('#twice-in-a-row').change(function() {
    updateGroup().then(reloadGroup).then(drawGroup)
})

$('#run').click(function() {
    setMenu(true).then(run).then(selectChoice).then(function() {
        setMenu(false)
    })
})

$('#disabled').click(function() {
    $('#group-display').slideToggle()
})

$('#reset').click(function() {
    resetPopup()
})

$('#add-group').click(function() {
    addGroupPopup()
})

$('#delete-group').click(function() {
    deleteGroupPopup()
})

const resetPopup = function() {
    openPopup(i18n.__('Reset'), i18n.__('Are you sure you want to reset?')).then(reset).then(updateGroup).then(reloadGroup).then(drawGroup)
        .then(updateGroupDisplay).catch(nothing)
}

const addGroupPopup = function() {
    $('#ok').prop('disabled', true)
    const enableOk = function() {
        if ($('#new-group-name').val().trim() == '' || $('#new-group-choices').val().trim() == '') {
            $('#ok').prop('disabled', true)
        } else {
            $('#ok').prop('disabled', false)
        }
    }

    const groupForm = $('
', {
        css: {
            display: 'flex',
            flexDirection: 'column'
        }
    })
    groupForm.append($('<input>', {
        id: 'new-group-name',
        placeholder: i18n.__('Group name'),
        size: 50,
        keyup: enableOk
    }))
    groupForm.append($('<textarea>', {
        id: 'new-group-choices',
        rows: 20,
        placeholder: i18n.__('Choices, each on a new line'),
        keyup: enableOk
    }))
    openPopup(i18n.__('Add a group'), groupForm).then(addGroup).then(function() {
        setMenu(false)
    }).catch(nothing)
}

const deleteGroupPopup = function() {
    openPopup(i18n.__('Delete the group'), i18n.__(`Are you sure you want to delete the group "{{groupName}}"?`, {
        groupName: $('#groups').val()
    })).then(function() {
        return deleteGroup($('#groups').val())
    }).catch(nothing).then(populateGroups).then(reloadGroup).then(drawGroup).catch(function() {
        group = undefined
        redraw().then(updateGroupDisplay).then(function() {
            setTimeout(addGroupPopup, 1000)
            $('#run').prop('disabled', true)
            setMenu(true)
        })
    })
}

const about = function() {
    openPopup(i18n.__('About'), `<div style="margin-bottom:30px">The Wheel of Misfortune, v${require('../package.json').version}</div><div id="license" style="white-space: pre-wrap;width:75vw;"></div>`).then(nothing).catch(nothing)
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. Reg. 12: t. 964. 1826

#### Original name
null

### Remarks
null


text:
namespace TroutStreamMangler.US
{
    public class CensusFipsCodes
    {
        private string _state;
        private int _fipsCounty;
        private int _fipsState;
        private string _countyName;

        public string State
        {
            get { return _state.Trim(); }
            set { _state = value; }
        }

        public string County_Name
        {
            get { return _countyName.Trim(); }
            set { _countyName = value; }
        }

        public int FIPS_State
        {
            get { return _fipsState; }
            set { _fipsState = value; }
        }

        public int FIPS_County
        {
            get { return _fipsCounty; }
            set { _fipsCounty = value; }
        }
    }
}


text:
namespace Nz
{
	class NAZARA_PLATFORM_API Clipboard
	{
		public:
			Clipboard() = delete;
			~Clipboard() = delete;

			static ClipboardContentType GetContentType();
			static std::string GetString();
			static void SetString(const std::string& str);
	};
}

#include <Nazara/Platform/Clipboard.inl>

#endif // NAZARA_PLATFORM_CLIPBOARD_HPP


text:
module.exports = function(dir) {
  var res;
  res = require("./src/a/data.json");
  var filename = res;
  res = require("./src/b/data.json");
  if(filename !== res) return '"'+filename+'" not equal "'+res+'"';
  res = require("./src/c/target.json");
  if(filename !== res) return '"'+filename+'" not equal "'+res+'"';
  return 'ok';
};


text:
using System;
using System.CodeDom.Compiler;
using System.Configuration;
using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace PresentationAssistant.GlobalZoom.Properties
{
	[GeneratedCode("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0"), CompilerGenerated]
	internal sealed class Settings : ApplicationSettingsBase
	{
		private static Settings defaultInstance = (Settings)SettingsBase.Synchronized(new Settings());
		public static Settings Default
		{
			get
			{
				return Settings.defaultInstance;
			}
		}
		[DefaultSettingValue("100"), UserScopedSetting, DebuggerNonUserCode]
		public double LastZoomLevel
		{
			get
			{
				return (double)this["LastZoomLevel"];
			}
			set
			{
				this["LastZoomLevel"] = value;
			}
		}
		[DefaultSettingValue("20"), UserScopedSetting, DebuggerNonUserCode]
		public double MinZoomLevel
		{
			get
			{
				return (double)this["MinZoomLevel"];
			}
			set
			{
				this["MinZoomLevel"] = value;
			}
		}
		[DefaultSettingValue("400"), UserScopedSetting, DebuggerNonUserCode]
		public double MaxZoomLevel
		{
			get
			{
				return (double)this["MaxZoomLevel"];
			}
			set
			{
				this["MaxZoomLevel"] = value;
			}
		}
	}
}


text:
package org.apache.phoenix.index;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.phoenix.hbase.index.ValueGetter;
import org.apache.phoenix.hbase.index.builder.BaseIndexCodec;
import org.apache.phoenix.hbase.index.covered.IndexCodec;
import org.apache.phoenix.hbase.index.covered.IndexMetaData;
import org.apache.phoenix.hbase.index.covered.IndexUpdate;
import org.apache.phoenix.hbase.index.covered.TableState;
import org.apache.phoenix.hbase.index.covered.update.ColumnReference;
import org.apache.phoenix.hbase.index.util.GenericKeyValueBuilder;
import org.apache.phoenix.hbase.index.util.KeyValueBuilder;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

/**
 * Phoenix-based {@link IndexCodec}. Manages all the logic of how to cleanup an index (
 * {@link #getIndexDeletes(TableState, IndexMetaData)}) as well as what the new index state should be (
 * {@link #getIndexUpserts(TableState, IndexMetaData)}).
 */
public class PhoenixIndexCodec extends BaseIndexCodec {
    public static final String INDEX_MD = "IdxMD";
    public static final String INDEX_PROTO_MD = "IdxProtoMD";
    public static final String INDEX_UUID = "IdxUUID";
    public static final String INDEX_MAINTAINERS = "IndexMaintainers";
    private static KeyValueBuilder KV_BUILDER = GenericKeyValueBuilder.INSTANCE;

    private RegionCoprocessorEnvironment env;

    @Override
    public void initialize(RegionCoprocessorEnvironment env) throws IOException {
        super.initialize(env);
        this.env = env;
    }

    boolean hasIndexMaintainers(Map<String, byte[]> attributes) {
        if (attributes == null) { return false; }
        byte[] uuid = attributes.get(INDEX_UUID);
        if (uuid == null) { return false; }
        return true;
    }

    @Override
    public Iterable<IndexUpdate> getIndexUpserts(TableState state, IndexMetaData context) throws IOException {
        PhoenixIndexMetaData metaData = (PhoenixIndexMetaData)context;
        List<IndexMaintainer> indexMaintainers = metaData.getIndexMaintainers();
        if (indexMaintainers.get(0).isRowDeleted(state.getPendingUpdate())) {
            return Collections.emptyList();
        }
        ImmutableBytesWritable ptr = new ImmutableBytesWritable();
        ptr.set(state.getCurrentRowKey());
        List<IndexUpdate> indexUpdates = Lists.newArrayList();
        for (IndexMaintainer maintainer : indexMaintainers) {
            Pair<ValueGetter, IndexUpdate> statePair = state.getIndexUpdateState(maintainer.getAllColumns(), metaData.ignoreNewerMutations(), false);
            ValueGetter valueGetter = statePair.getFirst();
            IndexUpdate indexUpdate = statePair.getSecond();
            indexUpdate.setTable(maintainer.isLocalIndex() ? state.getEnvironment().getRegion()
                    .getTableDesc().getName() : maintainer.getIndexTableName());
            Put put = maintainer.buildUpdateMutation(KV_BUILDER, valueGetter, ptr, state.getCurrentTimestamp(), env
                    .getRegion().getRegionInfo().getStartKey(), env.getRegion().getRegionInfo().getEndKey());
            indexUpdate.setUpdate(put);
            indexUpdates.add(indexUpdate);
        }
        return indexUpdates;
    }

    @Override
    public Iterable<IndexUpdate> getIndexDeletes(TableState state, IndexMetaData context) throws IOException {
        PhoenixIndexMetaData metaData = (PhoenixIndexMetaData)context;
        List<IndexMaintainer> indexMaintainers = metaData.getIndexMaintainers();
        ImmutableBytesWritable ptr = new ImmutableBytesWritable();
        ptr.set(state.getCurrentRowKey());
        List<IndexUpdate> indexUpdates = Lists.newArrayList();
        for (IndexMaintainer maintainer : indexMaintainers) {
            // For transactional tables, we use an index maintainer
            // to aid in rollback if there's a KeyValue column in the index. The alternative would be
            // to hold on to all uncommitted index row keys (even ones already sent to HBase) on the
            // client side.
            Set<ColumnReference> cols = Sets.newHashSet(maintainer.getAllColumns());
            cols.add(new ColumnReference(indexMaintainers.get(0).getDataEmptyKeyValueCF(), indexMaintainers.get(0).getEmptyKeyValueQualifier()));
            Pair<ValueGetter, IndexUpdate> statePair = state.getIndexUpdateState(cols, metaData.ignoreNewerMutations(), true);
            ValueGetter valueGetter = statePair.getFirst();
            if (valueGetter!=null) {
                IndexUpdate indexUpdate = statePair.getSecond();
                indexUpdate.setTable(maintainer.isLocalIndex() ? state.getEnvironment().getRegion()
                        .getTableDesc().getName() : maintainer.getIndexTableName());
                Delete delete = maintainer.buildDeleteMutation(KV_BUILDER, valueGetter, ptr, state.getPendingUpdate(),
                        state.getCurrentTimestamp(), env.getRegion().getRegionInfo().getStartKey(), env.getRegion().getRegionInfo().getEndKey());
                indexUpdate.setUpdate(delete);
                indexUpdates.add(indexUpdate);
            }
        }
        return indexUpdates;
    }

    @Override
    public boolean isEnabled(Mutation m) throws IOException {
        return hasIndexMaintainers(m.getAttributesMap());
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>net.sf.jasperreports.data.qe (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

net.sf.jasperreports.data.qe

Interfaces

QueryExecuterDataAdapter

Classes

QueryExecuterDataAdapterImpl

QueryExecuterDataAdapterService


text:
space-invaders
Have spent a lot of time on this project trying to understand the workings behind coding and design and how they relate with a player for a game. I have spent time commenting carefully on the code to ensure I understand it and making slight changes to the game to help me with practise.

==============


text:
package fi.helsinki.cs.tmc.intellij.snapshots;

import fi.helsinki.cs.tmc.core.domain.Exercise;
import fi.helsinki.cs.tmc.core.utilities.JsonMaker;
import fi.helsinki.cs.tmc.intellij.services.ClipboardService;
import fi.helsinki.cs.tmc.intellij.services.ObjectFinder;
import fi.helsinki.cs.tmc.intellij.services.PathResolver;
import fi.helsinki.cs.tmc.intellij.services.exercises.CourseAndExerciseManager;
import fi.helsinki.cs.tmc.snapshots.*;

import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;

import name.fraser.neil.plaintext.DiffMatchPatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * When a change in the listened document happens this class creates a diff patch. That created
 * patch is then analyzed and a json is generated from it that is added to the list of items to be
 * sent to the snapshots server.
 */
public class TextInputListener implements DocumentListener {

    private static final Logger logger = LoggerFactory.getLogger(TextInputListener.class);

    private final DiffMatchPatch diff = new DiffMatchPatch();
    private String previous;
    private String modified;

    @Override
    public void beforeDocumentChange(DocumentEvent documentEvent) {
        previous = documentEvent.getDocument().getText();
    }

    @Override
    public void documentChanged(DocumentEvent documentEvent) {
        modified = documentEvent.getDocument().getText();
        if (!isThisCorrectProject() || changeIsNotJustWhitespace(documentEvent)) {
            logger.info(
                    "not creating path for event, as project wasn't "
                            + "correct one or change was just white space");
            return;
        }

        logger.info("Creating patches for ", documentEvent.getSource());
        createPatches(
                PathResolver.getExercise(new ObjectFinder().findCurrentProject().getBasePath()),
                documentEvent);
    }

    private boolean isThisCorrectProject() {
        return new CourseAndExerciseManager()
                .isCourseInDatabase(
                        PathResolver.getCourseName(
                                new ObjectFinder().findCurrentProject().getBasePath()));
    }

    private boolean changeIsNotJustWhitespace(DocumentEvent documentEvent) {
        return !documentEvent.getNewFragment().toString().trim().isEmpty()
                || !documentEvent.getOldFragment().toString().trim().isEmpty();
    }

    private void createPatches(Exercise exercise, DocumentEvent documentEvent) {
        List<DiffMatchPatch.Patch> patches;
        patches = diff.patch_make(previous, modified);

        if (isRemoveEvent(documentEvent)) {
            addEventToManager(
                    exercise, "text_remove", generatePatchDescription(documentEvent, patches));
        } else if (isPasteEvent(documentEvent)) {
            addEventToManager(
                    exercise, "text_paste", generatePatchDescription(documentEvent, patches));
        } else {
            addEventToManager(
                    exercise, "text_insert", generatePatchDescription(documentEvent, patches));
        }
    }

    private boolean isPasteEvent(DocumentEvent documentEvent) {
        if (ClipboardService.getClipBoard() == null) {
            return false;
        }
        return (documentEvent.getNewLength() > 2)
                && ClipboardService.getClipBoard()
                        .trim()
                        .equals(documentEvent.getNewFragment().toString().trim());
    }

    private String generatePatchDescription(
            DocumentEvent documentEvent, List<DiffMatchPatch.Patch> patches) {

        logger.info("Creating JSON from patches.");
        String source = documentEvent.getSource().toString();

        if (documentEvent.getSource().toString().length() <= 20) {
            return null;
        }

        source = source.substring(20, source.length() - 1);
        return JsonMaker.create()
                .add("file", new PathResolver().getPathRelativeToProject(source))
                .add("patches", diff.patch_toText(patches))
                .add(
                        "full_document",
                        documentEvent.getNewLength() == documentEvent.getDocument().getTextLength())
                .toString();
    }

    private boolean isRemoveEvent(DocumentEvent documentEvent) {
        return (documentEvent.getOldLength() > 0 && documentEvent.getNewLength() == 0);
    }

    private void addEventToManager(Exercise exercise, String eventType, String text) {
        if (text == null) {
            return;
        }

        LoggableEvent event = new LoggableEvent(exercise, eventType, text.getBytes());
        SnapshotsEventManager.add(event);
    }
}


text:
package ch.epfl.data.squall.examples.imperative.debug;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import ch.epfl.data.squall.components.DataSourceComponent;
import ch.epfl.data.squall.expressions.ColumnReference;
import ch.epfl.data.squall.expressions.ValueSpecification;
import ch.epfl.data.squall.operators.ProjectOperator;
import ch.epfl.data.squall.operators.SelectOperator;
import ch.epfl.data.squall.predicates.ComparisonPredicate;
import ch.epfl.data.squall.query_plans.QueryBuilder;
import ch.epfl.data.squall.query_plans.QueryPlan;
import ch.epfl.data.squall.types.DateType;
import ch.epfl.data.squall.types.IntegerType;
import ch.epfl.data.squall.types.Type;

public class HyracksL1SelectDatePlan extends QueryPlan {
    private static Logger LOG = Logger.getLogger(HyracksL1SelectDatePlan.class);

    private final QueryBuilder _queryBuilder = new QueryBuilder();

    private static final IntegerType _ic = new IntegerType();
    private static final Type<Date> _dc = new DateType();
    private static final Date _dateConst = _dc.fromString("1954-01-01");

    public HyracksL1SelectDatePlan(String dataPath, String extension, Map conf) {
	// -------------------------------------------------------------------------------------
	// start of query plan filling
	// the selections are no-ops
	final SelectOperator selCustomer = new SelectOperator(
		new ComparisonPredicate(ComparisonPredicate.GREATER_OP,
			new ColumnReference(_ic, 0), new ValueSpecification(_ic, -1)));
	final SelectOperator selOrders = new SelectOperator(
		new ComparisonPredicate(ComparisonPredicate.GREATER_OP,
			new ColumnReference(_dc, 4), new ValueSpecification(_dc, _dateConst)));

	final ProjectOperator projectionCustomer = new ProjectOperator(0, 6);
	final List<Integer> hashCustomer = Arrays.asList(0);
	DataSourceComponent relationCustomer = new DataSourceComponent("customer", conf)
		.add(selCustomer)
		.add(projectionCustomer)
		.setOutputPartKey(hashCustomer)
		.setPrintOut(false);
	_queryBuilder.add(relationCustomer);

	// -------------------------------------------------------------------------------------
	final ProjectOperator projectionOrders = new ProjectOperator(1);
	final List<Integer> hashOrders = Arrays.asList(0);
	DataSourceComponent relationOrders = new DataSourceComponent("orders", conf)
		.add(selOrders)
		.add(projectionOrders)
		.setOutputPartKey(hashOrders)
		.setPrintOut(false);
	_queryBuilder.add(relationOrders);

    }

    @Override
    public QueryBuilder getQueryPlan() {
	return _queryBuilder;
    }

}


text:
typedef enum {STATE_UNOPENED, STATE_OPEN, STATE_CLOSED} State;

struct AudioSink {
  int n_refs;
  GstElement *pipe, *source;
  State state;
  int n_channels;
};

static void open(AudioSink *sink) {
  unsigned int endianness_test_int = 1;
  bool big_endian = ((char*) &endianness_test_int)[0] == 0;
  char const *format = big_endian ? "F32BE" : "F32LE";
  char const *layout = "interleaved";

  GstElement *pipe = gst_pipeline_new("pipe");
  GstElement *source = gst_element_factory_make("appsrc", NULL);
  GstElement *resampler = gst_element_factory_make("audioresample", NULL);
  GstElement *adapter = gst_element_factory_make("audioconvert", NULL);
  GstElement *gst_sink = gst_element_factory_make("autoaudiosink", NULL);
  GstCaps *caps = gst_caps_new_simple("audio/x-raw",
				      "rate", G_TYPE_INT, AUDIO_SAMPLE_RATE,
				      "channels", G_TYPE_INT, sink->n_channels,
				      "format", G_TYPE_STRING, format,
				      "layout", G_TYPE_STRING, layout,
				      NULL);

  g_object_set(source, "caps", caps, NULL);
  g_object_set(source, "block", true, NULL);
  g_object_set(source, "max-bytes", 1, NULL);
  g_object_set(source, "format", GST_FORMAT_TIME, NULL);
  gst_bin_add_many(GST_BIN(pipe), source, resampler, adapter, gst_sink, NULL);
  gst_element_link_many(source, resampler, adapter, gst_sink, NULL);
  gst_element_set_state(pipe, GST_STATE_PLAYING);
  gst_caps_unref(caps);

  sink->source = source;
  sink->pipe = pipe;
}

AudioSink *audio_sink_create() {
  gst_init(NULL, NULL);
  int n_bytes = sizeof(AudioSink);
  AudioSink *sink = (AudioSink*) malloc(n_bytes);
  sink->n_refs = 1;
  sink->state = STATE_UNOPENED;
  sink->source = NULL;
  sink->pipe = NULL;
  sink->n_channels = 0;
  return sink;
 }

void audio_sink_acquire(AudioSink *sink) {
  if (sink)
    sink->n_refs++;
}

void audio_sink_release(AudioSink *sink) {
  if (sink)
    sink->n_refs--;
  if (sink && !sink->n_refs) {
    audio_sink_close(sink);
    free(sink);
  }
}

void audio_sink_close(AudioSink *sink) {
  if (sink->state == STATE_OPEN) {
    sink->state = STATE_CLOSED;
    gst_element_set_state(sink->pipe, GST_STATE_NULL);
    gst_object_unref(sink->pipe);
  }
}

void audio_sink_write(AudioSink *sink, Sound *clip) {
  int n_samples = sound_get_n_samples(clip);
  int n_channels = sound_get_n_channels(clip);

  if (sink->state == STATE_UNOPENED) {
    assert(n_channels == 1 || n_channels == 2);
    sink->n_channels = n_channels;
    sink->state = STATE_OPEN;
    open(sink);
  }
  else {
    assert(sink->state == STATE_OPEN);
    assert(n_channels == sink->n_channels);
  }

  int n_bytes = n_samples * n_channels * sizeof(float);
  float *i_data = sound_get_data(clip);
  float *o_data = (float*) malloc(n_bytes);
  memcpy(o_data, i_data, n_bytes);

  GstBuffer *buffer;
  GstFlowReturn flow_result;
  buffer = gst_buffer_new_wrapped(o_data, n_bytes);
  g_signal_emit_by_name(sink->source, "push-buffer", buffer, &flow_result);
  gst_buffer_unref(buffer);
}


text:
@class FRZDatabase;

// The type of change made.
//   FRZChangeTypeAdd    - A new value was added.
//   FRZChangeTypeRemove - An existing value was removed.
typedef enum : NSInteger {
	FRZChangeTypeAdd,
	FRZChangeTypeRemove,
} FRZChangeType;

// A change that was applied to a store.
@interface FRZChange : NSObject <NSCopying>

// The type of the change.
@property (nonatomic, readonly, assign) FRZChangeType type;

// The ID which was changed.
@property (nonatomic, readonly, copy) NSString *ID;

// The key which was changed.
@property (nonatomic, readonly, copy) NSString *key;

// The value which was added or removed.
@property (nonatomic, readonly, strong) id delta;

// The database before the change was applied. This may be nil if the addition
// was the first value added to the store.
@property (atomic, readonly, copy) FRZDatabase *previousDatabase;

// The database after the change was applied.
@property (atomic, readonly, copy) FRZDatabase *changedDatabase;

// Initializes the receiver with the given properties.
//
// type             - The type of change.
// ID               - The ID whose value of key was changed. Cannot be nil.
// key              - The key whose value was changed. Cannot be nil.
// delta            - The delta for the change. Cannot be nil.
// previousDatabase - The database before the change. May be nil.
// changedDatabase  - The database after the change. Cannot be nil.
//
// Returns the initialized object.
- (id)initWithType:(FRZChangeType)type ID:(NSString *)ID key:(NSString *)key delta:(id)delta previousDatabase:(FRZDatabase *)previousDatabase changedDatabase:(FRZDatabase *)changedDatabase;

@end


text:
package com.meisolsson.githubsdk.service.organizations;

import com.meisolsson.githubsdk.model.Page;
import com.meisolsson.githubsdk.model.User;
import com.meisolsson.githubsdk.model.request.organization.EditOrganization;

import io.reactivex.Single;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.PATCH;
import retrofit2.http.Path;
import retrofit2.http.Query;

public interface OrganizationService {

    @GET("/user/orgs")
    Single<Response<Page<User>>> getMyOrganizations(@Query("page") long page);

    @GET("/organizations")
    Single<Response<Page<User>>> getAllOrganizations(@Query("page") long page);

    @GET("users/{username}/orgs")
	Single<Response<Page<User>>> getUserPublicOrganizations(@Path("username") String username, @Query("page") long page);

    @GET("orgs/{org}")
	Single<Response<Page<User>>> getOrganization(@Path("org") String org, @Query("page") long page);

    @PATCH("orgs/{org}")
	Single<Response<User>> editOrganization(@Path("org") String org, @Body EditOrganization body);

}


text:
	* After you create a new model.json and model.js file remember to update model-config.json
	* The name in the model-config.json file needs to be identical to the name in the model.json file

### Endpoints
	* If you create a new remote method using Model.remoteMethod remember to update component-config.json `loopback-component-jsonapi` with the name of the remote method


text:
import rethinkdb as r
from optparse import OptionParser
import sys
import json

def main(port, process_id):
    conn = r.connect("localhost", port, db="samplesdb")
    value = list(r.table("processes").get_all(process_id)
                 .eq_join("id", r.table("process2sample"), index="process_id")
                 .zip()
                 .eq_join("attribute_set_id", r.table("sample2attribute_set"),
                          index="attribute_set_id")
                 .zip()
                 .merge(lambda aset: {
                     "attributes": r.table("attribute_set2attribute")
                     .get_all(aset["attribute_set_id"],
                              index="attribute_set_id")
                     .eq_join("attribute_id", r.table("attributes"))
                     .zip()
                     .merge(lambda attr: {
                         "best_measure": r.table("measurements")
                         .get(attr["best_measure_id"]),
                         "history": r.table("best_measure_history")
                         .get_all(attr["id"], index="attribute_id")
                         .merge(lambda best: {
                             "measurement": r.table("measurements")
                             .get(best["measurement_id"]).default("")
                         })
                         .coerce_to("array"),
                         "measurements": r.table("attribute2measurement")
                         .get_all(attr["id"], index="attribute_id")
                         .eq_join("measurement_id", r.table("measurements"))
                         .zip()
                         .coerce_to("array")
                     })
                     .coerce_to("array")
                 })
                 .run(conn, time_format="raw"))
    print json.dumps(value[0])

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-P", "--port", dest="port", type="int",
                      help="rethinkdb port", default=30815)
    parser.add_option("-p", "--process", dest="process",
                      help="process id")
    (options, args) = parser.parse_args()
    if options.process is None:
        print "You must specify a process id"
        sys.exit(1)
    main(options.port, options.process)


text:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <stroke
      android:color="#2b2b2b"
      android:width="2dp" />
</shape>


text:
/* $Id$ */

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.manifoldcf.crawler.connectors.cmis;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.Property;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService;
import org.apache.chemistry.opencmis.client.bindings.spi.atompub.AtomPubParser;
import org.apache.chemistry.opencmis.commons.PropertyIds;
import org.apache.chemistry.opencmis.commons.definitions.PropertyDefinition;
import org.apache.chemistry.opencmis.commons.enums.Cardinality;
import org.apache.chemistry.opencmis.commons.enums.PropertyType;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.manifoldcf.agents.interfaces.RepositoryDocument;
import org.apache.manifoldcf.core.interfaces.ManifoldCFException;
import org.apache.manifoldcf.crawler.system.Logging;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;

/**
 *
 * @author Piergiorgio Lucidi
 *
 */
public class CmisRepositoryConnectorUtils {

    private static final String LOAD_LINK_METHOD_NAME = "loadLink";
    private static final String FROM_TOKEN = "from";
    private static final String SEP = " ";
    private static final String SELECT_STAR_CLAUSE = "select *";
    private static final String OBJECT_ID_TERM = PropertyIds.OBJECT_ID + ",";
    private static final String SELECT_CLAUSE_TERM_SEP = ",";
    private static final String SELECT_PREFIX = "select ";
    private final static String TOKENIZER_SEP = ",\n\t";
    public static final String SLASH = "/";

    public static final String getDocumentURL(final Document document, final Session session)
            throws ManifoldCFException {

    		String link = null;
        try {
            Method loadLink = AbstractAtomPubService.class.getDeclaredMethod(LOAD_LINK_METHOD_NAME,
                    new Class[]{String.class, String.class, String.class, String.class});

            loadLink.setAccessible(true);

            link = (String) loadLink.invoke(session.getBinding().getObjectService(), session.getRepositoryInfo().getId(),
                    document.getId(), AtomPubParser.LINK_REL_CONTENT, null);
        } catch (Exception e) {
            Logging.connectors.error(
                    "CMIS: Error during getting the content stream url: "
                    + e.getMessage(), e);
            throw new ManifoldCFException(e.getMessage(), e);
        }

        return link;
    }

    /**
     * Utility method to consider the objectId whenever it is not present in the select clause
     * @param cmisQuery
     * @return the cmisQuery with the cmis:objectId property added in the select clause
     */
    public static String getCmisQueryWithObjectId(String cmisQuery) {
        String cmisQueryResult = StringUtils.EMPTY;
        String selectClause = getSelectClause(cmisQuery);
        if (selectClause.equalsIgnoreCase(SELECT_STAR_CLAUSE)) {
            cmisQueryResult = cmisQuery;
        } else {
            //get the select term and add the cmis:objectId term or prefix.cmis:objectId
            StringTokenizer selectClauseTokenized = new StringTokenizer(selectClause.trim());
            boolean firstTermSelectClause = true;
            String selectTerm = StringUtils.EMPTY;
            String prefix = StringUtils.EMPTY;
            boolean foundObjIdClause = false;
            boolean foundPrefixClause = false;
            while (selectClauseTokenized.hasMoreElements()) {
                String term = selectClauseTokenized.nextToken();
                if (firstTermSelectClause) {
                    selectTerm = term;
                    firstTermSelectClause = false;
                } else {
                    if (term.contains(PropertyIds.OBJECT_ID)){
                        foundObjIdClause = true;
                        cmisQueryResult = cmisQuery;
                        break;
                    }
                    //if a term use a prefix table, get the prefix
                    if (!foundPrefixClause && term.contains(".")){
                        int i = term.indexOf(".");
                        prefix = term.substring(0,i);
                        foundPrefixClause = true;
                    }
                }
            }
            // if the cmis:objectId term is not found, add it
            if (!foundObjIdClause) {
                String toReplace = selectTerm + " ";
                if (foundPrefixClause) {
                    toReplace += prefix + "." + OBJECT_ID_TERM;
                } else {
                    toReplace += OBJECT_ID_TERM;
                }
                cmisQueryResult = StringUtils.replaceOnce(cmisQuery, selectTerm, toReplace);
            }
        }
        return cmisQueryResult;
    }

  /**
   * Utility method to understand if a property must be indexed or not
   * @param cmisQuery
   * @param propertyId
   * @return TRUE if the property is included in the select clause of the query, otherwise it will return FALSE
   */
  public static boolean existsInSelectClause(String cmisQuery, String propertyId) {
        String selectClause = getSelectClause(cmisQuery);
        if (selectClause.toLowerCase(Locale.ROOT).startsWith(SELECT_STAR_CLAUSE)) {
            return true;
        } else {
            StringTokenizer cmisQueryTokenized = new StringTokenizer(cmisQuery.trim());
            while (cmisQueryTokenized.hasMoreElements()) {
                String term = cmisQueryTokenized.nextToken();
                if (!term.equalsIgnoreCase(FROM_TOKEN)) {
                    if (term.equalsIgnoreCase(propertyId)) {
                        return true;
                    } else if (StringUtils.contains(term, SELECT_CLAUSE_TERM_SEP)) {
                        //in this case means that we have: select cmis:objectId,cmis:name from ...
                        StringTokenizer termsTokenized = new StringTokenizer(term, SELECT_CLAUSE_TERM_SEP);
                        while (termsTokenized.hasMoreElements()) {
                            String termTokenized = termsTokenized.nextToken().trim();
                            if (termTokenized.equalsIgnoreCase(propertyId)) {
                                return true;
                            }
                        }
                    }
                } else {
                    break;
                }
            }
            return false;
        }
    }

    /**
     * @param rd : object that contains the properties to pass to connector
     * @param cmisQuery : cmis query
     */
    public static void addValuesOfProperties(Document document, RepositoryDocument rd, String cmisQuery) {
    		if(document.getPaths() != null) {
    			List<String> sourcePath = document.getPaths();
    			rd.setSourcePath(sourcePath);
    		}

    		List<Property<?>> props = document.getProperties();
        Map<String, String> cmisQueryColumns = CmisRepositoryConnectorUtils.getSelectMap(cmisQuery);
        boolean isWildcardQuery = CmisRepositoryConnectorUtils.isWildcardQuery(cmisQuery);
        addValuesOfProperty(props, isWildcardQuery, cmisQueryColumns, rd);
    }

    /**
     * @param props : list properties of a document
     * @param isWildcardQuery : if the query select is of type '*'
     * @param cmisQueryColumns : selectors query
     * @param rd : object that contains the properties to pass to connector
     */
    public static void addValuesOfProperty(final List<Property<?>> props, final boolean isWildcardQuery, final Map<String, String> cmisQueryColumns, RepositoryDocument rd) {

        for (Property<?> property : props) {
            String propertyId = property.getId();
            if (isWildcardQuery || cmisQueryColumns.containsKey(propertyId)) {
                try {
                    addPropertyValue(property, rd);
                } catch (Exception e) {
                    Logging.connectors.error("Error when adding property[" + propertyId + "] msg=[" + e.getMessage() + "]", e);
                }

            }
        }
    }

    /**
     * @param property : the property
     * @param rd : object to which we add the association property -> value
     * @throws Exception
     *
     */
    private static void addPropertyValue(Property<?> property, RepositoryDocument rd) throws Exception {

        DateTimeFormatter format = ISODateTimeFormat.dateTime();
        PropertyDefinition<?> propertyDefinitionType = property.getDefinition();
        PropertyType propertyType = propertyDefinitionType.getPropertyType();
        boolean isMultiValue = (propertyDefinitionType.getCardinality() == Cardinality.MULTI);
        String currentProperty = property.getId();

        switch (propertyType) {

            case STRING:
            case ID:
            case URI:
            case HTML:
                List<String> listValues = (List<String>) property.getValues();
                if (!CollectionUtils.isEmpty(listValues)) {
                    if (isMultiValue) {
                        for (String htmlPropertyValue : listValues) {
                            rd.addField(currentProperty, htmlPropertyValue);
                        }
                    } else {
                        String stringValue = (String) listValues.get(0);
                        if (StringUtils.isNotEmpty(stringValue)) {
                            rd.addField(currentProperty, stringValue);
                        }
                    }
                }
                break;

            case BOOLEAN:
                List<Boolean> booleanPropertyValues = (List<Boolean>) property.getValues();
                if (!CollectionUtils.isEmpty(booleanPropertyValues)) {
                    if (isMultiValue) {
                        for (Boolean booleanPropertyValue : booleanPropertyValues) {
                            rd.addField(currentProperty, booleanPropertyValue.toString());
                        }
                    } else {
                        Boolean booleanValue = (Boolean) booleanPropertyValues.get(0);
                        if (booleanValue != null) {
                            rd.addField(currentProperty, booleanValue.toString());
                        }
                    }
                }
                break;

            case INTEGER:
                List<BigInteger> integerPropertyValues = (List<BigInteger>) property.getValues();
                if (!CollectionUtils.isEmpty(integerPropertyValues)) {
                    if (isMultiValue) {
                        for (BigInteger integerPropertyValue : integerPropertyValues) {
                            rd.addField(currentProperty, integerPropertyValue.toString());
                        }
                    } else {
                        BigInteger integerValue = (BigInteger) integerPropertyValues.get(0);
                        if (integerValue != null) {
                            rd.addField(currentProperty, integerValue.toString());
                        }
                    }
                }
                break;

            case DECIMAL:
                List<BigDecimal> decimalPropertyValues = (List<BigDecimal>) property.getValues();
                if (!CollectionUtils.isEmpty(decimalPropertyValues)) {
                    if (isMultiValue) {
                        for (BigDecimal decimalPropertyValue : decimalPropertyValues) {
                            rd.addField(currentProperty, decimalPropertyValue.toString());
                        }
                    } else {
                        BigDecimal decimalValue = (BigDecimal) decimalPropertyValues.get(0);
                        if (decimalValue != null) {
                            rd.addField(currentProperty, decimalValue.toString());
                        }
                    }
                }
                break;

            case DATETIME:
                List<GregorianCalendar> datePropertyValues = (List<GregorianCalendar>) property.getValues();
                if (!CollectionUtils.isEmpty(datePropertyValues)) {
                    if (isMultiValue) {
                        for (GregorianCalendar datePropertyValue : datePropertyValues) {
                            rd.addField(currentProperty, format.print(datePropertyValue.getTimeInMillis()));
                        }
                    } else {
                        GregorianCalendar dateValue = (GregorianCalendar) datePropertyValues.get(0);
                        if (dateValue != null) {
                            rd.addField(currentProperty, format.print(dateValue.getTimeInMillis()));
                        }
                    }
                }
                break;

            default:
                break;
        }
    }

    private static String getSelectClause(String cmisQuery) {
        StringTokenizer cmisQueryTokenized = new StringTokenizer(cmisQuery.trim());
        String selectClause = StringUtils.EMPTY;
        boolean firstTerm = true;
        while (cmisQueryTokenized.hasMoreElements()) {
            String term = cmisQueryTokenized.nextToken();
            if (!term.equalsIgnoreCase(FROM_TOKEN)) {
                if (firstTerm) {
                    selectClause += term;
                    firstTerm = false;
                } else {
                    selectClause += SEP + term;
                }

            } else {
                break;
            }
        }
        return selectClause;
    }

    //create a map with the field term and the alias (if present)
    public static Map<String, String> getSelectMap(String cmisQuery) {
        Map<String, String> cmisQueryColumns = new HashMap<>();
        String selectClause = getSelectClause(cmisQuery.trim());

        StringTokenizer cmisQueryTokenized = new StringTokenizer(selectClause.substring(SELECT_PREFIX.length()), TOKENIZER_SEP);
        while (cmisQueryTokenized.hasMoreElements()) {
            String term = cmisQueryTokenized.nextToken();
            ColumnSet column = getColumnName(term);
            cmisQueryColumns.put(column.getName(), column.getAlias());
        }
        return cmisQueryColumns;
    }

    //get a columset object given a term of the select clause
    private static ColumnSet getColumnName(String orig) {
        final String sep = " as ";
        final int sepLen = sep.length();
        String justColumnName = null;
        String alias = null;

        if (orig == null) {
            return null;
        }

        justColumnName = orig.trim();

        int idx = orig.indexOf(sep);
        if (idx < 0) {
            idx = orig.indexOf(sep.toUpperCase(Locale.ROOT));
        }

        if (idx > 1) {
            alias = orig.substring(idx + sepLen).trim();
            justColumnName = orig.substring(0, idx).trim();
        }

        // Now we identify the column name and the prefix as alias if it's null,
        idx = justColumnName.indexOf(".");
        if(idx > 0){
            justColumnName = justColumnName.substring(idx + 1);
        }

        if (alias == null) {
            alias = justColumnName;
        }

        return new ColumnSet(justColumnName, alias);
    }

    //check if the query is a select *
    public static boolean isWildcardQuery(String selectClause) {
        return selectClause.toLowerCase(Locale.ROOT).startsWith(SELECT_STAR_CLAUSE);
    }
}


text:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { LoadingPageModule, MaterialBarModule } from 'angular-loading-page';

import { AppRoutingModule } from './app-routing.module';

import { LayoutModule, BoxModule } from 'angular-admin-lte';
import { adminLteConf } from './admin-lte.conf';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent
  ],
  imports: [
    AppRoutingModule,
    HttpClientModule,
    BrowserModule,
    BoxModule,
    LoadingPageModule, MaterialBarModule,
    LayoutModule.forRoot(adminLteConf),
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}


text:
#ifndef _MACH_O_DYLD_PRIV_H_
#define _MACH_O_DYLD_PRIV_H_

#include <stdbool.h>
#include <Availability.h>
#include <mach-o/dyld.h>
#include <mach-o/dyld_images.h>

#if __cplusplus
extern "C" {
#endif /* __cplusplus */

//
// private interface between libSystem.dylib and dyld
//
extern int _dyld_func_lookup(const char* dyld_func_name, void **address);

//
// _dyld_moninit() is a private interface between libSystem.dylib and dyld
//
extern void _dyld_moninit(void (*monaddition)(char *lowpc, char *highpc));

//
// private interface between libSystem.dylib and dyld
//
extern void _dyld_fork_child();

//
// Possible state changes for which you can register to be notified
//
enum dyld_image_states
{
	dyld_image_state_mapped					= 10,		// No batch notification for this
	dyld_image_state_dependents_mapped		= 20,		// Only batch notification for this
	dyld_image_state_rebased				= 30,
	dyld_image_state_bound					= 40,
	dyld_image_state_dependents_initialized	= 45,		// Only single notification for this
	dyld_image_state_initialized			= 50,
	dyld_image_state_terminated				= 60		// Only single notification for this
};

//
// Callback that provides a bottom-up array of images
// For dyld_image_state_[dependents_]mapped state only, returning non-NULL will cause dyld to abort loading all those images
// and append the returned string to its load failure error message. dyld does not free the string, so
// it should be a literal string or a static buffer
//
typedef const char* (*dyld_image_state_change_handler)(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info info[]);

//
// Register a handler to be called when any image changes to the requested state.
// If 'batch' is true, the callback is called with an array of all images that are in the requested state sorted by dependency.
// If 'batch' is false, the callback is called with one image at a time as each image transitions to the the requested state.
// During the call to this function, the handler may be called back with existing images and the handler should
// not return a string, since there is no load to abort.  In batch mode, existing images at or past the request
// state supplied in the callback.  In non-batch mode, the callback is called for each image exactly in the
// requested state.
//
extern void
dyld_register_image_state_change_handler(enum dyld_image_states state, bool batch, dyld_image_state_change_handler handler);

//
// Possible thread-local variable state changes for which you can register to be notified
//
enum dyld_tlv_states {
    dyld_tlv_state_allocated = 10,   // TLV range newly allocated
    dyld_tlv_state_deallocated = 20  // TLV range about to be deallocated
};

//
// Info about thread-local variable storage.
//
typedef struct {
    size_t info_size;    // sizeof(dyld_tlv_info)
    void * tlv_addr;     // Base address of TLV storage
    size_t tlv_size;     // Byte size of TLV storage
} dyld_tlv_info;

#if __BLOCKS__

//
// Callback that notes changes to thread-local variable storage.
//
typedef void (^dyld_tlv_state_change_handler)(enum dyld_tlv_states state, const dyld_tlv_info *info);

//
// Register a handler to be called when a thread adds or removes storage for thread-local variables.
// The registered handler will only be called from and on behalf of the thread that owns the storage.
// The registered handler will NOT be called for any storage that was
//   already allocated before dyld_register_tlv_state_change_handler() was
//   called. Use dyld_enumerate_tlv_storage() to get that information.
// Exists in Mac OS X 10.7 and later
//
extern void
dyld_register_tlv_state_change_handler(enum dyld_tlv_states state, dyld_tlv_state_change_handler handler);

//
// Enumerate the current thread-local variable storage allocated for the current thread.
// Exists in Mac OS X 10.7 and later
//
extern void
dyld_enumerate_tlv_storage(dyld_tlv_state_change_handler handler);

#endif

//
// get slide for a given loaded mach_header
// Mac OS X 10.6 and later
//
extern intptr_t _dyld_get_image_slide(const struct mach_header* mh);

//
// get pointer to this process's dyld_all_image_infos
// Exists in Mac OS X 10.4 and later through _dyld_func_lookup()
// Exists in Mac OS X 10.6 and later through libSystem.dylib
//
const struct dyld_all_image_infos* _dyld_get_all_image_infos();

struct dyld_unwind_sections
{
	const struct mach_header*		mh;
	const void*						dwarf_section;
	uintptr_t						dwarf_section_length;
	const void*						compact_unwind_section;
	uintptr_t						compact_unwind_section_length;
};

//
// Returns true iff some loaded mach-o image contains "addr".
//	info->mh							mach header of image containing addr
//  info->dwarf_section					pointer to start of __TEXT/__eh_frame section
//  info->dwarf_section_length			length of __TEXT/__eh_frame section
//  info->compact_unwind_section		pointer to start of __TEXT/__unwind_info section
//  info->compact_unwind_section_length	length of __TEXT/__unwind_info section
//
// Exists in Mac OS X 10.6 and later
extern bool _dyld_find_unwind_sections(void* addr, struct dyld_unwind_sections* info);

//
// This is an optimized form of dladdr() that only returns the dli_fname field.
//
// Exists in Mac OS X 10.6 and later
extern const char* dyld_image_path_containing_address(const void* addr);

//
// This is finds the SDK version a binary was built against.
// Returns zero on error, or if SDK version could not be determined.
//
// Exists in Mac OS X 10.8 and later
extern uint32_t dyld_get_sdk_version(const struct mach_header* mh);

//
// This is finds the SDK version the main executable was built against.
// Returns zero on error, or if SDK version could not be determined.
//
// Exists in Mac OS X 10.8 and later
extern uint32_t dyld_get_program_sdk_version();

//
// This is finds the min OS version a binary was built to run on.
// Returns zero on error, or if no min OS recorded in binary.
//
// Exists in Mac OS X 10.8 and later
extern uint32_t dyld_get_min_os_version(const struct mach_header* mh);

//
// This is finds the min OS version the main executable was built to run on.
// Returns zero on error, or if no min OS recorded in binary.
//
// Exists in Mac OS X 10.8 and later
extern uint32_t dyld_get_program_min_os_version();

#if __IPHONE_OS_VERSION_MIN_REQUIRED
//
// Returns if any OS dylib has overridden its copy in the shared cache
//
// Exists in iPhoneOS 3.1 and later
extern bool dyld_shared_cache_some_image_overridden();
#endif

#if __cplusplus
}
#endif /* __cplusplus */

#endif /* _MACH_O_DYLD_PRIV_H_ */


text:
import ShareYourSystem as SYS

#define
@SYS.InspecterClass()
class MakerClass(object):

	def default_init(self,
			_MakingMyStr,
			_MakingMyInt=0,
			**_KwargVariablesDict
		):
		object.__init__(self,**_KwargVariablesDict)

	def do_make(self):

		#str
		self.MadeMyStr=str(self.MakingMyStr)

#print
print('MakerClass.InspectedArgumentDict is ')
print(SYS.indent(
		MakerClass.InspectedArgumentDict
	)
)


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe VContainer::SimpleProvider do

  before do
    @container = VContainer::Container.new
  end

  it "support dependency injection when providing a service" do
    @container.use VContainer::SimpleProvider.new(BasicComponent)
    @container.use VContainer::SimpleProvider.new(SimpleEmailSender)
    basic = @container.provide(BasicComponent)
    basic.sender.class.should == SimpleEmailSender
  end

  it "support dependency injection based on a module" do
    @container.use VContainer::SimpleProvider.new(EmailComponent)
    @container.use VContainer::SimpleProvider.new(SimpleEmailSender)
    basic = @container.provide(EmailComponent)
    basic.sender.class.should == SimpleEmailSender
  end

end


text:
package sttnf.app.nfkita.utils;

import android.Manifest;
import android.app.Activity;

import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;

import java.util.List;

/**
 * Created by isfaaghyth on 7/27/17.
 * github: @isfaaghyth
 */

public class RuntimePermissions {

    public static void request(Activity activity) {
        Dexter.withActivity(activity)
                .withPermissions(
                        Manifest.permission.CAMERA
                ).withListener(new MultiplePermissionsListener() {
            @Override public void onPermissionsChecked(MultiplePermissionsReport report) {}
            @Override public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {}
        }).check();
    }

}


text:
function getToId(target, liImage) {
    while (!$(target).children().last().get(0).isEqualNode($(liImage).get(0))) {
        lastToFirst($(target));
    }
}

function leftToRight(target) {
    $(target).stop();
    var origin = $(target).position();
    if ($(target).attr("data_top") == undefined) {
        $(origin).each(function() {
            for (testi in this) {
                $(target).attr("data_" + testi, this[testi]);
                $(target).removeAttr("style");
            }
        })
    }
    $(target).offset({
        left: $(target).parent().offset().left - $(target).width()
    });
    $(target).animate({
        left: $(target).attr("data_left"),
        top: $(target).attr("data_top")
    }, 500);
}

function rightToLeft(target) {
    $(target).stop();
    var origin = $(target).position();
    if ($(target).attr("data_top") == undefined) {
        $(origin).each(function() {
            for (testi in this) {
                $(target).attr("data_" + testi, this[testi]);
                $(target).removeAttr("style");
            }
        })
    }
    $(target).offset({
        left: $(target).parent().width() + $(target).offset().left
    });
    $(target).animate({
        left: $(target).attr("data_left"),
        top: $(target).attr("data_top")
    }, 500);
}

function slideshow(name) {
    this.slideshow = $(name).get(0);
    this.slides = new Array();
    for (slideElement in this.slideshow.childNodes) {
        if(this.slideshow.childNodes[slideElement].nodeType === 1){
            this.slides.push(new slide(this.slideshow.childNodes[slideElement]));
        }
    }
}

slideshow.prototype.nextSlide = function() {

    $(this.slideshow).append($(this.slideshow).children().first());
    $(this.slideshow).children().each(function() {
        $(this).css("zIndex", $(this).css("zIndex") - 1);
    });
    $(this.slideshow).children().last().find('div').each(function(index) {
        leftToRight(this);
    });
    rightToLeft($(this.slideshow).children().last().find('img').get(0));
    $(this.slideshow).children().last().css("zIndex", $(this.slideshow).children().length)

}

slideshow.prototype.previousSlide = function() {
    $(this.slideshow).children().last().css("zIndex", $(this.slideshow).children().length)
    $(this.slideshow).prepend($(this.slideshow).children().last());
    $(this.slideshow).children().each(function() {
        $(this).css("zIndex", $(this).css("zIndex") - 1);
    });
    $(this.slideshow).children().last().find('div').each(function(index) {
        rightToLeft(this);
    });
    leftToRight($(this.slideshow).children().last().find('img').get(0));
    $(this.slideshow).children().last().css("zIndex", $(this.slideshow).children().length)
}

function slide(targetSlide) {
    this.slide = targetSlide;
}


text:
/*
Package health has integrations with webpa-common/health for monitoring
httppool Dispatchers.
*/
package health


text:
#ifndef _ERRNO_H
#define _ERRNO_H

/* Invalid errno */
#define errno (-2)

/* Just to get it out of the way */
#define EINTR 1

#endif