text:
:-use_module(support).
:-use_module(data).

%%
%	Generates all possible combos for passed lines conditions, and length
%%
generate(LineCombos, Lines, Size) :- generate_supp(1, LineCombos, Lines, Size).

%%
%	Supportive predicate for generate/3 to include line number
%%
generate_supp(_, [], [], _).
generate_supp(LineNumber, [line(LineNumber,Combos)|LineCombosTail], [Line|LinesTail], Size) :-
		findall(Combo, combinate(Line, Size, Combo), Combos),
		NextLineNumber is LineNumber + 1,
		generate_supp(NextLineNumber, LineCombosTail, LinesTail, Size).

%%
%	Returns possible line for passed conditions and size
%%
combinate(Line, Size, Combo) :-
		sum(Sum, Line),
		length(Line, Length),
		CortegeLength is Sum + Length - 1,
		combinate_supp(Line, 1, CortegeLength, Size, [], Combo).

%%
%	Supportive predicate for combinate/3
%%
combinate_supp([0], _, _, _, _, []).
combinate_supp([Number], Start, _, Size, PreCombo, Combo) :-
		End is Size - Number + 1,
		inRange(First, Start, End),
		Last is First + Number - 1,
		range(EndCombo, First, Last),
		append(PreCombo, EndCombo, Combo).
combinate_supp([Number|Tail], Start, CortegeLength, Size, PreCombo, Combo) :-
		End is Size - CortegeLength + 1,
		inRange(First, Start, End),
		Last is First + Number - 1,
		range(EndCombo, First, Last),
		NewCortegeLength is CortegeLength - Number - 1,
		NewStart is Last + 2,
		append(PreCombo, EndCombo, LowCombo),
		combinate_supp(Tail, NewStart, NewCortegeLength, Size, LowCombo, Combo).
%%
%	Takes combos that contains line Number.
%%
numberContainers(_, [], []).
numberContainers(Number, [List|Tails], Containers) :-
		member(Number,List), Containers = [List|CTail], numberContainers(Number, Tails, CTail), !;
		numberContainers(Number, Tails, Containers).

%%
%	Takes lines which numbers are members of specified comb and refines them.
%	Refination means taking only these combs which contains LineNumber.
%%
combMatch(_, [], _, []).
combMatch(LineNumber, [H|Tail], Lines, [MatchedLinesHead|MLTail]) :-
		member(line(H, Combs), Lines),
		numberContainers(LineNumber, Combs, MatchedCombs), MatchedCombs \= [],
		MatchedLinesHead = line(H, MatchedCombs),
		combMatch(LineNumber, Tail, Lines, MLTail).

linesMatch([], _, []).
linesMatch([line(RowNumber, [RowCombHead|RCTail])|RowsTail], Cols, MatchedLines) :-
		combMatch(RowNumber, RowCombHead, Cols, MatchedRefinedCols), MatchedRefinedCols \= [], replaceLines(Cols, MatchedRefinedCols, ColsWithMatchedRefinedCols), MatchedLines = [/*line(RowNumber, [*/RowCombHead/*])*/|MLTail], linesMatch(RowsTail, ColsWithMatchedRefinedCols, MLTail);
		linesMatch([line(RowNumber, RCTail)|RowsTail], Cols, MatchedLines).

%%
%	Nonogram printing.
%%
printlist([]).
printlist([H|T]) :- number(H), swritef(S, '~` t#~%w|', [H]), format(S, []), printlist(T).

printNonogram([]).
printNonogram([H|T]):- printlist(H), nl, printNonogram(T).

%%
%	Solving nonograns.
%%
solveNonogram(Rows,Cols,Solution):-
		length(Rows, VSize),
		length(Cols, HSize),
		generate(RowCombos, Rows, HSize),
		generate(ColCombos, Cols, VSize),
		linesMatch(RowCombos, ColCombos, Solution).
solveNonogram(Nonogram):-nonogram(Nonogram,Rows,Cols),solveNonogram(Rows,Cols,Solution),printNonogram(Solution).


text:
package io.quarkus.kubernetes.deployment;

import static io.quarkus.kubernetes.deployment.Constants.STATEFULSET;

import java.util.HashMap;
import java.util.List;
import java.util.function.Function;

import io.dekorate.kubernetes.decorator.ResourceProvidingDecorator;
import io.dekorate.utils.Strings;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesListFluent;
import io.fabric8.kubernetes.api.model.apps.StatefulSet;
import io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder;
import io.fabric8.kubernetes.api.model.apps.StatefulSetFluent;

public class AddStatefulSetResourceDecorator extends ResourceProvidingDecorator<KubernetesListFluent<?>> {

    private final String name;
    private final PlatformConfiguration config;

    public AddStatefulSetResourceDecorator(String name, PlatformConfiguration config) {
        this.name = name;
        this.config = config;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void visit(KubernetesListFluent<?> list) {
        StatefulSetBuilder builder = list.getItems().stream()
                .filter(this::containsStatefulSetResource)
                .map(replaceExistingStatefulSetResource(list))
                .findAny()
                .orElseGet(this::createStatefulSetResource)
                .accept(StatefulSetBuilder.class, this::initStatefulSetResourceWithDefaults);

        list.addToItems(builder.build());
    }

    private boolean containsStatefulSetResource(HasMetadata metadata) {
        return STATEFULSET.equalsIgnoreCase(metadata.getKind()) && name.equals(metadata.getMetadata().getName());
    }

    private void initStatefulSetResourceWithDefaults(StatefulSetBuilder builder) {
        StatefulSetFluent.SpecNested<StatefulSetBuilder> spec = builder.editOrNewSpec();

        spec.editOrNewSelector()
                .endSelector()
                .editOrNewTemplate()
                .editOrNewSpec()
                .endSpec()
                .editOrNewMetadata()
                .endMetadata()
                .endTemplate();

        // defaults for:
        // - replicas
        if (spec.getReplicas() == null) {
            spec.withReplicas(1);
        }
        // - service name
        if (Strings.isNullOrEmpty(spec.getServiceName())) {
            spec.withServiceName(name);
        }
        // - match labels
        if (spec.getSelector().getMatchLabels() == null) {
            spec.editSelector().withMatchLabels(new HashMap<>()).endSelector();
        }
        // - termination grace period seconds
        if (spec.getTemplate().getSpec().getTerminationGracePeriodSeconds() == null) {
            spec.editTemplate().editSpec().withTerminationGracePeriodSeconds(10L).endSpec().endTemplate();
        }
        // - container
        if (!containsContainerWithName(spec)) {
            spec.editTemplate().editSpec().addNewContainer().withName(name).endContainer().endSpec().endTemplate();
        }

        spec.endSpec();
    }

    private StatefulSetBuilder createStatefulSetResource() {
        return new StatefulSetBuilder().withNewMetadata().withName(name).endMetadata();
    }

    private Function<HasMetadata, StatefulSetBuilder> replaceExistingStatefulSetResource(KubernetesListFluent<?> list) {
        return metadata -> {
            list.removeFromItems(metadata);
            return new StatefulSetBuilder((StatefulSet) metadata);
        };
    }

    private boolean containsContainerWithName(StatefulSetFluent.SpecNested<StatefulSetBuilder> spec) {
        List<Container> containers = spec.getTemplate().getSpec().getContainers();
        return containers == null || containers.stream().anyMatch(c -> name.equals(c.getName()));
    }
}

redpajama_set_name: RedPajamaGithub


text:
import optparse

from django.core.management.base import BaseCommand, CommandError

from cumulus.authentication import Auth
from cumulus.settings import CUMULUS

class Command(BaseCommand):
    help = "Create a container."
    args = "[container_name]"

