text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>paco: Error 🔥</title>
    <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
    <link href="../../../../../bootstrap.min.css" rel="stylesheet">
    <link href="../../../../../bootstrap-custom.css" rel="stylesheet">
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

             Coq bench

clean / released

8.8.2 / paco - 2.0.3

            « Up

              paco

                2.0.3
                Error 🔥

📅  (2022-09-22 01:18:02 UTC)

Context

# Packages matching: installed
# Name              # Installed # Synopsis
base-bigarray       base
base-num            base        Num library distributed with the OCaml compiler
base-ocamlbuild     base        OCamlbuild binary and libraries distributed with the OCaml compiler
base-threads        base
base-unix           base
camlp5              7.14        Preprocessor-pretty-printer of OCaml
conf-findutils      1           Virtual package relying on findutils
conf-perl           2           Virtual package relying on perl
coq                 8.8.2       Formal proof management system
num                 0           The Num library for arbitrary-precision integer and rational arithmetic
ocaml               4.02.3      The OCaml compiler (virtual package)
ocaml-base-compiler 4.02.3      Official 4.02.3 release
ocaml-config        1           OCaml Switch Configuration
ocamlfind           1.9.5       A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "paco@sf.snu.ac.kr"
version: "2.0.3"
homepage: "https://github.com/snu-sf/paco/"
dev-repo: "git+https://github.com/snu-sf/paco.git"
bug-reports: "https://github.com/snu-sf/paco/issues/"
authors: [
  "Chung-Kil Hur <gil.hur@sf.snu.ac.kr>"
  "Georg Neis <neis@mpi-sws.org>"
  "Derek Dreyer <dreyer@mpi-sws.org>"
  "Viktor Vafeiadis <viktor@mpi-sws.org>"
]
license: "BSD-3"
build: [
  [make "-C" "src" "all" "-j%{jobs}%"]
]
install: [
  [make "-C" "src" "-f" "Makefile.coq" "install"]
]
remove: ["rm" "-r" "-f" "%{lib}%/coq/user-contrib/Paco"]
depends: [
  "ocaml"
  "coq" {>= "8.6" & < "8.10"}
]
synopsis: "Coq library implementing parameterized coinduction"
tags: [
  "date:2018-02-11"
  "category:Computer Science/Programming Languages/Formal Definitions and Theory"
  "category:Mathematics/Logic"
  "keyword:co-induction"
  "keyword:simulation"
  "keyword:parameterized greatest fixed point"
]
flags: light-uninstall
url {
  src: "https://github.com/snu-sf/paco/archive/v2.0.3.tar.gz"
  checksum: "md5=30705f61294a229215149a024060f06d"
}

Lint

Command

true

Return code

0

Dry install 🏜

Dry install with the current Coq version:

Command

opam install -y --show-action coq-paco.2.0.3 coq.8.8.2

Return code

0

Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:

Command

true

Return code

0

Install dependencies

Command

opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-paco.2.0.3 coq.8.8.2

Return code

0

Duration

10 s

Install 🚀

Command

opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-paco.2.0.3 coq.8.8.2

Return code

7936

Duration

38 s

Output

# Packages matching: installed
# Name              # Installed # Synopsis
base-bigarray       base
base-num            base        Num library distributed with the OCaml compiler
base-ocamlbuild     base        OCamlbuild binary and libraries distributed with the OCaml compiler
base-threads        base
base-unix           base
camlp5              7.14        Preprocessor-pretty-printer of OCaml
conf-findutils      1           Virtual package relying on findutils
conf-perl           2           Virtual package relying on perl
coq                 8.8.2       Formal proof management system
num                 0           The Num library for arbitrary-precision integer and rational arithmetic
ocaml               4.02.3      The OCaml compiler (virtual package)
ocaml-base-compiler 4.02.3      Official 4.02.3 release
ocaml-config        1           OCaml Switch Configuration
ocamlfind           1.9.5       A library manager for OCaml
[NOTE] Package coq is already installed (current version is 8.8.2).
The following actions will be performed:
  - install coq-paco 2.0.3
<><> Gathering sources ><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
Processing  1/1: [coq-paco.2.0.3: http]
[coq-paco.2.0.3] downloaded from https://github.com/snu-sf/paco/archive/v2.0.3.tar.gz
Processing  1/1:
<><> Processing actions <><><><><><><><><><><><><><><><><><><><><><><><><><><><>
Processing  1/2: [coq-paco: make src]
+ /home/bench/.opam/opam-init/hooks/sandbox.sh "build" "make" "-C" "src" "all" "-j4" (CWD=/home/bench/.opam/ocaml-base-compiler.4.02.3/.opam-switch/build/coq-paco.2.0.3)
- make: Entering directory '/home/bench/.opam/ocaml-base-compiler.4.02.3/.opam-switch/build/coq-paco.2.0.3/src'
- make: Circular Makefile.coq <- Makefile dependency dropped.
- make: Circular paco.v <- Makefile.coq dependency dropped.
- make: Circular paco16.v <- Makefile.coq dependency dropped.
- make: Circular examples.v <- Makefile.coq dependency dropped.
- make: Circular paco15.v <- Makefile.coq dependency dropped.
- make: Circular paco11_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco2_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco10.v <- Makefile.coq dependency dropped.
- make: Circular paco14.v <- Makefile.coq dependency dropped.
- make: Circular paco17_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco9.v <- Makefile.coq dependency dropped.
- make: Circular paco6.v <- Makefile.coq dependency dropped.
- make: Circular paco3.v <- Makefile.coq dependency dropped.
- make: Circular paco12_upto.v <- Makefile.coq dependency dropped.
- make: Circular tutorial.v <- Makefile.coq dependency dropped.
- make: Circular paco16_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco4.v <- Makefile.coq dependency dropped.
- make: Circular paco0.v <- Makefile.coq dependency dropped.
- make: Circular paconotation.v <- Makefile.coq dependency dropped.
- make: Circular hpattern.v <- Makefile.coq dependency dropped.
- make: Circular paco13.v <- Makefile.coq dependency dropped.
- make: Circular paco10_upto.v <- Makefile.coq dependency dropped.
- make: Circular pacotac.v <- Makefile.coq dependency dropped.
- make: Circular paco5.v <- Makefile.coq dependency dropped.
- make: Circular paco1.v <- Makefile.coq dependency dropped.
- make: Circular pacon.v <- Makefile.coq dependency dropped.
- make: Circular pacotacuser.v <- Makefile.coq dependency dropped.
- make: Circular paco17.v <- Makefile.coq dependency dropped.
- make: Circular paco7_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco15_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco8.v <- Makefile.coq dependency dropped.
- make: Circular paco18.v <- Makefile.coq dependency dropped.
- make: Circular paco6_upto.v <- Makefile.coq dependency dropped.
- make: Circular paconotation_internal.v <- Makefile.coq dependency dropped.
- make: Circular paco0_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco14_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco11.v <- Makefile.coq dependency dropped.
- make: Circular paco7.v <- Makefile.coq dependency dropped.
- make: Circular paco2.v <- Makefile.coq dependency dropped.
- make: Circular paco13_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco8_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco18_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco5_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco1_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco4_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco9_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco3_upto.v <- Makefile.coq dependency dropped.
- make: Circular paco12.v <- Makefile.coq dependency dropped.
- (echo "-R . Paco"; \
-    \
-    echo *.v) > _CoqProject
- coq_makefile -f _CoqProject -o Makefile.coq
- make -f Makefile.coq "Makefile"
- make[1]: Entering directory '/home/bench/.opam/ocaml-base-compiler.4.02.3/.opam-switch/build/coq-paco.2.0.3/src'
- COQDEP VFILES
- make[1]: Nothing to be done for 'Makefile'.
- make[1]: Leaving directory '/home/bench/.opam/ocaml-base-compiler.4.02.3/.opam-switch/build/coq-paco.2.0.3/src'
- make -f Makefile.coq all
- make[1]: Entering directory '/home/bench/.opam/ocaml-base-compiler.4.02.3/.opam-switch/build/coq-paco.2.0.3/src'
- COQC paconotation.v
- COQC hpattern.v
- COQC pacotac.v
- COQC paconotation_internal.v
- COQC pacotacuser.v
- COQC pacon.v
- COQC paco0.v
- COQC paco1.v
- COQC paco2.v
- COQC paco3.v
- COQC paco4.v
- COQC paco5.v
- COQC paco6.v
- COQC paco7.v
- COQC paco8.v
- COQC paco9.v
- COQC paco10.v
- COQC paco11.v
- COQC paco12.v
- COQC paco13.v
- COQC paco14.v
- COQC paco15.v
- COQC paco16.v
- COQC paco17.v
- COQC paco18.v
- File "./paco18.v", line 141, characters 0-446:
- Error: System error: "No space left
- make[1]: *** [Makefile.coq:318: all] Error 2
- make[1]: Leaving directory '/home/bench/.opam/ocaml-base-compiler.4.02.3/.opam-switch/build/coq-paco.2.0.3/src'
- make: *** [Makefile:7: all] Error 2
- make: Leaving directory '/home/bench/.opam/ocaml-base-compiler.4.02.3/.opam-switch/build/coq-paco.2.0.3/src'
[ERROR] The compilation of coq-paco failed at "/home/bench/.opam/opam-init/hooks/sandbox.sh build make -C src all -j4".
#=== ERROR while compiling coq-paco.2.0.3 =====================================#
# context              2.0.6 | linux/x86_64 | ocaml-base-compiler.4.02.3 | file:///home/bench/run/opam-coq-archive/released
# path                 ~/.opam/ocaml-base-compiler.4.02.3/.opam-switch/build/coq-paco.2.0.3
# command              ~/.opam/opam-init/hooks/sandbox.sh build make -C src all -j4
# exit-code            2
# env-file             ~/.opam/log/coq-paco-8821-865888.env
# output-file          ~/.opam/log/coq-paco-8821-865888.out
### output ###
# [...]
# COQC paco12.v
# COQC paco13.v
# COQC paco14.v
# COQC paco15.v
# COQC paco16.v
# COQC paco17.v
# COQC paco18.v
# File "./paco18.v", line 141, characters 0-446:
# Error: System error: "No space left make[1]: *** [Makefile.coq:318: all] Error 2
# make[1]: Leaving directory '/home/bench/.opam/ocaml-base-compiler.4.02.3/.opam-switch/build/coq-paco.2.0.3/src'
# make: *** [Makefile:7: all] Error 2
# make: Leaving directory '/home/bench/.opam/ocaml-base-compiler.4.02.3/.opam-switch/build/coq-paco.2.0.3/src'
<><> Error report <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
+- The following actions failed
| - build coq-paco 2.0.3
+-
- No changes have been performed
# Run eval $(opam env) to update the current shell environment
'opam install -y -v coq-paco.2.0.3 coq.8.8.2' failed.

Installation size

No files were installed.

Uninstall 🧹

Command

true

Return code

0

Missing removes

                none

Wrong removes

                none

          Sources are on GitHub © Guillaume Claret 🐣


text:
from __future__ import unicode_literals

from datetime import timedelta

from .base import (AppointmentDataTestCase, Notification, Appointment,
    TimelineSubscription, now)
