text:
package org.ocpsoft.rewrite.servlet.impl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.junit.Test;
import org.ocpsoft.rewrite.servlet.DispatcherType;
import org.ocpsoft.rewrite.servlet.spi.DispatcherTypeProvider;

public class Servlet3DispatcherTypeProviderTest
{

   @Test
   public void testShouldReturnCorrectDispatcherTypeForServlet3()
   {

      // GIVEN a Servlet 3.0 container
      ServletContext servletContext = mock(ServletContext.class);
      when(servletContext.getMajorVersion()).thenReturn(3);

      // AND a forwarded request
      HttpServletRequest request = mock(HttpServletRequest.class);
      when(request.getDispatcherType()).thenReturn(javax.servlet.DispatcherType.FORWARD);

      // WHEN the provider is asked for the DispatcherType
      DispatcherTypeProvider provider = new Servlet3DispatcherTypeProvider();
      DispatcherType dispatcherType = provider.getDispatcherType(request, servletContext);

      // THEN it should return FORWARD
      assertEquals(DispatcherType.FORWARD, dispatcherType);

   }

   @Test
   public void testShouldReturnNullForServlet25()
   {

      // GIVEN a Servlet 2.5 container
      ServletContext servletContext = mock(ServletContext.class);
      when(servletContext.getMajorVersion()).thenReturn(2);
      HttpServletRequest request = mock(HttpServletRequest.class);
      when(request.getDispatcherType()).thenThrow(new IllegalStateException("Call not allowed"));

      // WHEN the provider is asked for the DispatcherType
      DispatcherTypeProvider provider = new Servlet3DispatcherTypeProvider();
      DispatcherType dispatcherType = provider.getDispatcherType(request, servletContext);

      // THEN it should return null
      assertNull(dispatcherType);

   }

}


text:
package com.javarush.task.task18.task1810;

/*
DownloadException
1 Считывать с консоли имена файлов.
2 Если файл меньше 1000 байт, то:
2.1 Закрыть потоки работы с файлами.
2.2 Выбросить исключение DownloadException.
*/

import java.io.*;

public class Solution {
    public static void main(String[] args) throws DownloadException, IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true){
            String in = reader.readLine();
            FileInputStream fileInputStream = new FileInputStream(in);
            if (fileInputStream.available()< 1000){
                fileInputStream.close();
                reader.close();
                throw new DownloadException();
            }
            fileInputStream.close();
            }

        }

    public static class DownloadException extends Exception {

    }
}

redpajama_set_name: RedPajamaGithub


text:
                                new_releases EDITAR INDUCCIÓN

Se editara modulo de inducción

                            <a class="btn-floating btn-large tooltipped" data-tooltip="Regresar" data-position="top" data-delay="50" href="<?= base_url().'induccion/config' ?>">
                                undo

                            <button class="btn-floating btn-large white tooltipped scrollToTop" data-tooltip="Scroll to top" data-position="top" data-delay="50">
                                keyboard_arrow_up
                            </button>

                        <?php
                        $hidden = array('induccion_id' => $edicion->induccion_id);
                        echo form_open(base_url().'induccion/edit/'.$edicion->induccion_id, '', $hidden);
                        ?>

                                    <?php
                                    $msg = $this->session->flashdata('msg');
                                    if ($msg){
                                        echo $msg;
                                    }
                                    ?>

                                                    <input name="titulo" id="titulo" type="text" value="<?= $edicion->titulo ?>">
                                                    Titulo
                                                    <?php echo form_error('titulo'); ?>

                                                    <select name="seccion" id="seccion">
                                                        <option value="" disabled selected></option>
                                                        <option value="manual" <?= $this->general->setSelect('manual', $edicion->seccion); ?>>Manual de Bienvenida</option>
                                                        <option value="video" <?= $this->general->setSelect('video', $edicion->seccion); ?>>Video Corporativo</option>
                                                        <option value="mision" <?= $this->general->setSelect('mision', $edicion->seccion); ?>>Mision</option>
                                                        <option value="vision" <?= $this->general->setSelect('vision', $edicion->seccion); ?>>Vision</option>
                                                        <option value="valores" <?= $this->general->setSelect('valores', $edicion->seccion); ?>>Valores</option>
                                                        <option value="mensaje-director" <?= $this->general->setSelect('mensaje-dir', $edicion->seccion); ?>>Mensaje del Director</option>
                                                    </select>
                                                    Sección
                                                    <?php echo form_error('seccion'); ?>

                                                    <select name="status" id="status">
                                                        <option value="" disabled selected></option>
                                                        <option value="1" <?= $this->general->setSelect(1, $edicion->status); ?>>ACTIVADO</option>
                                                        <option value="0" <?= $this->general->setSelect(0, $edicion->status); ?>>DESACTIVADO</option>
                                                    </select>
                                                    Status
                                                    <?php echo form_error('status'); ?>

                                                    <form class="col s12 m8 l6">

                                                                <textarea id="mytextarea" name="contenido"><?= $edicion->contenido ?></textarea>
                                                                <?php echo form_error('contenido'); ?>

                                                    </form>

                                                <button type="reset" class="btn-flat waves-effect">
                                                    BORRAR
                                                </button>
                                                <button type="submit" class="btn-flat waves-effect">
                                                    GUARDAR
                                                </button>

                        <?= form_close() ?>


text:
mod_security ruleset based on the Comodo Web Application Firewall and OWASP ModSecurity Core Rule Set (CRS) with modifications to prevent false positives.

This ruleset has also been stripped down in order to provide support for CentOS 5,6,7.

## Installation

### CentOS and CloudLinux 5,6,7
```
curl -sL https://raw.githubusercontent.com/sliqua-hosting/modsecurity/master/install/install.sh | bash
service httpd restart
```

## Credits