    option_list = BaseCommand.option_list + (
        optparse.make_option("-p", "--private", action="store_true", default=False,
                             dest="private", help="Make a private container."),)

    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Pass one and only one [container_name] as an argument")

        self._connection = Auth()._get_connection()

        container_name = args[0]
        print("Creating container: {0}".format(container_name))
        container = self._connection.create_container(container_name)
        if options.get("private"):
            print("Private container: {0}".format(container_name))
            container.make_private()
        else:
            print("Public container: {0}".format(container_name))
            container.make_public(ttl=CUMULUS["TTL"])


text:
<!doctype html>

{% include '../includes/head.html' %}

    {% if adminEnabled %}

    {% endif %}

                    Add Project

                    Add Document

                    Recent Projects

{{rec_prj}}

Document Legend

 AS-Built

 Construction Plan

 Acceptance Letter

 Warranty Letter

 Statement of Cost

 Permit

 Plat

              {% block content %}

              {% endblock %}

    {% include '../includes/foot.html' %}


text:
using System;

namespace IsolatedIslandGame.Library.Quests.RequirementRecords
{
    public class CloseDealWithOutlanderQuestRequirementRecord : QuestRequirementRecord
    {
        private bool hasCloseDealWithOutlander;
        public bool HasCloseDealWithOutlander
        {
            get { return hasCloseDealWithOutlander; }
            private set
            {
                hasCloseDealWithOutlander = value;
                QuestRecordFactory.Instance?.UpdateCloseDealWithOutlanderQuestRequirementRecord(this);
                onRequirementStatusChange?.Invoke(this);
            }
        }
        public override bool IsSufficient
        {
            get
            {
                return HasCloseDealWithOutlander;
            }
        }

        public override string ProgressStatus
        {
            get
            {
                return (HasCloseDealWithOutlander) ? "已達成" : "尚未達成" ;
            }
        }

        private event Action<QuestRequirementRecord> onRequirementStatusChange;
        public override event Action<QuestRequirementRecord> OnRequirementStatusChange { add { onRequirementStatusChange += value; } remove { onRequirementStatusChange -= value; } }

        public CloseDealWithOutlanderQuestRequirementRecord(int questRequirementRecordID, QuestRequirement requirement, bool hasCloseDealWithOutlander) : base(questRequirementRecordID, requirement)
        {
            this.hasCloseDealWithOutlander = hasCloseDealWithOutlander;
        }
        internal override void RegisterObserverEvents(Player player)
        {
            player.OnTransactionStart += (transaction) =>
            {
                transaction.OnTransactionEnd += (transactionID, isSuccessful) =>
                {
                    if (!IsSufficient && isSuccessful)
                    {
                        int otherPlayerID;
                        if(transaction.RequesterPlayerID == player.PlayerID)
                        {
                            otherPlayerID = transaction.AccepterPlayerID;
                        }
                        else
                        {
                            otherPlayerID = transaction.RequesterPlayerID;
                        }
                        FriendInformation friendInformation;
                        if(!player.FindFriend(otherPlayerID, out friendInformation) || !friendInformation.isConfirmed)
                        {
                            HasCloseDealWithOutlander = true;
                        }
                    }
                };
            };
        }
    }
}


text:
<?php

namespace Dragoon\MoviesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
use Dragoon\MoviesBundle\Entity\Fiche;

class MoviesController extends Controller
{

    public function jsonAction()
    {

        // On récupère le repository
        $repository = $this->getDoctrine()
                     ->getManager()
                     ->getRepository('DragoonMoviesBundle:Fiche');

        // On récupère l'entité correspondant à l'id $id
        $fiches  = $repository->findAll();

        $aFilm = array();
        $i = 0;
        while($i<10) {
        if (is_array($fiches) && !empty($fiches)) {
            foreach($fiches as $fiche) {
                $tmp = array();
                $tmp['id'] = $fiche->getId();
                $tmp['name'] = $fiche->getTitleFr().$i;
                $tmp['support'] = 'dvd';
                $aFilm[] = $tmp;
            }
        }
$i++;
   }
        $aFilm2['aaData'] = $aFilm;
        return new Response(json_encode($aFilm2));
    }

    public function listAction()
    {
        return $this->render('DragoonMoviesBundle:Movies:list.html.twig', array(
            'id'  => $id,
        ));
    }

