text:
<?php

namespace Xsolve\SalesforceClient\QueryBuilder\Visitor\Parameters;

use PHPUnit\Framework\TestCase;
use Xsolve\SalesforceClient\QueryBuilder\Expr\Compare\AbstractMultiCompare;
use Xsolve\SalesforceClient\QueryBuilder\Expr\Compare\AbstractSingleCompare;

class ParametersReplacingVisitorTest extends TestCase
{
    public function testVisitSingleCompare()
    {
        $visitor = $this->createVisitor([
            'test key 1' => 'test value 1',
            'test key 2' => 'test value 2',
        ]);
        $compare = $this->prophesize(AbstractSingleCompare::class);
        $compare->getLeft()->willReturn('test left with {test key 1}');
        $compare->getRight()->willReturn('{test key 2} of test right');
        $compare->update([
            'left' => 'test left with \'test value 1\'',
            'right' => '\'test value 2\' of test right',
        ])->shouldBeCalled();
        $visitor->visitSingleCompare($compare->reveal());
    }

    public function testVisitMultiCompare()
    {
        $visitor = $this->createVisitor([
            'test key 1' => 'test value 1',
            'test key 2' => 'test value 2',
        ]);
        $compare = $this->prophesize(AbstractMultiCompare::class);
        $compare->getValues()->willReturn([
            'first value with {test key 1}',
            '{test key 2} of second value',
        ]);
        $compare->update([
            'first value with \'test value 1\'',
            '\'test value 2\' of second value',
        ])->shouldBeCalled();
        $visitor->visitMultiCompare($compare->reveal());
    }

    private function createVisitor(array $parameters): ParametersReplacingVisitor
    {
        return new ParametersReplacingVisitor($parameters);
    }
}


text:
from django.views.generic.edit import CreateView
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect

from libs.mixins.views import SuccessURLAliasViewMixin
from .forms import RegistrationForm
from .tasks import send_welcome_message
from . import constants

class RegistrationFormView(SuccessURLAliasViewMixin,
        CreateView):
    form_class = RegistrationForm
    template_name = 'registration/registration_form.html'
    success_url_alias = 'employee:questionnaire_signup_add'
    initial = dict(
        is_employer=constants.USER_REGISTRATION_IS_EMPLOYER_CHOICES.EMPLOYER)

    def form_valid(self, form):
        response = super(RegistrationFormView, self).form_valid(form)
        user = authenticate(
            username=form.cleaned_data['email'],
            password=form.cleaned_data['password'])
        login(self.request, user)
        send_welcome_message.delay(self.request.META['HTTP_HOST'],
            form.cleaned_data['email'])
        if form.cleaned_data['is_employer']:
            return redirect('employer:business')
        return response

redpajama_set_name: RedPajamaGithub


text:
import { CommonModule } from "@angular/common";
// angular modules
import { NgModule } from "@angular/core";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
// custom components
import { AddCourseComponent } from "./add-course.component";
// routes
import { routes } from "./add-course.routes";

import { MdButtonModule, MdInputModule, MdDatepickerModule } from "@angular/material";
import { PublishedDateModule } from "./published-date";
import { DurationModule } from "./duration/duration.module";
import { AuthorModule } from "./author/author.module";
import { CoursesService } from "../../core/services/courses/courses.service";

@NgModule({
    declarations: [
        AddCourseComponent
    ],
    imports: [
        routes,
        PublishedDateModule,
        FormsModule,
        ReactiveFormsModule,
        CommonModule,
        MdInputModule,
        MdDatepickerModule,
        MdButtonModule,
        DurationModule,
        AuthorModule
    ],
    providers: [ CoursesService ]
})
export class AddCourseModule {
}


text: Flask demo for graph api usage in azure active directory


text:
package core_test

import (
	"testing"

	"k8s.io/kubernetes/pkg/api"
	metav1 "k8s.io/kubernetes/pkg/apis/meta/v1"
	clientsetfake "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake"
)

func TestFakeClientSetFiltering(t *testing.T) {
	tc := clientsetfake.NewSimpleClientset(
		testPod("nsA", "pod-1"),
		testPod("nsB", "pod-2"),
		testSA("nsA", "sa-1"),
		testSA("nsA", "sa-2"),
		testSA("nsB", "sa-1"),
		testSA("nsB", "sa-2"),
		testSA("nsB", "sa-3"),
	)

	saList1, err := tc.Core().ServiceAccounts("nsA").List(api.ListOptions{})
	if err != nil {
		t.Fatalf("ServiceAccounts.List: %s", err)
	}
	if actual, expected := len(saList1.Items), 2; expected != actual {
		t.Fatalf("Expected %d records to match, got %d", expected, actual)
	}
	for _, sa := range saList1.Items {
		if sa.Namespace != "nsA" {
			t.Fatalf("Expected namespace %q; got %q", "nsA", sa.Namespace)
		}
	}

	saList2, err := tc.Core().ServiceAccounts("nsB").List(api.ListOptions{})
	if err != nil {
		t.Fatalf("ServiceAccounts.List: %s", err)
	}
	if actual, expected := len(saList2.Items), 3; expected != actual {
		t.Fatalf("Expected %d records to match, got %d", expected, actual)
	}
	for _, sa := range saList2.Items {
		if sa.Namespace != "nsB" {
			t.Fatalf("Expected namespace %q; got %q", "nsA", sa.Namespace)
		}
	}

	pod1, err := tc.Core().Pods("nsA").Get("pod-1", metav1.GetOptions{})
	if err != nil {
		t.Fatalf("Pods.Get: %s", err)
	}
	if pod1 == nil {
		t.Fatalf("Expected to find pod nsA/pod-1 but it wasn't found")
	}
	if pod1.Namespace != "nsA" || pod1.Name != "pod-1" {
		t.Fatalf("Expected to find pod nsA/pod-1t, got %s/%s", pod1.Namespace, pod1.Name)
	}

	wrongPod, err := tc.Core().Pods("nsB").Get("pod-1", metav1.GetOptions{})
	if err == nil {
		t.Fatalf("Pods.Get: expected nsB/pod-1 not to match, but it matched %s/%s", wrongPod.Namespace, wrongPod.Name)
	}

	allPods, err := tc.Core().Pods(api.NamespaceAll).List(api.ListOptions{})
	if err != nil {
		t.Fatalf("Pods.List: %s", err)
	}
	if actual, expected := len(allPods.Items), 2; expected != actual {
		t.Fatalf("Expected %d pods to match, got %d", expected, actual)
	}

	allSAs, err := tc.Core().ServiceAccounts(api.NamespaceAll).List(api.ListOptions{})
	if err != nil {
		t.Fatalf("ServiceAccounts.List: %s", err)
	}
	if actual, expected := len(allSAs.Items), 5; expected != actual {
		t.Fatalf("Expected %d service accounts to match, got %d", expected, actual)
	}
}

func testSA(ns, name string) *api.ServiceAccount {
	return &api.ServiceAccount{
		ObjectMeta: api.ObjectMeta{
			Namespace: ns,
			Name:      name,
		},
	}
}

func testPod(ns, name string) *api.Pod {
	return &api.Pod{
		ObjectMeta: api.ObjectMeta{
			Namespace: ns,
			Name:      name,
		},
	}
}


text:
FROM centos:7
MAINTAINER William Ivanski <william.ivanski@gmail.com>

USER root
ENV HOME /root
WORKDIR /root
SHELL ["/bin/bash", "-c"]

ENV PYTHON_VERSION=3.6.5

RUN yum install -y gcc gcc-c++ make git patch openssl-devel zlib-devel readline-devel sqlite-devel bzip2-devel rpm-build curl epel-release \
 && yum groupinstall -y "GNOME Desktop" \
 && git clone --depth 1 https://github.com/pyenv/pyenv.git ~/.pyenv \
 && echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc \
 && echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc \
 && echo 'eval "$(pyenv init -)"' >> ~/.bashrc \
 && source ~/.bashrc \
 && env PYTHON_CONFIGURE_OPTS="--enable-shared" pyenv install $PYTHON_VERSION \
 && pyenv global $PYTHON_VERSION \
 && curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash - \
 && yum -y install nodejs

COPY clone.sh $HOME/


text:
//
//  Created by Lennart Oymanns on 03.05.17.
//

#include "NumberRepr.hpp"

using namespace Equation;

NumberRepr::NumberRepr() {
  value_double = 0.0;
  isValid = false;
  rational = Rational_t(0);
}

NumberRepr::NumberRepr(const std::string &s) {
  auto dot_pos = s.find_first_of("eE.");
  if (dot_pos != std::string::npos) {
    value_double = strtod(s.c_str(), NULL);
    isFraction = false;
  } else {
    rational = Integer_t(s);
    isFraction = true;
  }
  isValid = true;
}

/** SetFromInt sets the value of this number to fraction num/denom. */
void NumberRepr::SetFromInt(long num, long denom) {
  isFraction = true;
  rational = Rational_t(num, denom);

  value_double = 0.0;
  if (denom == 0) {
    isValid = false;
  } else {
    isValid = true;
  }
}

/** normal *= operator. If *this and rhs are both fractions the result is also a
 * fraction. Otherwise the result is a floating point number. */
NumberRepr &NumberRepr::operator*=(const NumberRepr &rhs) {
  if (!rhs.isValid) {
    isValid = false;
  }
  if (rhs.isFraction && isFraction) {
    rational *= rhs.rational;
    return *this;
  }
  SetFromDouble(Double() * rhs.Double());
  return *this;
}

/** normal /= operator. If *this and rhs are both fractions the result is also a
 * fraction. Otherwise the result is a floating point number. If rhs is a
 * fraction and equal to zero, this number is set to invalid. */
NumberRepr &NumberRepr::operator/=(const NumberRepr &rhs) {
  if (!rhs.isValid) {
    isValid = false;
  }
  if (isFraction && rhs.isFraction) {
    if (rhs.rational == Rational_t(0)) {
      isValid = false;
      return *this;
    }
    rational /= rhs.rational;
    return *this;
  }
  SetFromDouble(Double() / rhs.Double());
  return *this;
}

/** normal += operator. If *this and rhs are both fractions the result is also a
 * fraction. Otherwise the result is a floating point number. */
NumberRepr &NumberRepr::operator+=(const NumberRepr &rhs) {
  if (!rhs.isValid) {
    isValid = false;
  }
  if (rhs.isFraction && isFraction) {
    rational += rhs.rational;
    return *this;
  }
  SetFromDouble(Double() + rhs.Double());
  return *this;
}

/** normal -= operator. If *this and rhs are both fractions the result is also a
 * fraction. Otherwise the result is a floating point number. */
NumberRepr &NumberRepr::operator-=(const NumberRepr &rhs) {
  if (!rhs.isValid) {
    isValid = false;
  }
  if (rhs.isFraction && isFraction) {
    rational -= rhs.rational;
    return *this;
  }
  SetFromDouble(Double() - rhs.Double());
  return *this;
}

std::ostream &operator<<(std::ostream &os, const NumberRepr &obj) {
  os << obj.String();
  return os;
}

/** Pow returns the result of base^exponent.

 If there are any problems (e.g. the exponent is too large), Pow returns an
 invalid number. */
