text:
package org.jboss.weld.tests.specialization.weld1651.broken;

import jakarta.enterprise.inject.spi.DefinitionException;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.ShouldThrowException;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.BeanArchive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.weld.test.util.Utils;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * @author Matus Abaffy
 */
@RunWith(Arquillian.class)
public class GenericProducerMethodRawSpecializationTest {

    @Deployment
    @ShouldThrowException(DefinitionException.class)
    public static Archive<?> createArchive() {
        return ShrinkWrap.create(BeanArchive.class, Utils.getDeploymentNameAsHash(GenericProducerMethodRawSpecializationTest.class))
                .addClasses(SpecializingProducerBean2.class, ProducerBean2.class);
    }

    @Test
    public void testDeploymentWithSpecializationOfRawType() {
        // should throw definition exception
     }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML>

<title>nl.esciencecenter.xenon.filesystems (xenon 3.0.2 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Package nl.esciencecenter.xenon.filesystems

This package contains classes and interfaces for manipulating files.

Interface Summary

Interface
Description

CopyStatus

CopyStatus contains status information for a specific copy operation.

FileSystemAdaptorDescription

PathAttributes

FileAttributes represents a set of attributes of a path.

Class Summary

Class
Description

FileSystem

FileSystem represent a (possibly remote) file system that can be used to access data.

Path

Path contains a sequence of path elements separated by a separator.

Enum Summary

Enum
Description

CopyMode

CopyOption is an enumeration containing all possible options for copying a file.

PosixFilePermission

PosixFilePermission is an enumeration containing all supported Posix file permissions.

Exception Summary

Exception
Description

AttributeNotSupportedException

Signals that a requested file attribute is not supported by the underlying file system implementation.

CopyCancelledException

DirectoryNotEmptyException

Signals that directory is not empty.

FileSystemClosedException

Signals that a unknown Copy handle was provided.

InvalidOptionsException

Signals that an invalid combination of OpenOptions have been specified.

InvalidPathException

Signals that an end-of-file was encountered.

InvalidResumeTargetException

Signals that the data in the target of a resume does not match the data in the source.

NoSuchCopyException

Signals that a unknown Copy handle was provided.

NoSuchPathException

Signals that a path does not exists.

PathAlreadyExistsException

Signals that a path already exists.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.


text:
from ..extensions import db
from ..utils import USERNAME_LEN_MAX
from .forms import MESSAGE_LEN_MAX, EMAIL_LEN_MAX, TIMEZONE_LEN_MAX

class Appointment(db.Model):

    __tablename__ = 'appointments'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(USERNAME_LEN_MAX), nullable=False)
    email = db.Column(db.String(EMAIL_LEN_MAX), nullable=False)
    start_time = db.Column(db.Integer, nullable=False)
    end_time = db.Column(db.Integer, nullable=False)
    timezone = db.Column(db.String(TIMEZONE_LEN_MAX), nullable=False)
    message = db.Column(db.String(MESSAGE_LEN_MAX), nullable=False)


text:
require "json"

module CacheableFlash
  def self.included(base)
    base.prepend_around_filter :write_flash_to_cookie
  end

  def write_flash_to_cookie
    yield

    cookie_flash = cookies['flash'] ? JSON.parse(cookies['flash']) : {}

    flash.each do |key, value|
      if cookie_flash[key.to_s].blank?
        cookie_flash[key.to_s] = value
      else
        cookie_flash[key.to_s] << "<br/>#{value}" # TODO should be an array
      end
    end