    public function ficheAction($id)
    {
        // On récupère la requête
        $request = $this->getRequest();

        // On récupère notre paramètre tag
        $tag = $request->query->get('tag');
    }

}


text:
/*
 * service_reference.h
 *
 *  \date       Jul 20, 2010
 *  \author    	Apache Celix Project Team
 *  \copyright	Apache License, Version 2.0
 */

#ifndef SERVICE_REFERENCE_H_
#define SERVICE_REFERENCE_H_

typedef struct serviceReference * service_reference_pt;

#include "celixbool.h"
#include "array_list.h"
#include "service_registration.h"
#include "bundle.h"
#include "framework_exports.h"

celix_status_t serviceReference_create(bundle_pt bundle, service_registration_pt registration, service_reference_pt *reference);
celix_status_t serviceReference_destroy(service_reference_pt reference);

FRAMEWORK_EXPORT celix_status_t serviceReference_invalidate(service_reference_pt reference);
FRAMEWORK_EXPORT celix_status_t serviceRefernce_isValid(service_reference_pt reference, bool *result);

FRAMEWORK_EXPORT celix_status_t serviceReference_getServiceRegistration(service_reference_pt reference, service_registration_pt *registration);
FRAMEWORK_EXPORT celix_status_t serviceReference_getBundle(service_reference_pt reference, bundle_pt *bundle);

FRAMEWORK_EXPORT bool serviceReference_isAssignableTo(service_reference_pt reference, bundle_pt requester, char * serviceName);

FRAMEWORK_EXPORT celix_status_t serviceReference_getUsingBundles(service_reference_pt reference, array_list_pt *bundles);
FRAMEWORK_EXPORT celix_status_t serviceReference_equals(service_reference_pt reference, service_reference_pt compareTo, bool *equal);
FRAMEWORK_EXPORT unsigned int serviceReference_hashCode(void *referenceP);
FRAMEWORK_EXPORT int serviceReference_equals2(void *reference1, void *reference2);

#endif /* SERVICE_REFERENCE_H_ */


text:
namespace net {
class WebSocket;
}  // namespace net

namespace chrome_browser_net_websocket_experiment {

class WebSocketExperimentTask : public URLFetcher::Delegate,
                                public net::WebSocketDelegate {
 public:
  enum State {
    STATE_NONE,
    STATE_URL_FETCH,
    STATE_URL_FETCH_COMPLETE,
    STATE_WEBSOCKET_CONNECT,
    STATE_WEBSOCKET_CONNECT_COMPLETE,
    STATE_WEBSOCKET_SEND_HELLO,
    STATE_WEBSOCKET_RECV_HELLO,
    STATE_WEBSOCKET_KEEP_IDLE,
    STATE_WEBSOCKET_KEEP_IDLE_COMPLETE,
    STATE_WEBSOCKET_RECV_PUSH_MESSAGE,
    STATE_WEBSOCKET_ECHO_BACK_MESSAGE,
    STATE_WEBSOCKET_RECV_BYE,
    STATE_WEBSOCKET_CLOSE,
    STATE_WEBSOCKET_CLOSE_COMPLETE,
    NUM_STATES,
  };

  class Config {
   public:
    Config();
    ~Config();

    GURL url;
    std::string ws_protocol;
    std::string ws_origin;
    std::string ws_location;
    net::WebSocket::ProtocolVersion protocol_version;

    GURL http_url;

    int64 url_fetch_deadline_ms;
    int64 websocket_onopen_deadline_ms;
    std::string websocket_hello_message;
    int64 websocket_hello_echoback_deadline_ms;
    int64 websocket_idle_ms;
    int64 websocket_receive_push_message_deadline_ms;
    std::string websocket_bye_message;
    int64 websocket_bye_deadline_ms;
    int64 websocket_close_deadline_ms;
  };

  class Context {
   public:
    Context() {}
    virtual ~Context() {}

    virtual URLFetcher* CreateURLFetcher(
        const Config& config, URLFetcher::Delegate* delegate);
    virtual net::WebSocket* CreateWebSocket(
        const Config& config, net::WebSocketDelegate* delegate);

   private:
    DISALLOW_COPY_AND_ASSIGN(Context);
  };

  class Result {
   public:
    Result()
        : last_result(net::OK),
          last_state(STATE_NONE) {}
    int last_result;
    State last_state;

    base::TimeDelta url_fetch;
    base::TimeDelta websocket_connect;
    base::TimeDelta websocket_echo;
    base::TimeDelta websocket_idle;
    base::TimeDelta websocket_total;
  };

  // WebSocketExperimentTask will call |callback| with the last status code
  // when the task is finished.
  WebSocketExperimentTask(const Config& config,
                          net::CompletionCallback* callback);
  virtual ~WebSocketExperimentTask();

  // Initializes histograms that WebSocketExperimentTask will use to save
  // results.  Must be called once before calling SaveResult().
  static void InitHistogram();

  // Releases histograms to store results.
  // Must be called after all WebSocketExperimentTasks are finished.
  static void ReleaseHistogram();

  void Run();
  void Cancel();
  void SaveResult() const;

  const Config& config() const { return config_; }
  const Result& result() const { return result_; }

  // URLFetcher::Delegate method.
  virtual void OnURLFetchComplete(const URLFetcher* source,
                                  const GURL& url,
                                  const net::URLRequestStatus& status,
                                  int response_code,
                                  const ResponseCookies& cookies,
                                  const std::string& data);

  // net::WebSocketDelegate methods
  virtual void OnOpen(net::WebSocket* websocket);
  virtual void OnMessage(net::WebSocket* websocket, const std::string& msg);
  virtual void OnError(net::WebSocket* websocket);
  virtual void OnClose(net::WebSocket* websocket, bool was_clean);
  virtual void OnSocketError(const net::WebSocket* websocket, int error);

  void SetContext(Context* context);

 private:
  void OnTimedOut();

  void DoLoop(int result);

  int DoURLFetch();
  int DoURLFetchComplete(int result);
  int DoWebSocketConnect();
  int DoWebSocketConnectComplete(int result);
  int DoWebSocketSendHello();
  int DoWebSocketReceiveHello(int result);
  int DoWebSocketKeepIdle();
  int DoWebSocketKeepIdleComplete(int result);
  int DoWebSocketReceivePushMessage(int result);
  int DoWebSocketEchoBackMessage();
  int DoWebSocketReceiveBye(int result);
  int DoWebSocketClose();
  int DoWebSocketCloseComplete(int result);
  void SetTimeout(int64 deadline_ms);
  void RevokeTimeoutTimer();
  void Finish(int result);

  Config config_;
  scoped_ptr<Context> context_;
  Result result_;

  ScopedRunnableMethodFactory<WebSocketExperimentTask> method_factory_;
  net::CompletionCallback* callback_;
  State next_state_;

  scoped_ptr<URLFetcher> url_fetcher_;
  base::TimeTicks url_fetch_start_time_;

  scoped_refptr<net::WebSocket> websocket_;
  int last_websocket_error_;
  std::deque<std::string> received_messages_;
  std::string push_message_;
  base::TimeTicks websocket_connect_start_time_;
  base::TimeTicks websocket_echo_start_time_;
  base::TimeTicks websocket_idle_start_time_;

  DISALLOW_COPY_AND_ASSIGN(WebSocketExperimentTask);
};

}  // namespace chrome_browser_net

#endif  // CHROME_BROWSER_NET_WEBSOCKET_EXPERIMENT_WEBSOCKET_EXPERIMENT_TASK_H_


text:
<!doctype html>

    <title>Neil Armstrong | Home</title>
    <meta name="author" content="Neil Armstrong">
    <meta name="description" content="This is the description for the site.">

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <link rel="stylesheet" href="./assets/css/style.css" />

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

            </button>

 Home

       About

       Research

       Contact

Hello, my name is Neil Armstrong
NASA Astronaut and Aerospace Engineer

            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque consequuntur laudantium, corporis culpa dolores dignissimos quod pariatur ut quos voluptatem, accusantium soluta, libero doloremque. Asperiores adipisci quae rerum minus quasi?

            Read More

                Tweets by astro_reid

 Recent Research Articles

Testing the X-17

        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque consequuntur laudantium, corporis culpa dolores dignissimos quod pariatur ut quos voluptatem, accusantium soluta, libero doloremque. Asperiores adipisci quae rerum minus quasi?

Testing the X-16

        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque consequuntur laudantium, corporis culpa dolores dignissimos quod pariatur ut quos voluptatem, accusantium soluta, libero doloremque. Asperiores adipisci quae rerum minus quasi?

Copyright © 2014, Neil Armstrong


text:
using System;
using System.Collections.Generic;
using System.Text;
using Tridion.ContentDelivery.Services.Utilities;
using Tridion.ContentDelivery.Web.Jvm;

namespace TcmDeployer
{
	public class ServiceConsole
	{
		private const String CONFIG_PARAMETER = "configLocation";

		private static bool IsSpecified(String argument, String parameter)
		{
			if (String.IsNullOrEmpty(argument))
				return false;

			return argument.StartsWith("-" + parameter, StringComparison.OrdinalIgnoreCase) ||
				argument.StartsWith("--" + parameter, StringComparison.OrdinalIgnoreCase);
		}