from ..handlers.confirm import ConfirmHandler
from ..handlers.move import MoveHandler
from ..handlers.new import NewHandler
from ..handlers.quit import QuitHandler
from ..handlers.status import StatusHandler

class NewHandlerTestCase(AppointmentDataTestCase):
    "Keyword handler for adding users to timelines"

    def setUp(self):
        self.timeline = self.create_timeline(name='Test', slug='foo')

    def test_help(self):
        "Prefix and keyword should return the help for adding subscriptions."
        replies = NewHandler.test('APPT NEW')
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('APPT NEW <KEY> <NAME/ID> <DATE>' in reply)

    def test_match(self):
        "Send a successful match to create user timeline subscription."
        replies = NewHandler.test('APPT NEW foo bar')
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Thank you'), reply)

    def test_match_with_date(self):
        "Use start date if given."
        tomorrow = (now() + timedelta(days=1)).strftime('%Y-%m-%d')
        replies = NewHandler.test('APPT NEW foo bar %s' % tomorrow)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Thank you'), reply)

    def test_no_keyword_match(self):
        "Keyword does not match any existing timelines."
        self.timeline.delete()
        replies = NewHandler.test('APPT NEW foo bar')
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Sorry'))

    def test_no_name_given(self):
        "No name is given."
        replies = NewHandler.test('APPT NEW foo')
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Sorry'))

    def test_invalid_date_format_given(self):
        "Invalid date format."
        replies = NewHandler.test('APPT NEW foo bar baz')
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Sorry'))

    def test_already_joined(self):
        "Attempting to register and already registered connection/name pair."
        connection = self.create_connection()
        NewHandler._mock_backend = connection.backend
        self.create_timeline_subscription(timeline=self.timeline,
            connection=connection, pin='bar')
        replies = NewHandler.test('APPT NEW foo bar', identity=connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Sorry'))
        del NewHandler._mock_backend

class ConfirmHandlerTestCase(AppointmentDataTestCase):
    "Keyword handler for confirming appointments."

    def setUp(self):
        self.timeline = self.create_timeline(name='Test', slug='foo')
        self.connection = self.create_connection()
        self.subscription = self.create_timeline_subscription(
            timeline=self.timeline, connection=self.connection, pin='bar')
        ConfirmHandler._mock_backend = self.connection.backend
        self.milestone = self.create_milestone(timeline=self.timeline)
        self.appointment = self.create_appointment(milestone=self.milestone)
        self.notification = self.create_notification(appointment=self.appointment)

    def test_help(self):
        "Prefix and keyword should return the help."
        replies = ConfirmHandler.test('APPT CONFIRM')
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('APPT CONFIRM <KEY> <NAME/ID>' in reply)

    def test_appointment_confirmed(self):
        "Successfully confirm an upcoming appointment."
        replies = ConfirmHandler.test('APPT CONFIRM foo bar', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Thank you'))
        notification = Notification.objects.get(pk=self.notification.pk)
        self.assertTrue(notification.confirmed)
        self.assertEqual(notification.status, Notification.STATUS_CONFIRMED)
        appointment = Appointment.objects.get(pk=self.appointment.pk)
        self.assertTrue(appointment.confirmed)

    def test_no_upcoming_appointment(self):
        "Matched user has no upcoming appointment notifications."
        self.notification.delete()
        replies = ConfirmHandler.test('APPT CONFIRM foo bar', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('no unconfirmed' in reply)

    def test_already_confirmed(self):
        "Matched user has already confirmed the upcoming appointment."
        self.notification.confirm()
        replies = ConfirmHandler.test('APPT CONFIRM foo bar', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('no unconfirmed' in reply)

    def test_no_subscription(self):
        "Name/ID does not match a subscription."
        self.subscription.delete()
        replies = ConfirmHandler.test('APPT CONFIRM foo bar', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('does not match an active subscription' in reply)

    def test_subscription_ended(self):
        "Name/ID subscription has ended."
        self.subscription.end = now()
        self.subscription.save()
        replies = ConfirmHandler.test('APPT CONFIRM foo bar', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('does not match an active subscription' in reply)

class StatusHandlerTestCase(AppointmentDataTestCase):
    "Keyword handler for updating the status of appointments."

    def setUp(self):
        self.timeline = self.create_timeline(name='Test', slug='foo')
        self.connection = self.create_connection()
        self.subscription = self.create_timeline_subscription(
            timeline=self.timeline, connection=self.connection, pin='bar')
        StatusHandler._mock_backend = self.connection.backend
        self.milestone = self.create_milestone(timeline=self.timeline)
        self.appointment = self.create_appointment(milestone=self.milestone)

    def test_help(self):
        "Prefix and keyword should return the help."
        replies = StatusHandler.test('APPT STATUS')
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('APPT STATUS <KEY> <NAME/ID> <SAW|MISSED>' in reply)

    def test_appointment_status_updated(self):
        "Successfully update a recent appointment."
        for status in Appointment.STATUS_CHOICES[1:]:
            appt = self.create_appointment(milestone=self.milestone)
            replies = StatusHandler.test('APPT STATUS foo bar %s' % status[1].upper(),
                                         identity=self.connection.identity)
            self.assertEqual(len(replies), 1)
            reply = replies[0]
            self.assertTrue(reply.startswith('Thank you'))
            self.assertTrue(appt.status, status[0])

    def test_appointment_status_invalid_update(self):
        "Do not update if supplied status text is not in STATUS_CHOICES."
        replies = StatusHandler.test('APPT STATUS foo bar FOO', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Sorry, the status update must be in'))

    def test_no_recent_appointment(self):
        "Matched user has no recent appointment."
        self.appointment.delete()
        replies = StatusHandler.test('APPT STATUS foo bar SAW', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('no recent appointments' in reply)

    def test_no_recent_appointment_needing_update(self):
        "Matched user has no recent appointment that needs updating."
        self.appointment.status = Appointment.STATUS_MISSED
        self.appointment.save()
        replies = StatusHandler.test('APPT STATUS foo bar MISSED', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('no recent appointments' in reply)

    def test_future_appointment(self):
        "Matched user has no recent appointment."
        self.appointment.date = self.appointment.date + timedelta(days=1)
        self.appointment.save()
        replies = StatusHandler.test('APPT STATUS foo bar SAW', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('no recent appointments' in reply)

    def test_no_subscription(self):
        "Name/ID does not match a subscription."
        self.subscription.delete()
        replies = StatusHandler.test('APPT STATUS foo bar SAW', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('does not match an active subscription' in reply)

    def test_subscription_ended(self):
        "Name/ID subscription has ended."
        self.subscription.end = now()
        self.subscription.save()
        replies = StatusHandler.test('APPT STATUS foo bar MISSED', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('does not match an active subscription' in reply)

class MoveHandlerTestCase(AppointmentDataTestCase):
    "Keyword handler for rescheduling of appointments."

    def setUp(self):
        self.timeline = self.create_timeline(name='Test', slug='foo')
        self.connection = self.create_connection()
        self.subscription = self.create_timeline_subscription(
            timeline=self.timeline, connection=self.connection, pin='bar')
        MoveHandler._mock_backend = self.connection.backend
        self.milestone = self.create_milestone(timeline=self.timeline)
        self.appointment = self.create_appointment(milestone=self.milestone,
                                                   date=now() + timedelta(hours=1))
        self.tomorrow = (now() + timedelta(days=1)).strftime('%Y-%m-%d')

    def test_help(self):
        "Prefix and keyword should return the help."
        replies = MoveHandler.test('APPT MOVE')
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('APPT MOVE <KEY> <NAME/ID> <DATE>' in reply)

    def test_appointment_reschedule(self):
        "Successfully reschedule an upcoming appointment."
        self.assertEqual(1, Appointment.objects.all().count())
        replies = MoveHandler.test('APPT MOVE foo bar %s' % self.tomorrow,
                                   identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Thank you'))
        self.assertEqual(2, Appointment.objects.all().count())
        reschedule = Appointment.objects.all()[0]
        self.assertEqual(reschedule.appointments.all()[0], self.appointment)

    def test_appointment_reschedule_malformed_date(self):
        "Ensure the date is properly formatted."
        replies = MoveHandler.test('APPT MOVE foo bar tomorrow',
                                   identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Sorry, we cannot understand that date format'))

    def test_appointment_reschedule_future_date(self):
        "Ensure the date must be in the future."
        yesterday = (now() - timedelta(days=1)).strftime('%Y-%m-%d')
        replies = MoveHandler.test('APPT MOVE foo bar %s' % yesterday,
                                   identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Sorry, the reschedule date'))

    def test_no_future_appointment(self):
        "Matched user has no future appointment."
        self.appointment.delete()
        replies = MoveHandler.test('APPT MOVE foo bar %s' % self.tomorrow,
                                     identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('no future appointments' in reply)

    def test_no_future_appointment_needing_update(self):
        "Matched user has no future appointment that needs rescheduling."
        reschedule = self.create_appointment(subscription=self.subscription,
                                             milestone=self.milestone)
        self.appointment.reschedule = reschedule
        self.appointment.save()
        replies = MoveHandler.test('APPT MOVE foo bar %s' % self.tomorrow,
                                     identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('no future appointments' in reply)

    def test_prior_appointment(self):
        "Matched user has no future appointment."
        self.appointment.date = self.appointment.date - timedelta(days=1)
        self.appointment.save()
        replies = MoveHandler.test('APPT MOVE foo bar %s' % self.tomorrow,
                                     identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('no future appointments' in reply)

    def test_no_subscription(self):
        "Name/ID does not match a subscription."
        self.subscription.delete()
        replies = MoveHandler.test('APPT MOVE foo bar %s' % self.tomorrow,
                                     identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('does not match an active subscription' in reply)

    def test_subscription_ended(self):
        "Name/ID subscription has ended."
        self.subscription.end = now()
        self.subscription.save()
        replies = MoveHandler.test('APPT MOVE foo bar %s' % self.tomorrow,
                                     identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('does not match an active subscription' in reply)

class QuitHandlerTestCase(AppointmentDataTestCase):
    "Keyword handler for unsubscribing users to timelines"
    def setUp(self):
        self.timeline = self.create_timeline(name='Test', slug='foo')
        self.connection = self.create_connection()
        self.subscription = self.create_timeline_subscription(
            timeline=self.timeline, connection=self.connection, pin='bar')
        QuitHandler._mock_backend = self.connection.backend

    def test_help(self):
        "Prefix and keyword should return the help for quitting a subscription."
        replies = QuitHandler.test('APPT QUIT', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue('APPT QUIT <KEY> <NAME/ID> <DATE>' in reply)

    def test_match(self):
        "Send a successful match to end a timeline subscription."
        replies = QuitHandler.test('APPT QUIT foo bar', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Thank you'), reply)

    def test_match_with_date(self):
        "Use end date if given."
        end = (now() + timedelta(hours=1)).strftime('%Y-%m-%d')
        replies = QuitHandler.test('APPT QUIT foo bar %s' % end,
                                    identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Thank you'), reply)
        self.assertEqual(end, TimelineSubscription.objects.all()[0].end.strftime('%Y-%m-%d'))

    def test_no_keyword_match(self):
        "Keyword does not match any existing timelines."
        self.timeline.delete()
        replies = QuitHandler.test('APPT QUIT foo bar', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Sorry'))

    def test_no_name_given(self):
        "No name is given."
        replies = QuitHandler.test('APPT QUIT foo', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Sorry'))

    def test_invalid_date_format_given(self):
        "Invalid date format."
        replies = QuitHandler.test('APPT QUIT foo bar baz', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Sorry'))

    def test_already_quit(self):
        "Attempting to unsubscribe and already unsubcribed connection/name pair."
        self.subscription.end = now()
        self.subscription.save()
        replies = QuitHandler.test('APPT QUIT foo bar', identity=self.connection.identity)
        self.assertEqual(len(replies), 1)
        reply = replies[0]
        self.assertTrue(reply.startswith('Sorry'))

redpajama_set_name: RedPajamaGithub


text:
'''
Created on Nov 23, 2017

@author: prismtech
'''
import sys
from symbol import except_clause
sys.path.append('../dds')
from dds import DomainParticipant, Topic, Listener, Qos, DurabilityQosPolicy, DDSDurabilityKind, DDSException
import unittest
import time
import xmlrunner
import ddsutil
from threading import Event

# Data available listener
class DataAvailableListener(Listener):
    def __init__(self, holder, event):
        Listener.__init__(self)
        self.holder = holder
        self.event = event

    def on_data_available(self, entity):
        l = entity.read(10)
        for (sd, si) in l:
            if si.valid_data:
                sd.print_vars()
                self.holder.result = str(sd)
        self.event.set()

class ResultHolder(object):

    def __init__(self):
        self._result = ''

    @property
    def result(self):
        return self._result

    @result.setter
    def result(self, value):
        self._result = value

class Test(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testAccessingTopicMetaData(self):
        idl_path = 'idl/' + 'Thales' + '.idl'
        type_info = 'test::C_TopicStruct'
        gen_info = ddsutil.get_dds_classes_from_idl(idl_path, type_info)

        dp1 = DomainParticipant()
        tq1 = Qos([DurabilityQosPolicy(DDSDurabilityKind.PERSISTENT)])
        topic_dp1 = gen_info.register_topic(dp1, 'DP1_C_TopicStruct',tq1)

        self.assertEqual('DP1_C_TopicStruct', topic_dp1.name, 'Topic name not as expected')
        self.assertEqual(type_info, topic_dp1.type_name, 'Type name not as expected')
        self.assertEqual('A_ID.A_ID,A_ID.A_subID', topic_dp1.keylist, 'Key list not as expected')
        self.assertEqual('<MetaData version="1.0.0"><Module name="test"><Struct name="T_ID"><Member name="A_ID"><Long/></Member><Member name="A_subID"><Long/></Member></Struct><TypeDef name="T_IDList"><Sequence><Type name="T_ID"/></Sequence></TypeDef><Struct name="C_TopicStruct"><Member name="A_ID"><Type name="T_ID"/></Member><Member name="A_ForeignIDList"><Type name="T_IDList"/></Member><Member name="value"><Long/></Member></Struct></Module></MetaData>',
                         topic_dp1.metadescriptor, 'Meta descriptor not as expected')

        dp2 = DomainParticipant()
        topic_dp2 = dp2.find_topic('DP1_C_TopicStruct')
        self.assertIsNotNone(topic_dp2, 'Found topic is not None')
        self.assertEqual('DP1_C_TopicStruct', topic_dp2.name, 'Found topic name not as expected')
        self.assertEqual(type_info, topic_dp2.type_name, 'Found type name not as expected')
        self.assertEqual('A_ID.A_ID,A_ID.A_subID', topic_dp2.keylist, 'Found key list not as expected')
        self.assertEqual('<MetaData version="1.0.0"><Module name="test"><Struct name="T_ID"><Member name="A_ID"><Long/></Member><Member name="A_subID"><Long/></Member></Struct><TypeDef name="T_IDList"><Sequence><Type name="T_ID"/></Sequence></TypeDef><Struct name="C_TopicStruct"><Member name="A_ID"><Type name="T_ID"/></Member><Member name="A_ForeignIDList"><Type name="T_IDList"/></Member><Member name="value"><Long/></Member></Struct></Module></MetaData>',
                         topic_dp2.metadescriptor, 'Found meta descriptor not as expected')

        pub2 = dp2.create_publisher()
        sub2 = dp2.create_subscriber()
        try:
            wr2 = pub2.create_datawriter(topic_dp2)
            self.assertFalse('Expected pub2.create_datawriter to throw exception')
        except DDSException:
            pass
        try:
            rd2 = sub2.create_datareader(topic_dp2)
            self.assertFalse('Expected sub2.create_datareader to throw exception')
        except DDSException:
            pass

        # now register the found topic locally, and test reading and writing between the participants
        local_topic_dp2 = ddsutil.register_found_topic_as_local(topic_dp2)

        gen_info2 = ddsutil.get_dds_classes_for_found_topic(topic_dp2)
        self.assertIsNotNone(gen_info2, 'Returned gen_info2 is None')

        tq2 = topic_dp2.qos
        self.assertIsNotNone(tq2)

        # TODO: need get copy topic qos
        #local_topic_dp2 = register_topic_locally(topic_dp2)
#        local_topic_dp2 = gen_info2.register_topic(dp2, topic_dp2.get_name(), tq2)

        # Reader for dp2
        result_holder = ResultHolder()
        event = Event()
        rd2 = sub2.create_datareader(local_topic_dp2, tq2, DataAvailableListener(result_holder,event))

        # Writer for dp1
        pub1 = dp1.create_publisher()
        wr1 = pub1.create_datawriter(topic_dp1, tq1)

        # create the data
        Outer = gen_info.get_class('test::C_TopicStruct')
        Inner = gen_info.get_class('test::T_ID')
        data1 = Outer()
        data1.A_ID = Inner(A_ID=1,A_subID=12)
        data1.A_ForeignIDList = [Inner(A_ID=2,A_subID=23),Inner(A_ID=3,A_subID=34)]
        data1.value = 42

        wr1.write(data1)

        # let the listener catch up...
        self.assertTrue(event.wait(10.0), 'wait timed out')

        self.assertEqual(str(data1), result_holder.result, 'read and write results do not match')

    def testSimplifiedFindAPI(self):
        idl_path = 'idl/' + 'Thales' + '.idl'
        type_info = 'test::C_TopicStruct'
        gen_info = ddsutil.get_dds_classes_from_idl(idl_path, type_info)

        dp1 = DomainParticipant()
        tq1 = Qos([DurabilityQosPolicy(DDSDurabilityKind.PERSISTENT)])
        topic_dp1 = gen_info.register_topic(dp1, 'DP1_C_TopicStruct_2',tq1)

        self.assertEqual('DP1_C_TopicStruct_2', topic_dp1.name, 'Topic name not as expected')
        self.assertEqual(type_info, topic_dp1.type_name, 'Type name not as expected')
        self.assertEqual('A_ID.A_ID,A_ID.A_subID', topic_dp1.keylist, 'Key list not as expected')
        self.assertEqual('<MetaData version="1.0.0"><Module name="test"><Struct name="T_ID"><Member name="A_ID"><Long/></Member><Member name="A_subID"><Long/></Member></Struct><TypeDef name="T_IDList"><Sequence><Type name="T_ID"/></Sequence></TypeDef><Struct name="C_TopicStruct"><Member name="A_ID"><Type name="T_ID"/></Member><Member name="A_ForeignIDList"><Type name="T_IDList"/></Member><Member name="value"><Long/></Member></Struct></Module></MetaData>',
                         topic_dp1.metadescriptor, 'Meta descriptor not as expected')

        dp2 = DomainParticipant()

        topic_dp2, gen_info2 = ddsutil.find_and_register_topic(dp2, 'DP1_C_TopicStruct_2')
        self.assertIsNotNone(topic_dp2, 'Found topic is not None')
        self.assertEqual('DP1_C_TopicStruct_2', topic_dp2.name, 'Found topic name not as expected')
        self.assertEqual(type_info, topic_dp2.type_name, 'Found type name not as expected')
        self.assertEqual('A_ID.A_ID,A_ID.A_subID', topic_dp2.keylist, 'Found key list not as expected')
        self.assertEqual('<MetaData version="1.0.0"><Module name="test"><Struct name="T_ID"><Member name="A_ID"><Long/></Member><Member name="A_subID"><Long/></Member></Struct><TypeDef name="T_IDList"><Sequence><Type name="T_ID"/></Sequence></TypeDef><Struct name="C_TopicStruct"><Member name="A_ID"><Type name="T_ID"/></Member><Member name="A_ForeignIDList"><Type name="T_IDList"/></Member><Member name="value"><Long/></Member></Struct></Module></MetaData>',
                         topic_dp2.metadescriptor, 'Found meta descriptor not as expected')

        sub2 = dp2.create_subscriber()

        # now register the found topic locally, and test reading and writing between the participants
        self.assertIsNotNone(gen_info2, 'Returned gen_info2 is None')

        tq2 = topic_dp2.qos
        self.assertIsNotNone(tq2)

        # TODO: need get copy topic qos
        #local_topic_dp2 = register_topic_locally(topic_dp2)
#        local_topic_dp2 = gen_info2.register_topic(dp2, topic_dp2.get_name(), tq2)

        # Reader for dp2
        result_holder = ResultHolder()
        event = Event()
        rd2 = sub2.create_datareader(topic_dp2, tq2, DataAvailableListener(result_holder, event))

        # Writer for dp1
        pub1 = dp1.create_publisher()
        wr1 = pub1.create_datawriter(topic_dp1, tq1)

        # create the data
        Outer = gen_info.get_class('test::C_TopicStruct')
        Inner = gen_info.get_class('test::T_ID')
        data1 = Outer()
        data1.A_ID = Inner(A_ID=21,A_subID=212)
        data1.A_ForeignIDList = [Inner(A_ID=22,A_subID=223),Inner(A_ID=23,A_subID=234)]
        data1.value = 242

        wr1.write(data1)

        # let the listener catch up...
        self.assertTrue(event.wait(10.0), 'wait timed out')

        self.assertEqual(str(data1), result_holder.result, 'read and write results do not match')

    def testSimplifiedFindAPIWithNamedTuple(self):
        idl_path = 'idl/' + 'Thales' + '.idl'
        type_info = 'test::C_TopicStruct'
        gen_info = ddsutil.get_dds_classes_from_idl(idl_path, type_info)

        dp1 = DomainParticipant()
        tq1 = Qos([DurabilityQosPolicy(DDSDurabilityKind.PERSISTENT)])
        topic_dp1 = gen_info.register_topic(dp1, 'DP1_C_TopicStruct_3',tq1)

        self.assertEqual('DP1_C_TopicStruct_3', topic_dp1.name, 'Topic name not as expected')
        self.assertEqual(type_info, topic_dp1.type_name, 'Type name not as expected')
        self.assertEqual('A_ID.A_ID,A_ID.A_subID', topic_dp1.keylist, 'Key list not as expected')
        self.assertEqual('<MetaData version="1.0.0"><Module name="test"><Struct name="T_ID"><Member name="A_ID"><Long/></Member><Member name="A_subID"><Long/></Member></Struct><TypeDef name="T_IDList"><Sequence><Type name="T_ID"/></Sequence></TypeDef><Struct name="C_TopicStruct"><Member name="A_ID"><Type name="T_ID"/></Member><Member name="A_ForeignIDList"><Type name="T_IDList"/></Member><Member name="value"><Long/></Member></Struct></Module></MetaData>',
                         topic_dp1.metadescriptor, 'Meta descriptor not as expected')

        dp2 = DomainParticipant()

        topic_info = ddsutil.find_and_register_topic(dp2, 'DP1_C_TopicStruct_3')

        self.assertIsNotNone(topic_info.topic, 'Found topic is not None')
        self.assertEqual('DP1_C_TopicStruct_3', topic_info.topic.name, 'Found topic name not as expected')
        self.assertEqual(type_info, topic_info.topic.type_name, 'Found type name not as expected')
        self.assertEqual('A_ID.A_ID,A_ID.A_subID', topic_info.topic.keylist, 'Found key list not as expected')
        self.assertEqual('<MetaData version="1.0.0"><Module name="test"><Struct name="T_ID"><Member name="A_ID"><Long/></Member><Member name="A_subID"><Long/></Member></Struct><TypeDef name="T_IDList"><Sequence><Type name="T_ID"/></Sequence></TypeDef><Struct name="C_TopicStruct"><Member name="A_ID"><Type name="T_ID"/></Member><Member name="A_ForeignIDList"><Type name="T_IDList"/></Member><Member name="value"><Long/></Member></Struct></Module></MetaData>',
                         topic_info.topic.metadescriptor, 'Found meta descriptor not as expected')

        sub2 = dp2.create_subscriber()

        # now register the found topic locally, and test reading and writing between the participants
        self.assertIsNotNone(topic_info.gen_info, 'Returned topic_info.gen_info is None')

        tq2 = topic_info.topic.qos
        self.assertIsNotNone(tq2)

        # TODO: need get copy topic qos
        #local_topic_dp2 = register_topic_locally(topic_dp2)
#        local_topic_dp2 = gen_info2.register_topic(dp2, topic_dp2.get_name(), tq2)

        # Reader for dp2
        result_holder = ResultHolder()
        event = Event()
        rd2 = sub2.create_datareader(topic_info.topic, tq2, DataAvailableListener(result_holder, event))

        # Writer for dp1
        pub1 = dp1.create_publisher()
        wr1 = pub1.create_datawriter(topic_dp1, tq1)

        # create the data
        Outer = gen_info.get_class('test::C_TopicStruct')
        Inner = gen_info.get_class('test::T_ID')
        data1 = Outer()
        data1.A_ID = Inner(A_ID=31,A_subID=312)
        data1.A_ForeignIDList = [Inner(A_ID=32,A_subID=323),Inner(A_ID=33,A_subID=334)]
        data1.value = 342

        wr1.write(data1)

        # let the listener catch up...
        self.assertTrue(event.wait(10.0), 'wait timed out')

        self.assertEqual(str(data1), result_holder.result, 'read and write results do not match')

    def testSimplifiedFindAPIWithNamedTupleAndDefaultPubSub(self):
        idl_path = 'idl/' + 'Thales' + '.idl'
        type_info = 'test::C_TopicStruct'
        gen_info = ddsutil.get_dds_classes_from_idl(idl_path, type_info)

        dp1 = DomainParticipant()
        tq1 = Qos([DurabilityQosPolicy(DDSDurabilityKind.PERSISTENT)])
        topic_dp1 = gen_info.register_topic(dp1, 'DP1_C_TopicStruct_4',tq1)

        self.assertEqual('DP1_C_TopicStruct_4', topic_dp1.name, 'Topic name not as expected')
        self.assertEqual(type_info, topic_dp1.type_name, 'Type name not as expected')
        self.assertEqual('A_ID.A_ID,A_ID.A_subID', topic_dp1.keylist, 'Key list not as expected')
        self.assertEqual('<MetaData version="1.0.0"><Module name="test"><Struct name="T_ID"><Member name="A_ID"><Long/></Member><Member name="A_subID"><Long/></Member></Struct><TypeDef name="T_IDList"><Sequence><Type name="T_ID"/></Sequence></TypeDef><Struct name="C_TopicStruct"><Member name="A_ID"><Type name="T_ID"/></Member><Member name="A_ForeignIDList"><Type name="T_IDList"/></Member><Member name="value"><Long/></Member></Struct></Module></MetaData>',
                         topic_dp1.metadescriptor, 'Meta descriptor not as expected')

        dp2 = DomainParticipant()

        topic_info = ddsutil.find_and_register_topic(dp2, 'DP1_C_TopicStruct_4')

        self.assertIsNotNone(topic_info.topic, 'Found topic is not None')
        self.assertEqual('DP1_C_TopicStruct_4', topic_info.topic.name, 'Found topic name not as expected')
        self.assertEqual(type_info, topic_info.topic.type_name, 'Found type name not as expected')
        self.assertEqual('A_ID.A_ID,A_ID.A_subID', topic_info.topic.keylist, 'Found key list not as expected')
        self.assertEqual('<MetaData version="1.0.0"><Module name="test"><Struct name="T_ID"><Member name="A_ID"><Long/></Member><Member name="A_subID"><Long/></Member></Struct><TypeDef name="T_IDList"><Sequence><Type name="T_ID"/></Sequence></TypeDef><Struct name="C_TopicStruct"><Member name="A_ID"><Type name="T_ID"/></Member><Member name="A_ForeignIDList"><Type name="T_IDList"/></Member><Member name="value"><Long/></Member></Struct></Module></MetaData>',
                         topic_info.topic.metadescriptor, 'Found meta descriptor not as expected')

        # now register the found topic locally, and test reading and writing between the participants
        self.assertIsNotNone(topic_info.gen_info, 'Returned topic_info.gen_info is None')

        tq2 = topic_info.topic.qos
        self.assertIsNotNone(tq2)

        # TODO: need get copy topic qos
        #local_topic_dp2 = register_topic_locally(topic_dp2)
#        local_topic_dp2 = gen_info2.register_topic(dp2, topic_dp2.get_name(), tq2)

        # Reader for dp2
        result_holder = ResultHolder()
        event = Event()
        rd2 = dp2.create_datareader(topic_info.topic, tq2, DataAvailableListener(result_holder, event))

        # Writer for dp1
        wr1 = dp1.create_datawriter(topic_dp1, tq1)

        # create the data
        Outer = gen_info.get_class('test::C_TopicStruct')
        Inner = gen_info.get_class('test::T_ID')
        data1 = Outer()
        data1.A_ID = Inner(A_ID=41,A_subID=412)
        data1.A_ForeignIDList = [Inner(A_ID=42,A_subID=423),Inner(A_ID=43,A_subID=434)]
        data1.value = 442

        wr1.write(data1)

        # let the listener catch up...
        self.assertTrue(event.wait(10.0), 'wait timed out')

        self.assertEqual(str(data1), result_holder.result, 'read and write results do not match')

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testAccessingTopicMetaData']
    unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'),
        # these make sure that some options that are not applicable
        # remain hidden from the help menu.
        failfast=False, buffer=False, catchbreak=False)


text:
<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <title>Title</title>

iiuyyysss

    <form class="form-signin" role="form" name="form" th:action="@{/login}" action="/login" method="post">

            <input type="text" class="form-control" name="username" value="" placeholder="账号"/>

            <input type="password" class="form-control" name="password" placeholder="密码"/>

        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
        <input type="submit" id="login" value="Login" class="btn btn-primary"/>
    </form>


text:
layout: minimal
title:  'p5js colors'
permalink: colors
---

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.js"></script>

<script type="text/javascript" src="{{ site.baseurl }}/assets/javascript/p5/colors.js"></script>


text:
package io.crate.integrationtests;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import org.elasticsearch.test.IntegTestCase;
import org.junit.Test;

import io.crate.exceptions.ColumnUnknownException;
import io.crate.testing.Asserts;
import io.crate.testing.TestingHelpers;
import io.crate.testing.UseJdbc;
import io.crate.types.DataTypes;

@UseJdbc(0) // data types needed
public class ScalarIntegrationTest extends IntegTestCase {

    @Test
    public void testExtractFunctionReturnTypes() {
        execute("SELECT EXTRACT(DAY FROM CURRENT_TIMESTAMP)");
        assertThat(response.columnTypes()[0], is(DataTypes.INTEGER));

        execute("SELECT EXTRACT(EPOCH FROM CURRENT_TIMESTAMP)");
        assertThat(response.columnTypes()[0], is(DataTypes.DOUBLE));
    }

    @Test
    public void testSubscriptFunctionFromUnnest() {
        try (var session = sqlExecutor.newSession()) {
            session.sessionSettings().setErrorOnUnknownObjectKey(true);
            Asserts.assertThrowsMatches(
                () -> sqlExecutor.exec(
                    "SELECT unnest['x'] FROM UNNEST(['{\"x\":1,\"y\":2}','{\"y\":2,\"z\":3}']::ARRAY(OBJECT))",
                    session),
                ColumnUnknownException.class,
                "The object `{y=2, z=3}` does not contain the key `x`"
            );
            // This is documenting a bug. If this fails, it is a breaking change.
            var response = sqlExecutor.exec("SELECT [unnest]['x'] FROM UNNEST(['{\"x\":1,\"y\":2}','{\"y\":2,\"z\":3}']::ARRAY(OBJECT))",
                            session);
            assertThat(TestingHelpers.printedTable(response.rows()), is("[1]\n[null]\n"));
        }

        try (var session2 = sqlExecutor.newSession()) {
            session2.sessionSettings().setErrorOnUnknownObjectKey(false);
            response = sqlExecutor.exec("SELECT unnest['x'] FROM UNNEST(['{\"x\":1,\"y\":2}','{\"y\":2,\"z\":3}']::ARRAY(OBJECT))",
                                    session2);
            assertThat(TestingHelpers.printedTable(response.rows()), is("1\nNULL\n"));
            response = sqlExecutor.exec("SELECT [unnest]['x'] FROM UNNEST(['{\"x\":1,\"y\":2}','{\"y\":2,\"z\":3}']::ARRAY(OBJECT))",
                                            session2);
            assertThat(TestingHelpers.printedTable(response.rows()), is("[1]\n[null]\n"));
        }
    }
}


text:
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, authentication_keys: [:username]

  validates :username, presence: true, uniqueness: true,
                       format: { with: /\A[a-z0-9]{4,30}\Z/,
                                 message: 'Accepted format: "\A[a-z0-9]{4,30}\Z"' },
                       exclusion: { in: %w(portus),
                                    message: '%{value} is reserved.' }

  validate :private_namespace_available, on: :create

  has_many :team_users
  has_many :teams, through: :team_users
  has_many :stars

  def private_namespace_available
    return unless Namespace.exists?(name: username)
    errors.add(:username, 'cannot be used as name for private namespace')
  end

  def create_personal_namespace!
    # the registry is not configured yet, we cannot create the namespace
    return unless Registry.any?

    team = Team.find_by(name: username)
    if team.nil?
      team = Team.create!(name: username, owners: [self], hidden: true)
    end

    Namespace.find_or_create_by!(
      team: team,
      name: username,
      registry: Registry.last # TODO: fix once we handle more registries
    )
  end

  # Find the user that can be guessed from the given push event.
  def self.find_from_event(event)
    actor = User.find_by(username: event['actor']['name'])
    logger.error "Cannot find user #{event['actor']['name']}" if actor.nil?
    actor
  end

  # Toggle the 'admin' attribute for this user. It will also update the
  # registry accordingly.
  def toggle_admin!
    admin = !admin?
    return unless update_attributes(admin: admin) && Registry.any?

    team = Registry.first.global_namespace.team
    admin ? team.owners << self : team.owners.delete(self)
  end
end


text:
"""
      Title:
    Project:
     Author: Will Hardy
       Date:  2008
      Usage:
  $Revision$

Description:

"""

from django.conf.urls.defaults import *
from django_dms.apps.large_dms.views import document_view

urlpatterns = patterns('',
    url(r'^',  include(document_view.urls),  name="document_view"),
)


text:
<?php get_header(); ?>

		<?php
			global $post;
			$post_id = get_the_ID();
            $post_info = get_post($post_id);
            $permalink = get_permalink($id);
			$living_name = get_post_meta($post->ID, "living_name", true);
	        $living_img1 = get_post_meta($post->ID, "living_image_1.guid", true);
	        $living_img2 = get_post_meta($post->ID, "living_image_2.guid", true);
	        $living_img3 = get_post_meta($post->ID, "living_image_3.guid", true);
	        $living_img4 = get_post_meta($post->ID, "living_image_4.guid", true);
	        $living_img5 = get_post_meta($post->ID, "living_image_5.guid", true);
			$living_desc = get_the_content($post->ID);
			$living_add1 = get_post_meta($post->ID, "living_add_1", true);
	        $living_add2 = get_post_meta($post->ID, "living_add_2", true);
	        $living_city = get_post_meta($post->ID, "living_city", true);
	        $living_state = get_post_meta($post->ID, "living_state", true);
	        $living_zip = get_post_meta($post->ID, "living_zip", true);
			$living_property_type = get_post_meta($post->ID, "living_property_type.name", true);
			$living_phone_1_label = get_post_meta($post->ID, "living_phone_1_label", true);
			$living_phone_1 = get_post_meta($post->ID, "living_phone_1", true);
			$living_phone_2_label = get_post_meta($post->ID, "living_phone_2_label", true);
			$living_phone_2 = get_post_meta($post->ID, "living_phone_2", true);
			$living_email = get_post_meta($post->ID, "living_email", true);
	        $living_website = get_post_meta($post->ID, "living_website", true);
	        $living_price_label = get_post_meta($post->ID, "living_price_label", true);
	        $living_price = get_post_meta($post->ID, "living_price", true);
	        $living_price_term = get_post_meta($post->ID, "living_price_term", true);
	        $living_contact_photo = get_post_meta($post->ID, "living_contact_photo.guid", true);
	        $living_contact_name = get_post_meta($post->ID, "living_contact_name", true);
	        $living_contact_title = get_post_meta($post->ID, "living_contact_title", true);
	        $living_contact_phone_1_label = get_post_meta($post->ID, "living_contact_phone_1_label", true);
	        $living_contact_phone_1 = get_post_meta($post->ID, "living_contact_phone", true);
	        $living_contact_email = get_post_meta($post->ID, "living_contact_email", true);
	        $living_contact_website = get_post_meta($post->ID, "living_contact_website", true);

			echo '

' . $living_name . '

';

			/////////////// image
            if ( '' != $living_img1 )
							    echo '

';

			/////////////// Desc
			echo '
' . $post_info->post_content . '
';

            if ( '' != $living_phone_1 )
                $icon_ph1 = '' . $living_phone_1_label . '' . $living_phone_1 . '';

            if ( '' != $living_phone_2 )
                $icon_ph2 = '' . $living_phone_2_label . '' . $living_phone_2 . '';

            if ( '' != $living_contact_phone_1 )
							    $icon_contact_ph1 = '' . $living_contact_phone_1_label . '' . $living_contact_phone_1 . '';

					////////////////// Address info
            if(!empty($living_add1) || !empty($living_phone_1)) {
                echo '
';
                if(!empty($living_add1)) echo '
' . $living_add1 . '
';
                if(!empty($living_phone_1)) echo '
' . $icon_ph1 . '
';
                echo '
';
            }

					////////////////// Property info
					echo '
',
						'
 ' . $living_property_type . '
';

                if(!empty($living_price))
							echo '
 ' . $living_price_label . '' . $living_price . '' . $living_price_term . '
';
                if(!empty($icon_ph2))
							echo '
' . $icon_ph2 . '
';

					echo '
';

					////////////////// Info Bar
					echo '
';
					if(!empty($living_website)) {
							echo '
',
						' Website
';
							}
					if(!empty($business_fb)) {
							echo '
',
						' Facebook
';
							}
					echo '
';

					////////////////// Contact
					echo '
';

					if(!empty($living_contact_photo)) {
							echo '

';
							}

				echo '
' . $living_contact_name . '
',
						'
' . $living_contact_title . '
',
						'
' . $icon_contact_ph1  . '
';

						if(!empty($living_contact_email)) {
							echo '<button type="button" class="btn btn-primary btn-md">',
							  '' . eeb_email($living_contact_email, ' Email Me'),
							  '</button> ';
							}
						if(!empty($living_contact_website)) {
							echo '<button type="button" class="btn btn-primary btn-md">',
							  ' Website',
							  '</button>';
							}
						echo '
';

					//map
					echo '
' . do_shortcode( '[codepeople-post-map width="685" height="200"]' ) . '
';

			?>

            <?php get_sidebar(); ?>

<?php get_footer(); ?>


text:
    <form action="http://jipiboily.us7.list-manage1.com/subscribe/post?u=057aa15d4f31799882124acd5&id=da1eb7ce3d" method="post" target="_blank" novalidate="">

          <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Infolettre (courriel)">

          <input type="submit" value="Go!" name="subscribe" id="mc-embedded-subscribe" class="button postfix">

    </form>

@saglacio

groupe Facebook

info@saglac.io


text:
Mount a Rack application, that will act as a health check that ELB, Varnish, etc can use to verify that the application is healthy

## Installation

Add this line to your application's Gemfile:

    gem 'rails_server_status'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install rails_server_status

## Usage

In `config/routes.rb`:

    mount RailsServerStatus::Engine => "/server-status"

cURL the mounted endpoint:

    curl http://localhost:3000/server-status

    HTTP/1.1 200 OK
    up 48699 1.14 192.168.50.206

As JSON:

    curl -H "Accept: application/json" http://localhost:3000/server-status

    HTTP/1.1 200 OK
    {"database":"up","pid":52509,"uptime":1.16,"ip_address":"192.168.50.206"}

## Requirements

* Ruby 2.0.0-p247

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
/* global angular */
/* global Firebase */

var historyModule = angular.module('bplogger.history', ["firebase", "googlechart","ngRoute"]);

historyModule.value('googleChartApiConfig', {
    version: '1',
    optionalSettings: {
        packages: ['corechart'],
        language: 'es'
    }
});

historyModule.value('configuration', {
    bp: {
        type: "LineChart",
        options: {
            curveType: 'function',
            title: 'Blood pressure',
            explorer: {
                axis: 'horizontal',
                keepInBounds: true
            },
            trendlines: {
              0: {
                type: 'polynomial',
                opacity: 0.3,
                visibleInLegend: false,
                degree: 12
                },
              1: {
                type: 'polynomial',
                opacity: 0.3,
                visibleInLegend: false,
                degree: 12
              },
              2: {
                type: 'polynomial',
                opacity: 0.3,
                visibleInLegend: false,
                degree: 12
              }
            },
            height: '100%',
            width: '100%'
        },
        columns: [0,1,2,3]
    },
    hr: {
        type: "ScatterChart",
        options: {
            title: 'Pulse',
            explorer: {
                axis: 'horizontal',
                keepInBounds: true
            },
            trendlines: {
                0: {
                    type: 'polynomial',
                    opacity: 0.3,
                    visibleInLegend: false,
                    degree: 12
                }
            },
            theme: 'maximized',
            height: '100%',
            width: '100%'
        },
        columns: [0, 4]
    },
    bp7: {
        type: "LineChart",
        options: {
            curveType: 'function',
            title: 'Blood pressure',
            explorer: {
                axis: 'horizontal',
                keepInBounds: true
            },
            trendlines: {
              0: {
                type: 'polynomial',
                opacity: 0.3,
                visibleInLegend: false,
                degree: 12
                },
              1: {
                type: 'polynomial',
                opacity: 0.3,
                visibleInLegend: false,
                degree: 12
              },
              2: {
                type: 'polynomial',
                opacity: 0.3,
                visibleInLegend: false,
                degree: 12
              }
            },
            height: '100%',
            width: '100%'
        },
        columns: [0, 1, 2, 3],
        filters: [
            {
                column: 0,
                minValue: moment().subtract(7,'days').toDate()
            }
        ]
    },
    sysdist: {
        type: "ScatterChart",
        options: {
            title: 'Systolic distribution',
            explorer: {
                axis: 'horizontal',
                keepInBounds: true
            },
            trendlines: {
                0: {
                    type: 'polynomial',
                    opacity: 0.3,
                    visibleInLegend: false,
                    degree: 12
                }
            },
            height: '100%',
            width: '100%'
        },
        columns: [5, 1]
    },
    bpdist: {
        type: "ScatterChart",
        options: {
            title: 'Blood pressure distribution',
            explorer: {
                axis: 'horizontal',
                keepInBounds: true
            },
            trendlines: {
                0: {
                    type: 'polynomial',
                    opacity: 0.3,
                    visibleInLegend: false,
                    degree: 12
                },
                1: {
                    type: 'polynomial',
                    opacity: 0.3,
                    visibleInLegend: false,
                    degree: 12
                }
            },
            height: '100%',
            width: '100%'
        },
        columns: [5, 1 , 2]
    },
});

historyModule.controller('HistoryController', ["measurements","$routeParams","googleChartApiPromise","configuration", HistoryController]);

function HistoryController(measurements,$routeParams,googleChartApiPromise,configuration) {
    var self = this;

    googleChartApiPromise.then(function () {
        self.graphType = $routeParams.historyType;

        self.chartObject = {};

        self.chartObject.data = {};
        self.chartObject.type = configuration[self.graphType].type;
        self.chartObject.options = configuration[self.graphType].options;

        var dataTable = new google.visualization.DataTable({
            "cols": [
                {id: "t", label: "Time", type: "datetime"},
                { id: "sys", label: "Systolic", type: "number" },
                { id: "dia", label: "Diastolic", type: "number" },
                { id: "mean", label: "Mean", type: "number" },
                { id: "hr", label: "Pulse", type: "number" },
                { id: "td", label: "Time of Day", type: "timeofday" }
            ],
            "rows": []
        });

        self.chartObject.data = new google.visualization.DataView(dataTable);
        self.chartObject.data.setColumns(configuration[self.graphType].columns);

        function toTimeOfDay(value) {
            var m = moment(value);
            return [m.hours(), m.minutes(), m.seconds()];
        }

        measurements.$loaded().then(function (value) {
            value.forEach(function (element) {
                dataTable.addRow([new Date(element.timestamp), element.sys, element.dia, element.mean, element.hr, toTimeOfDay(element.timestamp)]);
            }, this);

            if (configuration[self.graphType].filters) {
                self.chartObject.data.setRows(dataTable.getFilteredRows(configuration[self.graphType].filters));
            }
        });
    });
}


text:
import { camelCase } from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';

import Tab from '../ui/Tab';

const EnvironmentConfigurationSidebar = ({
  activateTab,
  categories,
  isTabActive
}) => (

      {categories.map(({ title }, index) => {
        const tabName = camelCase(title);
        return (
          <Tab key={index} isActive={isTabActive(tabName)}>
             activateTab(tabName)}>
              {title}

          </Tab>
        );
      })}

);
EnvironmentConfigurationSidebar.propTypes = {
  activateTab: PropTypes.func.isRequired,
  categories: PropTypes.array.isRequired,
  isTabActive: PropTypes.func.isRequired
};
export default EnvironmentConfigurationSidebar;


text:
    Can I change when search results are loaded?

    Can Select2 wait until the user has typed a search term before triggering the request?

$('select').select2({
  ajax: {
    delay: 250 // wait 250 milliseconds before triggering the request
  }
});

  {% include options/not-written.html %}

    Select2 is allowing long search terms, can this be prevented?

$('select').select2({
  maximumInputLength: 20 // only allow terms up to 20 characters long
});

  {% include options/not-written.html %}

    I only want the search box if there are enough results

$('select').select2({
  minimumResultsForSearch: 20 // at least 20 results must be displayed
});

  {% include options/not-written.html %}

    How can I permanently hide the search box?

$('select').select2({
  minimumResultsForSearch: Infinity
});

  {% include options/not-written.html %}


text:
namespace physx { namespace Sn {
	class RepXCollection;

	class RepXUpgrader
	{
	public:
		//If a new collection is created, the source collection is destroyed.
		//Thus you only need to release the new collection.
		//This holds for all of the upgrade functions.
		//So be aware, that the argument to these functions may not be valid
		//after they are called, but the return value always will be valid.
		static RepXCollection& upgradeCollection( RepXCollection& src );
		static RepXCollection& upgrade10CollectionTo3_1Collection( RepXCollection& src );
		static RepXCollection& upgrade3_1CollectionTo3_2Collection( RepXCollection& src );
		static RepXCollection& upgrade3_2CollectionTo3_3Collection( RepXCollection& src );
	};
} }

#endif


text:
"use strict";

var Assert = require("assert");
var Client = require("./../lib/index");
var testAuth = require("./../testAuth.json");

describe("[authorization]", function() {
    var client;
    var token = testAuth["token"];

    beforeEach(function() {
        client = new Client();
        client.authenticate({
            type: "oauth",
            token: token
        });
    });

    it("should successfully execute POST /authorizations (create)",  function(next) {
        client.authorization.create(
            {
                scopes: "Array",
                note: "String",
                note_url: "String"
            },
            function(err, res) {
                Assert.equal(err, null);
                // other assertions go here
                next();
            }
        );
    });

    it("should successfully execute DELETE /authorizations/:id (delete)",  function(next) {
        client.authorization.delete(
            {
                id: "String"
            },
            function(err, res) {
                Assert.equal(err, null);
                // other assertions go here
                next();
            }
        );
    });

    it("should successfully execute GET /authorizations/:id (get)",  function(next) {
        client.authorization.get(
            {
                id: "String"
            },
            function(err, res) {
                Assert.equal(err, null);
                // other assertions go here
                next();
            }
        );
    });

    it("should successfully execute GET /authorizations (getAll)",  function(next) {
        client.authorization.getAll(
            {
                page: "Number",
                per_page: "Number"
            },
            function(err, res) {
                Assert.equal(err, null);
                // other assertions go here
                next();
            }
        );
    });

    it("should successfully execute PATCH /authorizations/:id (update)",  function(next) {
        client.authorization.update(
            {
                id: "String",
                scopes: "Array",
                add_scopes: "Array",
                remove_scopes: "Array",
                note: "String",
                note_url: "String"
            },
            function(err, res) {
                Assert.equal(err, null);
                // other assertions go here
                next();
            }
        );
    });
});


text:
describe('Airport', function() {
  var airport
  var plane;

  beforeEach(function() {
    airport = new Airport();
    plane = jasmine.createSpyObj('plane', ['land', 'takeOff', 'isFlying']);
  });

  describe('', function() {

    it('can land a plane', function() {
      airport.confirmLand(plane);
      expect(airport.planes).toEqual([plane]);
    });

    it('knows how many planes it contains', function() {
      airport.confirmLand(plane);
      expect(airport.planes.length).toEqual(1);
    });

  });

});


text:
import random
import string
import warnings

import click
import qrcode

from launchkey.factories import OrganizationFactory, DirectoryFactory, \
    ServiceFactory
from launchkey.exceptions import AuthorizationInProgress, \
    AuthorizationRequestCanceled, AuthorizationResponseExists, \
    EntityNotFound, RequestTimedOut
from launchkey.entities.service import DenialReason

from helpers import wait_for_response, get_service_client, \
    get_directory_client, print_result, SUCCESS_COLOR, \
    FAILURE_COLOR

@click.group()
@click.argument("entity_type", type=click.STRING)
@click.argument("entity_id", type=click.UUID)
@click.argument("private_key", type=click.File('rb'))
@click.option('--api', '-u', default="https://api.launchkey.com",
              help="API URL to send auth requests. Defaults to "
                   "https://api.launchkey.com",
              type=click.STRING)
@click.option('--additional-key', '-k',
              help="Path to a supplemental key file. If a response is "
                   "returned in which the client cannot decrypt it will "
                   "attempt to use any given additional keys. This option "
                   "can be used multiple times.",
              multiple=True,
              type=click.File('rb'))
@click.pass_context
def main(ctx, entity_type, entity_id, private_key, api, additional_key):
    """
    ENTITY_TYPE: Entity type for the given ID. This can be a Service,
    Directory, or Organization.

    ENTITY_ID: Entity ID in the form of a UUID for the given Service,
    Directory, or Organization.

    PRIVATE_KEY: Path to private key belonging to the given entity ID.
    This key will be used for signing and decrypting requests. In the case that
    you would like to separate signature and encryption keys the --additional-key
    option may be used to add explicit encryption keys.
    IE: /path/to/my.key
    """

    # ensure that ctx.obj exists and is a dict (in case `cli()` is called
    # by means other than the `if` block below
    ctx.ensure_object(dict)

    entity_type = entity_type.lower()
    private_key = private_key.read()
    if entity_type == "organization":
        ctx.obj['factory'] = OrganizationFactory(entity_id, private_key,
                                                 url=api)
    elif entity_type == "directory":
        ctx.obj['factory'] = DirectoryFactory(entity_id, private_key, url=api)
    elif entity_type == "service":
        ctx.obj['factory'] = ServiceFactory(entity_id, private_key, url=api)
    else:
        raise TypeError("Input entity type is not valid. Should be one of: "
                        "Organization, Directory, Service.")

    for k in additional_key:
        key = k.read()
        if key == private_key:
            warnings.warn("An additional key file was given that matches the "
                          "PRIVATE_KEY argument. Please verify this was "
                          "expected.", UserWarning)
        ctx.obj['factory'].add_encryption_private_key(key)

@main.command()
@click.argument("service_id", type=click.STRING)
@click.argument("username", type=click.STRING)
@click.option('--context',
              help="Auth context to pair with the auth and "
                   "display to the user.",
              type=click.STRING)
@click.option('--title',
              help="Auth title to display in the auth request window.",
              type=click.STRING)
@click.option('--ttl',
              help="How long the auth request should remain active for "
                   "until it expires.",
              type=click.INT)
@click.option('--push-title',
              help="Title to appear in the push message. "
                   "This will not work for Organization Services or when "
                   "using 3rd party push.",
              type=click.STRING)
@click.option('--push-body',
              help="Body to appear in the push message. "
                   "This will not work for Organization Services or when "
                   "using 3rd party push.",
              type=click.STRING)
@click.option('--denial-reason-count',
              help="How many custom denial reasons to include. "
                   "If this is not included default denial reasons are used.",
              type=click.IntRange(min=2))
@click.option('--use-advanced',
              is_flag=True,
              default=False,
              help="Whether to retrieve the Advanced Authorization Response "
                   "or the old Authorization Response",
              type=click.BOOL)
@click.pass_context
def authorize(ctx, service_id, username, context, title, ttl, push_title,
              push_body, denial_reason_count, use_advanced):
    """SERVICE_ID USERNAME"""
    client = get_service_client(service_id, ctx.obj['factory'])

    try:

        denial_reasons = None
        if denial_reason_count:
            denial_reasons = []
            for x in range(0, denial_reason_count):
                fraud = \
                    bool(random.randint(0, 1)) if x not in (0, 1) else bool(x)
                denial_reasons.append(
                    DenialReason(
                        denial_id=str(x),
                        reason="{0}-{1}-{2}".format(
                            "f" if fraud else "nf",
                            x,
                            ''.join(
                                random.choice(
                                    string.ascii_uppercase +
                                    string.ascii_lowercase +
                                    string.digits + " "*10
                                ) for _ in range(random.randint(5, 70))
                            )
                        ),
                        fraud=fraud
                    )
                )

        auth = client.authorization_request(
            username,
            context=context,
            title=title,
            ttl=ttl,
            push_title=push_title,
            push_body=push_body,
            denial_reasons=denial_reasons
        )
        print_result(
            "Authorization request successful",
            {
                "Auth Request": auth.auth_request,
                "Push Package": auth.push_package,
                "Device IDs": auth.device_ids
            },
            color=SUCCESS_COLOR
        )
    except AuthorizationInProgress as pre_existing_auth:
        print_result(
            pre_existing_auth.message,
            {
                "Auth Request": pre_existing_auth.authorization_request_id,
                "Expires": pre_existing_auth.expires,
                "Same Service": pre_existing_auth.from_same_service
            },
            color=FAILURE_COLOR
        )
        return

    click.echo("Checking for response from user.")

    try:
        if use_advanced:
            auth_response = wait_for_response(
                client.get_advanced_authorization_response, [auth.auth_request]
            )
        else:
            auth_response = wait_for_response(
                client.get_authorization_response, [auth.auth_request]
            )

        if auth_response.authorized:
            message = "Authorization request approved by user."
            color = SUCCESS_COLOR
        else:
            message = "Authorization request rejected by user."
            color = FAILURE_COLOR

        print_result(
            message,
            {
                "Resp Type":
                    auth_response.type.value if auth_response.type else None,
                "Resp Reason":
                    auth_response.reason.value if auth_response.reason
                    else None,
                "Denial Reason": auth_response.denial_reason,
                "Is Fraud": auth_response.fraud,
                "Auth Request": auth_response.authorization_request_id,
                "Device ID": auth_response.device_id,
                "Svc User Hash": auth_response.service_user_hash,
                "User Push ID": auth_response.user_push_id,
                "Org User Hash": auth_response.organization_user_hash,
                "Auth Methods": auth_response.auth_methods,
                "Auth Policy": auth_response.policy if use_advanced else
                auth_response.auth_policy
            },
            color=color
        )
    except RequestTimedOut:
        click.secho(
            "\nAuthorization request timed out.",
            fg=FAILURE_COLOR
        )
    except AuthorizationRequestCanceled:
        click.secho(
            "\nAuthorization request canceled.",
            fg=FAILURE_COLOR
        )

@main.command()
@click.argument("service_id", type=click.STRING)
@click.argument("auth_id", type=click.STRING)
@click.pass_context
def cancel_auth_request(ctx, service_id, auth_id):
    """SERVICE_ID AUTH_ID"""
    client = get_service_client(service_id, ctx.obj['factory'])
    try:
        client.cancel_authorization_request(auth_id)
        click.secho(
            "Authorization request canceled.", fg=SUCCESS_COLOR
        )
    except AuthorizationRequestCanceled:
        click.secho(
            "Authorization request already canceled.", fg=FAILURE_COLOR
        )
    except AuthorizationResponseExists:
        click.secho(
            "Authorization request has already been responded to.",
            fg=FAILURE_COLOR
        )
    except EntityNotFound:
        click.secho(
            "Authorization request not found.", fg=FAILURE_COLOR
        )

@main.command()
@click.argument("service_id", type=click.STRING)
@click.argument("username", type=click.STRING)
@click.pass_context
def session_start(ctx, service_id, username):
    """SERVICE_ID USERNAME"""
    client = get_service_client(service_id, ctx.obj['factory'])
    client.session_start(username, None)
    click.secho("User session is started.", fg=SUCCESS_COLOR)

@main.command()
@click.argument("service_id", type=click.STRING)
@click.argument("username", type=click.STRING)
@click.pass_context
def session_end(ctx, service_id, username):
    """SERVICE_ID USERNAME"""
    client = get_service_client(service_id, ctx.obj['factory'])
    client.session_end(username)
    click.secho("User session is ended.", fg=SUCCESS_COLOR)

@main.command()
@click.argument("directory_id", type=click.STRING)
@click.argument("user_identifier", type=click.STRING)
@click.option(
    '--ttl',
    help="How long the linking / QR code should remain active "
         "for until they expire.",
    type=click.INT
)
@click.pass_context
def device_link(ctx, directory_id, user_identifier, ttl):
    """DIRECTORY_ID USER_IDENTIFIER"""
    client = get_directory_client(directory_id, ctx.obj['factory'])
    kwargs = {}
    if ttl is not None:
        kwargs['ttl'] = ttl
    link_response = client.link_device(user_identifier, **kwargs)
    print_result(
        "Device link request successful",
        {
            "QR Code URL": link_response.qrcode,
            "Linking code": link_response.code,
            "Device ID": link_response.device_id
        },
        color=SUCCESS_COLOR
    )

@main.command()
@click.argument("directory_id", type=click.STRING)
@click.argument("user_identifier", type=click.STRING)
@click.pass_context
def devices_list(ctx, directory_id, user_identifier):
    """DIRECTORY_ID USER_IDENTIFIER"""
    client = get_directory_client(directory_id, ctx.obj['factory'])
    devices = client.get_linked_devices(user_identifier)
    if devices:
        for device in devices:
            print_result(
                device.name if device.name else "Pending Device",
                {
                    "ID": device.id,
                    "Type": device.type if device.type else "N/A",
                    "Status": device.status.status_code
                }
            )
    else:
        click.secho(
            "No devices found for the given identifier.",
            fg=FAILURE_COLOR
        )

@main.command()
@click.argument("directory_id", type=click.STRING)
@click.argument("user_identifier", type=click.STRING)
@click.argument("device_identifier", type=click.STRING)
@click.pass_context
def device_unlink(ctx, directory_id, user_identifier, device_identifier):
    """DIRECTORY_ID USER_IDENTIFIER DEVICE_IDENTIFIER"""
    client = get_directory_client(directory_id, ctx.obj['factory'])
    client.unlink_device(user_identifier, device_identifier)
    click.secho("Device unlinked", fg=SUCCESS_COLOR)

@main.command()
@click.argument("directory_id", type=click.STRING)
@click.argument("user_identifier", type=click.STRING)
@click.pass_context
def generate_user_totp(ctx, directory_id, user_identifier):
    """DIRECTORY_ID USER_IDENTIFIER"""
    client = get_directory_client(directory_id, ctx.obj['factory'])
    response = client.generate_user_totp(user_identifier)
    print_result(
        "TOTP Generated for User",
        {
            "Algorithm": response.algorithm,
            "Digits": response.digits,
            "Period": response.period,
            "Secret": response.secret
        },
        color=SUCCESS_COLOR
    )

    provisioning_uri = \
        f"otpauth://totp/LaunchKey%20Test%20TOTP:{user_identifier}?" \
            f"digits={response.digits}" \
            f"&secret={response.secret}" \
            f"&algorithm={response.algorithm}" \
            f"&period={response.period}" \
            f"&issuer=LaunchKey+Test+TOTP"

    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_Q,
        box_size=10,
        border=4,
    )
    qr.add_data(provisioning_uri)
    qr.make(fit=True)
    qr.print_ascii()

@main.command()
@click.argument("directory_id", type=click.STRING)
@click.argument("user_identifier", type=click.STRING)
@click.pass_context
def remove_user_totp(ctx, directory_id, user_identifier):
    """DIRECTORY_ID USER_IDENTIFIER"""
    client = get_directory_client(directory_id, ctx.obj['factory'])
    client.remove_user_totp(user_identifier)
    click.secho("TOTP configuration removed from user", fg=SUCCESS_COLOR)

@main.command()
@click.argument("service_id", type=click.STRING)
@click.argument("user_identifier", type=click.STRING)
@click.argument("otp_code", type=click.STRING)
@click.pass_context
def verify_user_totp(ctx, service_id, user_identifier, otp_code):
    """SERVICE_ID USER_IDENTIFIER OTP_CODE"""
    client = get_service_client(service_id, ctx.obj['factory'])
    valid = client.verify_totp(user_identifier, otp_code)
    if valid is True:
        click.secho("Input OTP code was valid", fg=SUCCESS_COLOR)
    else:
        click.secho("Input OTP code was not valid", fg=FAILURE_COLOR)

if __name__ == "__main__":
    main(obj={})


text:
import hashlib
import os
import tempfile

import mock
from oslo.config import cfg
from oslotest import mockpatch

from tempest import auth
from tempest.common import accounts
from tempest import config
from tempest import exceptions
from tempest.services.identity.json import token_client
from tempest.tests import base
from tempest.tests import fake_config
from tempest.tests import fake_identity

class TestAccount(base.TestCase):

    def setUp(self):
        super(TestAccount, self).setUp()
        self.useFixture(fake_config.ConfigFixture())
        self.stubs.Set(config, 'TempestConfigPrivate', fake_config.FakePrivate)
        self.temp_dir = tempfile.mkdtemp()
        cfg.CONF.set_default('lock_path', self.temp_dir)
        self.addCleanup(os.rmdir, self.temp_dir)
        self.test_accounts = [
            {'username': 'test_user1', 'tenant_name': 'test_tenant1',
             'password': 'p'},
            {'username': 'test_user2', 'tenant_name': 'test_tenant2',
             'password': 'p'},
            {'username': 'test_user3', 'tenant_name': 'test_tenant3',
             'password': 'p'},
            {'username': 'test_user4', 'tenant_name': 'test_tenant4',
             'password': 'p'},
            {'username': 'test_user5', 'tenant_name': 'test_tenant5',
             'password': 'p'},
            {'username': 'test_user6', 'tenant_name': 'test_tenant6',
             'password': 'p'},
        ]
        self.useFixture(mockpatch.Patch(
            'tempest.common.accounts.read_accounts_yaml',
            return_value=self.test_accounts))
        cfg.CONF.set_default('test_accounts_file', '', group='auth')
        self.useFixture(mockpatch.Patch('os.path.isfile', return_value=True))

    def _get_hash_list(self, accounts_list):
        hash_list = []
        for account in accounts_list:
            hash = hashlib.md5()
            hash.update(str(account))
            hash_list.append(hash.hexdigest())
        return hash_list

    def test_get_hash(self):
        self.stubs.Set(token_client.TokenClientJSON, 'raw_request',
                       fake_identity._fake_v2_response)
        test_account_class = accounts.Accounts('test_name')
        hash_list = self._get_hash_list(self.test_accounts)
        test_cred_dict = self.test_accounts[3]
        test_creds = auth.get_credentials(fake_identity.FAKE_AUTH_URL,
                                          **test_cred_dict)
        results = test_account_class.get_hash(test_creds)
        self.assertEqual(hash_list[3], results)

    def test_get_hash_dict(self):
        test_account_class = accounts.Accounts('test_name')
        hash_dict = test_account_class.get_hash_dict(self.test_accounts)
        hash_list = self._get_hash_list(self.test_accounts)
        for hash in hash_list:
            self.assertIn(hash, hash_dict.keys())
            self.assertIn(hash_dict[hash], self.test_accounts)

    def test_create_hash_file_previous_file(self):
        # Emulate the lock existing on the filesystem
        self.useFixture(mockpatch.Patch('os.path.isfile', return_value=True))
        with mock.patch('__builtin__.open', mock.mock_open(), create=True):
            test_account_class = accounts.Accounts('test_name')
            res = test_account_class._create_hash_file('12345')
        self.assertFalse(res, "_create_hash_file should return False if the "
                         "pseudo-lock file already exists")

    def test_create_hash_file_no_previous_file(self):
        # Emulate the lock not existing on the filesystem
        self.useFixture(mockpatch.Patch('os.path.isfile', return_value=False))
        with mock.patch('__builtin__.open', mock.mock_open(), create=True):
            test_account_class = accounts.Accounts('test_name')
            res = test_account_class._create_hash_file('12345')
        self.assertTrue(res, "_create_hash_file should return True if the "
                        "pseudo-lock doesn't already exist")

    @mock.patch('tempest.openstack.common.lockutils.lock')
    def test_get_free_hash_no_previous_accounts(self, lock_mock):
        # Emulate no pre-existing lock
        self.useFixture(mockpatch.Patch('os.path.isdir', return_value=False))
        hash_list = self._get_hash_list(self.test_accounts)
        mkdir_mock = self.useFixture(mockpatch.Patch('os.mkdir'))
        self.useFixture(mockpatch.Patch('os.path.isfile', return_value=False))
        test_account_class = accounts.Accounts('test_name')
        with mock.patch('__builtin__.open', mock.mock_open(),
                        create=True) as open_mock:
            test_account_class._get_free_hash(hash_list)
            lock_path = os.path.join(accounts.CONF.lock_path, 'test_accounts',
                                     hash_list[0])
            open_mock.assert_called_once_with(lock_path, 'w')
        mkdir_path = os.path.join(accounts.CONF.lock_path, 'test_accounts')
        mkdir_mock.mock.assert_called_once_with(mkdir_path)

    @mock.patch('tempest.openstack.common.lockutils.lock')
    def test_get_free_hash_no_free_accounts(self, lock_mock):
        hash_list = self._get_hash_list(self.test_accounts)
        # Emulate pre-existing lock dir
        self.useFixture(mockpatch.Patch('os.path.isdir', return_value=True))
        # Emulate all lcoks in list are in use
        self.useFixture(mockpatch.Patch('os.path.isfile', return_value=True))
        test_account_class = accounts.Accounts('test_name')
        self.assertRaises(exceptions.InvalidConfiguration,
                          test_account_class._get_free_hash, hash_list)

    @mock.patch('tempest.openstack.common.lockutils.lock')
    def test_get_free_hash_some_in_use_accounts(self, lock_mock):
        # Emulate no pre-existing lock
        self.useFixture(mockpatch.Patch('os.path.isdir', return_value=True))
        hash_list = self._get_hash_list(self.test_accounts)
        test_account_class = accounts.Accounts('test_name')

        def _fake_is_file(path):
            # Fake isfile() to return that the path exists unless a specific
            # hash is in the path
            if hash_list[3] in path:
                return False
            return True

        self.stubs.Set(os.path, 'isfile', _fake_is_file)
        with mock.patch('__builtin__.open', mock.mock_open(),
                        create=True) as open_mock:
            test_account_class._get_free_hash(hash_list)
            lock_path = os.path.join(accounts.CONF.lock_path, 'test_accounts',
                                     hash_list[3])
            open_mock.assert_called_once_with(lock_path, 'w')

    @mock.patch('tempest.openstack.common.lockutils.lock')
    def test_remove_hash_last_account(self, lock_mock):
        hash_list = self._get_hash_list(self.test_accounts)
        # Pretend the pseudo-lock is there
        self.useFixture(mockpatch.Patch('os.path.isfile', return_value=True))
        # Pretend the lock dir is empty
        self.useFixture(mockpatch.Patch('os.listdir', return_value=[]))
        test_account_class = accounts.Accounts('test_name')
        remove_mock = self.useFixture(mockpatch.Patch('os.remove'))
        rmdir_mock = self.useFixture(mockpatch.Patch('os.rmdir'))
        test_account_class.remove_hash(hash_list[2])
        hash_path = os.path.join(accounts.CONF.lock_path, 'test_accounts',
                                 hash_list[2])
        lock_path = os.path.join(accounts.CONF.lock_path, 'test_accounts')
        remove_mock.mock.assert_called_once_with(hash_path)
        rmdir_mock.mock.assert_called_once_with(lock_path)

    @mock.patch('tempest.openstack.common.lockutils.lock')
    def test_remove_hash_not_last_account(self, lock_mock):
        hash_list = self._get_hash_list(self.test_accounts)
        # Pretend the pseudo-lock is there
        self.useFixture(mockpatch.Patch('os.path.isfile', return_value=True))
        # Pretend the lock dir is empty
        self.useFixture(mockpatch.Patch('os.listdir', return_value=[
            hash_list[1], hash_list[4]]))
        test_account_class = accounts.Accounts('test_name')
        remove_mock = self.useFixture(mockpatch.Patch('os.remove'))
        rmdir_mock = self.useFixture(mockpatch.Patch('os.rmdir'))
        test_account_class.remove_hash(hash_list[2])
        hash_path = os.path.join(accounts.CONF.lock_path, 'test_accounts',
                                 hash_list[2])
        remove_mock.mock.assert_called_once_with(hash_path)
        rmdir_mock.mock.assert_not_called()

    def test_is_multi_user(self):
        test_accounts_class = accounts.Accounts('test_name')
        self.assertTrue(test_accounts_class.is_multi_user())

    def test_is_not_multi_user(self):
        self.test_accounts = [self.test_accounts[0]]
        self.useFixture(mockpatch.Patch(
            'tempest.common.accounts.read_accounts_yaml',
            return_value=self.test_accounts))
        test_accounts_class = accounts.Accounts('test_name')
        self.assertFalse(test_accounts_class.is_multi_user())

class TestNotLockingAccount(base.TestCase):

    def setUp(self):
        super(TestNotLockingAccount, self).setUp()
        self.useFixture(fake_config.ConfigFixture())
        self.stubs.Set(config, 'TempestConfigPrivate', fake_config.FakePrivate)
        self.temp_dir = tempfile.mkdtemp()
        cfg.CONF.set_default('lock_path', self.temp_dir)
        self.addCleanup(os.rmdir, self.temp_dir)
        self.test_accounts = [
            {'username': 'test_user1', 'tenant_name': 'test_tenant1',
             'password': 'p'},
            {'username': 'test_user2', 'tenant_name': 'test_tenant2',
             'password': 'p'},
            {'username': 'test_user3', 'tenant_name': 'test_tenant3',
             'password': 'p'},
        ]
        self.useFixture(mockpatch.Patch(
            'tempest.common.accounts.read_accounts_yaml',
            return_value=self.test_accounts))
        cfg.CONF.set_default('test_accounts_file', '', group='auth')
        self.useFixture(mockpatch.Patch('os.path.isfile', return_value=True))

    def test_get_creds(self):
        test_accounts_class = accounts.NotLockingAccounts('test_name')
        for i in xrange(len(self.test_accounts)):
            creds = test_accounts_class.get_creds(i)
            msg = "Empty credentials returned for ID %s" % str(i)
            self.assertIsNotNone(creds, msg)
        self.assertRaises(exceptions.InvalidConfiguration,
                          test_accounts_class.get_creds,
                          id=len(self.test_accounts))


text:
layout: post
authors: ["Clifton Franklund"]
title: "My Favourite Tool - RStudio"
date: 2017-11-07
time: "00:00:00"
tags: ["Statistics", "R","RStudio", "Shiny"]

---

My favorite tool is [RStudio](https://www.rstudio.com/). This integrated development environment (IDE) is really a force multiplier for data analysis and reporting.

RStudio provides an excellent interface to the R programming language (that much should be obvious). However, it is _much_ more than that. This application affords me easy workflows and shortcuts to interact with most of the other tools that I regularly use. These include:

- [GitHub](https://github.com)/git - for keeping all of my projects under version control and public-facing.
- make - for automating project builds and updates.
- bash shell - for when the GUI just isn't cutting it.
- pandoc - to create beautiful reports as .pdf, .html, .docx, or .epub files.

Like Jupyter notebooks, RStudio fully supports literary programming and its own implementation of the markdown language. With packages like `blogdown` or `bookdown`, RStudio can easily be used to support the construction of static websites as well.

Even better, I can also use RStudio to build presentation slides. I tend to use `revealjs`, but there are several other choices as well. When coupled with [Shiny](https://www.rstudio.com/products/shiny/), I can create free, reproducible, and interactive presentations that are available to anyone with a web browser.

I rely upon many different tools to get my work done, and all of them _can_ be used without the help of RStudio. But, when they work in concert with RStudio, my work gets done in a fraction of the time.

-- Clifton Franklund, Professor of Microbiology, Big Rapids, MI, USA.

-----

 Have you got a favourite tool you would like to tell us about?
 Please use this [form](https://docs.google.com/forms/d/e/1FAIpQLSeiu5NzJsLxYueaQrNn_qKbaa5JR2Sz12CeCRyedKQxwb54Dw/viewform)
 to add a bit of detail and we will do the rest. You can read
 the [background to these posts](https://software-carpentry.org/blog/2017/10/fave-tools.html) here,
 or see what [other tools people have written about](https://software-carpentry.org/blog/2017/11/favorites.html).


text:
package org.onosproject.cluster;

import java.util.Arrays;
import java.util.Collection;
import java.util.Set;

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

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * A data partition.
 *

 * Partition represents a slice of the data space and is made up of a collection
 * of {@link org.onosproject.cluster.ControllerNode nodes}
 * that all maintain copies of this data.
 */
public class Partition {

    private final String name;
    private final Set<NodeId> members;

    private Partition() {
        name = null;
        members = null;
    }

    public Partition(String name, Collection<NodeId> members) {
        this.name = checkNotNull(name);
        this.members = ImmutableSet.copyOf(checkNotNull(members));
    }

    /**
     * Returns the partition name.
     *

     * Each partition is identified by a unique name.
     * @return partition name
     */
    public String getName() {
        return this.name;
    }

    /**
     * Returns the collection of controller node identifiers that make up this partition.
     * @return collection of controller node identifiers
     */
    public Collection<NodeId> getMembers() {
        return this.members;
    }

    @Override
    public int hashCode() {
        return Arrays.deepHashCode(new Object[] {name, members});
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }

        if (other == null || !Partition.class.isInstance(other)) {
            return false;
        }

        Partition that = (Partition) other;

        if (!this.name.equals(that.name) || (this.members == null && that.members != null)
                || (this.members != null && that.members == null) || this.members.size() != that.members.size()) {
            return false;
        }

        return Sets.symmetricDifference(this.members, that.members).isEmpty();
    }
}


text:
/**
 * Created by ShawnZhang on 2017/9/3.
 */

/**
 * 通过资源实例化预制对象
 * @param res   资源字符串
 * @param cb    回调函数返回
 */
cc.createPrefab = function(res, cb) {
    cc.loader.loadRes(res, cc.Prefab, (error, prefab) => {
        let node = null;
        if (error) {
            cc.error(`createPrefab ${error}`);
        } else {
            node = cc.instantiate(prefab);
        }

        if (cb) {
            cb(error, node);
        }
    });
}

/**
 * 通过资源路径(预制)创建节点, 根据 sender 类型并完成节点挂接
 * @param sender
 * @param res
 * @param cb
 */
cc.Component.prototype.createNode = function(sender, res, cb) {
    cc.log(`createNode ${res}`);
    cc.createPrefab(res, (error, node) => {
        if (sender instanceof cc.Node) {
            sender.addChild(node);
        } else if (this.node && this.node instanceof cc.Node) {
            this.node.addChild(node, 0);
        }

        if (cb) {
            cb(node);
        }
    });
};

/**
 * 删除组件上的节点
 */
cc.Component.prototype.destroyNode = function() {
    if (!this.node) {
        return;
    }
    this.node.destroy();
};

/**
 * 节点上是否存在某些组件
 */
cc.Node.prototype.hasComponent = function (types) {
    if (!Array.isArray(types)) {
        types = [types];
    }

    let component = types.find(type => this.getComponent(type));
    return !!component;
};

/**
 * 获取精灵上的纹理文件名
 * @returns {*}
 */
cc.Sprite.prototype.getTextureFilename = function() {
    if (this.spriteFrame) {
        let fileName = this.spriteFrame._textureFilename;
        const index = fileName.indexOf('resources/');
        return fileName.substr(index + 10);
    }
    return '';
};

/**
 * 获取图集中的 spriteFrame, 图集需要预先加载
 * @param atlas
 * @param key
 * @returns {*}
 */
cc.getSpriteFrameByAtlas = function getFrameByAtlas(atlas, key) {
    let path = cc.path.mainFileName(atlas);
    let spriteAtlas = cc.loader.getRes(path, cc.SpriteAtlas);
    if (spriteAtlas) {
        return spriteAtlas.getSpriteFrame(key);
    }
    return null;
};

cc.createNodeComponent = function (componentType) {
    let node = new cc.Node();
    let component = node.addComponent(componentType);
    return component;
};

cc.Component.prototype.loadScene = function (sender, name, cb) {
    cc.director.loadScene(name, cb);
};


text:
'use strict';

//Private State Provider for Admin Accounts

angular.module('medCheckApp')
  .config(function ($stateProvider) {
    $stateProvider
      .state('admin', {
        url: '/admin',
        templateUrl: 'app/admin/admin.html',
        controller: 'AdminCtrl'
      });
  });