NumberRepr NumberRepr::Pow(const NumberRepr &base, const NumberRepr &exp) {
  if (!base.isValid || !exp.isValid) {
    // power of an invalid number is also invalid.
    auto inv = NumberRepr(0l);
    inv.isValid = false;
    return inv;
  }
  if (!base.IsFraction() || !exp.IsFraction()) {
    // if either base or exponent are floating point numbers, calculate the
    // floating point result.
    double b = base.Double();
    double e = exp.Double();
    return NumberRepr(pow(b, e));
  }
  if (exp.Denominator() == Integer_t(1)) {
    // calculate power if it is not a nth root.
    Integer_t abs_enum = boost::multiprecision::abs(exp.Numerator());
    if (abs_enum > Integer_t(100)) {
      // if the exponent is too large, return a invalid number
      auto inv = NumberRepr(0l);
      inv.isValid = false;
      return inv;
    }

    unsigned e = abs_enum.convert_to<unsigned>();
    auto rat = base.rational;
    Rational_t result_num =
        boost::multiprecision::pow(boost::multiprecision::numerator(rat), e);
    Rational_t result_denom =
        boost::multiprecision::pow(boost::multiprecision::denominator(rat), e);

    if (exp.Numerator() >= Integer_t(0)) {
      Rational_t res = result_num / result_denom;
      return NumberRepr(res);
    }
    Rational_t res = result_denom / result_num;
    return NumberRepr(res);
  }
  // calculate nth root numerically
  auto inv = NumberRepr(pow(base.Double(), exp.Double()));
  inv.isValid = false;
  return inv;
}

/** Double returns a floating point representation of the number. */
double NumberRepr::Double() const {
  if (isFraction) {
    return rational.convert_to<double>();
  }
  return value_double;
}

/** String returns a string representation of the number. */
std::string NumberRepr::String() const {
  if (!isValid) {
    return "nan";
  }
  std::stringstream ss;
  if (isFraction) {
    ss << Numerator().str();
    if (Denominator() != Integer_t(1)) {
      ss << " / " << Denominator().str();
    }
    return ss.str();
  }
  ss << std::setprecision(17) << Double();
  return ss.str();
}

bool NumberRepr::operator==(const NumberRepr &n) const {
  if (!isValid || !n.isValid) {
    return false;
  }
  if (isFraction && n.isFraction) {
    return rational == n.rational;
  }
  if (!isFraction && !n.isFraction) {
    return Double() == n.Double();
  }
  return false;
}

/** ToLatex writes a latex representation of this number to stream s. */
void NumberRepr::ToLatex(std::ostream &s) const {
  if (IsFraction()) {
    if (Denominator() != Integer_t(1)) {
      s << "\\frac{" << Numerator() << "}{" << Denominator() << "}";
    } else {
      s << Numerator();
    }
    return;
  }
  s << std::setprecision(17) << Double();
}

bool NumberRepr::operator<(const NumberRepr &n) {
  if (!isValid || !n.isValid) {
    return false;
  }
  if (isFraction && n.isFraction) {
    return rational < n.rational;
  }
  return Double() < n.Double();
}

bool NumberRepr::operator>(const NumberRepr &n) {
  if (*this < n) {
    return false;
  }
  if (*this == n) {
    return false;
  }
  return true;
}

/** SetFromDouble set the value of this number to the floating  point value l.
 */
void NumberRepr::SetFromDouble(double l) {
  isFraction = false;
  value_double = l;
  isValid = true;
  rational = boost::multiprecision::cpp_rational(0);
}


text:
@echo off
:: This is JUST the build command. You must
:: run dependencies.bat first to set up the folders

:: https://stackoverflow.com/questions/6359820/how-to-set-commands-output-as-a-variable-in-a-batch-file
FOR /F "tokens=* USEBACKQ" %%F IN (`git rev-parse HEAD`) DO (
SET gitsha=%%F
)
ECHO git sha: %gitsha%

:: https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-us
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
SET curtime=%mydate%
ECHO build date: %curtime%
:: TODO: The curtime command should be %mydate%_%mytime%, but mytime seems to have a space, which makes go unhappy
:: Also... should make it utc.

go build -o bin/connectordb.exe  -ldflags "-X commands.BuildStamp=%curtime% -X commands.GitHash=%gitsha%" src/main.go


text:
@implementation MZFayeMessage

- (instancetype)initFromDictionary:(NSDictionary *)dictionary
{
    if (self = [super init]) {
        self.Id = dictionary[@"id"];
        self.channel = dictionary[@"channel"];
        self.clientId = dictionary[@"clientId"];
        self.successful = @([dictionary[@"successful"] boolValue]);
        self.authSuccessful = @([dictionary[@"authSuccessful"] boolValue]);
        self.version = dictionary[@"version"];
        self.minimumVersion = dictionary[@"minimumVersion"];
        self.supportedConnectionTypes = dictionary[@"supportedConnectionTypes"];
        self.advice = dictionary[@"advice"];
        self.error = dictionary[@"error"];
        self.subscription = dictionary[@"subscription"];
        self.timestamp = [NSDate dateWithTimeIntervalSince1970:[dictionary[@"timestamp"] timeInterval]];
        self.data = dictionary[@"data"];
        self.ext = dictionary[@"ext"];
    }
    return self;
}

+ (instancetype)messageFromDictionary:(NSDictionary *)dictionary
{
    return [[[self class] alloc] initFromDictionary:dictionary];
}

@end


text:
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using DAL;
using SQLite;
using System.IO;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace DistroList
{
    [Activity(Label = "Linux Distribution List", MainLauncher = true, Icon = "@drawable/icon", LaunchMode = Android.Content.PM.LaunchMode.SingleTask)]
    public class MainActivity : Activity
    {
        private string dbPath;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);

            var releaseSpinner = FindViewById<Spinner>(Resource.Id.releaseSpinner);
            var statusLbl = FindViewById<TextView>(Resource.Id.statusTxtView);
            var listBtn = FindViewById<Button>(Resource.Id.viewListBtn);
            var addBtn = FindViewById<Button>(Resource.Id.addDistroBtn);

            dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "distros.db");

            if (!File.Exists(dbPath))
            {
                statusLbl.Text = "Please wait while the Database is created...";
                releaseSpinner.Enabled = false;
                listBtn.Enabled = false;
                addBtn.Enabled = false;

                // Extract the database asynchronously, allowing the rest of OnCreate to run in the mean time.
                // Would be more useful if the database was larger and took more time to extract.
                Task.Run(() => ExtractDatabase());
            }

            var releaseModels = Enum.GetNames(typeof(Distribution.ReleaseModels));
            var adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, releaseModels);
            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            releaseSpinner.Adapter = adapter;

            listBtn.Click += ListButtonClick;
            addBtn.Click += AddButtonClick;
        }

        private void ListButtonClick(object sender, EventArgs e)
        {
            var intent = new Intent(this, typeof(DistroListActivity));

            var releaseSpinner = FindViewById<Spinner>(Resource.Id.releaseSpinner);
            var releaseModel = (string)releaseSpinner.SelectedItem;

            intent.PutExtra("Model", releaseModel);

            StartActivity(intent);
        }

        private void AddButtonClick(object sender, EventArgs e)
        {
            var intent = new Intent(this, typeof(AddDistroActivity));
            StartActivity(intent);
        }

        private void ExtractDatabase()
        {
            using (var instream = Assets.Open("distros.db"))
            {
                using (var outstream = File.Create(dbPath))
                {
                    instream.CopyTo(outstream);
                }
            }

            var releaseSpinner = FindViewById<Spinner>(Resource.Id.releaseSpinner);
            var statusLbl = FindViewById<TextView>(Resource.Id.statusTxtView);
            var listBtn = FindViewById<Button>(Resource.Id.viewListBtn);
            var addBtn = FindViewById<Button>(Resource.Id.addDistroBtn);

            releaseSpinner.Enabled = true;
            listBtn.Enabled = true;
            addBtn.Enabled = true;
            statusLbl.Text = "Select a release model";
        }
    }
}


text:
#ifndef GRPC_INTERNAL_CORE_CHANNEL_CONNECTED_CHANNEL_H
#define GRPC_INTERNAL_CORE_CHANNEL_CONNECTED_CHANNEL_H

#include "src/core/channel/channel_stack.h"

/* A channel filter representing a channel that is on a connected transport.
   This filter performs actual sending and receiving of messages. */

extern const grpc_channel_filter grpc_connected_channel_filter;

/* Post construction fixup: set the transport in the connected channel.
   Must be called before any call stack using this filter is used. */
void grpc_connected_channel_bind_transport(grpc_channel_stack *channel_stack,
                                           grpc_transport *transport);

#endif /* GRPC_INTERNAL_CORE_CHANNEL_CONNECTED_CHANNEL_H */


text:
\chapter{Instrumentation, Measurement,
and Industrial Applications}

Instrumentation and measurement play a relevant role in any industrial applications.
Without sensors, transducers, converters, acquisition channels, signal processing, image
processing, no measurement system and procedure will exist and, in turn, no industry will
actually exist. They are in fact the irreplaceable foundation of any monitoring and
automatic control system as well as for any diagnosis and quality assurance.

A number of results concerning the use of neural techniques are known in
different applications, encompassing intelligent sensors and acquisition systems, system
models, signal processing, image processing, automatic control systems, and diagnosis.