		static void Main(String[] args)
		{
			// No arguments present or "-start"
			if (args.Length == 0 || IsSpecified(args[0], "start"))
			{
				// Instance config directory was specified
				if (args.Length == 3)
					ConfigurationHook.configFolder = args[2];

				if (Environment.UserInteractive)
				{
					if (args.Length == 3)
						Console.WriteLine("[i] Starting TcmDeployer Service, configuration \"{0}\".", args[2]);
					else
						Console.WriteLine("[i] Starting TcmDeployer Service.");

					Service.StartDeployer();
					Console.WriteLine("[!] Press any key to stop...");
					Console.ReadKey();
					Console.WriteLine("[i] Stopping...");
					Service.StopDeployer();
				}
				else
					Service.StartService();

				return;
			}

			if (IsSpecified(args[0], "install"))
			{
				if (args.Length == 1)
				{
					Console.WriteLine("[i] Installing TcmDeployer Service");
					Installation.InstallService("TcmDeployer.exe");
					return;
				}
				else if (args.Length == 3)
				{
					Console.WriteLine("[i] Installing TcmDeployer Service instance \"{0}\", configuration \"{1}\".", args[1], args[2]);
					Installation.instanceID = args[1];
					Installation.serviceArguments = " -" + CONFIG_PARAMETER + "=" + args[2];
					Installation.InstallService("TcmDeployer.exe");
					return;
				}
			}

			if (IsSpecified(args[0], "remove"))
			{
				if (args.Length == 2)
				{
					Console.WriteLine("[i] Uninstalling TcmDeployer Service instance \"{0}\".", args[1]);
					Installation.instanceID = args[1];
				}
				else
					Console.WriteLine("[i] Uninstalling TcmDeployer Service");

				Installation.UninstallService("TcmDeployer.exe");
				return;
			}

			// Handle initialization from TcmDeployer as a service with a specified configuration directory
			if (IsSpecified(args[0], CONFIG_PARAMETER))
			{
				String[] values = args[0].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);

				if (values.Length == 2)
				{
					ConfigurationHook.configFolder = values[1];
					Service.StartService();
					return;
				}
			}

			Console.WriteLine("Usage: TcmDeployer (-start|-install [instance-id instance-config-directory]|-remove [instance-id])");
		}
	}
}


text:
package upload

import (
	"encoding/json"
	"errors"
	"io"
	"io/ioutil"
	"mime"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
)

func getSeekerSize(seeker io.Seeker) (int64, error) {
	size, err := seeker.Seek(0, io.SeekEnd)
	if err != nil {
		return 0, err
	}
	_, err = seeker.Seek(0, io.SeekStart)
	if err != nil {
		return 0, err
	}
	return size, nil
}

// Upload upload specific file to LeanCloud
func Upload(name string, mimeType string, reader io.ReadSeeker, opts *Options) (*File, error) {
	if opts.serverURL() == "https://api.leancloud.cn" || opts.serverURL() == "https://leancloud.cn" {
		return uploadToQiniu(name, mimeType, reader, opts)
	}
	return uploadViaLeanCloud(name, mimeType, reader, opts)
}

func uploadToQiniu(name string, mimeType string, reader io.ReadSeeker, opts *Options) (*File, error) {
	size, err := getSeekerSize(reader)
	if err != nil {
		return nil, err
	}
	tokens, err := getFileTokens(name, mimeType, size, opts)
	if err != nil {
		return nil, err
	}

	out, in := io.Pipe()
	part := multipart.NewWriter(in)
	done := make(chan error)

	go func() {
		if err := part.WriteField("key", tokens.Key); err != nil {
			in.Close()
			done <- err
			return
		}
		if err := part.WriteField("token", tokens.Token); err != nil {
			in.Close()
			done <- err
			return
		}
		writer, err := part.CreateFormFile("file", name)
		if err != nil {
			in.Close()
			done <- err
			return
		}
		_, err = io.Copy(writer, reader)
		if err != nil {
			in.Close()
			done <- err
			return
		}
		if err := part.Close(); err != nil {
			in.Close()
			done <- err
			return
		}
		in.Close()
		done <- nil
	}()

	request, err := http.NewRequest("POST", "https://up.qbox.me/", out)
	request.Header.Set("Content-Type", part.FormDataContentType())
	if err != nil {
		return nil, err
	}

	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return nil, err
	}

	err = <-done
	if err != nil {
		return nil, err
	}

	content, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}
	if response.StatusCode != 200 {
		return nil, errors.New(string(content))
	}

	return &File{
		ObjectID: tokens.ObjectID,
		URL:      tokens.URL,
	}, nil
}

func uploadViaLeanCloud(name string, mimeType string, reader io.ReadSeeker, opts *Options) (*File, error) {
	url := opts.serverURL() + "/1.1/files/" + name
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		return nil, err
	}

	request.Header.Set("X-LC-Id", opts.AppID)
	request.Header.Set("X-LC-Key", opts.AppKey)
	request.Header.Set("User-Agent", "LeanCloud-Go-Upload/"+version)

	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}

	if response.StatusCode != 201 {
		return nil, newErrorFromBody(body)
	}

	result := new(File)
	err = json.Unmarshal(body, result)
	if result.URL == "" {
		return nil, errors.New("Upload file failed")
	}
	return result, err
}

// UploadFileVerbose will open an file and upload it
func UploadFileVerbose(name string, mimeType string, path string, opts *Options) (*File, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	return Upload(name, mimeType, f, opts)
}

// UploadFile will open an file and upload it. the file name and mime type is autodetected
func UploadFile(path string, opts *Options) (*File, error) {
	_, name := filepath.Split(path)
	mimeType := mime.TypeByExtension(filepath.Ext(path))
	return UploadFileVerbose(name, mimeType, path, opts)
}


text: Converts a String-building statement that uses concatenation (+) to one that uses a raw string.


text:
require 'validates-structure'

I18n.enforce_available_locales = false

RSpec.configure do |config|
  config.run_all_when_everything_filtered = true
  config.filter_run :focus
  config.expect_with :rspec do |c|
    c.syntax = [:should, :expect]
  end
  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = 'random'
end


text:
<?php

namespace Collections\Iterator;

use Collections\Enumerable;

class LazySliceIterable implements Enumerable
{
    use LazyIterableTrait;

    /**
     * @var Enumerable
     */
    private $Enumerable;

    /**
     * @var int
     */
    private $start;

    /**
     * @var int
     */
    private $len;

    public function __construct($Enumerable, $start, $len)
    {
        $this->Enumerable = $Enumerable;
        $this->start = $start;
        $this->len = $len;
    }

    public function getIterator()
    {
        return new LazySliceIterator($this->Enumerable->getIterator(), $this->start, $this->len);
    }
}


text:
package mathgl

type PlaneEnum int

const (
	PLANE_LEFT PlaneEnum = iota
	PLANE_RIGHT
	PLANE_BOTTOM
	PLANE_TOP
	PLANE_NEAR
	PLANE_FAR
)

type PointClassificationEnum int

const (
	POINT_INFRONT_OF_PLANE PointClassificationEnum = iota
	POINT_BEHIND_PLANE
	POINT_ON_PLANE
)

type Plane struct {
	A, B, C, D float32
}


text:
<TITLE>Review for Can't Hardly Wait (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Can't Hardly Wait (1998)

reviewed by
Jamie Peck