    cookies['flash'] = cookie_flash.to_json
    flash.clear
  end
end


text:
$(document).ready(function(){
    var username;
    username = getFromCookie("displayname");
    //getDisplayNameFromAjax(username);
    updateMenu(username);
});

function createMenu(){

}

function getDisplayNameFromAjax(username){

			   $.ajax({
			   		url: '../assets/php/user_id.php',
			   		type: 'POST',
			   		dataType: 'json'
			   		}).done(function(response){

			   		    // console.log(response);
			   		      if(response.status === 'logged_in'){
			   		        username = response.UID;
			   		        console.log(username);
			   		     }
			   		    else if(response.status === 'logged_out'){
			   		      username = "";
			   		    }
			   		    else{
			   		            username = response.message;
			   		    }

		                updateMenu(username); //update the menu after the ajax menu completer

			    });

}

function getFromCookie(cname){
     var name = cname + "=";
     var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";

}

//Updates the User menu passed on logged in and oout status
function updateMenu(username){
    //jquery set items in menu lists active:
    console.log(username);
  $('.nav.navbar-nav > li').on('click', function() {
    $(this).addClass('active');
    $(this).siblings().removeClass('active');
  });
    //var username_item = document.getElementById('username_li');
    var logged_in_menu = document.getElementById('menu_logged_in');
    var login_menu = document.getElementById('menu_logged_out');
    var user_li = document.createElement("li");
    var user_link = document.createElement("a");

    if(username == null || username == ""){
        logged_in_menu.style.display = 'none';
        login_menu.style.display = 'block';

    }
    else{
            //jquery set items in menu lists active:
 $('.nav.navbar-nav > li').on('click', function() {
    $(this).addClass('active');
    $(this).siblings().removeClass('active');
  });
        console.log(username);
        logged_in_menu.style.display = 'block';
        login_menu.style.display = 'none';
        var userlist = document.getElementById('userlist');
        var userText = document.createTextNode(username);
        var icon = document.createElement('span');
        icon.setAttribute('class', "glyphicon glyphicon-user");
       user_link.href='/profile/'+ getFromCookie("displayname");

       user_link.appendChild(icon);
       user_link.appendChild(userText);
       user_li.append(user_link);

        userlist.insertBefore(user_li, userlist.firstChild);

    }

}


text:
[Demo here](https://elm-chessboard-4rsiydksha-uc.a.run.app)

A 2-player Chessboard implementation in [elm-lang](http://elm-lang.org/).

A personal pet project to try out [The Elm Architecture](http://guide.elm-lang.org/architecture/).

## Todo

### Minimal

- All Possible Moves (Done)
  - ~~Basic moves for all pieces~~
  - ~~Enpassant~~
  - ~~Promotion~~
  - ~~Castling~~
  - ~~Handling King Check~~
- ~~Better Styling~~
- ~~Use images for pieces~~
- Undo/Redo
- Chess record notation

### LICENSE

MIT


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

  <fragment
    android:id="@+id/place_order_fragment"
    android:name="de.dev.eth0.bitcointrader.ui.fragments.WalletHistoryFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</LinearLayout>


text:
set -e
set -x

ARGS=$*

vagrant ssh worker -c "sudo service rf-worker stop || /bin/true"
vagrant ssh worker -c "cd /opt/app && envdir /etc/rf.d/env ./manage.py poll $ARGS"


text:
import datetime
import random
from will.plugin import WillPlugin
from will.decorators import respond_to, periodic, hear, randomly, route, rendered_template, require_settings

RESPONSES = [
    "Pretty good, all things considered. You?",
    "Doing alright.  How are you?",
    "Pretty solid for a %(day_name)s, thanks.  And you?",
    "Last night was crazy, but today is looking good. What about you?",
    "A little bored, if I'm honest.  How're you?",
    "Up and down, but good overall.  What about you?",
]

class HowAreYouPlugin(WillPlugin):

    @hear("^how are you\?")
    def how_are_you(self, message):
        now = datetime.datetime.now()
        context = {
            "day_name": now.strftime("%A")
        }
        reply = random.choice(RESPONSES) % context
        message.said_to_how_are_you = True
        self.say(reply, message=message)

    # @hear("")
    # def how_are_you_reply(self, message):
    #     print(message.analysis["history"][0].data)
    #     print(message.analysis["history"][1].data)


text:
This is my ([wjd](https://github.com/williamdemeo)) version of the
[fpinscala repository](https://github.com/fpinscala/fpinscala).
I created it when working through the exercises in the book
"Functional Programming in Scala", so it contains my solutions,
along with some test code to check that my answers are correct.

(For the [original README file](#original-readme-file) scroll down, or go to
the original [fpinscala git repository](https://github.com/fpinscala/fpinscala).)

The first section of this README file contains my notes on how to get started
working on the exercises in Eclipse.  It was slightly non-trivial to set this up
so that I could use some libraries for testing my solutions to the exercises, so
the notes below record the steps that worked.

------------------------------------

### Getting Started with fpinscala in Eclipse

To get started solving the exercises in the book "Functional Programming in Scala"
using the Eclipse IDE, I followed these steps:

1. Clone the [fpinscala repository](https://github.com/fpinscala/fpinscala)
   to my local drive:

        git clone git@github.com:fpinscala/fpinscala.git

2. Create a new repository called fpinscala_wjd in my
   GitHub account, set the remote url of my copy of fpinscala to point
   to my new repo, and push the files:

        git remote set-url origin git@github.com:williamdemeo/fpinscala_wjd.git
		git push -u origin master

3. Prepare the project files to be imported into Eclipse.

   The first step is to make sure the Scala build tool (sbt) is installed with
   the right plugins and libraries. (I already had sbt installed, so just need
   to configure it.)

   - To add the eclipse plugin to sbt, put the following line in the file
     ~/.sbt/0.13/plugins/plugins.sbt:

            addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "3.0.0")

   - To use [ScalaCheck](https://www.scalacheck.org/) and
     [ScalaTest](http://www.scalatest.org/) for testing solutions to the
     exercises, add a new file called build.sbt in the exercises directory, with
     the following lines:

            libraryDependencies += "org.scalacheck" %% "scalacheck" % "1.12.2" % "test"

            libraryDependencies += "org.scalatest" % "scalatest_2.11" % "2.2.4" % "test"

            libraryDependencies += "junit" % "junit" % "4.10" % "test"

     (These commands must be separated by blank lines, as shown above.)

   - Enter the fpinscala_wjd directory and execute the following:

            ~/git/PROGRAMMING/Scala/fpinscala_wjd$ sbt
            > project exercises
            > compile
    		> eclipse

     This switches to the exercises project, where your code lives, compiles the
     code, and then generates Eclipse files necessary to import the project into
     Eclipse.

	 **update:** If you're using an encrypted filesystem, the above compile
     command might result in the following error message:

            [error] File name too long
            [error] one error found
            [error] (exercises/compile:compile) Compilation failed

	 To fix this, add the following line to the file `~/.sbt/0.13/local.sbt`
     (create that file if it doesn't already exist):

            scalacOptions ++= Seq("-Xmax-classfile-name","78")

     (See [this page](http://stackoverflow.com/questions/28565837/filename-too-long-sbt)
     for more details.)

4. Finally, we can import projects into Eclipse:

        File --> Import --> Git --> Projects From Git --> etc.

   The result: three projects are imported into Eclipse, called `answers`,
   `chapter-code`, and `exercises`.

---------------------------------

## Original Readme File

*The contents of the original readme file appear below.*

This repository contains exercises, hints, and answers for the book
[Functional Programming in Scala](http://manning.com/bjarnason/). Along
with the book itself, it's the closest you'll get to having your own
private functional programming tutor without actually having one.

Here's how to use this repository:

Each chapter in the book develops a fully working library of functions
and data types, built up through a series of exercises and example code
given in the book text. The shell of this working library and exercise
stubs live in
`exercises/src/main/scala/fpinscala/<chapter-description>`, where
`<chapter-description>` is a package name that corresponds to the
chapter title (see below). When you begin working on a chapter, we
recommend you open the exercise file(s) for that chapter, and when you
encounter exercises, implement them in the exercises file and make sure
they work.

If you get stuck on an exercise, let's say exercise 4 in the chapter,
you can find hints in `answerkey/<chapter-description>/04.hint.txt` (if
no hints are available for a problem, the file will just have a single
'-' as its contents) and the answer along with an explanation of the
answer and any variations in
`answerkey/<chapter-description>/04.answer.scala` or
`04.answer.markdown`. The finished Scala modules, with all answers for
each chapter live in
`answers/src/main/scala/fpinscala/<chapter-description>`. Please feel
free to submit pull requests for alternate answers, improved hints, and
so on, so we can make this repo the very best resource for people
working through the book.

Chapter descriptions:

* Chapter 2: gettingstarted
* Chapter 3: datastructures
* Chapter 4: errorhandling
* Chapter 5: laziness
* Chapter 6: state
* Chapter 7: parallelism
* Chapter 8: testing
* Chapter 9: parsing
* Chapter 10: monoids
* Chapter 11: monads
* Chapter 12: applicative
* Chapter 13: iomonad
* Chapter 14: localeffects
* Chapter 15: streamingio

To build the code for the first time, if on windows:

    $ .\sbt.cmd

If on mac/linux, first make sure you have not checked out the code onto
an encrypted file system, otherwise you will get compile errors
regarding too long file names (one solution is to put the fpinscala repo
on a unencrypted usb key, and symlink it into your preferred code
location).

    $ chmod a+x ./sbt
    $ ./sbt

This will download and launch [sbt](http://scala-sbt.org), a build tool
for Scala. Once it is finished downloading, you'll get a prompt from
which you can issue commands to build and interact with your code. Try
the following:

    > project exercises
    > compile

This switches to the exercises project, where your code lives, and
compiles the code. You can also do:

    > console

to get a Scala REPL with access to your exercises, and

    > run

To get a menu of possible main methods to execute.

To create project files for the eclipse IDE you can install the
[sbteclipse](https://github.com/typesafehub/sbteclipse)
[sbt](http://scala-sbt.org) plugin. This makes a new command available
in [sbt](http://scala-sbt.org):

    > eclipse

All code in this repository is
[MIT-licensed](http://opensource.org/licenses/mit-license.php). See the
LICENSE file for details.

Have fun, and good luck! Also be sure to check out [the community
wiki](https://github.com/fpinscala/fpinscala/wiki) for the **chapter
notes**, links to more reading, and more.

_Paul and Rúnar_


text:
using Lavspent.DaisyChain.Gpio;
using Lavspent.DaisyChain.Misc;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Lavspent.DaisyChain.Adc
{
    /// <summary>
    /// Wraps a adc channel and provides a IGpio interface.
    /// </summary>
    internal class AdcChannelGpioWrapper : IGpio, IDisposable
    {
        /// <summary>
        /// The AdcChannel we're wrapping.
        /// </summary>
        private IAdcChannel _adcChannel;

        /// <summary>
        ///
        /// </summary>
        private double _lowerThreshold;

        /// <summary>
        ///
        /// </summary>
        private double _upperThreshold;

        /// <summary>
        ///
        /// </summary>
        private bool _disposeAdcChannel;

        /// <summary>
        ///
        /// </summary>
        private IDisposable _adcChannelSubscription;

        /// <summary>
        ///
        /// </summary>
        private Source<GpioEdge> _source;

        /// <summary>
        ///
        /// </summary>
        private GpioValue _lastGpioValue;

        public AdcChannelGpioWrapper(IAdcChannel adcChannel, bool disposeAdcChannel = true)
            : this(adcChannel, 0.45d, 0.55d, disposeAdcChannel)
        {
        }

        public AdcChannelGpioWrapper(IAdcChannel adcChannel, double lowerThreshold, double upperThreshold, bool disposeAdcChannel = true)
        {
            _adcChannel = adcChannel ?? throw new ArgumentNullException(nameof(adcChannel));
            if (lowerThreshold >= upperThreshold)
                throw new ArgumentOutOfRangeException($"{nameof(lowerThreshold)} must be smaller than {nameof(upperThreshold)}.");

            _lowerThreshold = lowerThreshold;
            _upperThreshold = upperThreshold;
            _disposeAdcChannel = disposeAdcChannel;

            _source = new Source<GpioEdge>();

            _adcChannelSubscription = _adcChannel.Subscribe(
                new Observer<IAdcChannelValue>(OnObservation));
        }

        private void OnObservation(IAdcChannelValue adcChannelValue)
        {
            DisposedUtil.Check(this, disposed);

            GpioValue gpioValue = GetGpioValue(adcChannelValue);
            if (_lastGpioValue != gpioValue)
            {
                _lastGpioValue = gpioValue;

                GpioEdge gpioEdge;

                if (gpioValue == GpioValue.High)
                {
                    gpioEdge = GpioEdge.RisingEdge;
                }
                else
                {
                    gpioEdge = GpioEdge.FallingEdge;
                }

                _source.Next(gpioEdge);
            }
        }

        /// <summary>
        /// Not supported.
        /// </summary>
        /// <param name="cancellationToken">A cancellation token that can be used to cancel the work</param>
        /// <returns></returns>
        public Task<GpioDriveMode> GetDriveModeAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            DisposedUtil.Check(this, disposed);
            throw new NotSupportedException("AdcChannels does not support drive mode.");
        }

        /// <summary>
        /// Not supported.
        /// </summary>
        /// <param name="driveMode"></param>
        /// <param name="cancellationToken">A cancellation token that can be used to cancel the work</param>
        /// <returns></returns>
        public Task<bool> IsDriveModeSupportedAsync(GpioDriveMode driveMode, CancellationToken cancellationToken = default(CancellationToken))
        {
            DisposedUtil.Check(this, disposed);
            throw new NotSupportedException("AdcChannels does not support drive mode.");
        }

        public async Task<GpioValue> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            DisposedUtil.Check(this, disposed);
            var analogValue = await _adcChannel.ReadAsync(cancellationToken);
            return GetGpioValue(analogValue);
        }

        private GpioValue GetGpioValue(IAdcChannelValue analogGpioValue)
        {
            DisposedUtil.Check(this, disposed);
            if (analogGpioValue == null)
                throw new ArgumentNullException(nameof(analogGpioValue));

            var gpioValue = analogGpioValue.Ratio <= _lowerThreshold ? GpioValue.Low :
                            analogGpioValue.Ratio >= _upperThreshold ? GpioValue.High :
                            _lastGpioValue;

            return gpioValue;

        }

        /// <summary>
        /// Not supported.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="cancellationToken">A cancellation token that can be used to cancel the work</param>
        /// <returns></returns>
        public Task SetDriveModeAsync(GpioDriveMode value, CancellationToken cancellationToken = default(CancellationToken))
        {
            DisposedUtil.Check(this, disposed);
            throw new NotSupportedException("AdcChannels does not support drive mode.");
        }

        /// <summary>
        /// Not supported.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="cancellationToken">A cancellation token that can be used to cancel the work</param>
        /// <returns></returns>
        public Task WriteAsync(GpioValue value, CancellationToken cancellationToken = default(CancellationToken))
        {
            DisposedUtil.Check(this, disposed);
            throw new NotSupportedException("AdcChannels does not support writing.");
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="observer"></param>
        /// <returns></returns>
        public IDisposable Subscribe(IObserver<GpioEdge> observer)
        {
            DisposedUtil.Check(this, disposed);
            return _source.Subscribe(observer);
        }

        #region IDisposable
        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
                return;

            if (disposing)
            {
                _adcChannelSubscription.Dispose();

                if (_disposeAdcChannel)
                {
                    _adcChannel.Dispose();
                }
            }

            disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
        }
        #endregion

    }
}


text:
<?php
namespace PHPValueObject\DateTimeRange;

class DateTimeRangeSplitter
{
    /**
     * @param DateTimeRange $dateTimeRange
     * @param \DateInterval $dateInterval
     * @return DateTimeRange[]
     */
    public function split(DateTimeRange $dateTimeRange, \DateInterval $dateInterval) : array
    {
        $ranges = [];
        /** @var \DateTimeImmutable $date */
        foreach (new \DatePeriod($dateTimeRange->getStart(), $dateInterval, $dateTimeRange->getEnd()) as $date) {
            $end = $date->add($dateInterval);
            if ($end > $dateTimeRange->getEnd()) {
                $end = $dateTimeRange->getEnd();
            }

            $ranges[] = new DateTimeRange($date, $end);
        };

        return $ranges;
    }
}


text:
namespace MassTransit.AzureServiceBusTransport.Configuration
{
    using MassTransit.Configuration;

    public interface ISessionIdSendTopologyConvention :
        ISendTopologyConvention
    {
        /// <summary>
        /// The default, non-message specific routing key formatter used by messages
        /// when no specific convention has been specified.
        /// </summary>
        ISessionIdFormatter DefaultFormatter { get; set; }
    }
}


text:
<?php

namespace Aop\JoinPoint\Traits;

/**
 * Support `\Aop\JoinPoint\Support\PropertyValueSetterSupportInterface`
 *
 * @see \Aop\JoinPoint\Support\PropertyValueSetterSupportInterface
 *
 * @author Nicolas Tallefourtane <dev@nicolab.net>
 */
trait PropertyValueSetterTrait
{
    /**
     * @see \Aop\JoinPoint\Support\PropertyValueSetterSupportInterface::setPropertyValue()
     */
    public function setPropertyValue($value)
    {
        return $this->support->setPropertyValue($value);
    }
}


text:
<?php

namespace Conjecto\Nemrod\Bundle\ElasticaBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * FrameworkExtension configuration structure.
 */
class Configuration implements ConfigurationInterface
{
    /**
     * Generates the configuration tree builder.
     *
     * @return TreeBuilder The tree builder
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('elastica');

        $this->addElasticaSearchConfigurationSection($rootNode);

        return $treeBuilder;
    }

    /**
     * Adds elasticsearch configuration part.
     *
     * @param ArrayNodeDefinition $rootNode
     */
    private function addElasticaSearchConfigurationSection(ArrayNodeDefinition $rootNode)
    {
        $rootNode
            ->children()
                ->scalarNode('default_client')
                    ->info('Defaults to the first client defined')
                ->end()
                ->scalarNode('default_index')
                    ->info('Defaults to the first index defined')
                ->end()
                ->scalarNode('default_manager')->defaultValue('rm')->end()
            //clients
                ->arrayNode('clients')//node 'clients' is
                ->isRequired()
                ->prototype('array')//an array containing all clients definitions
                    ->children()//children for each array entries
                        ->scalarNode('host')// a 'host' (scalar) node
                        ->end()
                        ->scalarNode('port')// a 'port' (scalar) node
                        ->end()
                    ->end()
                ->end()
            ->end()
            //indexes
            ->arrayNode('indexes')
                ->validate()
                    ->ifNull()
                    ->thenEmptyArray()
                ->end()
                    ->prototype('array')
                        ->children()
                            ->scalarNode('index_name')
                                ->info('Defaults to the name of the index, but can be modified if the index name is different in ElasticSearch')
                            ->end()
                            ->scalarNode('client')->end()
                            ->variableNode('settings')->defaultValue(array())->end()
                            ->arrayNode('types')
                            ->prototype('array')
                                ->children()
                                ->scalarNode('type')
                                ->end()
                                ->scalarNode('frame')
                                ->end()
                                    ->append($this->getPropertiesNode())
                                    ->end()
                                ->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end();
    }

    //below: stuffs taken from foselasticabundle
    /**
     * Returns the array node used for "properties".
     */
    protected function getPropertiesNode()
    {
        $builder = new TreeBuilder();
        $node = $builder->root('properties');

        $node
            ->useAttributeAsKey('name')
            ->prototype('variable')
            ->treatNullLike(array());

        return $node;
    }
}


text:
FROM phusion/baseimage:0.9.15
RUN locale-gen en_US.UTF-8
ENV LANG       en_US.UTF-8
ENV LC_ALL     en_US.UTF-8
ENV DEBIAN_FRONTEND noninteractive
RUN echo "deb http://www.rabbitmq.com/debian/ testing main" >> /etc/apt/sources.list && curl http://www.rabbitmq.com/rabbitmq-signing-key-public.asc | sudo apt-key add -
ENV HOME /root
RUN /etc/my_init.d/00_regen_ssh_host_keys.sh
CMD ["/sbin/my_init"]
# Nginx-PHP Installation
RUN apt-get update
RUN apt-get install -y vim curl wget build-essential python-software-properties
RUN add-apt-repository -y ppa:ondrej/php5
RUN add-apt-repository -y ppa:nginx/stable
#php yaf
RUN add-apt-repository ppa:mikespook/php5-yaf
RUN apt-get update
RUN apt-get install -y --force-yes  imagemagick
RUN apt-get install -y --force-yes php-pear php5-dev  php5-cli php5-fpm php5-mysql php5-pgsql php5-sqlite php5-curl\
		       php5-gd php5-mcrypt php5-intl php5-imap php5-tidy php5-redis php5-imagick php5-yaf php5-memcached memcached
RUN pecl install mongo amqp
#install opencc extension
RUN apt-get install -y --force-yes opencc libopencc-dev
COPY ./opencc-php ./opencc-php
RUN cd opencc-php  && /usr/bin/phpize
RUN cd opencc-php &&  ./configure  && make && make install
#install opencc end

RUN sed -i "s/;date.timezone =.*/date.timezone = UTC/" /etc/php5/fpm/php.ini
RUN sed -i "s/;date.timezone =.*/date.timezone = UTC/" /etc/php5/cli/php.ini
#config opencc extension
RUN echo "extension=opencc.so" >> /etc/php5/fpm/php.ini
RUN apt-get install -y nginx
RUN mkdir -p /etc/php5/conf.d
RUN echo "extension=mongo.so" >> /etc/php5/conf.d/mongo.ini
RUN echo "daemon off;" >> /etc/nginx/nginx.conf
RUN sed -i -e "s/;daemonize\s*=\s*yes/daemonize = no/g" /etc/php5/fpm/php-fpm.conf
RUN sed -i "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/" /etc/php5/fpm/php.ini

RUN mkdir -p        /var/www
ADD build/default   /etc/nginx/sites-available/default
RUN mkdir           /etc/service/nginx
ADD build/nginx.sh  /etc/service/nginx/run
RUN chmod +x        /etc/service/nginx/run
RUN mkdir           /etc/service/phpfpm
ADD build/phpfpm.sh /etc/service/phpfpm/run
RUN chmod +x        /etc/service/phpfpm/run

EXPOSE 80
# End Nginx-PHP

RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*


text:
<?php
/**
 *
 * This file is part of the Aura Project for PHP.
 *
 * @package Aura.Intl
 *
 * @license http://opensource.org/licenses/MIT MIT
 *
 */
namespace Aura\Intl\Exception;

use Aura\Intl\Exception;

/**
 *
 * Could not instantiate a formatter object.
 *
 * @package Aura.Intl
 *
 */
class CannotInstantiateFormatter extends \Exception
{
}


text:
'use strict';

var url = require('url');

var <%= resourceName %> = require('./<%= resourceName %>Service');

<% httpMethods.forEach(function(method){-%>
<% if (method === 'delete') { -%>
module.exports.delete<%= resourceName %> = function delete<%= resourceName %> (req, res, next) {
    <%= resourceName %>.delete<%= resourceName %> (req.swagger.params, res, next);
};
<% } -%>
<% if (method === 'get') { -%>
module.exports.get<%= resourceName %> = function get<%= resourceName %> (req, res, next) {
    <%= resourceName %>.get<%= resourceName %> (req.swagger.params, res, next);
};
<% } -%>
<% if (method === 'patch') { -%>
module.exports.patch<%= resourceName %> = function patch<%= resourceName %> (req, res, next) {
    <%= resourceName %>.patch<%= resourceName %> (req.swagger.params, res, next);
};
<% } -%>
<% if (method === 'post') { -%>
module.exports.post<%= resourceName %> = function post<%= resourceName %> (req, res, next) {
    <%= resourceName %>.post<%= resourceName %> (req.swagger.params, res, next);
};
<% } -%>
<% if (method === 'put') { -%>
module.exports.put<%= resourceName %> = function put<%= resourceName %> (req, res, next) {
    <%= resourceName %>.put<%= resourceName %> (req.swagger.params, res, next);
};
<% } -%>

<%}) -%>


text:
Un simulateur pour pirates-caraibes.com

# Licence
The MIT License Copyright 2013 Cyril Moreau, cyril-moreau.fr


text:
package com.gamecraft.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.gamecraft.domain.SonarInstance;
import com.gamecraft.service.SonarInstanceService;
import com.gamecraft.web.rest.errors.BadRequestAlertException;
import com.gamecraft.web.rest.util.HeaderUtil;
import com.gamecraft.web.rest.util.PaginationUtil;
import com.gamecraft.service.dto.SonarInstanceCriteria;
import com.gamecraft.service.SonarInstanceQueryService;
import io.swagger.annotations.ApiParam;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing SonarInstance.
 */
@RestController
@RequestMapping("/api")
public class SonarInstanceResource {

    private final Logger log = LoggerFactory.getLogger(SonarInstanceResource.class);

    private static final String ENTITY_NAME = "sonarInstance";

    private final SonarInstanceService sonarInstanceService;

    private final SonarInstanceQueryService sonarInstanceQueryService;

    public SonarInstanceResource(SonarInstanceService sonarInstanceService, SonarInstanceQueryService sonarInstanceQueryService) {
        this.sonarInstanceService = sonarInstanceService;
        this.sonarInstanceQueryService = sonarInstanceQueryService;
    }

    /**
     * POST  /sonar-instances : Create a new sonarInstance.
     *
     * @param sonarInstance the sonarInstance to create
     * @return the ResponseEntity with status 201 (Created) and with body the new sonarInstance, or with status 400 (Bad Request) if the sonarInstance has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/sonar-instances")
    @Timed
    public ResponseEntity<SonarInstance> createSonarInstance(@Valid @RequestBody SonarInstance sonarInstance) throws URISyntaxException {
        log.debug("REST request to save SonarInstance : {}", sonarInstance);
        if (sonarInstance.getId() != null) {
            throw new BadRequestAlertException("A new sonarInstance cannot already have an ID", ENTITY_NAME, "idexists");
        }
        SonarInstance result = sonarInstanceService.save(sonarInstance);
        return ResponseEntity.created(new URI("/api/sonar-instances/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /sonar-instances : Updates an existing sonarInstance.
     *
     * @param sonarInstance the sonarInstance to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated sonarInstance,
     * or with status 400 (Bad Request) if the sonarInstance is not valid,
     * or with status 500 (Internal Server Error) if the sonarInstance couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/sonar-instances")
    @Timed
    public ResponseEntity<SonarInstance> updateSonarInstance(@Valid @RequestBody SonarInstance sonarInstance) throws URISyntaxException {
        log.debug("REST request to update SonarInstance : {}", sonarInstance);
        if (sonarInstance.getId() == null) {
            return createSonarInstance(sonarInstance);
        }
        SonarInstance result = sonarInstanceService.save(sonarInstance);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, sonarInstance.getId().toString()))
            .body(result);
    }

    /**
     * GET  /sonar-instances : get all the sonarInstances.
     *
     * @param pageable the pagination information
     * @param criteria the criterias which the requested entities should match
     * @return the ResponseEntity with status 200 (OK) and the list of sonarInstances in body
     */
    @GetMapping("/sonar-instances")
    @Timed
    public ResponseEntity<List<SonarInstance>> getAllSonarInstances(SonarInstanceCriteria criteria,@ApiParam Pageable pageable) {
        log.debug("REST request to get SonarInstances by criteria: {}", criteria);
        Page<SonarInstance> page = sonarInstanceQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/sonar-instances");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /sonar-instances/:id : get the "id" sonarInstance.
     *
     * @param id the id of the sonarInstance to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the sonarInstance, or with status 404 (Not Found)
     */
    @GetMapping("/sonar-instances/{id}")
    @Timed
    public ResponseEntity<SonarInstance> getSonarInstance(@PathVariable Long id) {
        log.debug("REST request to get SonarInstance : {}", id);
        SonarInstance sonarInstance = sonarInstanceService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(sonarInstance));
    }

    /**
     * DELETE  /sonar-instances/:id : delete the "id" sonarInstance.
     *
     * @param id the id of the sonarInstance to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/sonar-instances/{id}")
    @Timed
    public ResponseEntity<Void> deleteSonarInstance(@PathVariable Long id) {
        log.debug("REST request to delete SonarInstance : {}", id);
        sonarInstanceService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/sonar-instances?query=:query : search for the sonarInstance corresponding
     * to the query.
     *
     * @param query the query of the sonarInstance search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/sonar-instances")
    @Timed
    public ResponseEntity<List<SonarInstance>> searchSonarInstances(@RequestParam String query, @ApiParam Pageable pageable) {
        log.debug("REST request to search for a page of SonarInstances for query {}", query);
        Page<SonarInstance> page = sonarInstanceService.search(query, pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/sonar-instances");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

}


text:
package org.path.sync.service;

import android.os.Parcel;
import android.os.Parcelable;

public enum SyncStatus implements Parcelable {
  INIT, SYNCING, NETWORK_ERROR, FILE_ERROR, AUTH_RESOLUTION, CONFLICT_RESOLUTION, SYNC_COMPLETE;

  @Override
  public int describeContents() {
    return 0;
  }

  @Override
  public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(this.name());
  }

  public static final Parcelable.Creator<SyncStatus> CREATOR = new Parcelable.Creator<SyncStatus>() {
    public SyncStatus createFromParcel(Parcel in) {
      return SyncStatus.valueOf(in.readString());
    }

    public SyncStatus[] newArray(int size) {
      return new SyncStatus[size];
    }
  };

}


text:
require('isomorphic-fetch');
const TwitchtvStrategy = require('passport-twitchtv').Strategy;
const GitLabStrategy = require('passport-gitlab2');
const User = require('../models/User.js');

module.exports = (passport) => {

    // Serialize the user id for session storage
    passport.serializeUser((user, done) => {
        done(null, user._id);
    });

    // Find the user profile associated with id
    passport.deserializeUser((_id, done) => {
        User.findById(_id, (err, user) => {
            done(err, user);
        });
    });

    /* Twitch authentication */

    const { TWITCH_CLIENT_ID, TWITCH_CLIENT_SECRET, BASE_URL } = process.env;

    passport.use(
        new TwitchtvStrategy({
            clientID: TWITCH_CLIENT_ID,
            clientSecret: TWITCH_CLIENT_SECRET,
            callbackURL: BASE_URL + '/user/auth/twitch/callback',
            scope: 'user_read user_subscriptions',
            force_verify: true
        },
            (accessToken, refreshToken, profile, done) => {
                // Check if user is subscribed
                fetch(`https://api.twitch.tv/kraken/users/${profile.username}/subscriptions/${process.env.TWITCH_STREAMER}`, {
                    method: 'GET',
                    headers: {
                        Accept: 'application/vnd.twitchtv.v3+json',
                        Authorization: `OAuth ${accessToken}`
                    }
                })
                    .then(response => {
                        // Assign user role
                        let currentUserRole = '';
                        if (profile.username === process.env.TWITCH_STREAMER
                            || process.env.ADDITIONAL_ADMINS.indexOf(profile.username) !== -1) {
                            currentUserRole = 'admin';
                        }
                        else if (response.status === 200
                            || process.env.ADDITIONAL_SUBSCRIBERS.indexOf(profile.username) !== -1) {
                            currentUserRole = 'subscriber';
                        }
                        else if (response.status === 404 || response.status === 422) {
                            currentUserRole = 'member';
                        }

                        // Save or update user
                        User.getUser(profile.id)
                            .then(user => {
                                if (user) {
                                    // Current user, update role if needed
                                    if (user.role !== currentUserRole) {
                                        user.updateRole(currentUserRole)
                                            .then(user => done(null, user));
                                    }
                                    else {
                                        done(null, user);
                                    }
                                }
                                else {
                                    // New user, store in database
                                    User.createAndSave({
                                        _id: profile.id,
                                        username: profile.displayName,
                                        email: profile.email,
                                        role: currentUserRole
                                    }).then(newUser => {
                                        done(null, newUser);
                                    });
                                }
                            });
                    })
                    .catch(err => done(err));
            })
    );

    /* Gitlab authentication */

    const { GITLAB_CLIENT_ID, GITLAB_CLIENT_SECRET, GITLAB_GROUP_ID, GITLAB_ACCESS_TOKEN  } = process.env;

    passport.use(
        new GitLabStrategy({
            clientID: GITLAB_CLIENT_ID,
            clientSecret: GITLAB_CLIENT_SECRET,
            callbackURL: BASE_URL + '/user/auth/gitlab/callback',
            passReqToCallback: true
        },
            (req, accessToken, refreshToken, profile, done) => {
                // Add user's Gitlab account to the group
                fetch(`https://gitlab.com/api/v3/groups/${GITLAB_GROUP_ID}/members?user_id=${profile.id}&access_level=20`, {
                    method: 'POST',
                    headers: { 'PRIVATE-TOKEN': GITLAB_ACCESS_TOKEN }
                })
                    .then(res => {
                        if (!(res.ok || res.status == 409)) return done(); // Status 409 means user is already in GitLab group
                        return User.getUser(req.user._id);
                    })
                    .then(user => {
                        if (user) {
                            user.linkGitlab(profile.id)
                                .then(user => done(null, user));
                        }
                    })
                    .catch(err => {
                        return done(err);
                    });
            })
    );
};


text:
package org.ovirt.engine.api.restapi.resource;

import org.ovirt.engine.api.model.CdRom;
import org.ovirt.engine.api.model.CdRoms;
import org.ovirt.engine.api.resource.ReadOnlyDevicesResource;
import org.ovirt.engine.core.common.businessentities.IVdcQueryable;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;

import static org.ovirt.engine.api.restapi.types.CdRomMapper.CDROM_ID;

public class BackendReadOnlyCdRomsResource<Q extends IVdcQueryable>
        extends AbstractBackendReadOnlyDevicesResource<CdRom, CdRoms, Q>
        implements ReadOnlyDevicesResource<CdRom, CdRoms> {

    public BackendReadOnlyCdRomsResource(Class<Q> entityType, Guid parentId, VdcQueryType queryType, VdcQueryParametersBase queryParams) {
        super(CdRom.class, CdRoms.class, entityType, parentId, queryType, queryParams);
    }

    @Override
    protected boolean validate(CdRom cdrom) {
        return cdrom.isSetFile() && cdrom.getFile().isSetId() && !"".equals(cdrom.getFile().getId());
    }

    @Override
    protected boolean matchEntity(Q entity, Guid id) {
        return id.equals(CDROM_ID) && parentId.equals(entity.getQueryableId());
    }
}


text:
{% extends "simple.html" %}
{% load i18n %}

{% block title %}{% trans "Internal server error" %}{% endblock %}
{% block header %}{% trans "500 error - Internal server error" %}{% endblock %}

{% block content %}
<p>{% trans "An internal server error has occurred. Reload to try again, or simply use your browser's back button." %}</p>
{% endblock %}


text: Tabs indent, spaces align. Moron.


text: export const CONTENT_SCRIPT_PORT_NAME = 'WSInspect.CS'


text:
package com.flipkart.foxtrot.core.exception;

import com.google.common.collect.Maps;

import java.util.Map;

/***
 Created by mudit.g on May, 2019
 ***/
public class PortExtractionException extends FoxtrotException {

    private final String message;

    public PortExtractionException(String message) {
        super(ErrorCode.PORT_EXTRACTION_ERROR, message);
        this.message = message;
    }

    @Override
    public Map<String, Object> toMap() {
        Map<String, Object> map = Maps.newHashMap();
        map.put("message", message);
        return map;
    }
}


text:
package net.minecraft.entity.ai;

import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.MathHelper;

public class EntityLookHelper
{
    private EntityLiving entity;

    /**
     * The amount of change that is made each update for an entity facing a direction.
     */
    private float deltaLookYaw;

    /**
     * The amount of change that is made each update for an entity facing a direction.
     */
    private float deltaLookPitch;

    /** Whether or not the entity is trying to look at something. */
    private boolean isLooking;
    private double posX;
    private double posY;
    private double posZ;

    public EntityLookHelper(EntityLiving entitylivingIn)
    {
        this.entity = entitylivingIn;
    }

    /**
     * Sets position to look at using entity
     */
    public void setLookPositionWithEntity(Entity entityIn, float deltaYaw, float deltaPitch)
    {
        this.posX = entityIn.posX;

        if (entityIn instanceof EntityLivingBase)
        {
            this.posY = entityIn.posY + (double)entityIn.getEyeHeight();
        }
        else
        {
            this.posY = (entityIn.getEntityBoundingBox().minY + entityIn.getEntityBoundingBox().maxY) / 2.0D;
        }

        this.posZ = entityIn.posZ;
        this.deltaLookYaw = deltaYaw;
        this.deltaLookPitch = deltaPitch;
        this.isLooking = true;
    }

    /**
     * Sets position to look at
     */
    public void setLookPosition(double x, double y, double z, float deltaYaw, float deltaPitch)
    {
        this.posX = x;
        this.posY = y;
        this.posZ = z;
        this.deltaLookYaw = deltaYaw;
        this.deltaLookPitch = deltaPitch;
        this.isLooking = true;
    }

    /**
     * Updates look
     */
    public void onUpdateLook()
    {
        this.entity.rotationPitch = 0.0F;

        if (this.isLooking)
        {
            this.isLooking = false;
            double d0 = this.posX - this.entity.posX;
            double d1 = this.posY - (this.entity.posY + (double)this.entity.getEyeHeight());
            double d2 = this.posZ - this.entity.posZ;
            double d3 = (double)MathHelper.sqrt_double(d0 * d0 + d2 * d2);
            float f = (float)(MathHelper.func_181159_b(d2, d0) * 180.0D / Math.PI) - 90.0F;
            float f1 = (float)(-(MathHelper.func_181159_b(d1, d3) * 180.0D / Math.PI));
            this.entity.rotationPitch = this.updateRotation(this.entity.rotationPitch, f1, this.deltaLookPitch);
            this.entity.rotationYawHead = this.updateRotation(this.entity.rotationYawHead, f, this.deltaLookYaw);
        }
        else
        {
            this.entity.rotationYawHead = this.updateRotation(this.entity.rotationYawHead, this.entity.renderYawOffset, 10.0F);
        }

        float f2 = MathHelper.wrapAngleTo180_float(this.entity.rotationYawHead - this.entity.renderYawOffset);

        if (!this.entity.getNavigator().noPath())
        {
            if (f2 < -75.0F)
            {
                this.entity.rotationYawHead = this.entity.renderYawOffset - 75.0F;
            }

            if (f2 > 75.0F)
            {
                this.entity.rotationYawHead = this.entity.renderYawOffset + 75.0F;
            }
        }
    }

    private float updateRotation(float p_75652_1_, float p_75652_2_, float p_75652_3_)
    {
        float f = MathHelper.wrapAngleTo180_float(p_75652_2_ - p_75652_1_);

        if (f > p_75652_3_)
        {
            f = p_75652_3_;
        }

        if (f < -p_75652_3_)
        {
            f = -p_75652_3_;
        }

        return p_75652_1_ + f;
    }

    public boolean getIsLooking()
    {
        return this.isLooking;
    }

    public double getLookPosX()
    {
        return this.posX;
    }

    public double getLookPosY()
    {
        return this.posY;
    }

    public double getLookPosZ()
    {
        return this.posZ;
    }
}


text:
<?php

use BBC\ParserWrapper;
use ElkArte\User;

/**
 * This function deals with the poll ID associated to a topic.
 * It allows to retrieve or update the poll ID associated with this topic ID.
 *
 * If $pollID is not passed, the current poll ID of the topic, if any, is returned.
 * If $pollID is passed, the topic is updated to point to the new poll.
 *
 * @param int $topicID the ID of the topic
 * @param int|null $pollID = null the ID of the poll, if any. If null is passed, it retrieves the current ID.
 * @return int
 */
function associatedPoll($topicID, $pollID = null)
{
	// Retrieve the poll ID.
	if ($pollID === null)
	{
		require_once(SUBSDIR . '/Topic.subs.php');
		$pollID = topicAttribute($topicID, array('id_poll'));

		return $pollID['id_poll'];
	}

	setTopicAttribute($topicID, array('id_poll' => $pollID));

	return false;
}

/**
 * Remove a poll.
 *
 * @param int[]|int $pollID The id of the poll to remove
 * @throws \ElkArte\Exceptions\Exception
 */
function removePoll($pollID)
{
	$db = database();

	$pollID = is_array($pollID) ? $pollID : array($pollID);

	// Remove votes.
	$db->query('', '
		DELETE FROM {db_prefix}log_polls
		WHERE id_poll IN ({array_int:id_polls})',
		array(
			'id_polls' => $pollID,
		)
	);

	// Remove the choices associated with this poll.
	$db->query('', '
		DELETE FROM {db_prefix}poll_choices
		WHERE id_poll IN ({array_int:id_polls})',
		array(
			'id_polls' => $pollID,
		)
	);

	// Remove the poll.
	$db->query('', '
		DELETE FROM {db_prefix}polls
		WHERE id_poll IN ({array_int:id_polls})',
		array(
			'id_polls' => $pollID,
		)
	);
}

/**
 * Reset votes for the poll.
 *
 * @param int $pollID The ID of the poll to reset the votes on
 * @throws \ElkArte\Exceptions\Exception
 */
function resetVotes($pollID)
{
	$db = database();

	$db->query('', '
		UPDATE {db_prefix}polls
		SET
			num_guest_voters = {int:no_votes}, reset_poll = {int:time}
		WHERE id_poll = {int:id_poll}',
		array(
			'no_votes' => 0,
			'id_poll' => $pollID,
			'time' => time(),
		)
	);

	$db->query('', '
		UPDATE {db_prefix}poll_choices
		SET
			votes = {int:no_votes}
		WHERE id_poll = {int:id_poll}',
		array(
			'no_votes' => 0,
			'id_poll' => $pollID,
		)
	);

	$db->query('', '
		DELETE FROM {db_prefix}log_polls
		WHERE id_poll = {int:id_poll}',
		array(
			'id_poll' => $pollID,
		)
	);
}

/**
 * Get all poll information you wanted to know.
 *
 * - Only returns info on the poll, not its options.
 *
 * @param int $id_poll The id of the poll to load
 * @param bool $ignore_permissions if true permissions are not checked.
 *             If false, {query_see_board} boardsAllowedTo('poll_view') and
 *             $modSettings['postmod_active'] will be considered in the query.
 *             This param is currently used only in SSI, it may be useful in any
 *             kind of integration
 * @return array|false array of poll information, or false if no poll is found
 * @throws \ElkArte\Exceptions\Exception
 */
function pollInfo($id_poll, $ignore_permissions = true)
{
	global $modSettings;

	$db = database();

	$boardsAllowed = array();
	if ($ignore_permissions === false)
	{
		$boardsAllowed = boardsAllowedTo('poll_view');

		if (empty($boardsAllowed))
		{
			return false;
		}
	}

	// Read info from the db
	$request = $db->query('', '
		SELECT
			p.question, p.voting_locked, p.hide_results, p.expire_time, p.max_votes, p.change_vote,
			p.guest_vote, p.id_member, COALESCE(mem.real_name, p.poster_name) AS poster_name,
			p.num_guest_voters, p.reset_poll' . ($ignore_permissions ? '' : ',
			b.id_board') . '
		FROM {db_prefix}polls AS p
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = p.id_member)' . ($ignore_permissions ? '' : '
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)') . '
		WHERE p.id_poll = {int:id_poll}' . ($ignore_permissions ? '' : ((in_array(0, $boardsAllowed) ? '' : '
			AND b.id_board IN ({array_int:boards_allowed_see})') . (!$modSettings['postmod_active'] ? '' : '
			AND t.approved = {int:is_approved}'))) . '
		LIMIT 1',
		array(
			'id_poll' => $id_poll,
			'boards_allowed_see' => $boardsAllowed,
			'is_approved' => 1,
		)
	);
	$poll_info = $request->fetch_assoc();
	$request->free_result();

	if (empty($poll_info))
	{
		return false;
	}

	$request = $db->query('', '
		SELECT COUNT(DISTINCT id_member) AS total
		FROM {db_prefix}log_polls
		WHERE id_poll = {int:id_poll}
			AND id_member != {int:not_guest}',
		array(
			'id_poll' => $id_poll,
			'not_guest' => 0,
		)
	);
	list ($poll_info['total']) = $request->fetch_row();
	$request->free_result();

	// Total voters needs to include guest voters
	$poll_info['total'] += $poll_info['num_guest_voters'];

	return $poll_info;
}

/**
 * Retrieve poll information, for the poll associated
 * to topic $topicID.
 *
 * @param int $topicID the topic with an associated poll.
 *
 * @return string[]|bool
 * @throws \ElkArte\Exceptions\Exception
 */
function pollInfoForTopic($topicID)
{
	$db = database();

	// Check if a poll currently exists on this topic, and get the id, question and starter.
	$request = $db->query('', '
		SELECT
			t.id_member_started, p.id_poll, p.voting_locked, p.question,
			p.hide_results, p.expire_time, p.max_votes, p.change_vote,
			m.subject, p.guest_vote, p.id_member AS poll_starter
		FROM {db_prefix}topics AS t
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
			LEFT JOIN {db_prefix}polls AS p ON (p.id_poll = t.id_poll)
		WHERE t.id_topic = {int:current_topic}
		LIMIT 1',
		array(
			'current_topic' => $topicID,
		)
	);

	// The topic must exist
	if ($request->num_rows() == 0)
	{
		return false;
	}

	// Get the poll information.
	$pollinfo = $request->fetch_assoc();
	$request->free_result();

	return $pollinfo;
}

/**
 * Retrieve the id of the topic associated to a poll
 *
 * @param int $pollID the topic with an associated poll.
 * @return array the topic id and the board id, false if no topics found
 * @throws \ElkArte\Exceptions\Exception
 */
function topicFromPoll($pollID)
{
	$db = database();

	// Check if a poll currently exists on this topic, and get the id, question and starter.
	$request = $db->query('', '
		SELECT
			t.id_topic, b.id_board
		FROM {db_prefix}topics AS t
			LEFT JOIN {db_prefix}polls AS p ON (p.id_poll = t.id_poll)
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
		WHERE p.id_poll = {int:current_poll}
		LIMIT 1',
		array(
			'current_poll' => $pollID,
		)
	);

	// The topic must exist
	if ($request->num_rows() == 0)
	{
		$topicID = false;
	}
	// Get the poll information.
	else
	{
		list ($topicID, $boardID) = $request->fetch_row();
	}

	$request->free_result();

	return array($topicID, $boardID);
}

/**
 * Return poll options, customized for a given member.
 *
 * What it does:
 *
 * - The function adds to poll options the information if the user
 * has voted in this poll.
 * - It censors the label in the result array.
 *
 * @param int $id_poll The id of the poll to query
 * @param int $id_member The id of the member
 *
 * @return array
 * @throws \Exception
 */
function pollOptionsForMember($id_poll, $id_member)
{
	$db = database();

	// Get the choices
	$pollOptions = array();
	$db->fetchQuery('
		SELECT
			pc.id_choice, pc.label, pc.votes, COALESCE(lp.id_choice, -1) AS voted_this
		FROM {db_prefix}poll_choices AS pc
			LEFT JOIN {db_prefix}log_polls AS lp ON (lp.id_choice = pc.id_choice AND lp.id_poll = {int:id_poll} AND lp.id_member = {int:current_member} AND lp.id_member != {int:not_guest})
		WHERE pc.id_poll = {int:id_poll}
		ORDER by pc.id_choice',
		array(
			'current_member' => $id_member,
			'id_poll' => $id_poll,
			'not_guest' => 0,
		)
	)->fetch_callback(
		function ($row) use (&$pollOptions) {
			$row['label'] = censor($row['label']);
			$pollOptions[$row['id_choice']] = $row;
		}
	);

	return $pollOptions;
}

/**
 * Returns poll options.
 * It censors the label in the result array.
 *
 * @param int $id_poll The id of the poll to load its options
 *
 * @return array
 * @throws \Exception
 */
function pollOptions($id_poll)
{
	$db = database();

	$pollOptions = array();
	$db->fetchQuery('
		SELECT
			label, votes, id_choice
		FROM {db_prefix}poll_choices
		WHERE id_poll = {int:id_poll}',
		array(
			'id_poll' => $id_poll,
		)
	)->fetch_callback(
		function ($row) use (&$pollOptions) {
			$row['label'] = censor($row['label']);
			$pollOptions[$row['id_choice']] = $row;
		}
	);

	return $pollOptions;
}

/**
 * Create a poll
 *
 * @param string $question The title/question of the poll
 * @param int $id_member = false The id of the creator
 * @param string $poster_name The name of the poll creator
 * @param int $max_votes = 1 The maximum number of votes you can do
 * @param int $hide_results = 1 If the results should be hidden
 * @param int $expire = 0 The time in days that this poll will expire
 * @param int $can_change_vote = 0 If you can change your vote
 * @param int $can_guest_vote = 0 If guests can vote
 * @param mixed[] $options = array() The poll options
 * @return int the id of the created poll
 * @throws \Exception
 */
function createPoll($question, $id_member, $poster_name, $max_votes = 1, $hide_results = 1, $expire = 0, $can_change_vote = 0, $can_guest_vote = 0, array $options = array())
{
	$expire = empty($expire) ? 0 : time() + $expire * 3600 * 24;

	$db = database();
	$db->insert('',
		'{db_prefix}polls',
		array(
			'question' => 'string-255', 'hide_results' => 'int', 'max_votes' => 'int', 'expire_time' => 'int', 'id_member' => 'int',
			'poster_name' => 'string-255', 'change_vote' => 'int', 'guest_vote' => 'int'
		),
		array(
			$question, $hide_results, $max_votes, $expire, $id_member,
			$poster_name, $can_change_vote, $can_guest_vote,
		),
		array('id_poll')
	);

	$id_poll = $db->insert_id('{db_prefix}polls');

	if (!empty($options))
	{
		addPollOptions($id_poll, $options);
	}

	call_integration_hook('integrate_poll_add_edit', array($id_poll, false));

	return $id_poll;
}

/**
 * Modify an existing poll
 *
 * @param int $id_poll The id of the poll that should be updated
 * @param string $question The title/question of the poll
 * @param int $max_votes = 1 The maximum number of votes you can do
 * @param int $hide_results = 1 If the results should be hidden
 * @param int $expire = 0 The time in days that this poll will expire
 * @param int $can_change_vote = 0 If you can change your vote
 * @param int $can_guest_vote = 0 If guests can vote
 * @throws \ElkArte\Exceptions\Exception
 */
function modifyPoll($id_poll, $question, $max_votes = 1, $hide_results = 1, $expire = 0, $can_change_vote = 0, $can_guest_vote = 0)
{
	$db = database();

	$db->query('', '
		UPDATE {db_prefix}polls
		SET
			question = {string:question}, change_vote = {int:change_vote},' . (allowedTo('moderate_board') ? '
			hide_results = {int:hide_results}, expire_time = {int:expire_time}, max_votes = {int:max_votes},
			guest_vote = {int:guest_vote}' : '
			hide_results = CASE WHEN expire_time = {int:expire_time_zero} AND {int:hide_results} = 2 THEN 1 ELSE {int:hide_results} END') . '
		WHERE id_poll = {int:id_poll}',
		array(
			'id_poll' => $id_poll,
			'question' => $question,
			'max_votes' => $max_votes,
			'hide_results' => $hide_results,
			'expire_time' => $expire,
			'change_vote' => $can_change_vote,
			'guest_vote' => $can_guest_vote,
			'expire_time_zero' => 0,
		)
	);

	call_integration_hook('integrate_poll_add_edit', array($id_poll, true));
}

/**
 * Add options to an already created poll
 *
 * @param int $id_poll The id of the poll you're adding the options to
 * @param mixed[] $options The options to choose from
 * @throws \Exception
 */
function addPollOptions($id_poll, array $options)
{
	$db = database();

	$pollOptions = array();
	foreach ($options as $i => $option)
	{
		$pollOptions[] = array($id_poll, $i, $option);
	}

	$db->insert('insert',
		'{db_prefix}poll_choices',
		array('id_poll' => 'int', 'id_choice' => 'int', 'label' => 'string-255'),
		$pollOptions,
		array('id_poll', 'id_choice')
	);
}

/**
 * Insert some options to an already created poll
 *
 * @param mixed[] $options An array holding the poll choices
 * @throws \Exception
 */
function insertPollOptions($options)
{
	$db = database();

	$db->insert('',
		'{db_prefix}poll_choices',
		array(
			'id_poll' => 'int', 'id_choice' => 'int', 'label' => 'string-255', 'votes' => 'int',
		),
		$options,
		array()
	);
}

/**
 * Add a single option to an already created poll
 *
 * @param mixed[] $options An array holding the poll choices
 * @throws \ElkArte\Exceptions\Exception
 */
function modifyPollOption($options)
{
	$db = database();

	foreach ($options as $option)
	{
		$db->query('', '
			UPDATE {db_prefix}poll_choices
			SET
				label = {string:option_name}
			WHERE id_poll = {int:id_poll}
				AND id_choice = {int:id_choice}',
			array(
				'id_poll' => $option[0],
				'id_choice' => $option[1],
				'option_name' => $option[2],
			)
		);
	}
}

/**
 * Delete a bunch of options from a poll
 *
 * @param int $id_poll The id of the poll you're deleting the options from
 * @param int[] $id_options An array holding the choice id
 * @throws \ElkArte\Exceptions\Exception
 */
function deletePollOptions($id_poll, $id_options)
{
	$db = database();

	$db->query('', '
		DELETE FROM {db_prefix}log_polls
		WHERE id_poll = {int:id_poll}
			AND id_choice IN ({array_int:delete_options})',
		array(
			'delete_options' => $id_options,
			'id_poll' => $id_poll,
		)
	);

	$db->query('', '
		DELETE FROM {db_prefix}poll_choices
		WHERE id_poll = {int:id_poll}
			AND id_choice IN ({array_int:delete_options})',
		array(
			'delete_options' => $id_options,
			'id_poll' => $id_poll,
		)
	);
}

/**
 * Retrieves the topic and, if different, poll starter
 * for the poll associated with the $id_topic.
 *
 * @param int $id_topic The id of the topic
 *
 * @return array
 * @throws \ElkArte\Exceptions\Exception
 */
function pollStarters($id_topic)
{
	$db = database();

	$pollStarters = array();
	$request = $db->query('', '
		SELECT
			t.id_member_started, p.id_member AS poll_starter
		FROM {db_prefix}topics AS t
			INNER JOIN {db_prefix}polls AS p ON (p.id_poll = t.id_poll)
		WHERE t.id_topic = {int:current_topic}
		LIMIT 1',
		array(
			'current_topic' => $id_topic,
		)
	);

	if ($request->num_rows() != 0)
	{
		$pollStarters = $request->fetch_row();
	}

	$request->free_result();

	return $pollStarters;
}

/**
 * Check if they have already voted, or voting is locked.
 *
 * @param int $topic the topic with an associated poll
 * @return mixed[]
 * @throws \Exception
 */
function checkVote($topic)
{
	$db = database();

	return $db->fetchQuery('
		SELECT
			COALESCE(lp.id_choice, -1) AS selected, p.voting_locked, p.id_poll, p.expire_time, p.max_votes, p.change_vote,
			p.guest_vote, p.reset_poll, p.num_guest_voters
		FROM {db_prefix}topics AS t
			INNER JOIN {db_prefix}polls AS p ON (p.id_poll = t.id_poll)
			LEFT JOIN {db_prefix}log_polls AS lp ON (p.id_poll = lp.id_poll AND lp.id_member = {int:current_member} AND lp.id_member != {int:not_guest})
		WHERE t.id_topic = {int:current_topic}
		LIMIT 1',
		array(
			'current_member' => User::$info->id,
			'current_topic' => $topic,
			'not_guest' => 0,
		)
	)->fetch_assoc();
}

/**
 * Removes the member's vote from a poll.
 *
 * @param int $id_member The id of the member
 * @param int $id_poll The topic with an associated poll.
 * @throws \ElkArte\Exceptions\Exception
 */
function removeVote($id_member, $id_poll)
{
	$db = database();

	$db->query('', '
		DELETE FROM {db_prefix}log_polls
		WHERE id_member = {int:current_member}
			AND id_poll = {int:id_poll}',
		array(
			'current_member' => $id_member,
			'id_poll' => $id_poll,
		)
	);
}

/**
 * Used to decrease the vote counter for the given poll.
 *
 * @param int $id_poll The id of the poll to lower the vote count
 * @param int[] $options The available poll options
 * @throws \ElkArte\Exceptions\Exception
 */
function decreaseVoteCounter($id_poll, $options)
{
	$db = database();

	$db->query('', '
		UPDATE {db_prefix}poll_choices
		SET
		 	votes = votes - 1
		WHERE id_poll = {int:id_poll}
			AND id_choice IN ({array_int:poll_options})
			AND votes > {int:votes}',
		array(
			'poll_options' => $options,
			'id_poll' => $id_poll,
			'votes' => 0,
		)
	);
}

/**
 * Increase the vote counter for the given poll.
 *
 * @param int $id_poll The id of the poll to increase the vote count
 * @param int[] $options The available poll options
 * @throws \ElkArte\Exceptions\Exception
 */
function increaseVoteCounter($id_poll, $options)
{
	$db = database();

	$db->query('', '
		UPDATE {db_prefix}poll_choices
		SET
			votes = votes + 1
		WHERE id_poll = {int:id_poll}
			AND id_choice IN ({array_int:poll_options})',
		array(
			'poll_options' => $options,
			'id_poll' => $id_poll,
		)
	);
}

/**
 * Add a vote to a poll.
 *
 * @param mixed[] $insert array of vote details, includes member and their choice
 * @throws \Exception
 */
function addVote($insert)
{
	$db = database();

	$db->insert('insert',
		'{db_prefix}log_polls',
		array('id_poll' => 'int', 'id_member' => 'int', 'id_choice' => 'int'),
		$insert,
		array('id_poll', 'id_member', 'id_choice')
	);
}

/**
 * Increase the vote counter for guest votes.
 *
 * @param int $id_poll The id of the poll to increase
 * @throws \ElkArte\Exceptions\Exception
 */
function increaseGuestVote($id_poll)
{
	$db = database();

	$db->query('', '
		UPDATE {db_prefix}polls
		SET
			num_guest_voters = num_guest_voters + 1
		WHERE id_poll = {int:id_poll}',
		array(
			'id_poll' => $id_poll,
		)
	);
}

/**
 * Determines who voted what.
 *
 * @param int $id_member id of the member who's vote choice we want
 * @param int $id_poll id fo the poll the member voted in
 *
 * @return int[]
 * @throws \Exception
 */
function determineVote($id_member, $id_poll)
{
	$db = database();
	$pollOptions = array();

	$db->fetchQuery('
		SELECT
			id_choice
		FROM {db_prefix}log_polls
		WHERE id_member = {int:current_member}
			AND id_poll = {int:id_poll}',
		array(
			'current_member' => $id_member,
			'id_poll' => $id_poll,
		)
	)->fetch_callback(
		function ($row) use (&$pollOptions) {
			$pollOptions[] = $row[0];
		}
	);

	return $pollOptions;
}

/**
 * Get some basic details from a poll
 *
 * @param int $id_topic
 * @return string[]|bool
 * @throws \Exception
 * @deprecated since 2.0 - use pollInfoForTopic instead
 */
function pollStatus($id_topic)
{
	\ElkArte\Errors\Errors::instance()->log_deprecated('pollStatus()', 'pollInfoForTopic()');

	return pollInfoForTopic($id_topic);
}

/**
 * Update the locked status from a given poll.
 *
 * @param int $id_poll The id of the poll to check
 * @param int $locked the value to set in voting_locked
 * @throws \ElkArte\Exceptions\Exception
 */
function lockPoll($id_poll, $locked)
{
	$db = database();

	$db->query('', '
		UPDATE {db_prefix}polls
		SET
			voting_locked = {int:voting_locked}
		WHERE id_poll = {int:id_poll}',
		array(
			'voting_locked' => $locked,
			'id_poll' => $id_poll,
		)
	);
}

/**
 * Gets poll choices from a given poll.
 *
 * @param int $id_poll The id of the poll
 * @return array
 * @throws \Exception
 */
function getPollChoices($id_poll)
{
	$db = database();

	$choices = array();
	$number = 1;
	$db->fetchQuery('
		SELECT
			label, votes, id_choice
		FROM {db_prefix}poll_choices
		WHERE id_poll = {int:id_poll}',
		array(
			'id_poll' => $id_poll,
		)
	)->fetch_callback(
		function ($row) use (&$choices, &$number) {
			$row['label'] = censor($row['label']);
			$choices[$row['id_choice']] = array(
				'id' => $row['id_choice'],
				'number' => $number++,
				'votes' => $row['votes'],
				'label' => $row['label'],
				'is_last' => false
			);
		}
	);

	return $choices;
}

/**
 * Get the poll starter from a given poll.
 *
 * @param int $id_topic The id of the topic that has an associated poll
 *
 * @return array
 * @throws \ElkArte\Exceptions\Exception no_board
 */
function getPollStarter($id_topic)
{
	$db = database();

	$request = $db->query('', '
		SELECT
			t.id_member_started, t.id_poll, p.id_member AS poll_starter, p.expire_time
		FROM {db_prefix}topics AS t
			LEFT JOIN {db_prefix}polls AS p ON (p.id_poll = t.id_poll)
		WHERE t.id_topic = {int:current_topic}
		LIMIT 1',
		array(
			'current_topic' => $id_topic,
		)
	);
	if ($request->num_rows() === 0)
	{
		throw new \ElkArte\Exceptions\Exception('no_board');
	}
	$bcinfo = $request->fetch_assoc();
	$request->free_result();

	return $bcinfo;
}

/**
 * Loads in $context whatever is needed to show a poll
 *
 * @param int $poll_id simply a poll id...
 * @throws \ElkArte\Exceptions\Exception
 */
function loadPollContext($poll_id)
{
	global $context, $txt;

	// Get the question and if it's locked.
	$pollinfo = pollInfo($poll_id);

	// Get all the options, and calculate the total votes.
	$pollOptions = pollOptionsForMember($poll_id, User::$info->id);

	// Compute total votes.
	$realtotal = 0;
	$pollinfo['has_voted'] = false;
	foreach ($pollOptions as $choice)
	{
		$realtotal += $choice['votes'];
		$pollinfo['has_voted'] |= $choice['voted_this'] != -1;
	}

	// If this is a guest we need to do our best to work out if they have voted, and what they voted for.
	if (User::$info->is_guest && $pollinfo['guest_vote'] && allowedTo('poll_vote'))
	{
		if (!empty($_COOKIE['guest_poll_vote']) && preg_match('~^[0-9,;]+$~', $_COOKIE['guest_poll_vote']) && strpos($_COOKIE['guest_poll_vote'], ';' . $poll_id . ',') !== false)
		{
			// ;id,timestamp,[vote,vote...]; etc
			$guestinfo = explode(';', $_COOKIE['guest_poll_vote']);

			// Find the poll we're after.
			foreach ($guestinfo as $i => $guestvoted)
			{
				$guestvoted = explode(',', $guestvoted);
				if ($guestvoted[0] == $poll_id)
				{
					break;
				}
			}

			// Has the poll been reset since guest voted?
			if ($pollinfo['reset_poll'] > $guestvoted[1])
			{
				// Remove the poll info from the cookie to allow guest to vote again
				unset($guestinfo[$i]);
				if (!empty($guestinfo))
				{
					$_COOKIE['guest_poll_vote'] = ';' . implode(';', $guestinfo);
				}
				else
				{
					unset($_COOKIE['guest_poll_vote']);
				}
			}
			else
			{
				// What did they vote for?
				unset($guestvoted[0], $guestvoted[1]);
				foreach ($pollOptions as $choice => $details)
				{
					$pollOptions[$choice]['voted_this'] = in_array($choice, $guestvoted) ? 1 : -1;
					$pollinfo['has_voted'] |= $pollOptions[$choice]['voted_this'] != -1;
				}
				unset($choice, $details, $guestvoted);
			}
			unset($guestinfo, $guestvoted, $i);
		}
	}

	$bbc_parser = ParserWrapper::instance();

	// Set up the basic poll information.
	$starter_href = getUrl('profile', ['action' => 'profile', 'u' => $pollinfo['id_member'], 'name' => $pollinfo['poster_name']]);
	$context['poll'] = array(
		'id' => $poll_id,
		'image' => 'normal_' . (empty($pollinfo['voting_locked']) ? 'poll' : 'locked_poll'),
		'question' => $bbc_parser->parsePoll($pollinfo['question']),
		'total_votes' => $pollinfo['total'],
		'change_vote' => !empty($pollinfo['change_vote']),
		'is_locked' => !empty($pollinfo['voting_locked']),
		'options' => array(),
		'lock' => allowedTo('poll_lock_any') || ($context['user']['started'] && allowedTo('poll_lock_own')),
		'edit' => allowedTo('poll_edit_any') || ($context['user']['started'] && allowedTo('poll_edit_own')),
		'allowed_warning' => $pollinfo['max_votes'] > 1 ? sprintf($txt['poll_options6'], min(count($pollOptions), $pollinfo['max_votes'])) : '',
		'is_expired' => !empty($pollinfo['expire_time']) && $pollinfo['expire_time'] < time(),
		'expire_time' => !empty($pollinfo['expire_time']) ? standardTime($pollinfo['expire_time']) : 0,
		'has_voted' => !empty($pollinfo['has_voted']),
		'starter' => array(
			'id' => $pollinfo['id_member'],
			'name' => $pollinfo['poster_name'],
			'href' => $pollinfo['id_member'] == 0 ? '' : $starter_href,
			'link' => $pollinfo['id_member'] == 0 ? $pollinfo['poster_name'] : '<a href="' . $starter_href . '">' . $pollinfo['poster_name'] . '</a>'
		)
	);

	// Make the lock and edit permissions defined above more directly accessible.
	$context['allow_lock_poll'] = $context['poll']['lock'];
	$context['allow_edit_poll'] = $context['poll']['edit'];

	// You're allowed to vote if:
	// 1. the poll did not expire, and
	// 2. you're either not a guest OR guest voting is enabled... and
	// 3. you're not trying to view the results, and
	// 4. the poll is not locked, and
	// 5. you have the proper permissions, and
	// 6. you haven't already voted before.
	$context['allow_vote'] = !$context['poll']['is_expired'] && (User::$info->is_guest === false || ($pollinfo['guest_vote'] && allowedTo('poll_vote'))) && empty($pollinfo['voting_locked']) && allowedTo('poll_vote') && !$context['poll']['has_voted'];

	// You're allowed to view the results if:
	// 1. you're just a super-nice-guy, or
	// 2. anyone can see them (hide_results == 0), or
	// 3. you can see them after you voted (hide_results == 1), or
	// 4. you've waited long enough for the poll to expire. (whether hide_results is 1 or 2.)
	$context['allow_poll_view'] = allowedTo('moderate_board') || $pollinfo['hide_results'] == 0 || ($pollinfo['hide_results'] == 1 && $context['poll']['has_voted']) || $context['poll']['is_expired'];
	$context['poll']['show_results'] = $context['allow_poll_view'] && (isset($_REQUEST['viewresults']) || isset($_REQUEST['viewResults']));

	// You're allowed to change your vote if:
	// 1. the poll did not expire, and
	// 2. you're not a guest... and
	// 3. the poll is not locked, and
	// 4. you have the proper permissions, and
	// 5. you have already voted, and
	// 6. the poll creator has said you can!
	$context['allow_change_vote'] = !$context['poll']['is_expired'] && User::$info->is_guest === false && empty($pollinfo['voting_locked']) && allowedTo('poll_vote') && $context['poll']['has_voted'] && $context['poll']['change_vote'];

	// You're allowed to return to voting options if:
	// 1. you are (still) allowed to vote.
	// 2. you are currently seeing the results.
	$context['allow_return_vote'] = $context['allow_vote'] && $context['poll']['show_results'];

	// Calculate the percentages and bar lengths...
	$divisor = $realtotal == 0 ? 1 : $realtotal;

	// Determine if a decimal point is needed in order for the options to add to 100%.
	$precision = $realtotal == 100 ? 0 : 1;

	// Now look through each option, and...
	foreach ($pollOptions as $i => $option)
	{
		// First calculate the percentage, and then the width of the bar...
		$bar = round(($option['votes'] * 100) / $divisor, $precision);
		$barWide = $bar == 0 ? 1 : floor(($bar * 8) / 3);

		// Now add it to the poll's contextual theme data.
		$context['poll']['options'][$i] = array(
			'id' => 'options-' . $i,
			'percent' => $bar,
			'votes' => $option['votes'],
			'voted_this' => $option['voted_this'] != -1, /* Todo: I notice 'bar' here is not used in the theme any longer - only in SSI. */
			'bar' => '<div class="poll_gradient" style="width: ' . $barWide . 'px;"></div>',
			'bar_ndt' => $bar > 0 ? '<div class="bar poll-bar" style="width: ' . $bar . '%;"></div>' : '<div class="bar poll-bar"></div>',
			'bar_width' => $barWide,
			'option' => $bbc_parser->parsePoll($option['label']),
			'vote_button' => '<input type="' . ($pollinfo['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . $i . '" value="' . $i . '" class="input_' . ($pollinfo['max_votes'] > 1 ? 'check' : 'radio') . '" />'
		);
	}
}


text:
sjjk=~/anaconda3/envs/java_env/opt/scijava-jupyter-kernel

mvn clean package
mvn dependency:copy-dependencies
rm $sjjk/*.jar
cp target/dependency/*.jar $sjjk/
cp target/*.jar $sjjk/


text:
"""
test_djangocms-deflector
------------

Tests for `djangocms-deflector` models module.
"""

import os
import shutil
import unittest

from djangocms_deflector import models

class TestDjangocms_deflector(unittest.TestCase):

    def setUp(self):
        pass

    def test_something(self):
        pass

    def tearDown(self):
        pass


text:
@interface OGLFragmentShader : OGLShader

-(instancetype) initWithContents:(NSString *)contents;
-(instancetype) initWithFile:(NSString *)path;

@end


text:
/**
 * Support for JSON serialization of vTypes according to the following
 * (specification).
 */
package org.diirt.vtype.json;


text:
package org.commonjava.indy.repo.proxy.jaxrs;

import io.swagger.annotations.Api;
import org.commonjava.indy.bind.jaxrs.IndyResources;
import org.commonjava.indy.bind.jaxrs.util.REST;

import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.Path;

@Api( value = "Repository Proxy administration REST interface" )
@Path( "/api/repoproxy/admin" )
@ApplicationScoped
@REST
public class RepoProxyAdminResource implements IndyResources
{
}


text:
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using OrchardCore.ContentManagement.Display.ContentDisplay;
using OrchardCore.ContentManagement.Display.Models;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.Contents.Models;
using OrchardCore.Contents.ViewModels;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Views;
using OrchardCore.Security;

namespace OrchardCore.Contents.Drivers
{
    public class OwnerEditorDriver : ContentPartDisplayDriver<CommonPart>
    {
        private readonly IContentDefinitionManager _contentDefinitionManager;
        private readonly IAuthorizationService _authorizationService;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public OwnerEditorDriver(
            IContentDefinitionManager contentDefinitionManager,
            IAuthorizationService authorizationService,
            IHttpContextAccessor httpContextAccessor)
        {
            _contentDefinitionManager = contentDefinitionManager;
            _authorizationService = authorizationService;
            _httpContextAccessor = httpContextAccessor;
        }

        public override async Task<IDisplayResult> EditAsync(CommonPart part, BuildPartEditorContext context)
        {
            var currentUser = _httpContextAccessor.HttpContext?.User;

            if (currentUser == null || !(await _authorizationService.AuthorizeAsync(currentUser, StandardPermissions.SiteOwner, part)))
            {
                return null;
            }

            var settings = GetSettings(part);

            if (settings.DisplayOwnerEditor)
            {
                return Shape<OwnerEditorViewModel>("CommonPart_Edit__Owner", model =>
                {
                    model.Owner = part.ContentItem.Owner;
                });
            }

            return null;
        }

        public override async Task<IDisplayResult> UpdateAsync(CommonPart part, BuildPartEditorContext context)
        {
            var currentUser = _httpContextAccessor.HttpContext?.User;

            if (currentUser == null || !(await _authorizationService.AuthorizeAsync(currentUser, StandardPermissions.SiteOwner, part)))
            {
                return null;
            }

            var settings = GetSettings(part);

            if (settings.DisplayOwnerEditor)
            {
                var model = new OwnerEditorViewModel();
                await context.Updater.TryUpdateModelAsync(model, Prefix);

                if (!string.IsNullOrEmpty(part.ContentItem.Owner) || part.ContentItem.Number > 0)
                {
                    part.ContentItem.Owner = model.Owner;
                }
            }

            return await EditAsync(part, context);
        }

        public CommonPartSettings GetSettings(CommonPart part)
        {
            var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(part.ContentItem.ContentType);
            var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(x => String.Equals(x.PartDefinition.Name, "CommonPart", StringComparison.Ordinal));
            return contentTypePartDefinition.GetSettings<CommonPartSettings>();
        }
    }
}


text:
using Nito.AsyncEx;
using NullGuard;
using Q42.HueApi;
using Q42.HueApi.ColorConverters;
using Q42.HueApi.ColorConverters.HSB;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using static System.FormattableString;

namespace Hspi.Devices
{
    [NullGuard(ValidationFlags.Arguments | ValidationFlags.NonPublic)]
    internal sealed class PhilipsHueControl : IPAddressableDeviceControl
    {
        public PhilipsHueControl(string name, IPAddress deviceIP,
                                  string userName,
                                  IEnumerable<string> devices,
                                  TimeSpan defaultCommandDelay,
                                  IConnectionProvider connectionProvider,
                                  AsyncProducerConsumerQueue<DeviceCommand> commandQueue,
                                  AsyncProducerConsumerQueue<FeedbackValue> feedbackQueue) :
            base(name, deviceIP, defaultCommandDelay, connectionProvider, commandQueue, feedbackQueue)
        {
            this.userName = userName;
            this.devices = devices.ToImmutableList();

            AddCommand(new DeviceCommand(CommandName.PowerOff, fixedValue: -96));
            AddCommand(new DeviceCommand(CommandName.PowerOn, fixedValue: -95));
            AddCommand(new DeviceCommand(CommandName.PowerQuery, fixedValue: -94));
            AddCommand(new DeviceCommand(CommandName.AlertWhite, fixedValue: -93));

            AddFeedback(new DeviceFeedback(FeedbackName.Power, TypeCode.Boolean));
        }

        public override bool InvalidState
        {
            get
            {
                return false;
            }
        }

        public override Task Refresh(CancellationToken token)
        {
            return ExecuteCommand(GetCommand(CommandName.PowerQuery), token);
        }

        protected override async Task ExecuteCommandCore(DeviceCommand command, CancellationToken token)
        {
            using (var _ = await connectionLock.LockAsync(token).ConfigureAwait(false))
            {
                Trace.WriteLine(Invariant($"Sending {command.Id} to Hue {Name} on {DeviceIP}"));

                if (!Connected)
                {
                    await Connect(token).ConfigureAwait(false);
                }

                switch (command.Id)
                {
                    case CommandName.PowerOff:
                        {
                            var hueCommand = new LightCommand();
                            hueCommand.TurnOff();
                            hueCommand.Brightness = 100;
                            await client.SendCommandAsync(hueCommand, this.devices).ConfigureAwait(false);
                            await UpdatePowerStatus(token).ConfigureAwait(false);
                        }
                        break;

                    case CommandName.AlertWhite:
                        {
                            var hueCommand = new LightCommand();
                            hueCommand.TurnOn().SetColor(new RGBColor("FFFFFF"));
                            hueCommand.Alert = Alert.Multiple;
                            await client.SendCommandAsync(hueCommand, this.devices).ConfigureAwait(false);
                            await UpdatePowerStatus(token).ConfigureAwait(false);
                        }
                        break;

                    case CommandName.PowerOn:
                        {
                            var hueCommand = new LightCommand();
                            hueCommand.TurnOn();
                            await client.SendCommandAsync(hueCommand, this.devices).ConfigureAwait(false);
                            await UpdatePowerStatus(token).ConfigureAwait(false);
                        }
                        break;

                    case CommandName.PowerQuery:
                        {
                            await UpdatePowerStatus(token).ConfigureAwait(false);
                        }
                        break;
                }
            }
        }

        private async Task Connect(CancellationToken token)
        {
            if (!await IsNetworkOn().ConfigureAwait(false))
            {
                throw new DevicePoweredOffException($"Hue {Name} on {DeviceIP} not powered On");
            }

            client = new LocalHueClient(DeviceIP.ToString());
            client.Initialize(this.userName);
            await UpdateConnectedState(true, token).ConfigureAwait(false);
        }

        private async Task<bool> IsNetworkOn()
        {
            TimeSpan networkPingTimeout = TimeSpan.FromMilliseconds(500);
            return await NetworkHelper.PingAddress(DeviceIP, networkPingTimeout).ConfigureAwait(false);
        }

        private async Task UpdatePowerStatus(CancellationToken token)
        {
            bool isOff = false;
            foreach (var device in this.devices)
            {
                var light = await client.GetLightAsync(device).ConfigureAwait(false);
                if (!light.State.On)
                {
                    // all need to be off
                    isOff = true;
                    break;
                }
                token.ThrowIfCancellationRequested();
            }

            await UpdateFeedback(FeedbackName.Power, !isOff, token).ConfigureAwait(false);
        }

        private readonly AsyncLock connectionLock = new AsyncLock();
        private readonly IReadOnlyList<string> devices;
        private readonly string userName;
        private LocalHueClient client;
    }
}


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

<title>io.github.privacystreams.location Class Hierarchy</title>
<meta name="date" content="2017-08-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package io.github.privacystreams.location

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

io.github.privacystreams.location.GeolocationOperators

io.github.privacystreams.core.Item

io.github.privacystreams.location.Geolocation

io.github.privacystreams.location.LatLon

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
class LikesCommentsCoursePost < ActiveRecord::Base
  attr_accessible :comments_course_post_id, :user_id

  belongs_to :user
  belongs_to :comments_course_post
end


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/firestore/admin/v1/firestore_admin.proto

package com.google.firestore.admin.v1;

public interface UpdateDatabaseMetadataOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.firestore.admin.v1.UpdateDatabaseMetadata)
    com.google.protobuf.MessageOrBuilder {}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SurfaceView
        android:id="@+id/base_preview_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/default_base_black"/>

    <com.angcyo.zxingzbar.ViewfinderView
        android:id="@+id/base_viewfinder_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <com.angcyo.uiview.widget.RTextView
        android:id="@+id/base_code_tip_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="@dimen/base_120dpi"
        android:text="@string/qr_code_scan_tip"
        android:textColor="@color/default_base_white"
        android:textSize="12dp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|bottom"
        android:layout_marginBottom="@dimen/base_40dpi">

        <com.angcyo.uiview.widget.RImageCheckView
            android:id="@+id/base_light_switch_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/base_light_switch_selector"
            app:r_tint_color="false"/>

        <android.support.v4.widget.Space
            android:layout_width="@dimen/base_120dpi"
            android:layout_height="0dp"/>

        <com.angcyo.uiview.widget.RImageCheckView
            android:id="@+id/base_photo_selector_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/base_photo_album"/>

    </LinearLayout>

</FrameLayout>


text:
/**
 * Package which contains Wicket events for 'orienteer-users' module
 */
package org.orienteer.users.component.event;


text:
package org.wildfly.swarm.netflix.archaius.runtime;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;

import com.netflix.config.ConfigurationManager;
import org.apache.commons.configuration.AbstractConfiguration;
import org.wildfly.swarm.container.runtime.ConfigurableHandle;
import org.wildfly.swarm.container.runtime.ConfigurableManager;
import org.wildfly.swarm.spi.api.Customizer;
import org.wildfly.swarm.spi.api.config.ConfigKey;
import org.wildfly.swarm.spi.runtime.annotations.Post;

/**
 * @author Bob McWhirter
 */
@Post
@ApplicationScoped
public class ArchaiusCustomizer implements Customizer {

    @Inject
    ConfigurableManager configurableManager;

    @Inject
    @Any
    Instance<ArchaiusLinkage> links;

    Set<String> linkable = new HashSet<>();

    @PostConstruct
    protected void buildLinkNameSet() {
        for (ArchaiusLinkage link : this.links) {
            this.linkable.add(link.name() + ".");
        }
    }

    @Override
    public void customize() {
        AbstractConfiguration config = ConfigurationManager.getConfigInstance();

        Set<ConfigKey> seen = new HashSet<>();

        this.configurableManager.configurables().stream()
                .filter(this::shouldLink)
                .forEach(e -> {
                    try {
                        Object value = e.currentValue();
                        if (value != null) {
                            config.setProperty(e.key().subkey(1).name(), e.currentValue());
                        }
                        seen.add(e.key());
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                });

        this.configurableManager.configView().allKeysRecursively()
                .filter(this::shouldLink)
                .filter(k -> !seen.contains(k))
                .forEach(k -> {
                    Object value = this.configurableManager.configView().valueOf(k);
                    if (value != null) {
                        config.setProperty(k.subkey(1).name(), value);
                    }
                });
    }

    protected boolean shouldLink(ConfigKey key) {
        if (!key.head().name().equals("swarm")) {
            return false;
        }
        return linkable.stream().anyMatch(e -> key.subkey(1).name().startsWith(e));
    }

    protected boolean shouldLink(ConfigurableHandle configurable) {
        return shouldLink(configurable.key());
    }

}