\section{Fundamentals}
The concept of measurement has been deep-rooted in the human culture since the origin of
civilization, as it has always represented the basis of the experimental knowledge, the
quantitative assessment of goods in commercial transactions, the assertion of a right, and so
on.
After Galileo Galilei put experimentation at the base of the modern science and showed
that it is the only possible starting point for the validation of any scientific theory, the
measurement activity has become more and more important. More than one century ago,
William Thomson, Lord Kelvin, reinforced this concept by stating: \textbf{"I often say that when
you can measure what you are speaking about, and can express it in numbers, you know
something about it; but when you cannot express it in numbers your knowledge about it is
of meager and unsatisfactory kind; it may be the beginning of knowledge, but you have
scarcely, in your thoughts, advanced to the stage of science, whatever the matter may be.
So, therefore, if science is measurement, then without metrology there can be no science"}.

Under this modem vision of science, the measurement of a physical quantity is
generally defined as the quantitative comparison of this same quantity with another one,
which is homogeneous with the measured one, and is considered as the measurement unit.
In order to perform this quantitative comparison, five agents are needed,

\begin{itemize}
\item \textbf{The measurand}: it is the quantity to be measured, and it often represents a property of a
physical object and is described by a suitable mathematical model.
\item \textbf{The standard}: it is the physical realization of the measurement unit.
\item \textbf{The instrument}: it is the physical device that performs the comparison.
\item \textbf{The method}: the comparison between the measurand and the standard is performed by
exploiting some physical phenomena (thermal dilatation, mechanical force between
electric charges, and so on); according to the considered phenomenon, different methods
can be implemented.
\item \textbf{The operator}: he supervises the whole measurement process, operates the measurement
devices and reads the instrument.
\end{itemize}

\begin{figure}
\centering
\caption{Pictorial representation of Measurement}
\label{fig:pictorial_representation_of_measurement}
\includegraphics[scale=.5]{./img/measurement.png}
\end{figure}


text:
package dist

func buildable() {}


text:
package org.onosproject.netconf;

import com.google.common.base.Preconditions;
import org.onlab.packet.IpAddress;
import org.onosproject.net.DeviceId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Objects;

/**
 * Represents a Netconf device information.
 */
public class NetconfDeviceInfo {

    public static final Logger log = LoggerFactory
            .getLogger(NetconfDeviceInfo.class);

    private String name;
    private String password;
    private IpAddress ipAddress;
    private int port;
    private File keyFile;
    private DeviceId deviceId;

    /**
     * Information for contacting the controller.
     *
     * @param name      the connection type
     * @param password  the password for the device
     * @param ipAddress the ip address
     * @param port      the tcp port
     */
    public NetconfDeviceInfo(String name, String password, IpAddress ipAddress,
                             int port) {
        Preconditions.checkArgument(!name.equals(""), "Empty device name");
        Preconditions.checkNotNull(port > 0, "Negative port");
        Preconditions.checkNotNull(ipAddress, "Null ip address");
        this.name = name;
        this.password = password;
        this.ipAddress = ipAddress;
        this.port = port;
    }

    /**
     * Information for contacting the controller.
     *
     * @param name      the connection type
     * @param password  the password for the device
     * @param ipAddress the ip address
     * @param port      the tcp port
     * @param keyString the string containing the key.
     */
    public NetconfDeviceInfo(String name, String password, IpAddress ipAddress,
                             int port, String keyString) {
        Preconditions.checkArgument(!name.equals(""), "Empty device name");
        Preconditions.checkNotNull(port > 0, "Negative port");
        Preconditions.checkNotNull(ipAddress, "Null ip address");
        this.name = name;
        this.password = password;
        this.ipAddress = ipAddress;
        this.port = port;
        this.keyFile = new File(keyString);
    }

    /**
     * Exposes the name of the controller.
     *
     * @return String name
     */
    public String name() {
        return name;
    }

    /**
     * Exposes the password of the controller.
     *
     * @return String password
     */
    public String password() {
        return password;
    }

    /**
     * Exposes the ip address of the controller.
     *
     * @return IpAddress ip address
     */
    public IpAddress ip() {
        return ipAddress;
    }

    /**
     * Exposes the port of the controller.
     *
     * @return int port address
     */
    public int port() {
        return port;
    }

    /**
     * Exposes the keyFile of the controller.
     *
     * @return int port address
     */
    public File getKeyFile() {
        return keyFile;
    }

    /**
     * Return the info about the device in a string.
     * String format: "netconf:name@ip:port"
     *
     * @return String device info
     */
    public String toString() {
        return "netconf:" + name + "@" + ipAddress + ":" + port;
    }

    /**
     * Return the DeviceId about the device containing the URI.
     *
     * @return DeviceId
     */
    public DeviceId getDeviceId() {
        if (deviceId == null) {
            try {
                deviceId = DeviceId.deviceId(new URI("netconf", ipAddress.toString() + ":" + port, null));
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException("Unable to build deviceID for device " + toString(), e);
            }
        }
        return deviceId;
    }

    @Override
    public int hashCode() {
        return Objects.hash(ipAddress, port, name);
    }

    @Override
    public boolean equals(Object toBeCompared) {
        if (toBeCompared instanceof NetconfDeviceInfo) {
            NetconfDeviceInfo netconfDeviceInfo = (NetconfDeviceInfo) toBeCompared;
            if (netconfDeviceInfo.name().equals(name)
                    && netconfDeviceInfo.ip().equals(ipAddress)
                    && netconfDeviceInfo.port() == port
                    && netconfDeviceInfo.password().equals(password)) {
                return true;
            }
        }
        return false;
    }
}


text:
   View
   Manage

   Check


text:
#ifndef FSM_H
#define FSM_H

#include "nfa.hpp"
#include "alphabet.hpp"
#include "../../utils/src/bitsequence.hpp"

#include <map>
#include <set>
#include <vector>

template<typename C, typename O = int> class Fsm
{
public:
	typedef int State;
	typedef O Token;
	typedef C Char;
	const static State ERROR_STATE;

protected:
	//static std::vector<bool> emptySet;

	struct Transition
	{
		Transition() : nextState(ERROR_STATE) {}
		Transition(State next, const BitSequence<Token>& out) : nextState(next), output(out) {}
		State nextState;
		//std::set<Token> output;
		//std::vector<bool> output;
		BitSequence<Token> output;
		bool operator<(const Transition& rhs) const { return nextState < rhs.nextState
			|| (nextState == rhs.nextState && output < rhs.output); }
		bool operator==(const Transition& rhs) const { return nextState == rhs.nextState && output == rhs.output; }
	};

	typedef std::map<Char, Transition> Transitions;
	typedef std::vector<Transitions> TransitionTable;
	Alphabet<Char> alphabet;
	TransitionTable transition_table;
	Interval<Token> tokenRange;

public:
	Fsm();
	Fsm(const Nfa<Char, Token>&);

	const BitSequence<Token>& next(State& state, const Char& symbol) const;
	bool error(State state) const;

	bool isAcceptingState(State state) const;
	void getAcceptedSymbols(State state, std::set<Char>& symbols) const;
	State getNumberOfStates() const;
	const Alphabet<Char>& input() const;

	//Token getMinOutput() const;
	//Token getMaxOutput() const;
	//size_t getOutputSize() const;
	/// Sets entries to true for output.
	void getOutput(BitSequence<Token>& tokens) const;

	/// Converts index in output to token.
	//Token getToken(size_t index) const;
	/// Converts token to index into output.
	//size_t getIndex(Token token) const;

	/// Resulting map maps from Tokens to corresponding prefixes.
	/// A token p is prefix of token t if ... TODO
	void getPrefixAssociations(std::map<Token, BitSequence<Token> >& prefixes) const;
	/// Result maps from States to corresponding prefixes.
	void getStatePrefixes(std::map<State, BitSequence<Token> >& prefixes) const;
	/// Result maps from state to outputs of reachable transitions.
	void getPotentialOutputs(std::map<State,BitSequence<Token> >& outputs) const;

	//State noStates() const;

	void create(const Nfa<Char, Token>&);
	void reduce();

	/// @param outputs prio sorted list.
	void disambiguate(const std::list<Token>& outputs);
	void strip(const BitSequence<Token>& outputs, bool strict);
	/// Strips outputs of outgoing transitions from state which are not contained in outputs
	void stripTransitions(State state, const BitSequence<Token>& outputs);
	/// creates fsm where state i is start of fsms[i]
	void mergeDemux(const std::vector<Fsm<Char, Token> >& fsms);
	//void printTable();
	/// Transforms fsm into a unique form.
	void normalize();
	/// Strips transitions to states without potential output.
	void stripDeadEnds(const std::map<State,BitSequence<Token> >& outputs);

	/// Successive states of linear subpaths without intermediate output are moved to the end in a way so their state numbers are successive.
	/// @param minState States <minState are not touched.
	/// @param minLength minimum length for sequence.
	void groupLinearPaths(State minState, int minLength);

	/// Computes the beginning of linear sequences. That means, all following states are part of linear sequences.
	/// @param minLength minimal length of sequence to declare it linear.
	/// @return first state of linear sequences.
	State getFirstLinearSequence(int minLength) const;

	/// Computes linear sequence starting at state.
	/// @return exit state of sequence.
	State getNextLinearSequence(State state, std::basic_string<Char>& input, BitSequence<Token>& output) const;

protected:
	void stripTransition(Transition& transition, const BitSequence<Token>& outputs);
	void stripUnreachableTransitions();
	//void partition(const std::map<State,State>& curr_map;
};

#endif


text:
package org.glassfish.jaxb.runtime.v2.model.annotation;

import java.text.MessageFormat;
import java.util.ResourceBundle;

/**
 * Message resources
 */
enum Messages {
    // AnnotationParser
    DUPLICATE_ANNOTATIONS,
    CLASS_NOT_FOUND
    ;

    private static final ResourceBundle rb = ResourceBundle.getBundle(Messages.class.getName());

    @Override
    public String toString() {
        return format();
    }

    public String format( Object... args ) {
        return MessageFormat.format( rb.getString(name()), args );
    }
}


text:
Document Utilities
==================

Creating Definition Documents
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. automodule:: pybel_tools.definition_utils
    :members:

Creating Knowledge Documents
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. automodule:: pybel_tools.document_utils
    :members:


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

<title>org.datavec.api.transform.ui.components Class Hierarchy</title>
<meta name="date" content="2016-09-19">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.datavec.api.transform.ui.components

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.datavec.api.transform.ui.components.RenderableComponent

org.datavec.api.transform.ui.components.RenderableComponentHistogram

org.datavec.api.transform.ui.components.RenderableComponentLineChart

org.datavec.api.transform.ui.components.RenderableComponentTable

org.datavec.api.transform.ui.components.RenderableComponentHistogram.Builder

org.datavec.api.transform.ui.components.RenderableComponentLineChart.Builder

org.datavec.api.transform.ui.components.RenderableComponentTable.Builder

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
var igatajs = function (templateID, dataSet, opening, closing) {
  try {
    // check if the templateID is a valid string
    if (typeof templateID !== 'string') {
      return new Error('The template id must be a string.');
    }
    // check if dataSet is defined and is a valid object
    if (dataSet && typeof dataSet !== 'object') {
      return new Error('The dataset must be an object.');
    }
    // check if the opening symbol is defined and is a string
    if (opening && typeof opening !== 'string') {
      return new Error('The opening symbol must be a string.');
    }
    // check if the closing symbol is defined and is a string
    if (closing && typeof closing !== 'string') {
      return new Error('The closing symbol must be a string.');
    }

    // if the opening or closing symbol isn't defined there are equal to {{ and }}
    var opening = opening || '{{';
    var closing = closing || '}}';

    // function to put the dataSet inside the template
    function parseString(string, dataSet, opening, closing) {
      try {
        var open = opening.replace(/[-[\]()*\s]/g, "\\$&").replace(/\$/g, '\\$')
        var close = closing.replace(/[-[\]()*\s]/g, "\\$&").replace(/\$/g, '\\$')
        var r = new RegExp(open + '(.+?)' + close, 'g')
        var matches = string.match(r) || [];

        matches.forEach(function(match) {
          var key = match.substring(opening.length, match.length - closing.length).trim();//chop {{ and }}
          var value = typeof dataSet[key] == 'undefined' ? '' : dataSet[key];
          string = string.replace(match, value);
        });

        return string;
      } catch (err) {
        return err;
      }
    }

    // add # if the templateID does not have it
    if (templateID.indexOf('#') === -1) {
      templateID = '#' + templateID;
    }

    // get the template
    var template = document.querySelector(templateID);
    var clone;

    // if the user pass a dataSet, replace it in the clone
    if (dataSet) {
      // get the innerHTML as string
      clone    = template.innerHTML.trim()
      clone = parseString(clone, dataSet, opening, closing);
      // create de dom parser
      var parser = new DOMParser();

      // parse clone to DOM Element
      clone = parser.parseFromString(clone, 'text/html').all[2]

      // get the correct element
      clone = clone.children[0]
    } else {
      clone = document.importNode(template.content, true)
    }

    // return the clone
    return clone;
  } catch (err) {
    return err;
  }
}

module.exports = igatajs;


text:
package org.omg.PortableInterceptor;

/**
* org/omg/PortableInterceptor/ORBInitializerOperations.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from c:/workspace/8-2-build-windows-amd64-cygwin/jdk8u65/4987/corba/src/share/classes/org/omg/PortableInterceptor/Interceptors.idl
* Tuesday, October 6, 2015 4:40:34 PM PDT
*/

/**
   * Facilitates interceptor registration and ORB initialization.
   *

   * Interceptors are intended to be a means by which ORB services gain
   * access to ORB processing, effectively becoming part of the ORB.
   * Since Interceptors are part of the ORB, when ORB.init
   * returns an ORB, the Interceptors shall have been registered.
   * Interceptors cannot be registered on an ORB after it has been
   * returned by a call to ORB.init.
   *

   * An Interceptor is registered by registering an associated
   * ORBInitializer object which implements the
   * ORBInitializer interface. When an ORB is initializing,
   * it shall call each registered ORBInitializer, passing it
   * an ORBInitInfo object which is used to register its
   * Interceptor.
   *

   * Registering ORB Initializers in Java
   *

   * ORBInitializers are registered via Java ORB properties.
   *

   * The property names are of the form:
   *

   *     org.omg.PortableInterceptor.ORBInitializerClass.<Service>
   *

   * where <Service> is the string name of a class
   * which implements
   *

   *     org.omg.PortableInterceptor.ORBInitializer
   *

   * To avoid name collisions, the reverse DNS name convention should be
   * used. For example, if company X has three initializers, it could define
   * the following properties:
   *

   *

   *     org.omg.PortableInterceptor.ORBInitializerClass.com.x.Init1
   *

   *

   *     org.omg.PortableInterceptor.ORBInitializerClass.com.x.Init2
   *

   *

   *     org.omg.PortableInterceptor.ORBInitializerClass.com.x.Init3
   *

   *

   * During ORB.init, these ORB properties which begin with
   * org.omg.PortableInterceptor.ORBInitializerClass shall be
   * collected, the <Service> portion of each property
   * shall be extracted, an object shall be instantiated with the
   * <Service> string as its class name, and the
   * pre_init and post_init methods shall be
   * called on that object. If there are any exceptions, the ORB shall
   * ignore them and proceed.
   *

   * Example
   *

   * A client-side logging service written by company X, for example, may
   * have the following ORBInitializer implementation:
   *

   * package com.x.logging;
   *
   * import org.omg.PortableInterceptor.Interceptor;
   * import org.omg.PortableInterceptor.ORBInitializer;
   * import org.omg.PortableInterceptor.ORBInitInfo;
   *
   * public class LoggingService implements ORBInitializer {
   *     void pre_init( ORBInitInfo info ) {
   *         // Instantiate the Logging Service s Interceptor.
   *         Interceptor interceptor = new LoggingInterceptor();
   *
   *         // Register the Logging Service s Interceptor.
   *         info.add_client_request_interceptor( interceptor );
   *     }
   *
   *     void post_init( ORBInitInfo info ) {
   *         // This service does not need two init points.
   *     }
   * }
   *

   * To run a program called MyApp using this logging
   * service, the user could type:
   *

   *     java
   *-Dorg.omg.PortableInterceptor.ORBInitializerClass.com.x.Logging.LoggingService
   *     MyApp
   *

   *

   * Notes about Registering Interceptors
   *

   * Request Interceptors are registered on a per-ORB basis.
   *

   * To achieve virtual per-object Interceptors, query the policies on the
   * target from within the interception points to determine whether they
   * should do any work.
   *

   * To achieve virtual per-POA Interceptors, instantiate each POA with a
   * different ORB. While Interceptors may be ordered administratively,
   * there is no concept of order with respect to the registration of
   * Interceptors. Request Interceptors are concerned with service contexts.
   * Service contexts have no order, so there is no purpose for request
   * Interceptors to have an order. IOR Interceptors are concerned with
   * tagged components. Tagged components also have no order, so there
   * is no purpose for IOR Interceptors to have an order.
   *

   * Registration code should avoid using the ORB (i.e., calling
   * ORB.init with the provided orb_id). Since
   * registration occurs during ORB initialization, results of invocations
   * on this ORB while it is in this state are undefined.
   *
   * @see ORBInitInfo
   */
public interface ORBInitializerOperations
{

  /**
     * Called during ORB initialization.  If it is expected that initial
     * services registered by an interceptor will be used by other
     * interceptors, then those initial services shall be registered at
     * this point via calls to
     * ORBInitInfo.register_initial_reference.
     *
     * @param info provides initialization attributes and operations by
     *     which Interceptors can be registered.
     */
  void pre_init (org.omg.PortableInterceptor.ORBInitInfo info);

  /**
     * Called during ORB initialization. If a service must resolve initial
     * references as part of its initialization, it can assume that all
     * initial references will be available at this point.
     *

     * Calling the post_init operations is not the final
     * task of ORB initialization. The final task, following the
     * post_init calls, is attaching the lists of registered
     * interceptors to the ORB. Therefore, the ORB does not contain the
     * interceptors during calls to post_init. If an
     * ORB-mediated call is made from within post_init, no
     * request interceptors will be invoked on that call.
     * Likewise, if an operation is performed which causes an IOR to be
     * created, no IOR interceptors will be invoked.
     *
     * @param info provides initialization attributes and
     *     operations by which Interceptors can be registered.
     */
  void post_init (org.omg.PortableInterceptor.ORBInitInfo info);
} // interface ORBInitializerOperations


text:
package org.cafe.game.clientes;

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

public class GeradorDeNomes {

    static List<String> names = new ArrayList<>();
    static List<String> surnames = new ArrayList<>();
    static Random r = new Random();

    static {
        names.add("Jack");
        names.add("John");
        names.add("James");
        names.add("Martin");
        names.add("Bruce");
        names.add("Robert");
        names.add("Tony");
        names.add("Mike");
        names.add("Clint");
        names.add("Jhonny");
        names.add("Paul");
        names.add("Peter");
        names.add("Ethan");
        names.add("Richard");
        names.add("Vito");
        names.add("Vince");
        names.add("Frank");
        names.add("Hector");
        names.add("Emmet");
        names.add("Harry");
        names.add("Stanley");
        names.add("Dick");
        names.add("Leonard");

        surnames.add("Black");
        surnames.add("Carter");
        surnames.add("Bond");
        surnames.add("McFly");
        surnames.add("Wayne");
        surnames.add("Montana");
        surnames.add("Stark");
        surnames.add("Jackson");
        surnames.add("Eastwood");
        surnames.add("Deep");
        surnames.add("Willians");
        surnames.add("White");
        surnames.add("Mccoy");
        surnames.add("Hatfield");
        surnames.add("Corleone");
        surnames.add("Vercetti");
        surnames.add("Jones");
        surnames.add("Barbossa");
        surnames.add("Brown");
        surnames.add("Lee");
        surnames.add("Trace");
        surnames.add("Cooper");
        surnames.add("Gold");
    }

    public static String gerarNome() {
        String name = names.get(r.nextInt(names.size()));
        String surname = surnames.get(r.nextInt(surnames.size()));

        return name + " " + surname;
    }
}


text:
/*globals SproutCoreWysiwyg */
SC.WYSIWYGStyleView = SC.PopupButtonView.extend({
  layout: { width: 120 },

  title: 'Paragraph'.loc(),

  editorStateDidChange: function () {
    var currentStyle = this.currentEditorStyle(),
      value = SproutCoreWysiwyg.styles.findProperty('value', currentStyle);

    if (!value) value = {
        title: "Paragraph"
    };

    var title = value.title.replace(/<[^>]+>([^<]+)<[^>]+>/, '$1');

    this.set('title', title.loc());
  },

  currentEditorStyle: function () {
    var editor = this.get('editor'),
      style = editor.queryCommandValue('formatBlock') || 'p';
    // because IE is stupid;
    if (style === 'Normal') {
      style = "p";
    } else if (style.indexOf('Heading') !== -1) {
      style = style.replace('Heading ', 'h');
    }
    return style;
  },

  _instantiateMenu: function () {
    var menu = this.get('menu');
    if (!menu || !menu.isClass) return;
    this.menu = menu.create({
      button: this
    });
    this._setupMenu();
  },

  formatBlock: function (source) {
    this.command.set('argument', '<%@>'.fmt(this.menu.selectedItem.value.toUpperCase()));

    this.invokeCommand();
  },

  menu: SC.MenuPane.extend({
    layout: {
      width: SC.browser.isMac ? 240 : 260
    },
    menuHeightPadding: 0,
    items: function () {
      var button = this.button;
      return SproutCoreWysiwyg.styles.map(function (values) {
        return SC.Object.create(values, {
          target: button,
          shortcut: function () {
            return SproutCoreWysiwyg.beautifyShortcut(this.get('keyEquivalent'));
          }.property(),
          title: values.title.loc()
        });
      });
    }.property().cacheable(),

    exampleView: SC.MenuItemView.extend({
      classNames: 'sc-wysiwyg-menu-item',
      escapeHTML: NO,
      render: function (context) {
        sc_super();
        context.addStyle({
          lineHeight: this.get('layout').height + 'px'
        });
      }

    })
  })
});


text:
from __future__ import print_function
import json, requests, tarfile, argparse, os, errno
import time
import traceback
from urlparse import urljoin
import glob
import re
import shutil
import threading
from Queue import Queue

from flask import Flask, jsonify, request, abort

from deploy import Deployer, DeployException

app = Flask(__name__)

deployer = None
arg_extract_path = None
arg_symlink = None
arg_webhook_token = None
arg_api_token = None

workQueue = Queue()

def create_symlink(source, linkname):
    try:
        os.symlink(source, linkname)
    except OSError, e:
        if e.errno == errno.EEXIST:
            # atomic modification
            os.symlink(source, linkname + ".tmp")
            os.rename(linkname + ".tmp", linkname)
        else:
            raise e

def req_headers():
    return {
        "Authorization": "Bearer %s" % (arg_api_token,),
    }

# Buildkite considers a poke to have failed if it has to wait more than 10s for
# data (any data, not just the initial response) and it normally takes longer than
# that to download an artifact from buildkite. Apparently there is no way in flask
# to finish the response and then keep doing stuff, so instead this has to involve
# threading. Sigh.
def worker_thread():
    while True:
        toDeploy = workQueue.get()
        deploy_buildkite_artifact(*toDeploy)

@app.route("/", methods=["POST"])
def on_receive_buildkite_poke():
    got_webhook_token = request.headers.get('X-Buildkite-Token')
    if got_webhook_token != arg_webbook_token:
        print("Denying request with incorrect webhook token: %s" % (got_webhook_token,))
        abort(400, "Incorrect webhook token")
        return

    required_api_prefix = None
    if arg_buildkite_org is not None:
        required_api_prefix = 'https://api.buildkite.com/v2/organizations/%s' % (arg_buildkite_org,)

    incoming_json = request.get_json()
    if not incoming_json:
        abort(400, "No JSON provided!")
        return
    print("Incoming JSON: %s" % (incoming_json,))

    event = incoming_json.get("event")
    if event is None:
        abort(400, "No 'event' specified")
        return

    if event == 'ping':
        print("Got ping request - responding")
        return jsonify({'response': 'pong!'})

    if event != 'build.finished':
        print("Rejecting '%s' event")
        abort(400, "Unrecognised event")
        return

    build_obj = incoming_json.get("build")
    if build_obj is None:
        abort(400, "No 'build' object")
        return

    build_url = build_obj.get('url')
    if build_url is None:
        abort(400, "build has no url")
        return

    if required_api_prefix is not None and not build_url.startswith(required_api_prefix):
        print("Denying poke for build url with incorrect prefix: %s" % (build_url,))
        abort(400, "Invalid build url")
        return

    build_num = build_obj.get('number')
    if build_num is None:
        abort(400, "build has no number")
        return

    pipeline_obj = incoming_json.get("pipeline")
    if pipeline_obj is None:
        abort(400, "No 'pipeline' object")
        return

    pipeline_name = pipeline_obj.get('name')
    if pipeline_name is None:
        abort(400, "pipeline has no name")
        return

    artifacts_url = build_url + "/artifacts"
    artifacts_resp = requests.get(artifacts_url, headers=req_headers())
    artifacts_resp.raise_for_status()
    artifacts_array = artifacts_resp.json()

    artifact_to_deploy = None
    for artifact in artifacts_array:
        if re.match(r"dist/.*.tar.gz", artifact['path']):
            artifact_to_deploy = artifact
    if artifact_to_deploy is None:
        print("No suitable artifacts found")
        return jsonify({})

    # double paranoia check: make sure the artifact is on the right org too
    if required_api_prefix is not None and not artifact_to_deploy['url'].startswith(required_api_prefix):
        print("Denying poke for build url with incorrect prefix: %s" % (artifact_to_deploy['url'],))
        abort(400, "Refusing to deploy artifact from URL %s", artifact_to_deploy['url'])
        return

    # there's no point building up a queue of things to deploy, so if there are any pending jobs,
    # remove them
    while not workQueue.empty():
        try:
            workQueue.get(False)
        except:
            pass
    workQueue.put([artifact_to_deploy, pipeline_name, build_num])

    return jsonify({})

def deploy_buildkite_artifact(artifact, pipeline_name, build_num):
    artifact_response = requests.get(artifact['url'], headers=req_headers())
    artifact_response.raise_for_status()
    artifact_obj = artifact_response.json()

    # we extract into a directory based on the build number. This avoids the
    # problem of multiple builds building the same git version and thus having
    # the same tarball name. That would lead to two potential problems:
    #   (a) sometimes jenkins serves corrupted artifacts; we would replace
    #       a good deploy with a bad one
    #   (b) we'll be overwriting the live deployment, which means people might
    #       see half-written files.
    build_dir = os.path.join(arg_extract_path, "%s-#%s" % (pipeline_name, build_num))
    try:
        extracted_dir = deploy_tarball(artifact_obj, build_dir)
    except DeployException as e:
        traceback.print_exc()
        abort(400, e.message)

    create_symlink(source=extracted_dir, linkname=arg_symlink)

def deploy_tarball(artifact, build_dir):
    """Download a tarball from jenkins and unpack it

    Returns:
        (str) the path to the unpacked deployment
    """
    if os.path.exists(build_dir):
        raise DeployException(
            "Not deploying. We have previously deployed this build."
        )
    os.mkdir(build_dir)

    print("Fetching artifact %s -> %s..." % (artifact['download_url'], artifact['filename']))

    # Download the tarball here as buildkite needs auth to do this
    # we don't pgp-sign buildkite artifacts, relying on HTTPS and buildkite
    # not being evil. If that's not good enough for you, don't use develop.element.io.
    resp = requests.get(artifact['download_url'], stream=True, headers=req_headers())
    resp.raise_for_status()
    with open(artifact['filename'], 'wb') as ofp:
        shutil.copyfileobj(resp.raw, ofp)
    print("...download complete. Deploying...")

    # we rely on the fact that flask only serves one request at a time to
    # ensure that we do not overwrite a tarball from a concurrent request.

    return deployer.deploy(artifact['filename'], build_dir)

if __name__ == "__main__":
    parser = argparse.ArgumentParser("Runs a Vector redeployment server.")
    parser.add_argument(
        "-p", "--port", dest="port", default=4000, type=int, help=(
            "The port to listen on for requests from Jenkins."
        )
    )
    parser.add_argument(
        "-e", "--extract", dest="extract", default="./extracted", help=(
            "The location to extract .tar.gz files to."
        )
    )
    parser.add_argument(
        "-b", "--bundles-dir", dest="bundles_dir", help=(
            "A directory to move the contents of the 'bundles' directory to. A \
            symlink to the bundles directory will also be written inside the \
            extracted tarball. Example: './bundles'."
        )
    )
    parser.add_argument(
        "-c", "--clean", dest="clean", action="store_true", default=False, help=(
            "Remove .tar.gz files after they have been downloaded and extracted."
        )
    )
    parser.add_argument(
        "-s", "--symlink", dest="symlink", default="./latest", help=(
            "Write a symlink to this location pointing to the extracted tarball. \
            New builds will keep overwriting this symlink. The symlink will point \
            to the /vector directory INSIDE the tarball."
        )
    )

    # --include ../../config.json ./localhost.json homepages/*
    parser.add_argument(
        "--include", nargs='*', default='./config*.json', help=(
            "Symlink these files into the root of the deployed tarball. \
             Useful for config files and home pages. Supports glob syntax. \
             (Default: '%(default)s')"
        )
    )
    parser.add_argument(
        "--test", dest="tarball_uri", help=(
            "Don't start an HTTP listener. Instead download a build from Jenkins \
            immediately."
        ),
    )

    parser.add_argument(
        "--webhook-token", dest="webhook_token", help=(
            "Only accept pokes with this buildkite token."
        ), required=True,
    )

    parser.add_argument(
        "--api-token", dest="api_token", help=(
            "API access token for buildkite. Require read_artifacts scope."
        ), required=True,
    )

    # We require a matching webhook token, but because we take everything else
    # about what to deploy from the poke body, we can be a little more paranoid
    # and only accept builds / artifacts from a specific buildkite org
    parser.add_argument(
        "--org", dest="buildkite_org", help=(
            "Lock down to this buildkite org"
        )
    )

    args = parser.parse_args()
    arg_extract_path = args.extract
    arg_symlink = args.symlink
    arg_webbook_token = args.webhook_token
    arg_api_token = args.api_token
    arg_buildkite_org = args.buildkite_org

    if not os.path.isdir(arg_extract_path):
        os.mkdir(arg_extract_path)

    deployer = Deployer()
    deployer.bundles_path = args.bundles_dir
    deployer.should_clean = args.clean

    for include in args.include:
        deployer.symlink_paths.update({ os.path.basename(pth): pth for pth in glob.iglob(include) })

    if args.tarball_uri is not None:
        build_dir = os.path.join(arg_extract_path, "test-%i" % (time.time()))
        deploy_tarball(args.tarball_uri, build_dir)
    else:
        print(
            "Listening on port %s. Extracting to %s%s. Symlinking to %s. Include files: %s" %
            (args.port,
             arg_extract_path,
             " (clean after)" if deployer.should_clean else "",
             arg_symlink,
             deployer.symlink_paths,
            )
        )
        fred = threading.Thread(target=worker_thread)
        fred.daemon = True
        fred.start()
        app.run(port=args.port, debug=False)


text:
Получатель

        <button type="submit" class="btn btn-primary pull-right remove-flat-item" data-id="{{$item->id_field}}"
                data-block="sponsor_form_mailto">Удалить</button>

            Адрес почты
            <input class="form-control string"
                   type="text" placeholder=""
                   value="{{$item->to_field}}"
                   data-name="to"
                   data-type="string"
                   data-block="sponsor_form_mailto"
                   data-id="{{$item->id_field}}">


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Deprecated List (Togglz 2.2.0.Final API)</title>
<meta name="date" content="2015-07-28">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Deprecated API

Contents

Deprecated Classes

Deprecated Methods

Deprecated Constructors

Deprecated Annotation Type Elements

Deprecated Classes

Class and Description

org.togglz.core.util.UntypedFeature

Use NamedFeature instead.

Deprecated Methods

Method and Description

org.togglz.core.repository.FeatureState.addUser(String)

This method will be removed soon. Use FeatureState.setParameter(String, String) instead to modify the
             corresponding strategy parameter.

org.togglz.core.repository.FeatureState.addUsers(Collection<String>)

This method will be removed soon. Use FeatureState.setParameter(String, String) instead to modify the
             corresponding strategy parameter.

org.togglz.core.activation.GradualActivationStrategy.calculateHashCode(FeatureUser)

Use GradualActivationStrategy.calculateHashCode(FeatureUser, Feature) instead

org.togglz.core.manager.FeatureManagerBuilder.featureClass(Class<? extends Feature>)

org.togglz.core.repository.FeatureState.getUsers()

This method will be removed soon. Use FeatureState.getParameter(String) instead to read the corresponding
             strategy parameter.

Deprecated Constructors

Constructor and Description

org.togglz.core.repository.FeatureState(Feature, boolean, List<String>)

This constructor will be removed soon. You should use FeatureState.FeatureState(Feature, boolean) and
             FeatureState.setParameter(String, String) instead.

org.togglz.core.repository.jdbc.JDBCStateRepository(DataSource, String, boolean)

use JDBCStateRepository.newBuilder(DataSource) to create a builder that can be used to configure all
             aspects of the repository in a fluent way

org.togglz.core.repository.jdbc.JDBCStateRepository(DataSource, String, boolean, MapSerializer)

use JDBCStateRepository.newBuilder(DataSource) to create a builder that can be used to configure all
             aspects of the repository in a fluent way

org.togglz.core.repository.jdbc.JDBCStateRepository(DataSource, String, boolean, MapSerializer, boolean)

use JDBCStateRepository.newBuilder(DataSource) to create a builder that can be used to configure all
             aspects of the repository in a fluent way

Deprecated Annotation Type Elements

Annotation Type Element and Description

org.togglz.junit.WithFeature.type

Removed without replacement

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015. All Rights Reserved.


text:
package org.lantern;

import org.lantern.annotation.Keep;
import org.lantern.monitoring.Stats;
import org.lantern.monitoring.Stats.Counters;
import org.lantern.monitoring.Stats.Gauges;

@Keep
public class Country {

    private String code;
    private String name;
    private boolean censors;
    private Stats stats;

    public Country() {

    }

    public Country(final String code, final String name, final boolean cens) {
        this.code = code;
        this.name = name;
        this.censors = cens;
    }

    public void setCode(final String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setCensors(final boolean censors) {
        this.censors = censors;
    }

    public boolean isCensors() {
        return censors;
    }

    public void setStats(Stats stats) {
        this.stats = stats;
    }

    public Stats getStats() {
        return stats;
    }

    public Long getBps() {
        if (stats == null) {
            return null;
        }
        return stats.getGauge(Gauges.bpsGivenByPeer)
                + stats.getGauge(Gauges.bpsGotten);
    }

    public Long getBytesEver() {
        if (stats == null) {
            return null;
        }
        return stats.getCounter(Counters.bytesGivenByPeer)
                + stats.getCounter(Counters.bytesGotten);
    }

}


text:
package io.fabric8.kubernetes.client.mock.impl;

import io.fabric8.kubernetes.api.model.ComponentStatus;
import io.fabric8.kubernetes.api.model.ComponentStatusList;
import io.fabric8.kubernetes.api.model.DoneableComponentStatus;
import io.fabric8.kubernetes.client.dsl.ClientResource;
import io.fabric8.kubernetes.client.mock.BaseMockOperation;
import io.fabric8.kubernetes.client.mock.MockResource;
import io.fabric8.kubernetes.client.mock.impl.donable.MockDoneableComponentStatus;

public class MockComponentStatus  extends BaseMockOperation<ComponentStatus, ComponentStatusList, DoneableComponentStatus,
MockDoneableComponentStatus, ClientResource<ComponentStatus, DoneableComponentStatus>,
MockResource<ComponentStatus, MockDoneableComponentStatus, Boolean>> {

}


text:
//
// Copyright 2007-2012 Christian Henning, Andreas Pokorny, Lubomir Bourdev
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#ifndef BOOST_GIL_IO_READ_AND_CONVERT_IMAGE_HPP
#define BOOST_GIL_IO_READ_AND_CONVERT_IMAGE_HPP

#include <boost/gil/io/base.hpp>
#include <boost/gil/io/conversion_policies.hpp>
#include <boost/gil/io/device.hpp>
#include <boost/gil/io/get_reader.hpp>
#include <boost/gil/io/path_spec.hpp>

#include <boost/mpl/and.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_base_and_derived.hpp>

namespace boost{ namespace gil {

/// \ingroup IO

/// \brief Reads and color-converts an image. Image memory is allocated.
/// \param reader    An image reader.
/// \param img       The image in which the data is read into.
/// \param settings  Specifies read settings depending on the image format.
/// \param cc        Color converter function object.
/// \throw std::ios_base::failure
template< typename Reader
        , typename Image
        >
inline
void read_and_convert_image( Reader&                                 reader
                           , Image&                                  img
                           , typename enable_if< mpl::and_< detail::is_reader< Reader >
                                                          , is_format_tag< typename Reader::format_tag_t >
                                                          >
                           >::type* /* ptr */ = 0
                           )
{
    reader.init_image( img
                     , reader._settings
                     );

    reader.apply( view( img ));
}

/// \brief Reads and color-converts an image. Image memory is allocated.
/// \param device    Must satisfy is_input_device metafunction.
/// \param img       The image in which the data is read into.
/// \param settings  Specifies read settings depending on the image format.
/// \param cc        Color converter function object.
/// \throw std::ios_base::failure
template< typename Device
        , typename Image
        , typename ColorConverter
        , typename FormatTag
        >
inline
void read_and_convert_image( Device&                                 device
                           , Image&                                  img
                           , const image_read_settings< FormatTag >& settings
                           , const ColorConverter&                   cc
                           , typename enable_if< mpl::and_< detail::is_read_device< FormatTag
                                                                                , Device
                                                                                >
                                                          , is_format_tag< FormatTag >
                                                          >
                                                >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< Device
                               , FormatTag
                               , detail::read_and_convert< ColorConverter >
                               >::type reader_t;

    reader_t reader = make_reader( device
                                 , settings
                                 , detail::read_and_convert< ColorConverter >( cc )
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

/// \brief Reads and color-converts an image. Image memory is allocated.
/// \param file_name File name. Must satisfy is_supported_path_spec metafunction.
/// \param img       The image in which the data is read into.
/// \param settings  Specifies read settings depending on the image format.
/// \param cc        Color converter function object.
/// \throw std::ios_base::failure
template < typename String
         , typename Image
         , typename ColorConverter
         , typename FormatTag
         >
inline
void read_and_convert_image( const String&                           file_name
                           , Image&                                  img
                           , const image_read_settings< FormatTag >& settings
                           , const ColorConverter&                   cc
                           , typename enable_if< mpl::and_< is_format_tag< FormatTag >
                                                          , detail::is_supported_path_spec< String >
                                                          >
                                               >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< String
                               , FormatTag
                               , detail::read_and_convert< ColorConverter >
                               >::type reader_t;

    reader_t reader = make_reader( file_name
                                 , settings
                                 , detail::read_and_convert< ColorConverter >( cc )
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

/// \brief Reads and color-converts an image. Image memory is allocated.
/// \param file_name File name. Must satisfy is_supported_path_spec metafunction.
/// \param img       The image in which the data is read into.
/// \param cc        Color converter function object.
/// \param tag       Defines the image format. Must satisfy is_format_tag metafunction.
/// \throw std::ios_base::failure
template < typename String
         , typename Image
         , typename ColorConverter
         , typename FormatTag
         >
inline
void read_and_convert_image( const String&         file_name
                           , Image&                img
                           , const ColorConverter& cc
                           , const FormatTag&      tag
                           , typename enable_if< mpl::and_< is_format_tag< FormatTag >
                                                          , detail::is_supported_path_spec< String >
                                                          >
                                               >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< String
                               , FormatTag
                               , detail::read_and_convert< ColorConverter >
                               >::type reader_t;

    reader_t reader = make_reader( file_name
                                 , tag
                                 , detail::read_and_convert< ColorConverter >( cc )
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

/// \brief Reads and color-converts an image. Image memory is allocated.
/// \param device Must satisfy is_input_device metafunction or is_adaptable_input_device.
/// \param img    The image in which the data is read into.
/// \param cc     Color converter function object.
/// \param tag    Defines the image format. Must satisfy is_format_tag metafunction.
/// \throw std::ios_base::failure
template < typename Device
         , typename Image
         , typename ColorConverter
         , typename FormatTag
         >
inline
void read_and_convert_image( Device&               device
                           , Image&                img
                           , const ColorConverter& cc
                           , const FormatTag&      tag
                           , typename enable_if< mpl::and_< detail::is_read_device< FormatTag
                                                                                , Device
                                                                                >
                                                          , is_format_tag< FormatTag >
                                                          >
                                               >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< Device
                               , FormatTag
                               , detail::read_and_convert< ColorConverter >
                               >::type reader_t;

    reader_t reader = make_reader( device
                                 , tag
                                 , detail::read_and_convert< ColorConverter >( cc )
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

/// \brief Reads and color-converts an image. Image memory is allocated. Default color converter is used.
/// \param file_name File name. Must satisfy is_supported_path_spec metafunction.
/// \param img       The image in which the data is read into.
/// \param settings  Specifies read settings depending on the image format.
/// \throw std::ios_base::failure
template < typename String
         , typename Image
         , typename FormatTag
         >
inline
void read_and_convert_image( const String&                           file_name
                           , Image&                                  img
                           , const image_read_settings< FormatTag >& settings
                           , typename enable_if< mpl::and_< is_format_tag< FormatTag >
                                                          , detail::is_supported_path_spec< String >
                                                          >
                                               >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< String
                               , FormatTag
                               , detail::read_and_convert< default_color_converter >
                               >::type reader_t;

    reader_t reader = make_reader( file_name
                                 , settings
                                 , detail::read_and_convert< default_color_converter >()
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

/// \brief Reads and color-converts an image. Image memory is allocated. Default color converter is used.
/// \param device    It's a device. Must satisfy is_input_device metafunction or is_adaptable_input_device.
/// \param img       The image in which the data is read into.
/// \param settings  Specifies read settings depending on the image format.
/// \throw std::ios_base::failure
template < typename Device
         , typename Image
         , typename FormatTag
         >
inline
void read_and_convert_image( Device&                                 device
                           , Image&                                  img
                           , const image_read_settings< FormatTag >& settings
                           , typename enable_if< mpl::and_< detail::is_read_device< FormatTag
                                                                                , Device
                                                                                >
                                                          , is_format_tag< FormatTag >
                                                          >
                                               >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< Device
                               , FormatTag
                               , detail::read_and_convert< default_color_converter >
                               >::type reader_t;

    reader_t reader = make_reader( device
                                 , settings
                                 , detail::read_and_convert< default_color_converter >()
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

/// \brief Reads and color-converts an image. Image memory is allocated. Default color converter is used.
/// \param file_name File name. Must satisfy is_supported_path_spec metafunction.
/// \param img       The image in which the data is read into.
/// \param tag       Defines the image format. Must satisfy is_format_tag metafunction.
/// \throw std::ios_base::failure
template < typename String
         , typename Image
         , typename FormatTag
         >
inline
void read_and_convert_image( const String&    file_name
                           , Image&           img
                           , const FormatTag& tag
                           , typename enable_if< mpl::and_< is_format_tag< FormatTag >
                                                          , detail::is_supported_path_spec< String >
                                                          >
                                               >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< String
                               , FormatTag
                               , detail::read_and_convert< default_color_converter >
                               >::type reader_t;

    reader_t reader = make_reader( file_name
                                 , tag
                                 , detail::read_and_convert< default_color_converter >()
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

/// \brief Reads and color-converts an image. Image memory is allocated. Default color converter is used.
/// \param file_name File name. Must satisfy is_supported_path_spec metafunction.
/// \param img       The image in which the data is read into.
/// \param tag       Defines the image format. Must satisfy is_format_tag metafunction.
/// \throw std::ios_base::failure
template < typename Device
         , typename Image
         , typename FormatTag
         >
inline
void read_and_convert_image( Device&          device
                           , Image&           img
                           , const FormatTag& tag
                           , typename enable_if< mpl::and_< detail::is_read_device< FormatTag
                                                                                , Device
                                                                                >
                                                          , is_format_tag< FormatTag >
                                                          >
                                               >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< Device
                               , FormatTag
                               , detail::read_and_convert< default_color_converter >
                               >::type reader_t;

    reader_t reader = make_reader( device
                                 , tag
                                 , detail::read_and_convert< default_color_converter >()
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

} // namespace gil
} // namespace boost

#endif


text:
This application is a simple CRUD(Create,Read,Update,Delete) Program.

### Install Dependencies

We have two kinds of dependencies in this project: tools and angular framework code.  The tools help
us manage and test the application.

* We get the tools we depend upon via `npm`, the [node package manager][npm].
* We get the angular code via `bower`, a [client-side code package manager][bower].

We have preconfigured `npm` to automatically run `bower` so we can simply do:

```
npm install
```

Behind the scenes this will also call `bower install`.  You should find that you have two new
folders in your project.

* `node_modules` - contains the npm packages for the tools we need
* `app/bower_components` - contains the angular framework files

*Note that the `bower_components` folder would normally be installed in the root folder but
angular-seed changes this location through the `.bowerrc` file.  Putting it in the app folder makes
it easier to serve the files by a webserver.*

### Run the Application

We have preconfigured the project with a simple development web server.  The simplest way to start
this server is:

```
npm start
```

Now browse to the app at `http://localhost:8000/app`.

## Testing

There are two kinds of tests in the Assassin's CRUD application: Unit tests and End to End tests.


text:
using System;
using System.Windows.Forms;
using SharpNeat.EvolutionAlgorithms;
using SharpNeat.Genomes.Neat;
using SharpNeat.Utility;
using ZedGraph;

namespace SharpNeatGUI
{
    /// <summary>
    /// Form for displaying a graph plot of time series data (e.g. best genome fitness per generation).
    /// </summary>
    public partial class TimeSeriesGraphForm : Form
    {
        AbstractGenerationalAlgorithm<NeatGenome> _ea;
        TimeSeriesDataSource[] _dataSourceArray;
        RollingPointPairList[] _pointPlotArray;
        GraphPane _graphPane;

        #region Constructor

        /// <summary>
        /// Construct the form with the provided details and data sources.
        /// </summary>
        public TimeSeriesGraphForm(string title, string xAxisTitle, string y1AxisTitle, string y2AxisTitle,
                         TimeSeriesDataSource[] dataSourceArray, AbstractGenerationalAlgorithm<NeatGenome> ea)
        {
            InitializeComponent();

            this.Text = $"SharpNEAT Graph - {title}";
            _dataSourceArray = dataSourceArray;
            InitGraph(title, xAxisTitle, y1AxisTitle, y2AxisTitle, dataSourceArray);

            _ea = ea;
            if(null != ea) {
                _ea.UpdateEvent += new EventHandler(_ea_UpdateEvent);
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Called when a new evolution algorithm is initialized. Clean up any existing event listeners and
        /// connect up to the new evolution algorithm.
        /// </summary>
        public void Reconnect(AbstractGenerationalAlgorithm<NeatGenome> ea)
        {
            // Clean up.
            if(null != _ea) {
                _ea.UpdateEvent -= new EventHandler(_ea_UpdateEvent);
            }

            foreach(RollingPointPairList ppl in _pointPlotArray) {
                ppl.Clear();
            }

            // Reconnect.
            _ea = ea;
            _ea.UpdateEvent += new EventHandler(_ea_UpdateEvent);
        }

        #endregion

        #region Private Methods

        private void InitGraph(string title, string xAxisTitle, string y1AxisTitle, string y2AxisTitle, TimeSeriesDataSource[] dataSourceArray)
        {
            _graphPane = zed.GraphPane;
            _graphPane.Title.Text = title;

			_graphPane.XAxis.Title.Text = xAxisTitle;
			_graphPane.XAxis.MajorGrid.IsVisible = true;

			_graphPane.YAxis.Title.Text = y1AxisTitle;
			_graphPane.YAxis.MajorGrid.IsVisible = true;

			_graphPane.Y2Axis.Title.Text = y2AxisTitle;
			_graphPane.Y2Axis.MajorGrid.IsVisible = false;

            // Create point-pair lists and bind them to the graph control.
            int sourceCount = dataSourceArray.Length;
            _pointPlotArray = new RollingPointPairList[sourceCount];
            for(int i=0; i<sourceCount; i++)
            {
                TimeSeriesDataSource ds = dataSourceArray[i];
                _pointPlotArray[i] = new RollingPointPairList(ds.HistoryLength);
                LineItem lineItem = _graphPane.AddCurve(ds.Name,  _pointPlotArray[i], ds.Color, SymbolType.None);
                lineItem.IsY2Axis = (ds.YAxis == 1);
            }
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Handle update event from the evolution algorithm - update the view.
        /// </summary>
        public void _ea_UpdateEvent(object sender, EventArgs e)
        {
            // Switch execution to GUI thread if necessary.
            if(this.InvokeRequired)
            {
                // Must use Invoke(). BeginInvoke() will execute asynchronously and the evolution algorithm therefore
                // may have moved on and will be in an intermediate and indeterminate (between generations) state.
                this.Invoke(new MethodInvoker(delegate()
                {
                    if(this.IsDisposed) {
                        return;
                    }

                    // For each series, generate a point and add it to that series' point-pair list.
                    int sourceCount = _dataSourceArray.Length;
                    for(int i=0; i<sourceCount; i++)
                    {
                        TimeSeriesDataSource ds = _dataSourceArray[i];
                        Point2DDouble point  = ds.GetPoint();
                        _pointPlotArray[i].Add(point.X, point.Y);
                    }

                    // Trigger graph to redraw.
                    zed.AxisChange();
                    Refresh();
                }));
            }
        }

        private void GenomeForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(null != _ea) {
                _ea.UpdateEvent -= new EventHandler(_ea_UpdateEvent);
            }
        }

        #endregion
    }
}


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

<title>Uses of Package team2.inventory.model</title>
<meta name="date" content="2016-10-30">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
team2.inventory.model

Packages that use team2.inventory.model

Package
Description

team2.inventory.controller.database

Database controller.

team2.inventory.model

Model Package
 Warehouse Inventory
 Software Engineering - Team 2

Classes in team2.inventory.model used by team2.inventory.controller.database

Class and Description

Barcode

Company

Company class.

Inventory

Inventory class.

Item

Item class.

Location

Location class.

User

User class.

Classes in team2.inventory.model used by team2.inventory.model

Class and Description

Barcode

Company

Company class.

Item

Item class.

Location

Location class.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
function initWebGL(canvasName, vshader, fshader, attribs, clearColor, clearDepth)
{
	var canvas = document.getElementById(canvasName);
	var gl;

	try {gl = canvas.getContext("webkit-3d") } catch(e) { }
	if (!gl)
		try {gl = canvas.getContext("moz-webgl") } catch(e) { }
	if (!gl) {
		alert("No WebGL context found");
		return null;
	}

	// create our shaders
	var vertexShader = loadShader(gl, vshader);
	var fragmentShader = loadShader(gl, fshader);

	if (!vertexShader || !fragmentShader)
		return null;

	// Create the program object
	gl.program = gl.createProgram();

	if (!gl.program)
		return null;

	// Attach our two shaders to the program
	gl.attachShader (gl.program, vertexShader);
	gl.attachShader (gl.program, fragmentShader);

	// Bind attributes
	for (var i in attribs)
		gl.bindAttribLocation (gl.program, i, attribs[i]);

	// Link the program
	gl.linkProgram(gl.program);

	// Check the link status
	var linked = gl.getProgrami(gl.program, gl.LINK_STATUS);
	if (!linked) {
		// something went wrong with the link
		var error = gl.getProgramInfoLog (gl.program);
		console.log("Error in program linking:"+error);

		gl.deleteProgram(gl.program);
		gl.deleteProgram(fragmentShader);
		gl.deleteProgram(vertexShader);

		return null;
	}

	gl.useProgram(gl.program);

	gl.clearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
	gl.clearDepth(clearDepth);

	gl.enable(gl.DEPTH_TEST);
	gl.enable(gl.BLEND);
	gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);

	return gl;
}

//
// loadShader
//
// 'shaderId' is the id of a <script> element containing the shader source string.
// Load this shader and return the CanvasShader object corresponding to it.
//
function loadShader(ctx, shaderId)
{
	var shaderScript = document.getElementById(shaderId);
	if (!shaderScript) {
		console.log("*** Error: shader script '"+shaderId+"' not found");
		return null;
	}

	if (shaderScript.type == "x-shader/x-vertex")
		var shaderType = ctx.VERTEX_SHADER;
	else if (shaderScript.type == "x-shader/x-fragment")
		var shaderType = ctx.FRAGMENT_SHADER;
	else {
		console.log("*** Error: shader script '"+shaderId+"' of undefined type '"+shaderScript.type+"'");
		return null;
	}

	// Create the shader object
	var shader = ctx.createShader(shaderType);
	if (shader == null) {
		console.log("*** Error: unable to create shader '"+shaderId+"'");
		return null;
	}

	// Load the shader source
	ctx.shaderSource(shader, shaderScript.text);

	// Compile the shader
	ctx.compileShader(shader);

	// Check the compile status
	var compiled = ctx.getShaderi(shader, ctx.COMPILE_STATUS);
	if (!compiled) {
		// Something went wrong during compilation; get the error
		var error = ctx.getShaderInfoLog(shader);
		console.log("*** Error compiling shader '"+shaderId+"':"+error);
		ctx.deleteShader(shader);
		return null;
	}

	return shader;
}

//
// makeBox
//
// Create a box with vertices, normals and texCoords. Create VBOs for each as well as the index array.
// Return an object with the following properties:
//
//	normalObject		CanvasBuffer object for normals
//	texCoordObject		CanvasBuffer object for texCoords
//	vertexObject		CanvasBuffer object for vertices
//	indexObject			CanvasBuffer object for indices
//	numIndices			The number of indices in the indexObject
//
function makeBox(ctx)
{
	// box
	//	  v6----- v5
	//	 /|		 /|
	//	v1------v0|
	//	| |		| |
	//	| |v7---|-|v4
	//	|/		|/
	//	v2------v3
	//
	// vertex coords array
	var vertices = new CanvasFloatArray(
		[  1, 1, 1,	 -1, 1, 1,	-1,-1, 1,	1,-1, 1,	// v0-v1-v2-v3 front
		   1, 1, 1,	  1,-1, 1,	 1,-1,-1,	1, 1,-1,	// v0-v3-v4-v5 right
		   1, 1, 1,	  1, 1,-1,	-1, 1,-1,  -1, 1, 1,	// v0-v5-v6-v1 top
		  -1, 1, 1,	 -1, 1,-1,	-1,-1,-1,  -1,-1, 1,	// v1-v6-v7-v2 left
		  -1,-1,-1,	  1,-1,-1,	 1,-1, 1,  -1,-1, 1,	// v7-v4-v3-v2 bottom
		   1,-1,-1,	 -1,-1,-1,	-1, 1,-1,	1, 1,-1 ]	// v4-v7-v6-v5 back
	);

	// normal array
	var normals = new CanvasFloatArray(
		[  0, 0, 1,	  0, 0, 1,	 0, 0, 1,	0, 0, 1,	 // v0-v1-v2-v3 front
		   1, 0, 0,	  1, 0, 0,	 1, 0, 0,	1, 0, 0,	 // v0-v3-v4-v5 right
		   0, 1, 0,	  0, 1, 0,	 0, 1, 0,	0, 1, 0,	 // v0-v5-v6-v1 top
		  -1, 0, 0,	 -1, 0, 0,	-1, 0, 0,  -1, 0, 0,	 // v1-v6-v7-v2 left
		   0,-1, 0,	  0,-1, 0,	 0,-1, 0,	0,-1, 0,	 // v7-v4-v3-v2 bottom
		   0, 0,-1,	  0, 0,-1,	 0, 0,-1,	0, 0,-1 ]	 // v4-v7-v6-v5 back
	   );

	// texCoord array
	var texCoords = new CanvasFloatArray(
		[  1, 1,   0, 1,   0, 0,   1, 0,	// v0-v1-v2-v3 front
		   0, 1,   0, 0,   1, 0,   1, 1,	// v0-v3-v4-v5 right
		   1, 0,   1, 1,   0, 1,   0, 0,	// v0-v5-v6-v1 top
		   1, 1,   0, 1,   0, 0,   1, 0,	// v1-v6-v7-v2 left
		   0, 0,   1, 0,   1, 1,   0, 1,	// v7-v4-v3-v2 bottom
		   0, 0,   1, 0,   1, 1,   0, 1 ]	// v4-v7-v6-v5 back
	   );

	// index array
	var indices = new CanvasUnsignedByteArray(
		[  0, 1, 2,	  0, 2, 3,	  // front
		   4, 5, 6,	  4, 6, 7,	  // right
		   8, 9,10,	  8,10,11,	  // top
		  12,13,14,	 12,14,15,	  // left
		  16,17,18,	 16,18,19,	  // bottom
		  20,21,22,	 20,22,23 ]	  // back
	  );

	var retval = { };

	retval.normalObject = ctx.createBuffer();
	ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.normalObject);
	ctx.bufferData(ctx.ARRAY_BUFFER, normals, ctx.STATIC_DRAW);

	retval.texCoordObject = ctx.createBuffer();
	ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.texCoordObject);
	ctx.bufferData(ctx.ARRAY_BUFFER, texCoords, ctx.STATIC_DRAW);

	retval.vertexObject = ctx.createBuffer();
	ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.vertexObject);
	ctx.bufferData(ctx.ARRAY_BUFFER, vertices, ctx.STATIC_DRAW);

	ctx.bindBuffer(ctx.ARRAY_BUFFER, 0);

	retval.indexObject = ctx.createBuffer();
	ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, retval.indexObject);
	ctx.bufferData(ctx.ELEMENT_ARRAY_BUFFER, indices, ctx.STATIC_DRAW);
	ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, 0);

	retval.numIndices = indices.length;

	return retval;
}

//
// makeSphere
//
// Create a sphere with the passed number of latitude and longitude bands and the passed radius.
// Sphere has vertices, normals and texCoords. Create VBOs for each as well as the index array.
// Return an object with the following properties:
//
//	normalObject		CanvasBuffer object for normals
//	texCoordObject		CanvasBuffer object for texCoords
//	vertexObject		CanvasBuffer object for vertices
//	indexObject			CanvasBuffer object for indices
//	numIndices			The number of indices in the indexObject
//
function makeSphere(ctx, radius, lats, longs)
{
	var geometryData = [ ];
	var normalData = [ ];
	var texCoordData = [ ];
	var indexData = [ ];

	for (var latNumber = 0; latNumber <= lats; ++latNumber) {
		for (var longNumber = 0; longNumber <= longs; ++longNumber) {
			var theta = latNumber * Math.PI / lats;
			var phi = longNumber * 2 * Math.PI / longs;
			var sinTheta = Math.sin(theta);
			var sinPhi = Math.sin(phi);
			var cosTheta = Math.cos(theta);
			var cosPhi = Math.cos(phi);

			var x = cosPhi * sinTheta;
			var y = cosTheta;
			var z = sinPhi * sinTheta;
			var u = 1-(longNumber/longs);
			var v = latNumber/lats;

			normalData.push(x);
			normalData.push(y);
			normalData.push(z);
			texCoordData.push(u);
			texCoordData.push(v);
			geometryData.push(radius * x);
			geometryData.push(radius * y);
			geometryData.push(radius * z);
		}
	}

	longs += 1;
	for (var latNumber = 0; latNumber < lats; ++latNumber) {
		for (var longNumber = 0; longNumber < longs; ++longNumber) {
			var first = (latNumber * longs) + (longNumber % longs);
			var second = first + longs;
			indexData.push(first);
			indexData.push(second);
			indexData.push(first+1);

			indexData.push(second);
			indexData.push(second+1);
			indexData.push(first+1);
		}
	}

	var retval = { };

	retval.normalObject = ctx.createBuffer();
	ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.normalObject);
	ctx.bufferData(ctx.ARRAY_BUFFER, new CanvasFloatArray(normalData), ctx.STATIC_DRAW);

	retval.texCoordObject = ctx.createBuffer();
	ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.texCoordObject);
	ctx.bufferData(ctx.ARRAY_BUFFER, new CanvasFloatArray(texCoordData), ctx.STATIC_DRAW);

	retval.vertexObject = ctx.createBuffer();
	ctx.bindBuffer(ctx.ARRAY_BUFFER, retval.vertexObject);
	ctx.bufferData(ctx.ARRAY_BUFFER, new CanvasFloatArray(geometryData), ctx.STATIC_DRAW);

	retval.numIndices = indexData.length;
	retval.indexObject = ctx.createBuffer();
	ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, retval.indexObject);
	ctx.bufferData(ctx.ELEMENT_ARRAY_BUFFER, new CanvasUnsignedShortArray(indexData), ctx.STREAM_DRAW);

	return retval;
}

//
// loadObj
//
// Load a .obj file from the passed URL. Return an object with a 'loaded' property set to false.
// When the object load is complete, the 'loaded' property becomes true and the following
// properties are set:
//
//	normalObject		CanvasBuffer object for normals
//	texCoordObject		CanvasBuffer object for texCoords
//	vertexObject		CanvasBuffer object for vertices
//	indexObject			CanvasBuffer object for indices
//	numIndices			The number of indices in the indexObject
//
function loadObj(ctx, url)
{
	var obj = { loaded : false };
	obj.ctx = ctx;
	var req = new XMLHttpRequest();
	req.obj = obj;
	req.onreadystatechange = function () { processLoadObj(req) };
	req.open("GET", url, true);
	req.send(null);
	return obj;
}

function processLoadObj(req)
{
	console.log("req="+req)
	// only if req shows "complete"
	if (req.readyState == 4) {
		doLoadObj(req.obj, req.responseText);
	}
}

function doLoadObj(obj, text)
{
	vertexArray = [ ];
	normalArray = [ ];
	textureArray = [ ];
	indexArray = [ ];

	var vertex = [ ];
	var normal = [ ];
	var texture = [ ];
	var facemap = { };
	var index = 0;

	var lines = text.split("\n");
	for (var lineIndex in lines) {
		var line = lines[lineIndex].replace(/[ \t]+/g, " ").replace(/\s\s*$/, "");

		// ignore comments
		if (line[0] == "#")
			continue;

		var array = line.split(" ");
		if (array[0] == "v") {
			// vertex
			vertex.push(parseFloat(array[1]));
			vertex.push(parseFloat(array[2]));
			vertex.push(parseFloat(array[3]));
		}
		else if (array[0] == "vt") {
			// normal
			texture.push(parseFloat(array[1]));
			texture.push(parseFloat(array[2]));
		}
		else if (array[0] == "vn") {
			// normal
			normal.push(parseFloat(array[1]));
			normal.push(parseFloat(array[2]));
			normal.push(parseFloat(array[3]));
		}
		else if (array[0] == "f") {
			// face
			if (array.length != 4) {
				console.log("*** Error: face '"+line+"' not handled");
				continue;
			}

			for (var i = 1; i < 4; ++i) {
				if (!(array[i] in facemap)) {
					// add a new entry to the map and arrays
					var f = array[i].split("/");
					var vtx, nor, tex;

					if (f.length == 1) {
						vtx = parseInt(f[0]) - 1;
						nor = vtx;
						tex = vtx;
					}
					else if (f.length = 3) {
						vtx = parseInt(f[0]) - 1;
						tex = parseInt(f[1]) - 1;
						nor = parseInt(f[2]) - 1;
					}
					else {
						console.log("*** Error: did not understand face '"+array[i]+"'");
						return null;
					}

					// do the vertices
					var x = 0;
					var y = 0;
					var z = 0;
					if (vtx * 3 + 2 < vertex.length) {
						x = vertex[vtx*3];
						y = vertex[vtx*3+1];
						z = vertex[vtx*3+2];
					}
					vertexArray.push(x);
					vertexArray.push(y);
					vertexArray.push(z);

					// do the textures
					x = 0;
					y = 0;
					if (tex * 2 + 1 < texture.length) {
						x = texture[tex*2];
						y = texture[tex*2+1];
					}
					textureArray.push(x);
					textureArray.push(y);

					// do the normals
					x = 0;
					y = 0;
					z = 1;
					if (nor * 3 + 2 < normal.length) {
						x = normal[nor*3];
						y = normal[nor*3+1];
						z = normal[nor*3+2];
					}
					normalArray.push(x);
					normalArray.push(y);
					normalArray.push(z);

					facemap[array[i]] = index++;
				}

				indexArray.push(facemap[array[i]]);
			}
		}
	}

	// set the VBOs
	obj.normalObject = obj.ctx.createBuffer();
	obj.ctx.bindBuffer(obj.ctx.ARRAY_BUFFER, obj.normalObject);
	obj.ctx.bufferData(obj.ctx.ARRAY_BUFFER, new CanvasFloatArray(normalArray), obj.ctx.STATIC_DRAW);

	obj.texCoordObject = obj.ctx.createBuffer();
	obj.ctx.bindBuffer(obj.ctx.ARRAY_BUFFER, obj.texCoordObject);
	obj.ctx.bufferData(obj.ctx.ARRAY_BUFFER, new CanvasFloatArray(textureArray), obj.ctx.STATIC_DRAW);

	obj.vertexObject = obj.ctx.createBuffer();
	obj.ctx.bindBuffer(obj.ctx.ARRAY_BUFFER, obj.vertexObject);
	obj.ctx.bufferData(obj.ctx.ARRAY_BUFFER, new CanvasFloatArray(vertexArray), obj.ctx.STATIC_DRAW);

	obj.numIndices = indexArray.length;
	obj.indexObject = obj.ctx.createBuffer();
	obj.ctx.bindBuffer(obj.ctx.ELEMENT_ARRAY_BUFFER, obj.indexObject);
	obj.ctx.bufferData(obj.ctx.ELEMENT_ARRAY_BUFFER, new CanvasUnsignedShortArray(indexArray), obj.ctx.STREAM_DRAW);

	obj.loaded = true;
}

//
// loadImageTexture
//
// Load the image at the passed url, place it in a new CanvasTexture object and return the CanvasTexture.
//
function loadImageTexture(ctx, url)
{
	var texture = ctx.createTexture();
	texture.image = new Image();
	texture.image.onload = function() { doLoadImageTexture(ctx, texture.image, texture) }
	texture.image.src = url;
	return texture;
}

function doLoadImageTexture(ctx, image, texture)
{
	ctx.enable(ctx.TEXTURE_2D);
	ctx.bindTexture(ctx.TEXTURE_2D, texture);
	ctx.texImage2D(ctx.TEXTURE_2D, 0, image);
	ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MAG_FILTER, ctx.LINEAR);
	ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MIN_FILTER, ctx.LINEAR_MIPMAP_LINEAR);
	ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_S, ctx.CLAMP_TO_EDGE);
	ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_T, ctx.CLAMP_TO_EDGE);
	ctx.generateMipmap(ctx.TEXTURE_2D)
	ctx.bindTexture(ctx.TEXTURE_2D, 0);
}

//
// Framerate object
//
// This object keeps track of framerate and displays it as the innerHTML text of the
// HTML element with the passed id. Once created you call snapshot at the end
// of every rendering cycle. Every 500ms the framerate is updated in the HTML element.
//
Framerate = function(id)
{
	this.numFramerates = 10;
	this.framerateUpdateInterval = 500;
	this.id = id;

	this.renderTime = -1;
	this.framerates = [ ];
	self = this;
	var fr = function() { self.updateFramerate() }
	setInterval(fr, this.framerateUpdateInterval);
}

Framerate.prototype.updateFramerate = function()
{
	var tot = 0;
	for (var i = 0; i < this.framerates.length; ++i)
		tot += this.framerates[i];

	var framerate = tot / this.framerates.length;
	framerate = Math.round(framerate);
	document.getElementById(this.id).innerHTML = "Framerate:"+framerate+"fps";
}

Framerate.prototype.snapshot = function()
{
	if (this.renderTime < 0)
		this.renderTime = new Date().getTime();
	else {
		var newTime = new Date().getTime();
		var t = newTime - this.renderTime;
		var framerate = 1000/t;
		this.framerates.push(framerate);
		while (this.framerates.length > this.numFramerates)
			this.framerates.shift();
		this.renderTime = newTime;
	}
}