CAN'T HARDLY WAIT
Reviewed by Jamie Peck
Rating: **1/2 (out of ****)
Columbia / 1:36 / 1998 / PG-13 (teen sex and substance abuse, language)
Cast: Ethan Embry; Jennifer Love Hewitt; Charlie Korsmo; Lauren Ambrose;
Seth Green; Peter Facinelli; Jenna Elfman; Jerry O'Connell; Michelle
Brookhurst; Melissa Joan Hart
Director: Harry Elfont; Deborah Kaplan
Screenplay: Harry Elfont; Deborah Kaplan
Slasher flicks and teen comedies are probably the most well-known
cinematic staples of the 1980s, and their mainstream potency is still
being tested today. The "Scream" franchise may have boldly reinvented the
former, but throwbacks to the latter like "Can't Hardly Wait" aren't so
much of a revelation. The film doesn't put a new spin on its subgenre so
much as it repackages bits and pieces of its '80s predecessors and peppers
the proceedings with many timely pop culture quips. But however familiar
or shallow things get, an extraordinarily appealing cast runs to the
rescue; if "Can't Hardly Wait" comes close to working, it's in a large
part due to its ready-for-"Tiger Beat" players. These mostly fresh faces
really liven up some otherwise lackluster action.

Most of the action takes place at a big bash to celebrate Huntington High
School's graduation day. Attending the beer- and sex-soaked festivities
are our six main teenagers -- requisite nice guy Preston (Ethan Embry),
prom queen Amanda (Jennifer Love Hewitt), star jock Mike (Peter
Facinelli), acerbic wit Denise (Lauren Ambrose), white "homeboy" Kenny
(Seth Green) and unpopular brainiac William (Charlie Korsmo). Kenny,
hoping to hook up with a girl and lose his virginity, ends up bonding with
Denise, who's present out of emotional support for Preston, who wants tell
Amanda of his longtime crush on her. Amanda has just broken up with Mike,
who's been tormenting William, who will seek revenge against Mike before
the night is over. Did you get all that?

Actually, the gossipy character interaction that composes "Can't Hardly
Wait"'s various story threads ring true for the most part. (Gosh, I was
there only two years ago!) It's within the characters themselves where the
movie begins to falter. That they're walking, talking stereotypes really
doesn't matter; this seems like a deliberate effort on the part of
co-directors and -writers Harry Elfont and Deborah Kaplan to emanate such
"classics" as "The Breakfast Club." But they fail to make their entire
contemporary cross-section of young people completely interesting. Both
Michael and William are crudely rendered, and their conflict, particularly
how it ends, is pretty revolting. The Preston-Amanda romance (or lack
thereof) is supposed to be Wait's main event, but it's hard to care much
about either person.

Preston is solely defined by his affection for Amanda, while, in turn, all
she does throughout the film is mope and pout. The would-be relationship
somehow manages to click despite the strange, hindering oversight that
we're never allowed to see why she's so special to him. This is not
because we root for Preston, but because we root for Ethan Embry, whose
endearing, natural and occasionally goofy charm makes up for his
alter-ego's lack of distinction. Embry ("That Thing You Do!") does a fine
job of getting the audience to identify with the anxiety, longing,
hesitancy and heartbreak of first love; if only his Preston were fully
fleshed-out, he'd be worth following into a "Can't Hardly Wait" spin-off
feature.

On the other hand, Denise and Kenny already are; when the film eventually
breaks up into several superimposing stories, it is only theirs that
crackles with the completely realized good-time vibe that Elfont and
Kaplan were probably going for -- and that's very likely because Lauren
Ambrose and Seth Green have a great deal of fun bringing to life the most
comedically vibrant party patrons here. So, while the material is
distinctly uneven, these winning performers, their occasionally winning
characters and smattering of winning moments make the whole package not
much of a chore to endure. "Can't Hardly Wait" is a decent attempt to make
a film that definitively encapsulates a decade's worth of teen fads and
attitudes. It's just too bad the far more successful "Clueless" beat it to
the punch three summers ago.
Copyright 1998 Jamie Peck
E-mail: jpeck1@gl.umbc.edu
Visit the New and Improved Reel Deal Online:
http://www.gl.umbc.edu/~jpeck1/
"Joe's Apartment' would be a very bad comedy even without the roaches, but
it would not be a disgusting one. No, wait: I take that back. Even without
the roaches, we would still have the subplot involving the pink
disinfectant urinal cakes." -- Roger Ebert on "Joe's Apartment"

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
"""RunAbove SSH key service library."""

from base import Resource, BaseManagerWithList

class SSHKeyManager(BaseManagerWithList):
    """Manage the SSH keys attached to an account."""

    basepath = '/ssh'

    def get_by_name(self, region, name):
        """Get one SSH key from a RunAbove account.

        :param region: Region where the key is
        :param name: Name of the key to retrieve
        """
        try:
            region_name = region.name
        except AttributeError:
            region_name = region
        url = self.basepath + '/' + self._api.encode_for_api(name)
        key = self._api.get(url, {'region': region_name})
        return self._dict_to_obj(key)

    def _dict_to_obj(self, key):
        """Converts a dict to an SSHKey object."""
        region = self._handler.regions._name_to_obj(key['region'])
        return SSHKey(self,
                      key['name'],
                      key.get('fingerPrint'),
                      key.get('publicKey'),
                      region)

    def create(self, region, name, public_key):
        """Register a new SSH key in a RunAbove account.

        :param region: Region where the key will be added
        :param name: Name of the key
        :param public_key: Public key value
        """
        try:
            region_name = region.name
        except AttributeError:
            region_name = region
        content = {
            'publicKey': public_key,
            'region': region_name,
            'name': name
        }
        self._api.post(self.basepath, content)
        return self.get_by_name(region_name, name)

    def delete(self, region, key):
        """Delete an SSH key from an account.

        :param region: Region where the key is
        :param key: SSH key to be deleted
        """
        try:
            region_name = region.name
        except AttributeError:
            region_name = region
        try:
            name = key.name
        except AttributeError:
            name = key
        url = self.basepath + '/' + self._api.encode_for_api(name)
        return self._api.delete(url, {'region': region_name})

class SSHKey(Resource):
    """Represents one SSH key."""

    def __init__(self, manager, name, finger_print, public_key, region):
        self._manager = manager
        self.name = name
        self.finger_print = finger_print
        self.public_key = public_key
        self.region = region

    def delete(self):
        """Delete the key from the account."""
        self._manager.delete(self.region, self)