Copyright 2015 Sliqua Enterprise Hosting, Inc. (https://www.sliqua.com)

Copyright 2015 Comodo Security Solutions (http://waf.comodo.com)

Originally based on the OWASP Foundation's Core Rule Set (CRS)

Distributed under the Apache License, see LICENSE for more information.


text:
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Monkey HTTP Server
 *  ==================
 *  Copyright 2001-2017 Eduardo Silva <eduardo@monkey.io>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#ifndef MK_CHEETAH_H
#define MK_CHEETAH_H

/* Commands */
#define MK_CHEETAH_CLEAR "clear"
#define MK_CHEETAH_CLEAR_SC "\\c"

#define MK_CHEETAH_CONFIG "config"
#define MK_CHEETAH_CONFIG_SC "\\f"

#define MK_CHEETAH_STATUS "status"
#define MK_CHEETAH_STATUS_SC "\\s"

#define MK_CHEETAH_HELP "help"
#define MK_CHEETAH_HELP_SC "\\h"

#define MK_CHEETAH_SHELP "?"
#define MK_CHEETAH_SHELP_SC "\\?"

#define MK_CHEETAH_UPTIME "uptime"
#define MK_CHEETAH_UPTIME_SC "\\u"

#define MK_CHEETAH_PLUGINS "plugins"
#define MK_CHEETAH_PLUGINS_SC "\\g"

#define MK_CHEETAH_VHOSTS "vhosts"
#define MK_CHEETAH_VHOSTS_SC "\\v"

#define MK_CHEETAH_WORKERS "workers"
#define MK_CHEETAH_WORKERS_SC "\\w"

#define MK_CHEETAH_QUIT "quit"
#define MK_CHEETAH_QUIT_SC "\\q"

/* Constants */
#define MK_CHEETAH_PROMPT "%s%scheetah>%s "
#define MK_CHEETAH_PROC_TASK "/proc/%i/task/%i/stat"
#define MK_CHEETAH_ONEDAY  86400
#define MK_CHEETAH_ONEHOUR  3600
#define MK_CHEETAH_ONEMINUTE  60

/* Configurarion: Listen */
#define LISTEN_STDIN_STR "STDIN"
#define LISTEN_SERVER_STR "SERVER"

#define LISTEN_STDIN 0
#define LISTEN_SERVER 1

int listen_mode;

char *cheetah_server;

int cheetah_socket;
FILE *cheetah_input;
FILE *cheetah_output;

/* functions */
void mk_cheetah_welcome_msg();

#endif


text:
package com.timgroup.eventstore.diffing;

import com.google.common.collect.Iterators;
import com.google.common.collect.PeekingIterator;
import com.timgroup.eventstore.api.ResolvedEvent;
import com.timgroup.eventstore.diffing.listeners.DiffListener;

import java.util.stream.Stream;

public final class EventStreamDiffer {

    private final DiffListener listener;

    public EventStreamDiffer(DiffListener listener) {
        this.listener = listener;
    }

    public void diff(Stream<ResolvedEvent> streamA, Stream<ResolvedEvent> streamB) {
        PeekingIterator<DiffEvent> iteratorA = Iterators.peekingIterator(streamA.map(DiffEvent::from).iterator());
        PeekingIterator<DiffEvent> iteratorB = Iterators.peekingIterator(streamB.map(DiffEvent::from).iterator());

        while (iteratorA.hasNext() && iteratorB.hasNext()) {
            DiffEvent diffEventA = iteratorA.peek();
            DiffEvent diffEventB = iteratorB.peek();

            if (diffEventA.equals(diffEventB)) {
                listener.onMatchingEvents(iteratorA.next(), iteratorB.next());
            } else if (diffEventA.isSimilarTo(diffEventB)) {
                listener.onSimilarEvents(iteratorA.next(), iteratorB.next());
            } else if (diffEventA.isEffectiveOnOrBefore(diffEventB)){
                listener.onUnmatchedEventInStreamA(iteratorA.next());
            } else {
                listener.onUnmatchedEventInStreamB(iteratorB.next());
            }
        }
        iteratorA.forEachRemaining(listener::onUnmatchedEventInStreamA);
        iteratorB.forEachRemaining(listener::onUnmatchedEventInStreamB);
    }
}


text:
import hTools2.dialogs.glyphs.slide
reload(hTools2.dialogs.glyphs.slide)

hTools2.dialogs.glyphs.slide.slideGlyphsDialog()


text:
<!html>

<head>

    <script src="didalog.js"> </script>

</head>

Testing didalog

<body>

</body>

<script>

    (function() {
        var LOGGER = DIDALOG || {};
        //try to add llg
        LOGGER.log('warning', 'This is my warning log message');
        //clear previous log
        LOGGER.clear();

        LOGGER.log('warning', 'This is my warning log message');

        LOGGER.log('info', ['This is my info log message', 'My other message in log '] );

        //add grouping
        LOGGER.groupLogStart("Everything");
        LOGGER.log('debug', 'This is my debug log message');

        LOGGER.log('error', 'This is my error log message');
        //end grouping these logs
        LOGGER.groupLogEnd();

        //try to add something that isn/t defined
        LOGGER.log('slj', 'This is my slj log message transformed to info');

        //generate a lot of logs to check download
        for(var i=0; i<25; i++)
            LOGGER.log('error', 'This is my error log message');

        //LOGGER.logToServer(); this is not needed if batching is on

    })();

</script>
</html>


text:
from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from profiles.models import *
from django.db.models import F
from django.template.loader import get_template
from django.shortcuts import render, render_to_response

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from profiles.serializers import StartUpSerializer

from random import randint
from django.views.generic import TemplateView
from chartjs.views.lines import BaseLineChartView

class HomePage(generic.TemplateView):
    template_name = "home.html"

class AboutPage(generic.TemplateView):
    template_name = "about.html"

class StartUpCreate(CreateView):
    model = StartUpIdea
    template_name = "create_startup.html"
    fields = ['creator','name', 'description','category','tags']

class BrowsePage(generic.ListView):
    model = StartUpIdea
    template_name = "main_browse.html"

    def get_queryset(self):
        return StartUpIdea.objects.order_by('-pub_date')

class NameBrowsePage(generic.ListView):
    model = StartUpIdea
    template_name = "main_browse.html"

    def get_queryset(self):
        return StartUpIdea.objects.order_by('name')

class DateBrowsePage(generic.ListView):
    model = StartUpIdea
    template_name = "main_browse.html"

    def get_queryset(self):
        return StartUpIdea.objects.order_by('-pub_date')

class StartUpDetail(generic.DetailView):
    model = StartUpIdea
    template_name = "startup_detail.html"

class UpdateStartup(UpdateView):
    template_name = "create_startup.html"
    model = StartUpIdea
    fields = ['name', 'description','category','tags']
    success_url = "/my_startups"

class DeleteStartup(DeleteView):
    template_name = "delete_startup_confirm.html"
    model = StartUpIdea
    success_url = "/my_startups"

class UserListings(generic.ListView):
    template_name = "user_listings.html"
    model = StartUpIdea

class CategoryListView(generic.ListView):
    template_name = "browse.html"
    def get_queryset(self):
        category_id = self.kwargs['category_id']
        try:
            category = Category.objects.get(pk=category_id)
            return StartUpIdea.objects.filter(category=category)
        except Category.DoesNotExist:
            return StartUpIdea.objects.none()

class TagIndexView(generic.ListView):
    template_name = "browse.html"
    model = StartUpIdea
    context_object_name = 'startups'

    def get_queryset(self):
        return StartUpIdea.objects.filter(tags__slug=self.kwargs.get('slug'))

def like_startup(request, startup_id):
    StartUpIdea.objects.filter(pk=startup_id).update(likes=F('likes') + 1)
    object = StartUpIdea.objects.get(pk=startup_id)
    context = {'object':object}

    return render(request, 'startup_detail.html', context)

def dislike_startup(request, startup_id):
    StartUpIdea.objects.filter(pk=startup_id).update(likes=F('likes') - 1)
    object = StartUpIdea.objects.get(pk=startup_id)
    context = {'object':object}

    return render(request, 'startup_detail.html', context)

class JSONResponse(HttpResponse):
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

@csrf_exempt
def json_list(request, k, date1, date2):

    if request.method == 'GET':
        startups = StartUpIdea.objects.filter(pub_date__range=[date1, date2]).order_by('-likes')[:int(k)]
        serializer = StartUpSerializer(startups, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = StartUpSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)

class LineChartJSONView(BaseLineChartView):
    def get_labels(self):
        """Return 7 labels."""
        cat_list = []
        for e in Category.objects.all():
            cat_list.append(str(e.name))
        #return ['cat1', 'cat2', 'cat3', 'cat4', 'cat5' ]
        return cat_list

    def get_data(self):
        """Return 3 dataset to plot."""
        int_list = []
        counter = 1

        for e in Category.objects.all():
            int_list.append(int(StartUpIdea.objects.filter(category__id=counter).count()))
            counter = counter + 1

        return [int_list]

        '''
        return [[StartUpIdea.objects.filter(category__id=1).count(),
        StartUpIdea.objects.filter(category__id=2).count(),
        StartUpIdea.objects.filter(category__id=3).count(),
        StartUpIdea.objects.filter(category__id=4).count(),
        StartUpIdea.objects.filter(category__id=5).count()]]
        '''

line_chart = TemplateView.as_view(template_name='line_chart.html')
line_chart_json = LineChartJSONView.as_view()

'''
def like_startup(request):
    context = RequestContext(request)
    startup_id = None
    if request.method == 'GET':
        startup_id = request.GET['startup_id']

    likes = 0
    if startup_id:
        startup = StartUpIdea.objects.get(id=int(startup_id))
        if startup:
            likes = startup.likes + 1
            startup.likes = likes
            startup.save()

    return HttpResponse(likes)
'''


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <parent>
        <artifactId>jb5n-base</artifactId>
        <groupId>jb5n</groupId>
        <version>0.0.3-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>jb5n-maven-plugin</artifactId>
    <packaging>maven-plugin</packaging>
    <name>jb5n-maven-plugin</name>

    <dependencies>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-artifact</artifactId>
            <version>2.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-project</artifactId>
            <version>2.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>jb5n</groupId>
            <artifactId>jb5n</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.1.GA</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
Library for Arduino board talking to an ESP8266 Wi-Fi board (e.g., Adafruit HUZZAH or Sparkfun ESP8266 shield) using AT command sets over serial UART port.
This is NOT a wifi library for Arduino running natively on an ESP8266 board.

Much of this library is derived from [*Sparkfun esp8266 library*](https://github.com/sparkfun/SparkFun_ESP8266_AT_Arduino_Library).  However, the change deviates so much that it becomes impossible to merge back.  So instead I created a new library.

In the rest of this file, I'll assume Arduino UNO board and HUZZAH breakout board.

# Hardware connection

Note you need to prepare HUZZAH board to run the original AT command firmware, not the LUA firmware from Adafruit.  See below for instructions on how to do that.

Below is a typical setup:

* Connect esp8266 ground to Arduino ground
* Connect esp8266 V+ to 5V on Arduino board
* Connect esp8266 RX/TX pins to any two digital pins on Arduino except 0,1

![Arduino-ESP8266 wiring](http://junsun.net/local/esp8266-huzzah/arduino-esp8266-connection.png)

# Prepare Adafruit HUZZAH board

## Soldering the board

For Arduino connections, we only need to use the FTDI pins at the end.  And we solder them on the back side of board, which is different from what Adafruit recommends.  See pictures below.
![Soldering pins - front](http://junsun.net/local/esp8266-huzzah/soldering-front.jpg)
![Soldering pins - back](http://junsun.net/local/esp8266-huzzah/soldering-back.jpg)

## Download software

Adafruit HUZZAH board comes with LUA firmware.  This library needs the original AT command firmware from the chip maker.

* dowload flash tool and manul
  * http://bbs.espressif.com/viewtopic.php?f=7&t=641
  * my version is [FLASH_DOWNLOAD_TOOLS_v2.4_150924.rar] (http://bbs.espressif.com/download/file.php?id=856)
* download SDK which has firmware; download the non-OS version
  * http://bbs.espressif.com/viewtopic.php?f=46&t=850
  * my version is ESP8266_NONOS_SDK_V1.5.3_16_04_18

## Flashing ESP8266 AT firmware

* Connect HUZZAH board to PC via [FTDI cable.] (https://www.adafruit.com/product/70)
  * Note the black cable (marked with an arrow) connects to the ground pin on HUZZAH
* start and configure flash tool as shown.
  * Note the serial port number might be different on your computer.  A quick way to find is actually use arduino IDE, "Tools"/"Ports".
![HUZZAH flashing config](http://junsun.net/local/esp8266-huzzah/flashing-config.png)
* Make HUZZAH into firmware downloading mode
  * press and hold GPIO0 pin
  * press and release Reset pin
  * release GPIO0 pin
  * a red LED should be lit after this sequence
* click "Start" button on the flashing tool to update firmware
* verify newly flashed AT firmware
  * reset HUZZAH board
  * start serial terminal program (e.g., termite) or the serial console from Arduino IDE
    * Note the windows built-in hyperterminal does not work
  * use baud rate 115200
  * type "AT" and should get "OK"
  * type "AT" and should get version numbers
  * below are my version numbers:
```
at+GMR
AT version:1.0.0.0(Apr 16 2016 13:02:45)
SDK version:1.5.3(aec24ac9)
compile time:Apr 18 2016 14:20:15
OK
```

## Setup ESP8266 for running
* switch to 9600 baud rate (to reduce software serial buffer overflow)
```
AT+UART_DEF=9600,8,1,0,0
```
* set to station mode (most common, default is SoftAP)
```
AT+CWMODE=1
```
* enable DHCP in station mode
```
AT+CWDHCP_DEF=1,1
```
* set AP and password
```
AT+CWJAP_DEF="tzuming_guest","12345678"
```
* enable auto-connect to AP on startup
```
AT+CWAUTOCONN=1
```
Now your HUZZAH board is ready for running with this library!


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>it.drwolf</groupId>
  <artifactId>push</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
  	<dependency>
  		<groupId>org.apache.httpcomponents</groupId>
  		<artifactId>httpclient</artifactId>
  		<version>4.3.6</version>
  	</dependency>
  	<dependency>
  		<groupId>com.notnoop.apns</groupId>
  		<artifactId>apns</artifactId>
  		<version>1.0.0.Beta6</version>
  	</dependency>
  	<dependency>
  		<groupId>com.fasterxml.jackson.core</groupId>
  		<artifactId>jackson-databind</artifactId>
  		<version>2.1.4</version>
  	</dependency>
  </dependencies>
</project>


text:
def extractViolentfluffballWordpressCom(item):
	'''
	Parser for 'violentfluffball.wordpress.com'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	tagmap = [
		('The Adonis Next Door: 100 Days of Forced Love',       'The Adonis Next Door: 100 Days of Forced Love',                      'translated'),
		('How To Say I Love You',                               'How To Say I Love You',                                              'translated'),
		('HTSILY',                                              'How To Say I Love You',                                              'translated'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta content="text/html; charset=ISO-8859-1"  http-equiv="content-type" />
  <link rel="stylesheet" type="text/css" href="style.css" />
  <title>SOCI - reference</title>

SOCI - The C++ Database Access Library

Client interface reference

commonly used types

class session

class connection_pool

class transaction

function into

function use

class statement

class procedure

class type_conversion

class row

class column_properties

class values

class blob

class rowid

class backend_factory

Simple client interface

The core client interface is a set of classes and free functions declared in
the soci.h header file. All names are dbeclared in the soci
namespace.

There are also additional names declared in the soci::details
namespace, but they are not supposed to be directly used by the users
of the library and are therefore not documented here. When such types
are used in the declarations that are part of the "public" interface,
they are replaced by "IT", which means "internal type". Types related
to the backend interface are named here, but documented on the next page.

commonly used types

The following types are commonly used in the rest of the interface:

// data types, as seen by the user
enum data_type { dt_string, dt_date, dt_double, dt_integer,
                 dt_unsigned_long, dt_long_long };

// the enum type for indicator variables
enum indicator { i_ok, i_null, i_truncated };

// the type used for reporting exceptions
class soci_error : public std::runtime_error { /* ... */ };

The data_type type defines the basic SOCI data types.
User provided data types need to be associated with one of these basic
types.

The indicator type defines the possible states of data.

The soci_error type is used for error reporting.

class session

The session class encapsulates the connection to the
database.

class session
{
public:
    session();
    session(backend_factory const & factory, std::string const & connectString);
    session(std::string const & backendName, std::string const & connectString);
    explicit session(std::string const & connectString);
    explicit session(connection_pool & pool);

    ~session();

    void open(backend_factory const & factory, std::string const & connectString);
    void open(std::string const & backendName, std::string const & connectString);
    void open(std::string const & connectString);
    void close();
    void reconnect();

    void begin();
    void commit();
    void rollback();

    IT once;
    IT prepare;

    template <typename T> IT operator<<(T const & t);

    bool got_data() const;

    std::ostringstream & get_query_stream();

    void set_log_stream(std::ostream * s);
    std::ostream * get_log_stream() const;

    std::string get_last_query() const;

    void uppercase_column_names(bool forceToUpper);

    details::session_backend * get_backend();

    std::string get_backend_name() const;
};

This class contains the following members:

Various constructors. The default one creates the session in the disconnected state.
  The others expect the backend factory object, or the backend name, or the URL-like
  composed connection string. The last constructor creates a session proxy associated
  with the session that is available in the given pool and releases it back to the pool
  when its lifetime ends. Example:

session sql(postgresql, "dbname=mydb");
session sql("postgresql", "dbname=mydb");
session sql("postgresql://dbname=mydb");

  The constructors that take backend name as string load the shared library (if not yet loaded)
  with name computed as libsoci_ABC.so (or libsoci_ABC.dll on Windows)
  where ABC is the given backend name.

open, close and reconnect functions for
  reusing the same session object many times; the reconnect function attempts
  to establish the connection with the same parameters as most recently used with constructor
  or open. The arguments for open are treated in the same way as
  for constructors.

begin, commit and rollback
functions for transaction control.

once member, which is used for performing instant
queries that do not need to be separately prepared. Example:

sql.once << "drop table persons";

prepare member, which is used for statement
preparation - the result of the statement preparation must be provided
to the constructor of the statement class. Example:

int i;
statement st = (sql.prepare <<
                "insert into numbers(value) values(:val)", use(i));

operator<< that is a shortcut forwarder to the
equivalent operator of the once member. Example:

sql << "drop table persons";

got_data returns true if the last executed query had non-empty result.

get_query_stream provides direct access to the stream object that is used
  to accumulate the query text and exists in particular to allow the user to imbue specific locale
  to this stream.

set_log_stream and get_log_stream functions for setting and getting
  the current stream object used for basic query logging. By default, it is NULL, which means no logging.
  The string value that is actually logged into the stream is one-line verbatim copy of the query string provided by the user,
  without including any data from the use elements. The query is logged exactly once, before the preparation step.

get_last_query retrieves the text of the last used query.

uppercase_column_names allows to force all column names to uppercase in dynamic row description;
  this function is particularly useful for portability, since various database servers
  report column names differently (some preserve case, some change it).

get_backend returns the internal
pointer to the concrete backend implementation of the session. This is
provided for advanced users that need access to the functionality that
is not otherwise available.

get_backend_name is a convenience forwarder to the same function
of the backend object.

See Connections and simple queries for more
examples.

class connection_pool

The connection_pool class encapsulates the thread-safe pool of connections
and ensures that only one thread at a time has access to any connection that it manages.

class connection_pool
{
public:
    explicit connection_pool(std::size_t size);
    ~connection_pool();

    session & at(std::size_t pos);

    std::size_t lease();
    bool try_lease(std::size_t & pos, int timeout);
    void give_back(std::size_t pos);
};

The operations of the pool are:

Constructor that takes the intended size of the pool. After construction,
  the pool contains regular session objects in disconnected state.

at function that provides direct access to any given entry
  in the pool. This function is non-synchronized.

lease function waits until some entry is available (which means
  that it is not used) and returns the position of that entry in the pool, marking
  it as locked.

try_lease acts like lease, but allows to set up a
  time-out (relative, in milliseconds) on waiting. Negative time-out value means no time-out.
  Returns true if the entry was obtained, in which case its position
  is written to the pos parametr, and false if no entry
  was available before the time-out.

give_back should be called when the entry on the given position
  is no longer in use and can be passed to other requesting thread.

Note: calls to lease and give_back are automated by the
dedicated constructor of the session class, see above.

class transaction

The class transaction can be used for associating the transaction
with some code scope. It is a RAII wrapper for regular transaction operations that
automatically rolls back in its destructor if the transaction was not explicitly
committed before.

class transaction
{
public:
    explicit transaction(session & sql);

    ~transaction();

    void commit();
    void rollback();

private:
    // ...
};

Note that objects of this class are not notified of other transaction related operations
that might be executed by user code explicitly or hidden inside SQL queries.
It is not recommended to mix different ways of managing transactions.

function into

The function into is used for binding local output data
(in other words, it defines where the results of the query are stored).

template <typename T>
IT into(T & t);

template <typename T, typename T1>
IT into(T & t, T1 p1);

template <typename T>
IT into(T & t, indicator & ind);

template <typename T, typename T1>
IT into(T & t, indicator & ind, T1 p1);

template <typename T>
IT into(T & t, std::vector<indicator> & ind);

Example:

int count;
sql << "select count(*) from person", into(count);

See Binding local data
for more examples.

function use

The function use is used for binding local input data (in
other words, it defines where the parameters of the query come from).

template <typename T>
IT use(T & t);

template <typename T, typename T1>
IT use(T & t, T1 p1);

template <typename T>
IT use(T & t, indicator & ind);

template <typename T, typename T1>
IT use(T & t, indicator & ind, T1 p1);

template <typename T>
IT use(T & t, std::vector<indicator> const & ind);

template <typename T, typename T1>
IT use(T & t, std::vector<indicator> const & ind, T1 p1);

Example:

int val = 7;
sql << "insert into numbers(val) values(:val)", use(val);

See Binding local data
for more examples.

class statement

The statement class encapsulates the prepared statement.

class statement
{
public:
    statement(session & s);
    statement(IT const & prep);
    ~statement();

    statement(statement const & other);
    void operator=(statement const & other);

    void alloc();
    void bind(values & v);
    void exchange(IT const & i);
    void exchange(IT const & u);
    void clean_up();

    void prepare(std::string const & query);
    void define_and_bind();

    bool execute(bool withDataExchange = false);
    bool fetch();

    bool got_data() const;

    void describe();
    void set_row(row * r);
    void exchange_for_rowset(IT const & i);

    details::statement_backend * get_backend();
};

This class contains the following members:

Constructor accepting the session object. This can
be used for later query preparation. Example:

statement stmt(sql);

Constructor accepting the result of using prepare
on the session object, see example provided above for the
    session class.

Copy operations.

alloc function, which allocates necessary internal resources.

bind function, which is used to bind the values
object - this is used in the object-relational mapping and normally
called automatically.

exchange functions for registering the binding of local data -
they expect the result of calling the into or use
functions and are normally invoked automatically.

clean_up function for cleaning up resources, normally
called automatically.

prepare function for preparing the statement for
repeated execution.

define_and_bind function for actually executing the
registered bindings, normally called automatically.

execute function for executing the statement. If its
parameter is false then there is no data exchange with
locally bound variables (this form should be used if later fetch
of multiple rows is foreseen). Returns true if there was at least
one row of data returned.

fetch function for retrieving the next portion of
the result. Returns true if there was new data.

got_data return true if the most recent
execution returned any rows.

describe function for extracting the type
information for the result (note: no data is exchanged). This is normally
called automatically and only when dynamic resultset binding is used.

set_row function for associating the statement
and row objects, normally called automatically.

exchange_for_rowset as a special case for binding rowset
objects.

get_backend function that returns the internal
pointer to
the concrete backend implementation of the statement object. This is
provided
for advanced users that need access to the functionality that is not
otherwise available.

See Statement preparation and
repeated execution for example uses.

Most of the functions from the statement class
interface are called automatically, but can be also used explicitly.
See Interfaces for the description of various way to use
this interface.

class procedure

The procedure class encapsulates the call to the stored
procedure and is aimed for higher portability of the client code.

class procedure
{
public:
    procedure(IT const & prep);

    bool execute(bool withDataExchange = false);
    bool fetch();
    bool got_data() const;
};

The constructor expects the result of using prepare
on the session object.

See Stored procedures for
examples.

class type_conversion

The type_conversion class is a traits class that is
supposed to be provided (specialized) by the user for defining
conversions to and from one of the basic SOCI types.

template <typename T>
struct type_conversion
{
    typedef T base_type;

    static void from_base(base_type const & in, indicator ind, T & out);

    static void to_base(T const & in, base_type & out, indicator & ind);
};

Users are supposed to properly implement the from_base and to_base
functions in their specializations of this template class.

See Extending
SOCI to support custom (user-defined) C++ types.

class row

The row class encapsulates the data and type information
retrieved for the single row when the dynamic rowset binding is used.

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

    void uppercase_column_names(bool forceToUpper);

    std::size_t size() const;

    indicator get_indicator(std::size_t pos) const;
    indicator get_indicator(std::string const & name) const;

    column_properties const & get_properties (std::size_t pos) const;
    column_properties const & get_properties (std::string const & name) const;

    template <typename T>
    T get(std::size_t pos) const;

    template <typename T>
    T get(std::size_t pos, T const & nullValue) const;

    template <typename T>
    T get(std::string const & name) const;

    template <typename T>
    T get(std::string const & name, T const & nullValue) const;

    template <typename T>
    row const & operator>>(T & value) const;

    void skip(std::size_t num = 1) const;

    void reset_get_counter() const
};

This class contains the following members:

Default constructor that allows to declare a row
variable.

uppercase_column_names - see the same function in the session class.

size function that returns the number of columns in
the row.

get_indicator function that returns the indicator value
for the given column (column is specified by position - starting from 0
- or by name).

get_properties function that returns the properties
of the column given by position (starting from 0) or by name.

get functions that return the value of the column
given by position or name. If the column contains null, then these
functions either return the provided "default" nullValue
or throw an exception.

operator>> for convenience stream-like
extraction interface. Subsequent calls to this function are equivalent
to calling get with increasing position parameter,
starting from the beginning.

skip and reset_get_counter allow to change the
order of data extraction for the above operator.

See Dynamic resultset binding for
examples.

class column_properties

The column_properties class provides the type and name
information about the particular column in a rowset.

class column_properties
{
public:
    std::string get_name() const;
    data_type get_data_type() const;
};

This class contains the following members:

get_name function that returns the name of the column.

get_data_type that returns the type of the column.

See Dynamic resultset binding for
examples.

class values

The values class encapsulates the data and type
information and is used for object-relational mapping.

class values
{
public:
    values();

    void uppercase_column_names(bool forceToUpper);

    indicator get_indicator(std::size_t pos) const;
    indicator get_indicator(std::string const & name) const;

    template <typename T>
    T get(std::size_t pos) const;

    template <typename T>
    T get(std::size_t pos, T const & nullValue) const;

    template <typename T>
    T get(std::string const & name) const;

    template <typename T>
    T get(std::string const & name, T const & nullValue) const;

    template <typename T>
    values const & operator>>(T & value) const;

    void skip(std::size_t num = 1) const;
    void reset_get_counter() const;

    template <typename T>
    void set(std::string const & name, T const & value, indicator indic = i_ok);

    template <typename T>
    void set(const T & value, indicator indic = i_ok);

    template <typename T>
    values & operator<<(T const & value);
};

This class contains the same members as the row class (with the same meaning)
plus:

set function for storing values in named columns or in subsequent positions.

operator<< for convenience.

See Object-relational mapping
for examples.

class blob

The blob class encapsulates the "large object"
functionality.

class blob
{
public:
    explicit blob(session & s);
    ~blob();

    std::size_t getLen();
    std::size_t read(std::size_t offset, char * buf, std::size_t toRead);
    std::size_t write(std::size_t offset, char const * buf, std::size_t toWrite);
    std::size_t append(char const * buf, std::size_t toWrite);
    void trim(std::size_t newLen);

    details::blob_backend * get_backend();
};

This class contains the following members:

Constructor associating the blob object with the session object.

get_len function that returns the size of the BLOB
object.

read function that reads the BLOB data into provided
buffer.

write function that writes the BLOB data from
provided buffer.

append function that appends to the existing BLOB
data.

trim function that truncates the existing data to
the new length.

get_backend function that returns the internal
pointer to
the concrete backend implementation of the BLOB object. This is
provided
for advanced users that need access to the functionality that is not
otherwise available.

See Large objects (BLOBs) for more
discussion.

class rowid

The rowid class encapsulates the "row identifier" object.

class rowid
{
public:
    explicit rowid(Session & s);
    ~rowid();

    details::rowid_backend * get_backend();
};

This class contains the following members:

Constructor associating the rowid object with the session
object.

get_backend function that returns the internal
pointer to
the concrete backend implementation of the rowid object.

class backend_factory

The backend_factory class provides the abstract interface
for concrete backend factories.

struct backend_factory
{
    virtual details::session_backend * make_session(
        std::string const & connectString) const = 0;
};

The only member of this class is the make_session function
that is supposed to create concrete backend implementation of the
session object.

Objects of this type are declared by each backend and should be
provided to the constructor of the session class.
In simple programs users do not need to use this class directly, but
the example use is:

backend_factory & factory = postgresql;
std::string connectionParameters = "dbname=mydb";

session sql(factory, parameters);

Simple client interface

The simple client interface is provided with other languages in mind,
to allow easy integration of the SOCI library with script interpreters and those
languages that have the ability to link directly with object files using
the "C" calling convention.

The functionality of this interface is limited and in particular the
dynamic rowset description and type conversions are not supported in this release.
On the other hand, the important feature of this interface is that it does not
require passing pointers to data managed by the user, because all data is handled
at the SOCI side. This should make it easier to integrate SOCI with languages that
have constrained ability to understand the C type system.

Users of this interface need to explicitly #include <soci-simple.h>.

typedef void * session_handle;
session_handle soci_create_session(char const * connectionString);
void soci_destroy_session(session_handle s);

void soci_begin(session_handle s);
void soci_commit(session_handle s);
void soci_rollback(session_handle s);

int soci_session_state(session_handle s);
char const * soci_session_error_message(session_handle s);

The functions above provide the session abstraction with the help of opaque handle.
The soci_session_state function returns 1 if there was no error
during the most recently executed function and 0 otherwise, in which
case the soci_session_error_message can be used to obtain a human-readable
error description.

Note that the only function that cannot report all errors this way is soci_create_session,
which returns NULL if it was not possible to create an internal object
representing the session. However, if the proxy object was created, but the connection
could not be established for whatever reason, the error message can be obtained in
the regular way.

typedef void * statement_handle;
statement_handle soci_create_statement(session_handle s);
void soci_destroy_statement(statement_handle st);

int soci_statement_state(statement_handle s);
char const * soci_statement_error_message(statement_handle s);

The functions above create and destroy the statement object. If the statement cannot
be created by the soci_create_statement function, the error condition is set up in the related session object;
for all other functions the error condition is set in the statement object itself.

int soci_into_string   (statement_handle st);
int soci_into_int      (statement_handle st);
int soci_into_long_long(statement_handle st);
int soci_into_double   (statement_handle st);
int soci_into_date     (statement_handle st);

int soci_into_string_v   (statement_handle st);
int soci_into_int_v      (statement_handle st);
int soci_into_long_long_v(statement_handle st);
int soci_into_double_v   (statement_handle st);
int soci_into_date_v     (statement_handle st);

These functions create new data items for storing query results (into elements).
These elements can be later identified by their position, which is counted from 0. For convenience,
these function return the position of the currently added element. In case of error,
-1 is returned and the error condition is set in the statement object.

The _v versions create a vector into elements, which can be used
to retrieve whole arrays of results.

int soci_get_into_state(statement_handle st, int position);
int soci_get_into_state_v(statement_handle st, int position, int index);

This function returns 1 if the into element at the given position has non-null value and 0 otherwise.
The _v version works with vector elements and expects an array index.

int  soci_into_get_size_v(statement_handle st);
void soci_into_resize_v  (statement_handle st, int new_size);

The functions above allow to get and set the size of vector into element.

Note: the soci_into_resize_v always sets all into vectors in the given statement
to the same size, which guarantees that all vector into elements have equal size.

char const * soci_get_into_string   (statement_handle st, int position);
int          soci_get_into_int      (statement_handle st, int position);
long long    soci_get_into_long_long(statement_handle st, int position);
double       soci_get_into_double   (statement_handle st, int position);
char const * soci_get_into_date     (statement_handle st, int position);

char const * soci_get_into_string_v   (statement_handle st, int position, int index);
int          soci_get_into_int_v      (statement_handle st, int position, int index);
long long    soci_get_into_long_long_v(statement_handle st, int position, int index);
double       soci_get_into_double_v   (statement_handle st, int position, int index);
char const * soci_get_into_date_v     (statement_handle st, int position, int index);

The functions above allow to retrieve the current value of the given into element.

Note: the date function returns the date value in the "YYYY MM DD HH mm ss" string format.

void soci_use_string   (statement_handle st, char const * name);
void soci_use_int      (statement_handle st, char const * name);
void soci_use_long_long(statement_handle st, char const * name);
void soci_use_double   (statement_handle st, char const * name);
void soci_use_date     (statement_handle st, char const * name);

void soci_use_string_v   (statement_handle st, char const * name);
void soci_use_int_v      (statement_handle st, char const * name);
void soci_use_long_long_v(statement_handle st, char const * name);
void soci_use_double_v   (statement_handle st, char const * name);
void soci_use_date_v     (statement_handle st, char const * name);

The functions above allow to create new data elements that will be used to provide
data to the query (use elements). The new elements can be later identified by given name, which
must be unique for the given statement.

void soci_set_use_state(statement_handle st, char const * name, int state);

The soci_set_use_state function allows to set the state of the given use element.
If the state parameter is set to non-zero the use element is considered non-null
(which is also the default state after creating the use element).

int  soci_use_get_size_v(statement_handle st);
void soci_use_resize_v  (statement_handle st, int new_size);

These functions get and set the size of vector use elements (see comments for vector into elements above).

void soci_set_use_string   (statement_handle st, char const * name, char const * val);
void soci_set_use_int      (statement_handle st, char const * name, int val);
void soci_set_use_long_long(statement_handle st, char const * name, long long val);
void soci_set_use_double   (statement_handle st, char const * name, double val);
void soci_set_use_date     (statement_handle st, char const * name, char const * val);

void soci_set_use_state_v    (statement_handle st, char const * name, int index, int state);
void soci_set_use_string_v   (statement_handle st, char const * name, int index, char const * val);
void soci_set_use_int_v      (statement_handle st, char const * name, int index, int val);
void soci_set_use_long_long_v(statement_handle st, char const * name, int index, long long val);
void soci_set_use_double_v   (statement_handle st, char const * name, int index, double val);
void soci_set_use_date_v     (statement_handle st, char const * name, int index, char const * val);

The functions above set the value of the given use element, for both single and vector elements.

Note: the expected format for the data values is "YYYY MM DD HH mm ss".

int          soci_get_use_state    (statement_handle st, char const * name);
char const * soci_get_use_string   (statement_handle st, char const * name);
int          soci_get_use_int      (statement_handle st, char const * name);
long long    soci_get_use_long_long(statement_handle st, char const * name);
double       soci_get_use_double   (statement_handle st, char const * name);
char const * soci_get_use_date     (statement_handle st, char const * name);

These functions allow to inspect the state and value of named use elements.

Note: these functions are provide only for single use elements, not for vectors;
the rationale for this is that modifiable use elements are not supported for bulk operations.

void soci_prepare(statement_handle st, char const * query);
int  soci_execute(statement_handle st, int withDataExchange);
int  soci_fetch(statement_handle st);
int  soci_got_data(statement_handle st);

The functions above provide the core execution functionality for the statement object
and their meaning is equivalent to the respective functions in the core C++ interface
described above.

      Previous (Beyond SOCI)

      Next (Backends reference)

Copyright © 2004-2006 Maciej Sobczak, Stephen Hutton


text:
/* Sample3 */
public class Sample3 {
    public static void main(String[] args) {
        Book book = new Book("Learn to cook sushi", 55);
        System.out.println("Title = " + book.getTitle());
        System.out.println("Price = " + book.getPrice());

        OnlineBook obook = new OnlineBook(
					  "The Java Virtual Machine Specification", 0,
					  "http://java.sun.com/docs/books/vmspec/index.html");

        System.out.println("Title = " + obook.getTitle());
        System.out.println("Price = " + obook.getPrice());
        System.out.println("Website = " + obook.getWebsite());

        // 基本課題12
        OnlineMagazine omagazine = new OnlineMagazine(
					  "The Java Virtual Machine Specification", 0,
					  "http://java.sun.com/docs/books/vmspec/index.html",
					  1995, 12, 3);

        System.out.println(omagazine.getPublicationDate());

    }
}


text:
package org.openfact.models.ubl.common;

import java.math.BigDecimal;

public interface TaxCategoryModel {

    String getID();

    void setID(String value);

    String getName();

    void setName(String value);

    BigDecimal getPercent();

    void setPercent(BigDecimal value);

    MeasureModel getBaseUnitMeasure();

    void setBaseUnitMeasure(MeasureModel value);

    BigDecimal getPerUnitAmount();

    void setPerUnitAmount(BigDecimal value);

    String getTaxExemptionReasonCode();

    void setTaxExemptionReasonCode(String value);

    String getTaxExemptionReason();

    void setTaxExemptionReason(String value);

    String getTierRange();

    void setTierRange(String value);

    BigDecimal getTierRatePercent();

    void setTierRatePercent(BigDecimal value);

    TaxSchemeModel getTaxScheme();

    void setTaxScheme(TaxSchemeModel value);

    String getId();

}


text:
Sign up

                    <form class="form" name="form" ng-submit="register(form)" novalidate>

                            Name

                            <input id="name" type="text" name="name" class="form-control" ng-model="user.name" autofocus required/>

                            A name is required

                            Email

                            <input type="email" name="email" class="form-control" ng-model="user.email" required mongoose-error/>

                            Doesn't look like a valid email.

                            What's your email address?

                            {{ errors.email }}

                            Github User Name
                            <input type="text" name="github" id="github"  class="form-control" ng-model="user.githubLogin" ng-pattern="/^[a-zA-Z0-9-]+$/" required>

                            What's your github username?

                            {{ errors.github }}

                            Password

                            <input type="password" name="password" class="form-control" ng-model="user.password" ng-minlength="3" required mongoose-error/>

                            Password must be at least 3 characters.

                            {{ errors.password }}

                            Re-type Password

                            <input type="password" name="passwordverify" class="form-control" ng-model="user.passwordverify" ng-minlength="3" required match-field="password" />

                               Password must be at least 3 characters.

                            Passwords must match

                            <button class="btn btn-lg btn-success btn-login" ng-class="{'disabled': !form.$valid}" type="submit">
                                Sign up
                            </button>

                    </form>

                        Have an Account?

                            Login


text:
require './config/environment'
require 'active_record'
require 'sqlite3'

namespace :db do

  def create_db config

    # Open a database
    db = SQLite3::Database.new config['database']

    # Create a database
    db.execute <<-SQL
      CREATE TABLE properties (
        id            integer primary key autoincrement,
        email         varchar(30),
        title         varchar(30),
        property      varchar(30),
        address       varchar(30),
        nightly_rate  integer(10),
        max_guests    integer(10),
        phone_number  varchar(30),
        slug          varchar(8),
        completed     integer(1)
      );
    SQL

  end

  desc 'Create the database'
  task :create do
    create_db YAML.load_file('./config/database.yml')
  end

end


text:
package io.milton.httpclient.calsync.parse;

import io.milton.httpclient.annotation.Etag;
import io.milton.httpclient.calsync.parse.annotation.Description;
import io.milton.httpclient.calsync.parse.annotation.EndDate;
import io.milton.httpclient.annotation.Name;
import io.milton.httpclient.calsync.parse.annotation.Location;
import io.milton.httpclient.calsync.parse.annotation.Organizer;
import io.milton.httpclient.calsync.parse.annotation.StartDate;
import io.milton.httpclient.calsync.parse.annotation.Summary;
import io.milton.httpclient.calsync.parse.annotation.Timezone;
import io.milton.httpclient.calsync.parse.annotation.Uid;
import java.util.Date;

/**
 *
 * @author brad
 */
public class MyCalendarEventBean {
    private String name;
    private String uid;
    private String etag;
    private Date startDate;
    private Date endDate;
    private String timezone;
    private String summary;
    private String description;
    private String location;
    private String organizer;

    @Uid
    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    @Etag
    public String getEtag() {
        return etag;
    }

    public void setEtag(String etag) {
        this.etag = etag;
    }

    @Name
    public String getName() {
        return name;
    }

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

    @Description
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @EndDate
    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    @StartDate
    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    @Summary
    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    @Timezone
    public String getTimezone() {
        return timezone;
    }

    public void setTimezone(String timezone) {
        this.timezone = timezone;
    }

    @Location
    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    @Organizer
    public String getOrganizer() {
        return organizer;
    }

    public void setOrganizer(String organizer) {
        this.organizer = organizer;
    }

}


text:
"""Controllers for the Oppia learner view."""

__author__ = 'Sean Lip'

import copy
import logging

from core.controllers import base
from core.controllers import pages
from core.domain import config_domain
from core.domain import dependency_registry
from core.domain import event_services
from core.domain import exp_domain
from core.domain import exp_services
from core.domain import feedback_services
from core.domain import fs_domain
from core.domain import gadget_registry
from core.domain import interaction_registry
from core.domain import param_domain
from core.domain import rating_services
from core.domain import rights_manager
from core.domain import rte_component_registry
from core.domain import rule_domain
from core.domain import skins_services
import feconf
import jinja_utils
import utils

import jinja2

SHARING_OPTIONS = config_domain.ConfigProperty(
    'sharing_options', {
        'type': 'dict',
        'properties': [{
            'name': 'gplus',
            'schema': {
                'type': 'bool',
            }
        }, {
            'name': 'facebook',
            'schema': {
                'type': 'bool',
            }
        }, {
            'name': 'twitter',
            'schema': {
                'type': 'bool',
            }
        }]
    },
    'Sharing options to display in the learner view',
    default_value={
        'gplus': False,
        'facebook': False,
        'twitter': False,
    })

SHARING_OPTIONS_TWITTER_TEXT = config_domain.ConfigProperty(
    'sharing_options_twitter_text', {
        'type': 'unicode',
    },
    'Default text for the Twitter share message',
    default_value=(
        'Check out this interactive lesson from Oppia - a free, open-source '
        'learning platform!'))

def require_playable(handler):
    """Decorator that checks if the user can play the given exploration."""
    def test_can_play(self, exploration_id, **kwargs):
        """Checks if the user for the current session is logged in."""
        if rights_manager.Actor(self.user_id).can_play(exploration_id):
            return handler(self, exploration_id, **kwargs)
        else:
            raise self.PageNotFoundException

    return test_can_play

def _get_updated_param_dict(param_dict, param_changes, exp_param_specs):
    """Updates a param dict using the given list of param_changes.

    Note that the list of parameter changes is ordered. Parameter
    changes later in the list may depend on parameter changes that have
    been set earlier in the same list.
    """
    new_param_dict = copy.deepcopy(param_dict)
    for pc in param_changes:
        try:
            obj_type = exp_param_specs[pc.name].obj_type
        except:
            raise Exception('Parameter %s not found' % pc.name)
        new_param_dict[pc.name] = pc.get_normalized_value(
            obj_type, new_param_dict)
    return new_param_dict

def classify(
        exp_id, exp_param_specs, state, handler_name, answer, params):
    """Normalize the answer and return the first rulespec that it satisfies."""
    interaction_instance = interaction_registry.Registry.get_interaction_by_id(
        state.interaction.id)
    normalized_answer = interaction_instance.normalize_answer(
        answer, handler_name)

    handler = next(
        h for h in state.interaction.handlers if h.name == handler_name)
    fs = fs_domain.AbstractFileSystem(fs_domain.ExplorationFileSystem(exp_id))
    input_type = interaction_instance.get_handler_by_name(
        handler_name).obj_type
    for rule_spec in handler.rule_specs:
        if rule_domain.evaluate_rule(
                rule_spec.definition, exp_param_specs, input_type, params,
                normalized_answer, fs):
            return rule_spec

    raise Exception(
        'No matching rule found for handler %s. Rule specs are %s.' % (
            handler.name,
            [rule_spec.to_dict() for rule_spec in handler.rule_specs]
        )
    )

class ExplorationPage(base.BaseHandler):
    """Page describing a single exploration."""

    PAGE_NAME_FOR_CSRF = 'player'

    def _make_first_letter_uppercase(self, s):
        """Converts the first letter of a string to its uppercase equivalent,
        and returns the result.
        """
        # This guards against empty strings.
        if s:
            return s[0].upper() + s[1:]
        else:
            return s

    @require_playable
    def get(self, exploration_id):
        """Handles GET requests."""
        version = self.request.get('v')
        if not version:
            # The default value for a missing parameter seems to be ''.
            version = None
        else:
            version = int(version)

        try:
            exploration = exp_services.get_exploration_by_id(
                exploration_id, version=version)
        except Exception as e:
            raise self.PageNotFoundException(e)

        version = exploration.version

        if not rights_manager.Actor(self.user_id).can_view(exploration_id):
            raise self.PageNotFoundException

        is_iframed = (self.request.get('iframed') == 'true')

        # TODO(sll): Cache these computations.
        gadget_ids = exploration.get_gadget_ids()
        interaction_ids = exploration.get_interaction_ids()
        dependency_ids = (
            interaction_registry.Registry.get_deduplicated_dependency_ids(
                interaction_ids))
        dependencies_html, additional_angular_modules = (
            dependency_registry.Registry.get_deps_html_and_angular_modules(
                dependency_ids))

        gadget_templates = (
            gadget_registry.Registry.get_gadget_html(gadget_ids))

        interaction_templates = (
            rte_component_registry.Registry.get_html_for_all_components() +
            interaction_registry.Registry.get_interaction_html(
                interaction_ids))

        self.values.update({
            'GADGET_SPECS': gadget_registry.Registry.get_all_specs(),
            'INTERACTION_SPECS': interaction_registry.Registry.get_all_specs(),
            'SHARING_OPTIONS': SHARING_OPTIONS.value,
            'SHARING_OPTIONS_TWITTER_TEXT': SHARING_OPTIONS_TWITTER_TEXT.value,
            'additional_angular_modules': additional_angular_modules,
            'can_edit': (
                bool(self.username) and
                self.username not in config_domain.BANNED_USERNAMES.value and
                rights_manager.Actor(self.user_id).can_edit(exploration_id)
            ),
            'dependencies_html': jinja2.utils.Markup(
                dependencies_html),
            'exploration_title': exploration.title,
            'exploration_version': version,
            'gadget_templates': jinja2.utils.Markup(gadget_templates),
            'iframed': is_iframed,
            'interaction_templates': jinja2.utils.Markup(
                interaction_templates),
            'is_private': rights_manager.is_exploration_private(
                exploration_id),
            # Note that this overwrites the value in base.py.
            'meta_name': exploration.title,
            # Note that this overwrites the value in base.py.
            'meta_description': self._make_first_letter_uppercase(
                exploration.objective),
            'nav_mode': feconf.NAV_MODE_EXPLORE,
            'skin_templates': jinja2.utils.Markup(
                skins_services.Registry.get_skin_templates(
                    [exploration.default_skin])),
            'skin_js_url': skins_services.Registry.get_skin_js_url(
                exploration.default_skin),
            'skin_tag': jinja2.utils.Markup(
                skins_services.Registry.get_skin_tag(exploration.default_skin)
            ),
        })

        if is_iframed:
            self.render_template(
                'player/exploration_player.html', iframe_restriction=None)
        else:
            self.render_template('player/exploration_player.html')

class ExplorationHandler(base.BaseHandler):
    """Provides the initial data for a single exploration."""

    def get(self, exploration_id):
        """Populates the data on the individual exploration page."""
        version = self.request.get('v')
        version = int(version) if version else None

        try:
            exploration = exp_services.get_exploration_by_id(
                exploration_id, version=version)
        except Exception as e:
            raise self.PageNotFoundException(e)

        intro_card_color = (
            feconf.CATEGORIES_TO_COLORS[exploration.category] if
            exploration.category in feconf.CATEGORIES_TO_COLORS else
            feconf.DEFAULT_COLOR)

        self.values.update({
            'can_edit': (
                self.user_id and
                rights_manager.Actor(self.user_id).can_edit(exploration_id)),
            'exploration': exploration.to_player_dict(),
            'intro_card_image_url': (
                '/images/gallery/exploration_background_%s_large.png' %
                intro_card_color),
            'is_logged_in': bool(self.user_id),
            'session_id': utils.generate_random_string(24),
            'version': exploration.version,
        })
        self.render_json(self.values)

class AnswerSubmittedEventHandler(base.BaseHandler):
    """Tracks a learner submitting an answer."""

    REQUIRE_PAYLOAD_CSRF_CHECK = False

    @require_playable
    def post(self, exploration_id):
        old_state_name = self.payload.get('old_state_name')
        # The reader's answer.
        answer = self.payload.get('answer')
        # The answer handler (submit, click, etc.)
        handler_name = self.payload.get('handler')
        # Parameters associated with the learner.
        old_params = self.payload.get('params', {})
        old_params['answer'] = answer
        # The version of the exploration.
        version = self.payload.get('version')
        rule_spec_dict = self.payload.get('rule_spec')

        rule_spec = exp_domain.RuleSpec.from_dict_and_obj_type(
            rule_spec_dict, rule_spec_dict['obj_type'])

        exploration = exp_services.get_exploration_by_id(
            exploration_id, version=version)
        exp_param_specs = exploration.param_specs
        old_interaction = exploration.states[old_state_name].interaction

        old_interaction_instance = (
            interaction_registry.Registry.get_interaction_by_id(
                old_interaction.id))
        normalized_answer = old_interaction_instance.normalize_answer(
            answer, handler_name)
        # TODO(sll): Should this also depend on `params`?
        event_services.AnswerSubmissionEventHandler.record(
            exploration_id, version, old_state_name, handler_name, rule_spec,
            old_interaction_instance.get_stats_log_html(
                old_interaction.customization_args, normalized_answer))

class StateHitEventHandler(base.BaseHandler):
    """Tracks a learner hitting a new state."""

    REQUIRE_PAYLOAD_CSRF_CHECK = False

    @require_playable
    def post(self, exploration_id):
        """Handles POST requests."""
        new_state_name = self.payload.get('new_state_name')
        exploration_version = self.payload.get('exploration_version')
        session_id = self.payload.get('session_id')
        client_time_spent_in_secs = self.payload.get(
            'client_time_spent_in_secs')
        old_params = self.payload.get('old_params')

        # Record the state hit, if it is not the END state.
        if new_state_name is not None:
            event_services.StateHitEventHandler.record(
                exploration_id, exploration_version, new_state_name,
                session_id, old_params, feconf.PLAY_TYPE_NORMAL)
        else:
            logging.error('Unexpected StateHit event for the END state.')

class ClassifyHandler(base.BaseHandler):
    """Stateless handler that performs a classify() operation server-side and
    returns the corresponding rule_spec (as a dict).
    """

    REQUIRE_PAYLOAD_CSRF_CHECK = False

    @require_playable
    def post(self, exploration_id):
        """Handles POST requests."""
        exp_param_specs_dict = self.payload.get('exp_param_specs', {})
        exp_param_specs = {
            ps_name: param_domain.ParamSpec.from_dict(ps_val)
            for (ps_name, ps_val) in exp_param_specs_dict.iteritems()
        }
        # A domain object representing the old state.
        old_state = exp_domain.State.from_dict(self.payload.get('old_state'))
        # The name of the rule handler triggered.
        handler_name = self.payload.get('handler')
        # The learner's raw answer.
        answer = self.payload.get('answer')
        # The learner's parameter values.
        params = self.payload.get('params')
        params['answer'] = answer

        rule_spec = classify(
            exploration_id, exp_param_specs, old_state, handler_name,
            answer, params)

        self.render_json(rule_spec.to_dict_with_obj_type())

class ReaderFeedbackHandler(base.BaseHandler):
    """Submits feedback from the reader."""

    REQUIRE_PAYLOAD_CSRF_CHECK = False

    @require_playable
    def post(self, exploration_id):
        """Handles POST requests."""
        state_name = self.payload.get('state_name')
        subject = self.payload.get('subject', 'Feedback from a learner')
        feedback = self.payload.get('feedback')
        include_author = self.payload.get('include_author')

        feedback_services.create_thread(
            exploration_id,
            state_name,
            self.user_id if include_author else None,
            subject,
            feedback)
        self.render_json(self.values)

class ExplorationStartEventHandler(base.BaseHandler):
    """Tracks a learner starting an exploration."""

    REQUIRE_PAYLOAD_CSRF_CHECK = False

    @require_playable
    def post(self, exploration_id):
        """Handles POST requests."""
        event_services.StartExplorationEventHandler.record(
            exploration_id, self.payload.get('version'),
            self.payload.get('state_name'),
            self.payload.get('session_id'),
            self.payload.get('params'),
            feconf.PLAY_TYPE_NORMAL)

class ExplorationCompleteEventHandler(base.BaseHandler):
    """Tracks a learner completing an exploration.

    The state name recorded should be a state with a terminal interaction.
    """

    REQUIRE_PAYLOAD_CSRF_CHECK = False

    @require_playable
    def post(self, exploration_id):
        """Handles POST requests."""
        event_services.CompleteExplorationEventHandler.record(
            exploration_id,
            self.payload.get('version'),
            self.payload.get('state_name'),
            self.payload.get('session_id'),
            self.payload.get('client_time_spent_in_secs'),
            self.payload.get('params'),
            feconf.PLAY_TYPE_NORMAL)

class ExplorationMaybeLeaveHandler(base.BaseHandler):
    """Tracks a learner leaving an exploration without completing it.

    The state name recorded should be a state with a non-terminal interaction.
    """

    REQUIRE_PAYLOAD_CSRF_CHECK = False

    @require_playable
    def post(self, exploration_id):
        """Handles POST requests."""
        event_services.MaybeLeaveExplorationEventHandler.record(
            exploration_id,
            self.payload.get('version'),
            self.payload.get('state_name'),
            self.payload.get('session_id'),
            self.payload.get('client_time_spent_in_secs'),
            self.payload.get('params'),
            feconf.PLAY_TYPE_NORMAL)

# TODO(sll): This is a placeholder function. It should be deleted and the
# backend tests should submit directly to the handlers (to maintain parity with
# production and to avoid code skew).
def submit_answer_in_tests(
        exploration_id, state_name, answer, params, handler_name, version):
    """This function should only be used by tests."""
    params['answer'] = answer

    exploration = exp_services.get_exploration_by_id(
        exploration_id, version=version)
    exp_param_specs = exploration.param_specs
    old_state = exploration.states[state_name]

    rule_spec = classify(
        exploration_id, exp_param_specs, old_state, handler_name,
        answer, params)

    old_interaction_instance = (
        interaction_registry.Registry.get_interaction_by_id(
            old_state.interaction.id))
    normalized_answer = old_interaction_instance.normalize_answer(
        answer, handler_name)
    # TODO(sll): Should this also depend on `params`?
    event_services.AnswerSubmissionEventHandler.record(
        exploration_id, version, state_name, handler_name, rule_spec,
        old_interaction_instance.get_stats_log_html(
            old_state.interaction.customization_args, normalized_answer))

    # This is necessary due to legacy reasons with the old 'END' pseudostate
    # TODO(bhenning): remove the need for this in this function (should be
    # basing terminal logic on whether it is in a terminal state, not
    # specifically in the 'END' state)
    _OLD_END_DEST = 'END'
    new_state = (
        None if rule_spec.dest == _OLD_END_DEST
        else exploration.states[rule_spec.dest])
    finished = (rule_spec.dest == _OLD_END_DEST)
    new_params = _get_updated_param_dict(
        params, {} if finished else new_state.param_changes,
        exp_param_specs)

    return {
        'feedback_html': jinja_utils.parse_string(
            rule_spec.get_feedback_string(), params),
        'finished': finished,
        'params': new_params,
        'question_html': (
            new_state.content[0].to_html(new_params)
            if not finished else ''),
        'state_name': rule_spec.dest if not finished else None,
    }

class RatingHandler(base.BaseHandler):
    """Records the rating of an exploration submitted by a user.

    Note that this represents ratings submitted on completion of the
    exploration.
    """

    PAGE_NAME_FOR_CSRF = 'player'

    @require_playable
    def get(self, exploration_id):
        """Handles GET requests."""
        self.values.update({
            'overall_ratings':
                rating_services.get_overall_ratings(exploration_id),
            'user_rating': rating_services.get_user_specific_rating(
                self.user_id, exploration_id) if self.user_id else None
        })
        self.render_json(self.values)

    @base.require_user
    def put(self, exploration_id):
        """Handles PUT requests for submitting ratings at the end of an
        exploration.
        """
        user_rating = self.payload.get('user_rating')
        rating_services.assign_rating(
            self.user_id, exploration_id, user_rating)
        self.render_json({})


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

class RubyHaze::IdGenerator

  include RubyHaze::Mixins::DOProxy

  java_import 'com.hazelcast.core.IdGenerator'

  def initialize(name)
    @name = name.to_s
    @proxy_object = Hazelcast.get_id_generator @name
  end

end


text:
import { TestBed, inject } from '@angular/core/testing';

import { DataService } from './data.service';

describe('DataService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [DataService]
    });
  });

  it('should ...', inject([DataService], (service: DataService) => {
    expect(service).toBeTruthy();
  }));
});


text:
using System;
using Nest;

namespace Tests.Mapping.Types.Core.String
{
	public class StringTest
	{
		[String(
			Analyzer = "myanalyzer",
			Boost = 1.2,
			DocValues = true,
			IgnoreAbove = 50,
			IncludeInAll = false,
			Index = FieldIndexOption.NotAnalyzed,
			IndexOptions = IndexOptions.Offsets,
			NullValue = "na",
			PositionOffsetGap = 5,
			SearchAnalyzer = "mysearchanalyzer",
			Similarity = SimilarityOption.BM25,
			Store = true,
			TermVector = TermVectorOption.WithPositionsOffsets)]
		public string Full { get; set; }

		[String]
		public string Minimal { get; set; }

        public string Inferred { get; set; }

        public char Char { get; set; }

        public Guid Guid { get; set; }
	}

	public class StringMappingTests : TypeMappingTestBase<StringTest>
	{
		protected override object ExpectJson => new
		{
			properties = new
			{
				full = new
				{
					type = "string",
					analyzer = "myanalyzer",
					boost = 1.2,
					doc_values = true,
					ignore_above = 50,
					include_in_all = false,
					index = "not_analyzed",
					index_options = "offsets",
					null_value = "na",
					position_offset_gap = 5,
					search_analyzer = "mysearchanalyzer",
					similarity = "BM25",
					store = true,
					term_vector = "with_positions_offsets"
				},
				minimal = new
				{
					type = "string"
				},
                inferred = new
				{
					type = "string"
				},
                @char = new
				{
					type = "string"
				},
                guid = new
				{
					type = "string"
				}
			}
		};

		protected override Func<PropertiesDescriptor<StringTest>, IPromise<IProperties>> FluentProperties => p => p
			.String(s => s
				.Name(o => o.Full)
				.Analyzer("myanalyzer")
				.Boost(1.2)
				.DocValues()
				.IgnoreAbove(50)
				.IncludeInAll(false)
				.Index(FieldIndexOption.NotAnalyzed)
				.IndexOptions(IndexOptions.Offsets)
				.NullValue("na")
				.PositionOffsetGap(5)
				.SearchAnalyzer("mysearchanalyzer")
				.Similarity(SimilarityOption.BM25)
				.Store(true)
				.TermVector(TermVectorOption.WithPositionsOffsets)
			)
			.String(s => s
				.Name(o => o.Minimal)
			)
            .String(s => s
				.Name(o => o.Inferred)
			)
            .String(s => s
				.Name(o => o.Char)
			)
            .String(s => s
				.Name(o => o.Guid)
			);

		protected override object ExpectJsonFluentOnly => new
		{
			properties = new
			{
				full = new
				{
					type = "string",
					norms = new
					{
						enabled = true,
						loading = "lazy"
					}
				}
			}
		};
		protected override Func<PropertiesDescriptor<StringTest>, IPromise<IProperties>> FluentOnlyProperties => p => p
			.String(s => s
				.Name(o => o.Full)
				.Norms(n => n
					.Enabled()
					.Loading(NormsLoading.Lazy)
				)
			);
	}
}


text:
@class UICollectionViewLayout;
@class UICollectionViewController;

NS_CLASS_AVAILABLE_IOS(6_0) @interface UICollectionViewController : UIViewController <UICollectionViewDelegate, UICollectionViewDataSource>

- (instancetype)initWithCollectionViewLayout:(UICollectionViewLayout *)layout;

@property (nonatomic, retain) UICollectionView *collectionView;

// defaults to YES, and if YES, any selection is cleared in viewWillAppear:
// This property has not effect if the useLayoutToLayoutNavigationTransitions property is set to YES
@property (nonatomic) BOOL clearsSelectionOnViewWillAppear;

// Set to YES before pushing a a UICollectionViewController onto a
// UINavigationController. The top view controller of the navigation controller
// must be a UICollectionViewController that was pushed with this property set
// to NO. This property should NOT be changed on a UICollectionViewController that
// has already been pushed onto a UINavigationController.
@property (nonatomic,assign)   BOOL useLayoutToLayoutNavigationTransitions NS_AVAILABLE_IOS(7_0);

// The layout object is needed when defining interactive layout to layout transitions.
@property (nonatomic,readonly) UICollectionViewLayout *collectionViewLayout NS_AVAILABLE_IOS(7_0);

@end


text:
spockbot.mcdata package
=======================

Submodules
----------

.. toctree::

   spockbot.mcdata.biomes
   spockbot.mcdata.blocks
   spockbot.mcdata.constants
   spockbot.mcdata.items
   spockbot.mcdata.materials
   spockbot.mcdata.recipes
   spockbot.mcdata.utils
   spockbot.mcdata.windows

Module contents
---------------

.. automodule:: spockbot.mcdata
    :members:
    :undoc-members:
    :show-inheritance:


text:
#include "source/server/ssl_context_manager.h"

#include <cstddef>

#include "envoy/common/exception.h"
#include "envoy/registry/registry.h"

namespace Envoy {
namespace Server {

/**
 * A stub that provides a SSL context manager capable of reporting on
 * certificates' data in case there's no TLS implementation built
 * into Envoy.
 */
class SslContextManagerNoTlsStub final : public Envoy::Ssl::ContextManager {
  Ssl::ClientContextSharedPtr
  createSslClientContext(Stats::Scope& /* scope */,
                         const Envoy::Ssl::ClientContextConfig& /* config */) override {
    throwException();
  }

  Ssl::ServerContextSharedPtr
  createSslServerContext(Stats::Scope& /* scope */,
                         const Envoy::Ssl::ServerContextConfig& /* config */,
                         const std::vector<std::string>& /* server_names */) override {
    throwException();
  }

  absl::optional<uint32_t> daysUntilFirstCertExpires() const override {
    return absl::make_optional(std::numeric_limits<uint32_t>::max());
  }
  absl::optional<uint64_t> secondsUntilFirstOcspResponseExpires() const override {
    return absl::nullopt;
  }

  void iterateContexts(std::function<void(const Envoy::Ssl::Context&)> /* callback */) override{};

  Ssl::PrivateKeyMethodManager& privateKeyMethodManager() override { throwException(); }

  void removeContext(const Envoy::Ssl::ContextSharedPtr& old_context) override {
    if (old_context) {
      throw EnvoyException("SSL is not supported in this configuration");
    }
  }

private:
  [[noreturn]] void throwException() {
    throw EnvoyException("SSL is not supported in this configuration");
  }
};

Ssl::ContextManagerPtr createContextManager(const std::string& factory_name,
                                            TimeSource& time_source) {
  Ssl::ContextManagerFactory* factory =
      Registry::FactoryRegistry<Ssl::ContextManagerFactory>::getFactory(factory_name);
  if (factory != nullptr) {
    return factory->createContextManager(time_source);
  }

  return std::make_unique<SslContextManagerNoTlsStub>();
}

} // namespace Server
} // namespace Envoy


text:
<!DOCTYPE html>

   <meta charset="utf-8">
   <link rel="stylesheet" type="text/css" href="../stylesheets/default.css">
   <link rel="stylesheet" type="text/css" href="../stylesheets/blog.css">
   <title>kylefantastic Blog</title>

Blog

About Me

Projects

Contact

The kylefantastic Blog

        Welcome weary web wanderer to the official blog of Kyle Smith,

      web developer extraordinaire.  If this is your first time visiting,

      perhaps you would like to check out the About Me section to better

      understand what I'm all about.  Otherwise let's get to the blog.

        To the right you will find the navigation to my comprehensive

      blog posts, accrued during my tenure as a Dev BootCamp student.

      It has been an arduous and edifying journey of ups, downs, and

      hard-fought victories.  You can literally witness the progress

      of the last five months before your eyes (at a much faster pace).

      **What are the differences between relative, absolute, fixed, and static positioning?**

  I spent a very long time trying to figure this out this week and I feel like I've only scratched the surface.  There are a lot of nuances between these four different styles of positioning and it's important to understand that they don't just behave in a predetermined way, they behave in a predetermined way in relation to each other.

  When I first set about trying to position elements on my page I expected that I could give them directions and they would appear where I expected them to.  WRONG!  Not even close!  It was like trying to get cats to do what I want.  Before understanding how these potitions operate let's start with some basic definitions.

  **Static**

  Static position is the default poisition of an element in CSS meaning that it will fit into the normal flow of where it occurs in the code of a CSS document.  In other words if you created three different static elements, they would line up in a vertical row in the order they were created.  They can also be manipulated with displaying them as blocks, inline-blocks or inline, but that's a post for another day.  Static positioning will not be affected by commands such as left, right, top or bottom which try to force it into a position.  The divs in the following picture were postioned using static positioning.

  **Fixed**

  Fixed positioning stays fixed in its position on the webpage meaning wherever you scroll, it will stay in the same spot on your screen.  To place it where you want it, you can use the left, right, top or bottom commands.  An exxample of this would be a header or footer that always stays in one place on your screen as you move around the webpage.  It would be like that spot on your glasses that stays in the same spot in your vision no matter where you are looking.  In the example below the divs are positioned fixed to each of the four corners of the web page by setting their position to fixed and their attributes for top, bottom, left or right to 0 to correspond to each corner.

  **Absolute*

  Absolute positioning is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).  So if an ancestor of an absolute div already exists, the absolute element will take its positioning cues(top, left, bottom, right) in relationship to its ancestor.  In the example below the 2nd 3rd and 4th divs are positioned absolute to the first and all inherit from it.  Therefore they will all be positioned with div 1 as their starting point.  Div 2 has a left property of 50px and so is scooted 50 pixels from the left of the first div.  Div 3 has a top property of 240px and so is scooted down 240px from the top of div 1.  And div 4 has a left property of 200 px, and is scooted 200 pixels from the left.

  **Relative**

  Relative positioning takes the normal static positioning and positions it relative to the default.  So using left, right, top, bottom will make it relative to where it normally would have been without them.  In the picture below all the divs are relative and inherit from one another.  In other words they are relative to the previous div.  They are all scooted a little to the right and down from the previous div because of their left and top distances.

Post 1

Post 2

Post 3

Post 4

Post 5

Post 6

Post 7

Facebook

LinkedIn

GitHub

Quora

Twitter


text:
class System::SensorMode < Yeti::ActiveRecord
  self.table_name = 'sys.sensor_modes'

  # mode_id constants from this table
  IP_IP       = 1  # IP-IP encapsulation
  IP_ETHERNET = 2  # IP-Ethernet encapsulation

end


text:
#pragma once

#include "Base/BaseTypes.h"
#include "Base/FastName.h"
#include "FileSystem/FileSystem.h"
#include <iosfwd>

namespace DAVA
{
/**
    Structure that represent trace data in format of Chromium Trace Viewer.
    Also it allows to dump set of events to JSON-format, that can be opened by Trace Viewer.
*/
struct TraceEvent
{
    //! Valid values of event type
    enum EventPhase
    {
        PHASE_BEGIN = 0, ///< Begin of duration event. Must come before the corresponding end event. It does not use `duration` field
        PHASE_END, ///< End of duration event. It does not use `duration` field
        PHASE_INSTANCE, ///< The instance event-type. Correspond to something that happens buy has no duration. It does not use `duration` field
        PHASE_DURATION, ///< Complete event. Logically combines a pair of `Begin` and `End` events. Preferably to use this event type instead Begin/End because it reduce the size of the trace.

        PHASE_COUNT ///< Count of implemented event types.
    };

    FastName name; ///< The name of the event, as displayed in Trace Viewer.
    uint64 timestamp; ///< The tracing timestamp of the event.
    uint64 duration; ///< The tracing duration if the event.
    uint64 threadID; ///< The thread ID for the thread that generate this event.
    uint32 processID; ///< The process ID for the process that generate this event.
    EventPhase phase; ///< The event type. The valid values are listed in enum description.
    Vector<std::pair<FastName, uint32>> args; ///< Any arguments provided for the event. Used as `meta-info`. The arguments are displayed in Trace Viewer.

    /**
        Dump `trace` from any type container with value type `TraceEvent` to file with `filePath` in JSON-format
    */
    template <class Container>
    static void DumpJSON(const Container& trace, const FilePath& filePath);

    /**
        Dump `trace` from any type container with value type `TraceEvent` to `stream` in JSON-format
    */
    template <class Container>
    static void DumpJSON(const Container& trace, std::ostream& stream);
};

template <class Container>
void TraceEvent::DumpJSON(const Container& trace, const FilePath& filePath)
{
    FileSystem* fs = FileSystem::Instance();
    fs->CreateDirectory(filePath.GetDirectory(), true);
    fs->DeleteFile(filePath);
    ScopedPtr<File> json(File::Create(filePath, File::CREATE | File::WRITE));
    if (json)
    {
        std::stringstream stream;
        DumpJSON<Container>(trace, stream);
        json->WriteNonTerminatedString(stream.str());
    }
}

template <class Container>
void TraceEvent::DumpJSON(const Container& trace, std::ostream& stream)
{
    static_assert(std::is_same<typename Container::value_type, TraceEvent>::value, "Container should contain TraceEvent class");

    static const char* const PHASE_STR[PHASE_COUNT] = {
        "B", "E", "I", "X"
    };

    stream << "{ \"traceEvents\": [\n";

    auto begin = trace.begin(), end = trace.end();
    for (auto it = begin; it != end; ++it)
    {
        const TraceEvent& event = (*it);

        if (it != begin)
            stream << ",\n";

        stream << "{ ";
        stream << "\"pid\": " << event.processID << ", ";
        stream << "\"tid\": " << event.threadID << ", ";
        stream << "\"ts\": " << event.timestamp << ", ";

        if (event.phase == PHASE_DURATION)
        {
            stream << "\"dur\": " << event.duration << ", ";
        }

        stream << "\"ph\": \"" << PHASE_STR[event.phase] << "\", ";
        stream << "\"name\": \"" << event.name.c_str() << "\"";

        for (const std::pair<FastName, uint32>& arg : event.args)
        {
            stream << ", \"args\": { \"" << arg.first.c_str() << "\": " << arg.second << " }";
        }

        stream << " }";
    }

    stream << "\n] }\n";

    stream.flush();
}

}; //ns DAVA


text:
J'ai été affiché via Ajax

J'ai été affiché via Ajax. J'ai été affiché via Ajax. J'ai été affiché via Ajax. J'ai été affiché via Ajax. J'ai été affiché via Ajax.


text:
package org.scalatest.tools

import org.scalatest._
import org.scalatest.events.{SuiteCompleted, SuiteAborted, Ordinal, TestStarting}

class HtmlReporterSpec extends Spec with SharedHelpers {

  object `HtmlReporter ` {

    def `should throw IllegalStateException when SuiteCompleted is received without any suite events` {
      val tempDir = createTempDirectory()
      val htmlRep = new HtmlReporter(tempDir.getAbsolutePath, false, false, false, false, None, None)
      val suiteCompleted = SuiteCompleted(new Ordinal(99), "TestSuite", "TestSuite", Some("TestSuite"))
      val e = intercept[IllegalStateException] {
        htmlRep(suiteCompleted)
      }
      assert(e.getMessage === "Expected SuiteStarting for completion event: " + suiteCompleted + " in the head of suite events, but we got no suite event at all")
    }

    def `should throw IllegalStateException when SuiteCompleted is received without a SuiteStarting` {
      val tempDir = createTempDirectory()
      val htmlRep = new HtmlReporter(tempDir.getAbsolutePath, false, false, false, false, None, None)
      val testStarting = TestStarting(new Ordinal(99), "TestSuite", "TestSuite", Some("TestSuite"), "A Test", "A Test")
      htmlRep(testStarting)
      val suiteCompleted = SuiteCompleted(new Ordinal(99), "TestSuite", "TestSuite", Some("TestSuite"))
      val e = intercept[IllegalStateException] {
        htmlRep(suiteCompleted)
      }
      assert(e.getMessage === "Expected SuiteStarting for completion event: " + suiteCompleted + " in the head of suite events, but we got: " + testStarting)
    }

    def `should throw IllegalStateException when SuiteAborted is received without any suite events` {
      val tempDir = createTempDirectory()
      val htmlRep = new HtmlReporter(tempDir.getAbsolutePath, false, false, false, false, None, None)
      val suiteAborted = SuiteAborted(new Ordinal(99), "Error", "TestSuite", "TestSuite", Some("TestSuite"))
      val e = intercept[IllegalStateException] {
        htmlRep(suiteAborted)
      }
      assert(e.getMessage === "Expected SuiteStarting for completion event: " + suiteAborted + " in the head of suite events, but we got no suite event at all")
    }

    def `should throw IllegalStateException when SuiteAborted is received without a SuiteStarting` {
      val tempDir = createTempDirectory()
      val htmlRep = new HtmlReporter(tempDir.getAbsolutePath, false, false, false, false, None, None)
      val testStarting = TestStarting(new Ordinal(99), "TestSuite", "TestSuite", Some("TestSuite"), "A Test", "A Test")
      htmlRep(testStarting)
      val suiteAborted = SuiteAborted(new Ordinal(99), "Error", "TestSuite", "TestSuite", Some("TestSuite"))
      val e = intercept[IllegalStateException] {
        htmlRep(suiteAborted)
      }
      assert(e.getMessage === "Expected SuiteStarting for completion event: " + suiteAborted + " in the head of suite events, but we got: " + testStarting)
    }
  }

}


text:
export const environment = {
    production: false,
    restApiBaseUrl: 'app'
};