text:
/*! `qml` grammar compiled for Highlight.js 11.6.0 */
(()=>{var e=(()=>{"use strict";return e=>{
const n="[a-zA-Z_][a-zA-Z0-9\\._]*",r={className:"attribute",begin:"\\bid\\s*:",
starts:{className:"string",end:n,returnEnd:!1}},a={begin:n+"\\s*:",
returnBegin:!0,contains:[{className:"attribute",begin:n,end:"\\s*:",
excludeEnd:!0,relevance:0}],relevance:0},t={begin:e.regex.concat(n,/\s*\{/),
end:/\{/,returnBegin:!0,relevance:0,contains:[e.inherit(e.TITLE_MODE,{begin:n})]
};return{name:"QML",aliases:["qt"],case_insensitive:!1,keywords:{
keyword:"in of on if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await import",
literal:"true false null undefined NaN Infinity",
built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Behavior bool color coordinate date double enumeration font geocircle georectangle geoshape int list matrix4x4 parent point quaternion real rect size string url variant vector2d vector3d vector4d Promise"
},contains:[{className:"meta",begin:/^\s*['"]use (strict|asm)['"]/
},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"string",begin:"`",end:"`",
contains:[e.BACKSLASH_ESCAPE,{className:"subst",begin:"\\$\\{",end:"\\}"}]
},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"number",variants:[{
begin:"\\b(0[bB][01]+)"},{begin:"\\b(0[oO][0-7]+)"},{begin:e.C_NUMBER_RE}],
relevance:0},{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",
keywords:"return throw case",
contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.REGEXP_MODE,{begin:/</,
end:/>\s*[);\]]/,relevance:0,subLanguage:"xml"}],relevance:0},{
className:"keyword",begin:"\\bsignal\\b",starts:{className:"string",
end:"(\\(|:|=|;|,|//|/\\*|$)",returnEnd:!0}},{className:"keyword",
begin:"\\bproperty\\b",starts:{className:"string",end:"(:|=|;|,|//|/\\*|$)",
returnEnd:!0}},{className:"function",beginKeywords:"function",end:/\{/,
excludeEnd:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/[A-Za-z$_][0-9A-Za-z$_]*/
}),{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,
contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]}],illegal:/\[|%/},{
begin:"\\."+e.IDENT_RE,relevance:0},r,a,t],illegal:/#/}}})()
;hljs.registerLanguage("qml",e)})();


text:
/**
 * @Title: PostalService
 * @Package com.dvt.common
 * @author 李苜菲
 * @date 2014年4月28日 上午9:15:18
 * @version V1.0
 */
package com.poomoo.edao.widget;

import com.poomoo.edao.R;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

/**
 *
 * @ClassName MessageBox_YES
 * @Description TODO 只有确定按钮的对话框
 * @author 李苜菲
 * @date 2015-8-12 上午10:19:29
 */
public class MessageBox_YES extends Dialog {
	private int dialogResult;
	private Handler mHandler;
	private Activity context;
	private Button OkBtn;

	public MessageBox_YES(Activity context) {
		super(context);
		this.context = context;
		dialogResult = 0;
		setOwnerActivity(context);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		onCreate();
	}

	public void onCreate() {
		setContentView(R.layout.messagebox_yes);
		this.setCanceledOnTouchOutside(false);
	}

	public void setButtonText(String OK) {
		OkBtn = (Button) this.findViewById(R.id.messagebox_yes_btn_ok);
		OkBtn.setText(OK);
	}

	public int getDialogResult() {
		return dialogResult;
	}

	public void setDialogResult(int dialogResult) {
		this.dialogResult = dialogResult;
	}

	public void endDialog(int result) {
		dismiss();
		setDialogResult(result);
	}

	public int showDialog(String Msg,final DialogResultListener dialogResultListener) {
		TextView Info = (TextView) findViewById(R.id.messagebox_yes_textView_content);
		Info.setText(Msg);
		// 获取焦点
		// TvTitle.setFocusable(true);
		// TvTitle.setFocusableInTouchMode(true);
		// TvTitle.requestFocus();

		// TvTitle.setText(Title);
		super.show();

		findViewById(R.id.messagebox_yes_btn_ok).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View paramView) {
						endDialog(1);
						if (dialogResultListener != null)
							dialogResultListener.onFinishDialogResult(1);
					}
				});

		this.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				// TODO 自动生成的方法存根
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					return true;
				}
				return false;
			}
		});
		return dialogResult;
	}
}


text:
'use strict';

const chai = require('chai'),
  expect = chai.expect,
  Support = require('../../support'),
  dialect = Support.getTestDialect(),
  DataTypes = require('../../../../lib/data-types');

if (dialect !== 'mariadb') return;
describe('[MariaDB Specific] DAOFactory', () => {
  describe('constructor', () => {
    it('handles extended attributes (unique)', function() {
      const User = this.sequelize.define(`User${Support.rand()}`, {
        username: { type: DataTypes.STRING, unique: true }
      }, { timestamps: false });

      expect(
        this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(
          User.rawAttributes)).to.deep.equal({
        username: 'VARCHAR(255) UNIQUE',
        id: 'INTEGER NOT NULL auto_increment PRIMARY KEY'
      });
    });

    it('handles extended attributes (default)', function() {
      const User = this.sequelize.define(`User${Support.rand()}`, {
        username: { type: DataTypes.STRING, defaultValue: 'foo' }
      }, { timestamps: false });
      expect(
        this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(
          User.rawAttributes)).to.deep.equal({
        username: 'VARCHAR(255) DEFAULT \'foo\'',
        id: 'INTEGER NOT NULL auto_increment PRIMARY KEY'
      });
    });

    it('handles extended attributes (null)', function() {
      const User = this.sequelize.define(`User${Support.rand()}`, {
        username: { type: DataTypes.STRING, allowNull: false }
      }, { timestamps: false });
      expect(
        this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(
          User.rawAttributes)).to.deep.equal({
        username: 'VARCHAR(255) NOT NULL',
        id: 'INTEGER NOT NULL auto_increment PRIMARY KEY'
      });
    });

    it('handles extended attributes (primaryKey)', function() {
      const User = this.sequelize.define(`User${Support.rand()}`, {
        username: { type: DataTypes.STRING, primaryKey: true }
      }, { timestamps: false });
      expect(
        this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(
          User.rawAttributes)).to.deep.equal(
        { username: 'VARCHAR(255) PRIMARY KEY' });
    });

    it('adds timestamps', function() {
      const User1 = this.sequelize.define(`User${Support.rand()}`, {});
      const User2 = this.sequelize.define(`User${Support.rand()}`, {},
        { timestamps: true });

      expect(
        this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(
          User1.rawAttributes)).to.deep.equal({
        id: 'INTEGER NOT NULL auto_increment PRIMARY KEY',
        updatedAt: 'DATETIME NOT NULL',
        createdAt: 'DATETIME NOT NULL'
      });
      expect(
        this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(
          User2.rawAttributes)).to.deep.equal({
        id: 'INTEGER NOT NULL auto_increment PRIMARY KEY',
        updatedAt: 'DATETIME NOT NULL',
        createdAt: 'DATETIME NOT NULL'
      });
    });

    it('adds deletedAt if paranoid', function() {
      const User = this.sequelize.define(`User${Support.rand()}`, {},
        { paranoid: true });
      expect(
        this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(
          User.rawAttributes)).to.deep.equal({
        id: 'INTEGER NOT NULL auto_increment PRIMARY KEY',
        deletedAt: 'DATETIME',
        updatedAt: 'DATETIME NOT NULL',
        createdAt: 'DATETIME NOT NULL'
      });
    });

    it('underscores timestamps if underscored', function() {
      const User = this.sequelize.define(`User${Support.rand()}`, {},
        { paranoid: true, underscored: true });
      expect(
        this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(
          User.rawAttributes)).to.deep.equal({
        id: 'INTEGER NOT NULL auto_increment PRIMARY KEY',
        deleted_at: 'DATETIME',
        updated_at: 'DATETIME NOT NULL',
        created_at: 'DATETIME NOT NULL'
      });
    });

    it('omits text fields with defaultValues', function() {
      const User = this.sequelize.define(`User${Support.rand()}`,
        { name: { type: DataTypes.TEXT, defaultValue: 'helloworld' } });
      expect(User.rawAttributes.name.type.toString()).to.equal('TEXT');
    });

    it('omits blobs fields with defaultValues', function() {
      const User = this.sequelize.define(`User${Support.rand()}`,
        { name: { type: DataTypes.STRING.BINARY, defaultValue: 'helloworld' } });
      expect(User.rawAttributes.name.type.toString()).to.equal(
        'VARCHAR(255) BINARY');
    });
  });

  describe('primaryKeys', () => {
    it('determines the correct primaryKeys', function() {
      const User = this.sequelize.define(`User${Support.rand()}`, {
        foo: { type: DataTypes.STRING, primaryKey: true },
        bar: DataTypes.STRING
      });
      expect(
        this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(
          User.primaryKeys)).to.deep.equal(
        { 'foo': 'VARCHAR(255) PRIMARY KEY' });
    });
  });
});


text:
<?php

namespace Magento\Vault\Test\Unit\Model\Method;

use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;
use Magento\Payment\Gateway\Command\CommandManagerInterface;
use Magento\Payment\Gateway\Command\CommandManagerPoolInterface;
use Magento\Payment\Model\InfoInterface;
use Magento\Payment\Model\MethodInterface;
use Magento\Sales\Api\Data\OrderPaymentExtensionInterface;
use Magento\Sales\Api\Data\TransactionInterface;
use Magento\Sales\Model\Order\Payment;
use Magento\Vault\Api\Data\PaymentTokenInterface;
use Magento\Vault\Api\PaymentTokenManagementInterface;
use Magento\Vault\Model\Method\Vault;
use Magento\Vault\Model\VaultPaymentInterface;

class VaultTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var ObjectManager
     */
    private $objectManager;

    public function setUp()
    {
        $this->objectManager = new ObjectManager($this);
    }

    /**
     * @expectedException \DomainException
     * @expectedExceptionMessage Not implemented
     */
    public function testAuthorizeNotOrderPayment()
    {
        $paymentModel = $this->getMock(InfoInterface::class);

        /** @var Vault $model */
        $model = $this->objectManager->getObject(Vault::class);
        $model->authorize($paymentModel, 0);
    }

    /**
     * @expectedException \LogicException
     * @expectedExceptionMessage Token metadata should be defined
     */
    public function testAuthorizeNoTokenMetadata()
    {
        $paymentModel = $this->getMockBuilder(Payment::class)
            ->disableOriginalConstructor()
            ->getMock();

        $paymentModel->expects(static::once())
            ->method('getAdditionalInformation')
            ->willReturn([]);

        /** @var Vault $model */
        $model = $this->objectManager->getObject(Vault::class);
        $model->authorize($paymentModel, 0);
    }

    /**
     * @expectedException \LogicException
     * @expectedExceptionMessage No token found
     */
    public function testAuthorizeNoToken()
    {
        $customerId = 1;
        $publicHash = 'token_public_hash';

        $paymentModel = $this->getMockBuilder(Payment::class)
            ->disableOriginalConstructor()
            ->getMock();
        $tokenManagement = $this->getMock(PaymentTokenManagementInterface::class);

        $paymentModel->expects(static::once())
            ->method('getAdditionalInformation')
            ->willReturn(
                [
                    Vault::TOKEN_METADATA_KEY => [
                        PaymentTokenInterface::CUSTOMER_ID => $customerId,
                        PaymentTokenInterface::PUBLIC_HASH => $publicHash
                    ]
                ]
            );
        $tokenManagement->expects(static::once())
            ->method('getByPublicHash')
            ->with($publicHash, $customerId)
            ->willReturn(null);

        /** @var Vault $model */
        $model = $this->objectManager->getObject(
            Vault::class,
            [
                'tokenManagement' => $tokenManagement
            ]
        );
        $model->authorize($paymentModel, 0);
    }

    public function testAuthorize()
    {
        $customerId = 1;
        $publicHash = 'token_public_hash';
        $vaultProviderCode = 'vault_provider_code';
        $amount = 10.01;

        $paymentModel = $this->getMockBuilder(Payment::class)
            ->disableOriginalConstructor()
            ->getMock();
        $extensionAttributes = $this->getMockBuilder(OrderPaymentExtensionInterface::class)
            ->setMethods(['setVaultPaymentToken'])
            ->getMock();

        $commandManagerPool = $this->getMock(CommandManagerPoolInterface::class);
        $commandManager = $this->getMock(CommandManagerInterface::class);

        $vaultProvider = $this->getMock(MethodInterface::class);

        $tokenManagement = $this->getMock(PaymentTokenManagementInterface::class);
        $token = $this->getMock(PaymentTokenInterface::class);

        $paymentModel->expects(static::once())
            ->method('getAdditionalInformation')
            ->willReturn(
                [
                    Vault::TOKEN_METADATA_KEY => [
                        PaymentTokenInterface::CUSTOMER_ID => $customerId,
                        PaymentTokenInterface::PUBLIC_HASH => $publicHash
                    ]
                ]
            );
        $tokenManagement->expects(static::once())
            ->method('getByPublicHash')
            ->with($publicHash, $customerId)
            ->willReturn($token);
        $paymentModel->expects(static::once())
            ->method('getExtensionAttributes')
            ->willReturn($extensionAttributes);
        $extensionAttributes->expects(static::once())
            ->method('setVaultPaymentToken')
            ->with($token);

        $vaultProvider->expects(static::atLeastOnce())
            ->method('getCode')
            ->willReturn($vaultProviderCode);
        $commandManagerPool->expects(static::once())
            ->method('get')
            ->with($vaultProviderCode)
            ->willReturn($commandManager);
        $commandManager->expects(static::once())
            ->method('executeByCode')
            ->with(
                VaultPaymentInterface::VAULT_AUTHORIZE_COMMAND,
                $paymentModel,
                [
                    'amount' => $amount
                ]
            );

        $paymentModel->expects(static::once())
            ->method('setMethod')
            ->with($vaultProviderCode);

        /** @var Vault $model */
        $model = $this->objectManager->getObject(
            Vault::class,
            [
                'tokenManagement' => $tokenManagement,
                'commandManagerPool' => $commandManagerPool,
                'vaultProvider' => $vaultProvider
            ]
        );
        $model->authorize($paymentModel, $amount);
    }

    /**
     * @expectedException \DomainException
     * @expectedExceptionMessage Not implemented
     */
    public function testCaptureNotOrderPayment()
    {
        $paymentModel = $this->getMock(InfoInterface::class);

        /** @var Vault $model */
        $model = $this->objectManager->getObject(Vault::class);
        $model->capture($paymentModel, 0);
    }

    /**
     * @expectedException \DomainException
     * @expectedExceptionMessage Capture can not be performed through vault
     */
    public function testCapture()
    {
        $paymentModel = $this->getMockBuilder(Payment::class)
            ->disableOriginalConstructor()
            ->getMock();

        $authorizationTransaction = $this->getMock(TransactionInterface::class);
        $paymentModel->expects(static::once())
            ->method('getAuthorizationTransaction')
            ->willReturn($authorizationTransaction);

        /** @var Vault $model */
        $model = $this->objectManager->getObject(Vault::class);
        $model->capture($paymentModel, 0);
    }
}


text:
void panic(const char* reason);
void halt();
#ifdef X86
void halt_regs(registers_t* regs);
#endif
#endif


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no"/>
		<meta name="apple-mobile-web-app-capable" content="yes" />
		<title>DojoX Analytics Touch and Gesture Test</title>

				outer content
inner content


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>IStreamDeck (VVIERD Streamdeck API 1.0.2-SNAPSHOT API)</title>
<meta name="date" content="2019-01-13">
<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 Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

de.rcblum.stream.deck.device

Interface IStreamDeck

All Known Implementing Classes:

SoftStreamDeck, StreamDeck

public interface IStreamDeck

MIT License

 Copyright (c) 2017 Roland von Werden

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.

Author:

Roland von Werden

Method Summary

All Methods Instance Methods Abstract Methods Default Methods

Modifier and Type
Method and Description

void
addKey(int keyId,
      StreamItem item)

Adds a StreamKeyListener to the given index

boolean
addKeyListener(StreamKeyListener listener)

Adds an StreamKeyListener to the ESD.

void
clearButton(int i)

void
drawImage(int keyIndex,
         SDImage imgData)

Creates a Job to send the give icon to the ESD to be displayed on the given keyxIndex

purejavahidapi.HidDevice
getHidDevice()

Returns the Hid Devices representation the stream deck.

default int
getKeySize()

Returns the amount of keys on the StreamDeck.

boolean
isHardware()

Returns if behind the interface is actual hardware or a software only StreamDeck.

void
removeKey(int keyId)

Removes a registered Key.

boolean
removeKeyListener(StreamKeyListener listener)

Removes an StreamKeyListener from the ESD.

void
reset()

Queues a task to reset the stream deck.

void
setBrightness(int brightness)

Sets the desired brightness from 0 - 100 % and queues the change.

void
stop()

Tells the background task for the stream deck to stop working.

void
waitForCompletion()

Wait for all tasks to be executed

Method Detail

addKey

void addKey(int keyId,
            StreamItem item)

Adds a StreamKeyListener to the given index

Parameters:

keyId - Index of the key, 0..14

item - StreamItem to be bound to the index

Throws:

IndexOutOfBoundsException - when keyId is < 0 or > 14.

addKeyListener

boolean addKeyListener(StreamKeyListener listener)

Adds an StreamKeyListener to the ESD. WHenever a Event is generated, the Listener will be informed.

Parameters:

listener - Listener to be added

Returns:

true if listener was added, false if listener is already registered.

removeKeyListener

boolean removeKeyListener(StreamKeyListener listener)

Removes an StreamKeyListener from the ESD.

Parameters:

listener - Listener to be removed

Returns:

true if listener was removed, false if listener is not registered.

drawImage

void drawImage(int keyIndex,
               SDImage imgData)

Creates a Job to send the give icon to the ESD to be displayed on the given keyxIndex

Parameters:

keyIndex - Index of ESD (0..14)

imgData - Image in BGR format to be displayed

getHidDevice

purejavahidapi.HidDevice getHidDevice()

Returns the Hid Devices representation the stream deck.

Returns:

HidDevice representation the stream deck.

removeKey

void removeKey(int keyId)

Removes a registered Key. Queues update to the stream deck

Parameters:

keyId - id of the key to be removed

reset

void reset()

Queues a task to reset the stream deck.

setBrightness

void setBrightness(int brightness)

Sets the desired brightness from 0 - 100 % and queues the change.

Parameters:

brightness - Brightness in percentile

stop

void stop()

Tells the background task for the stream deck to stop working.

waitForCompletion

void waitForCompletion()

Wait for all tasks to be executed

clearButton

void clearButton(int i)

isHardware

boolean isHardware()

Returns if behind the interface is actual hardware or a software only StreamDeck.

Returns:

true if hardware is sued, false if the implementation is only software.

getKeySize

default int getKeySize()

Returns the amount of keys on the StreamDeck.

Returns:

Numbers of keys on the deck (Default 15).

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2019. All rights reserved.


text:
<?php

/*
	This cancels a previously-made request.
*/

// FROM HERE (until below where I say UNTIL HERE) is the intranet user authentication stuff which would need changing

$path = $_SERVER['DOCUMENT_ROOT'] . '/peds/pass/includes/catnetapps.inc';
require_once $path;

// instantiate class
$catn= NEW CatnetApps();
$keyid = $catn->getVariable("keyid");
$catn->setUserInfo($keyid);

$catn->dbconnect("catnet",$catn->dbuser,$catn->dbpassword);

// UNTIL HERE - note that this includes the database connection, so that would have to be redone as well

$whichRequest = $catn->getVariable("whichRequest");

// Delete request from database
$query = "delete from pass.requestmatrix where requestID=".$whichRequest;
mysql_query($query);

$catn->dbdisconnect();
?>

<script language='JavaScript'>
	alert('Request cancelled.');
	hideStudentRequest();
</script>


text:
package tlc2.tool.impl;

import tla2sany.semantic.SymbolNode;
import tlc2.output.EC;
import tlc2.tool.IContextEnumerator;
import tlc2.util.Context;
import tlc2.value.impl.TupleValue;
import tlc2.value.impl.Value;
import tlc2.value.impl.ValueEnumeration;
import util.Assert;

public final class ContextEnumerator implements IContextEnumerator {
  private Context con;
  private Object[] vars;
  private ValueEnumeration[] enums;
  private Value[] currentElems;
  private boolean isDone;

  public ContextEnumerator(Object[] vars, ValueEnumeration[] enums, Context con) {
    this.con = con;
    this.vars = vars;
    this.enums = enums;
    this.currentElems = new Value[enums.length];
    this.isDone = false;
    for (int i = 0; i < enums.length; i++) {
      this.currentElems[i] = this.enums[i].nextElement();
      if (this.currentElems[i] == null) {
	this.isDone = true;
	break;
      }
    }
  }

  @Override
  public final Context nextElement() {
      Context con1 = this.con;
      if (this.isDone) return null;
      for (int i = 0; i < enums.length; i++) {
          if (this.vars[i] instanceof SymbolNode) {
              con1 = con1.cons((SymbolNode)this.vars[i], this.currentElems[i]);
          }
          else {
              SymbolNode[] varList = (SymbolNode[])this.vars[i];
              Value argVal = this.currentElems[i];
              if (!(argVal instanceof TupleValue)) {
                  Assert.fail(EC.TLC_ARGUMENT_MISMATCH, varList[0].toString());
              }
              Value[] valList = ((TupleValue)argVal).elems;
              if (varList.length != valList.length) {
                  Assert.fail(EC.TLC_ARGUMENT_MISMATCH, varList[0].toString());
              }
              for (int j = 0; j < varList.length; j++) {
                  con1 = con1.cons(varList[j], valList[j]);
              }
          }
      }
      for (int i = 0; i < enums.length; i++) {
          this.currentElems[i] = this.enums[i].nextElement();
          if (this.currentElems[i] != null) break;
          if (i == this.enums.length - 1) {
              this.isDone = true;
              break;
          }
          this.enums[i].reset();
          this.currentElems[i] = this.enums[i].nextElement();
      }
      return con1;
  }

  public final boolean isDone() {
	return isDone;
  }
}