text:
<?php // vim:ts=4:sw=4:et:fdm=marker
/**
 * BaseException is parent of all exceptions in Agile Toolkit which
 * are meant to be for informational purposes. There are also some
 * exceptions (StopInit) which are used for data-flow.
 *
 * Learn:
 *
 * Reference:
 *//*
==ATK4===================================================
   This file is part of Agile Toolkit 4
    http://agiletoolkit.org/

   (c) 2008-2013 Agile Toolkit Limited <info@agiletoolkit.org>
   Distributed under Affero General Public License v3 and
   commercial license.

   See LICENSE or LICENSE_COM for more information
 =====================================================ATK4=*/
class BaseException extends Exception
{
    // Exception defines it's methods as "final", which is complete nonsence
    // and incorrect behavor in my opinion. Therefore I need to re-declare
    // it's class and re-define the methods so I could extend my own methods
    // in my classes.

    // Backtrace array
    public $my_backtrace;

    // Backtrace shift
    public $shift = 0;

    // Classname of exception
    public $name;

    // Array with more info
    public $more_info = array();

    // Plain text recommendation on how the poblem can be solved
    public $recommendation=false;

    // Array of available actions
    public $actions = array();

    // Link to another exception which caused this one
    public $by_exception=null;

    /**
     * Initialization
     */
    function init()
    {
    }

    /**
     * On class construct
     *
     * @param string $msg Error message
     * @param string $code Error code
     *
     * @return void
     */
    function __construct($msg, $code = 0)
    {
        parent::__construct($msg, $code);
        $this->collectBasicData($code);
    }

    /**
     * Collect basic data of exception
     *
     * @param string $code Error code
     *
     * @return void
     */
    function collectBasicData($code)
    {
        $this->name = get_class($this);
        $this->my_backtrace = debug_backtrace();
        array_shift($this->my_backtrace);
        array_shift($this->my_backtrace);
    }

    /**
     * Call this to add additional information to the exception you are about
     * to throw.
     *
     * @param string $key
     * @param string $value
     *
     * @return $this
     */
    function addMoreInfo($key, $value)
    {
        $this->more_info[$key] = $value;
        return $this;
    }

    /**
     * Add reference to the object.
     * Do not call this directly, exception() method takes care of that.
     *
     * @param string $t
     */
    function addThis($t)
    {
        return $this->addMoreInfo('Raised by object', $t);
    }

    function setCode(int $code){
        $this->code=$code;
    }

    /**
     * Records another exception as a cause of your current exception.
     * Wrapping one exception inside another helps you to track problems
     * better
     */
    function by(Exception $e){
        $this->by_exception=$e;
        return $this;
    }

    /**
     * Actions will be displayed as links on the exception page allowing viewer
     * to perform additional debug functions.
     * addAction('show info',array('info'=>true)) will result in link to &info=1
     *
     * @param string $key
     * @param array $descr
     *
     * @return $this
     */
    function addAction($key, $descr)
    {
        if(is_array($key)){
            $this->recommendation = $descr;
            $this->actions = array_merge($this->actions,$key);
            return $this;
        }
        $this->actions[$key] = $descr;
        return $this;
    }

    /**
     * Return collected backtrace info
     *
     * @return array
     */
    function getMyTrace()
    {
        return $this->my_backtrace;
    }

    /**
     * Return filename from backtrace log
     *
     * @return string
     */
    function getMyFile()
    {
        return $this->my_backtrace[2]['file'];
    }

    /**
     * Return line number from backtract log
     *
     * @return string
     */
    function getMyLine()
    {
        return $this->my_backtrace[2]['line'];
    }

    /**
     * Returns HTML representation of the exception
     *
     * @param string $message
     *
     * @return string
     */
    function getHTML()
    {
        $e=$this;

        $o='';
        $o='
';

        $o.=$this->getHTMLHeader();

        $o.=$this->getHTMLSolution();

        //$o.=$this->getHTMLBody();

        $o.='

';
        if(@$e->more_info){
            $o.= '
Additional information:
';
            $o.= $this->print_r($e->more_info,'
','
','
','
',' ');
        }
        if(method_exists($e,'getMyFile'))$o.= '
' . $e->getMyFile() . ':' . $e->getMyLine() . '
';

        if(method_exists($e,'getMyTrace'))$o.= $this->backtrace(3,$e->getMyTrace());
        else $o.= $this->backtrace(@$e->shift,$e->getTrace());

        if(@$e->by_exception){
            $o.="
This error was triggered by the following error:
";
            $o.=$e->by_exception->getHTML();
        }
        $o.='

';

        return $o;
    }

    function getHeader()
    {
        return get_class($this).": ". htmlspecialchars($this->getMessage()). ($this->getCode()?' [code: '.$this->getCode().']':'');
    }
    function getHTMLHeader()
    {

        return
        "
".
        "

".
        $this->getHeader().
        "
\n".
        '

';
    }

    function getSolution(){
        return $this->actions;
    }

    function getHTMLSolution()
    {
        $solution = $this->getSolution();
        $recommendation = '
'.$this->recommendation.'
';
        if(!$solution)return '';
        list($label,$url)=$solution;
        return
        "
".
        "
".
        $recommendation.
        $this->getHTMLActions().
        '

';
    }

    function getHTMLActions() {
        $o='';
        foreach($this->actions as $label=>$url){

            $o.="".
            $label.
            "\n";
        }
        return $o;
    }

    /**
     * Utility
     *
     * @param  [type] $key [description]
     * @param  [type] $gs  [description]
     * @param  [type] $ge  [description]
     * @param  [type] $ls  [description]
     * @param  [type] $le  [description]
     * @param  string $ind [description]
     * @return [type]      [description]
     */
    function print_r($key,$gs,$ge,$ls,$le,$ind=' '){
        $o='';
        if(strlen($ind)>3)return;
        if(is_array($key)){
            $o=$gs;
            foreach($key as $a=>$b){
                $o.= $ind.$ls.$a.': '.$this->print_r($b,$gs,$ge,$ls,$le,$ind.' ').$le;
            }
            $o.=$ge;

        }elseif(is_object($key)){
            $o.='Object '.get_class($key);
        }else{
            $o.=$gs?htmlspecialchars($key):$key;
        }
        return $o;
    }

    /**
     * Classes define a DOC constant which points to a on-line resource
     * containing documentation for given class. This method will
     * return full URL for the specified object.
     *
     * @return [type] [description]
     */
    function getDocURL($o)
    {
        if(!is_object($o))return false;

        if(!$o instanceof AbstractObject)return false;

        /*$refl = new ReflectionClass($o);
        $parent = $refl->getParentClass();

        if($parent) {
            // check to make sure property is overriden in child
            $const = $parent->getConstants();
        var_Dump($const);
            if ($const['DOC'] == $o::DOC) return false;
        }
        */

        $url=$o::DOC;
        if(substr($url,0,4)!='http')return 'http://book.agiletoolkit.org/'.$url.'.html';

        return $url;
    }

    function backtrace($sh=null,$backtrace=null){

        $output  = '
';
        $output .= "
\n";
        $output .= "
File	Object Name	Stack Trace	Help
";
        if(!isset($backtrace)) $backtrace=debug_backtrace();
        $sh-=2;

        $n=0;
        foreach($backtrace as $bt){
            $n++;
            $args = '';
            if(!isset($bt['args']))continue;
            foreach($bt['args'] as $a){
                if(!empty($args)){
                    $args .= ', ';
                }
                switch (gettype($a)) {
                    case 'integer':
                    case 'double':
                        $args .= $a;
                        break;
                    case 'string':
                        $a = htmlspecialchars(substr($a, 0, 128)).((strlen($a) > 128) ? '...' : '');
                        $args .= "\"$a\"";
                        break;
                    case 'array':
                        $args .= "Array(".count($a).")";
                        break;
                    case 'object':
                        $args .= "Object(".get_class($a).")";
                        break;
                    case 'resource':
                        $args .= "Resource(".strstr((string)$a, '#').")";
                        break;
                    case 'boolean':
                        $args .= $a ? 'True' : 'False';
                        break;
                    case 'NULL':
                        $args .= 'Null';
                        break;
                    default:
                        $args .= 'Unknown';
                }
            }

            if(($sh==null && strpos($bt['file'],'/atk4/lib/')===false) || (!is_int($sh) && $bt['function']==$sh)){
                $sh=$n;
            }

            $doc = $this->getDocURL($bt['object']);
            if($doc) $doc.='#'.get_class($bt['object']).'::'.$bt['function'];

            $output .= "
".htmlspecialchars(dirname($bt['file']))."/".
                "".htmlspecialchars(basename($bt['file']))."";
            $output .= ":{$bt['line']} 	";
            $name=(!isset($bt['object']->name))?get_class($bt['object']):$bt['object']->name;
            if($name)$output .= "".$name."	";else $output.="	";
            $output .= "".get_class($bt['object'])."{$bt['type']}{$bt['function']}($args)	";

            if($doc){
                $output .="	";

            }else{
                $output .= ' 	';

            }
            $output.='
';
        }
        $output .= "

\n";
        return $output;
    }

    /**
     * Returns Textual representation of the exception
     *
     * @return string
     */
    function getText()
    {
        $text = '';
        $args = array();
        foreach ($this->more_info as $key => $value) {
            if (is_array($value)) {
                $value = 'Array()';
            }
            $args[] = $key . '=' . $value;
        }

        $text .= get_class($this) . ': ' . $this->getMessage() .
                 ' (' . join(', ', $args) . ')';
        $text .= ' in ' . $this->getMyFile() . ':' . $this->getMyLine();
        return $text;
    }

    /**
     * Redefine this function to add additional HTML output
     *
     * @return string
     */
    function getDetailedHTML()
    {
        return '';
    }

    /**
     * Undocumented
     *
     * @return string
     * @todo Check this method, looks something useless. Optionally used only in Logger class.
     */
    function getAdditionalMessage()
    {
        return $this->recommendation;
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace Microsoft.Xml.Serialization
{
    using System.Reflection;
    using System.Reflection.Emit;
    using System.Collections;
    using System.IO;
    using System;
    using System.Text;
    using Microsoft.Xml;
    using System.Threading;
    using System.Security;

    using System.Diagnostics;
    using Microsoft.CodeDom.Compiler;
    using System.Globalization;
    using System.Runtime.Versioning;

    internal class TempAssembly
    {
        internal const string GeneratedAssemblyNamespace = "System.Xml.Serialization.GeneratedAssembly";
        private Assembly _assembly;
        private bool _pregeneratedAssmbly = false;
        private XmlSerializerImplementation _contract = null;
        private Hashtable _writerMethods;
        private Hashtable _readerMethods;
        private TempMethodDictionary _methods;
        private static object[] s_emptyObjectArray = new object[0];
        private Hashtable _assemblies = new Hashtable();

        internal class TempMethod
        {
            internal MethodInfo writeMethod;
            internal MethodInfo readMethod;
            internal string name;
            internal string ns;
            internal bool isSoap;
            internal string methodKey;
        }

        private TempAssembly()
        {
        }

        internal TempAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, string location)
        {
            throw new NotImplementedException();
        }

        internal TempAssembly(XmlMapping[] xmlMappings, Assembly assembly, XmlSerializerImplementation contract)
        {
            _assembly = assembly;
            InitAssemblyMethods(xmlMappings);
            _contract = contract;
            _pregeneratedAssmbly = true;
        }
        internal TempAssembly(XmlSerializerImplementation contract)
        {
            _contract = contract;
            _pregeneratedAssmbly = true;
        }

        internal XmlSerializerImplementation Contract
        {
            get
            {
                if (_contract == null)
                {
                    _contract = (XmlSerializerImplementation)Activator.CreateInstance(GetTypeFromAssembly(_assembly, "XmlSerializerContract"));
                }
                return _contract;
            }
        }

        internal void InitAssemblyMethods(XmlMapping[] xmlMappings)
        {
            _methods = new TempMethodDictionary();
            for (int i = 0; i < xmlMappings.Length; i++)
            {
                TempMethod method = new TempMethod();
                method.isSoap = xmlMappings[i].IsSoap;
                method.methodKey = xmlMappings[i].Key;
                XmlTypeMapping xmlTypeMapping = xmlMappings[i] as XmlTypeMapping;
                if (xmlTypeMapping != null)
                {
                    method.name = xmlTypeMapping.ElementName;
                    method.ns = xmlTypeMapping.Namespace;
                }
                _methods.Add(xmlMappings[i].Key, method);
            }
        }

        internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract)
        {
            throw new NotImplementedException();
        }

        // SxS: This method does not take any resource name and does not expose any resources to the caller.
        // It's OK to suppress the SxS warning.
        // // [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        // [ResourceExposure(ResourceScope.None)]
        private static MethodInfo GetMethodFromType(Type type, string methodName, Assembly assembly)
        {
            MethodInfo method = type.GetMethod(methodName);
            if (method != null)
                return method;

            MissingMethodException missingMethod = new MissingMethodException(string.Format("{0}:{1}", type.FullName, methodName));
            if (assembly != null)
            {
                throw new InvalidOperationException(string.Format(ResXml.XmlSerializerExpired, assembly.FullName, /*assembly.CodeBase*/ null), missingMethod);
            }
            throw missingMethod;
        }

        internal static Type GetTypeFromAssembly(Assembly assembly, string typeName)
        {
            typeName = GeneratedAssemblyNamespace + "." + typeName;
            Type type = assembly.GetType(typeName);
            if (type == null) throw new InvalidOperationException(string.Format(ResXml.XmlMissingType, typeName, assembly.FullName));
            return type;
        }

        internal bool CanRead(XmlMapping mapping, XmlReader xmlReader)
        {
            if (mapping == null)
                return false;

            if (mapping.Accessor.Any)
            {
                return true;
            }
            TempMethod method = _methods[mapping.Key];
            return xmlReader.IsStartElement(method.name, method.ns);
        }

        private string ValidateEncodingStyle(string encodingStyle, string methodKey)
        {
            if (encodingStyle != null && encodingStyle.Length > 0)
            {
                if (_methods[methodKey].isSoap)
                {
                    if (encodingStyle != Soap.Encoding && encodingStyle != Soap12.Encoding)
                    {
                        throw new InvalidOperationException(string.Format(ResXml.XmlInvalidEncoding3, encodingStyle, Soap.Encoding, Soap12.Encoding));
                    }
                }
                else
                {
                    throw new InvalidOperationException(string.Format(ResXml.XmlInvalidEncodingNotEncoded1, encodingStyle));
                }
            }
            else
            {
                if (_methods[methodKey].isSoap)
                {
                    encodingStyle = Soap.Encoding;
                }
            }
            return encodingStyle;
        }

        internal object InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, string encodingStyle)
        {
            XmlSerializationReader reader = null;
            try
            {
                encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key);
                reader = Contract.Reader;
                reader.Init(xmlReader, events, encodingStyle, this);
                if (_methods[mapping.Key].readMethod == null)
                {
                    if (_readerMethods == null)
                    {
                        _readerMethods = Contract.ReadMethods;
                    }
                    string methodName = (string)_readerMethods[mapping.Key];
                    if (methodName == null)
                    {
                        throw new InvalidOperationException(string.Format(ResXml.XmlNotSerializable, mapping.Accessor.Name));
                    }
                    _methods[mapping.Key].readMethod = GetMethodFromType(reader.GetType(), methodName, _pregeneratedAssmbly ? _assembly : null);
                }
                return _methods[mapping.Key].readMethod.Invoke(reader, s_emptyObjectArray);
            }
            catch (SecurityException e)
            {
                throw new InvalidOperationException(ResXml.XmlNoPartialTrust, e);
            }
            finally
            {
                if (reader != null)
                    reader.Dispose();
            }
        }

        internal void InvokeWriter(XmlMapping mapping, XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
        {
            XmlSerializationWriter writer = null;
            try
            {
                encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key);
                writer = Contract.Writer;
                writer.Init(xmlWriter, namespaces, encodingStyle, id, this);
                if (_methods[mapping.Key].writeMethod == null)
                {
                    if (_writerMethods == null)
                    {
                        _writerMethods = Contract.WriteMethods;
                    }
                    string methodName = (string)_writerMethods[mapping.Key];
                    if (methodName == null)
                    {
                        throw new InvalidOperationException(string.Format(ResXml.XmlNotSerializable, mapping.Accessor.Name));
                    }
                    _methods[mapping.Key].writeMethod = GetMethodFromType(writer.GetType(), methodName, _pregeneratedAssmbly ? _assembly : null);
                }
                _methods[mapping.Key].writeMethod.Invoke(writer, new object[] { o });
            }
            catch (SecurityException e)
            {
                throw new InvalidOperationException(ResXml.XmlNoPartialTrust, e);
            }
            finally
            {
                if (writer != null)
                    writer.Dispose();
            }
        }

        internal Assembly GetReferencedAssembly(string name)
        {
            return _assemblies != null && name != null ? (Assembly)_assemblies[name] : null;
        }

        internal bool NeedAssembyResolve
        {
            get { return _assemblies != null && _assemblies.Count > 0; }
        }

        internal sealed class TempMethodDictionary : DictionaryBase
        {
            internal TempMethod this[string key]
            {
                get
                {
                    return (TempMethod)Dictionary[key];
                }
            }
            internal void Add(string key, TempMethod value)
            {
                Dictionary.Add(key, value);
            }
        }
    }

    internal sealed class XmlSerializerCompilerParameters
    {
    }

    internal class TempAssemblyCacheKey
    {
        private string _ns;
        private object _type;

        internal TempAssemblyCacheKey(string ns, object type)
        {
            _type = type;
            _ns = ns;
        }

        public override bool Equals(object o)
        {
            TempAssemblyCacheKey key = o as TempAssemblyCacheKey;
            if (key == null) return false;
            return (key._type == _type && key._ns == _ns);
        }

        public override int GetHashCode()
        {
            return ((_ns != null ? _ns.GetHashCode() : 0) ^ (_type != null ? _type.GetHashCode() : 0));
        }
    }

    internal class TempAssemblyCache
    {
        private Hashtable _cache = new Hashtable();

        internal TempAssembly this[string ns, object o]
        {
            get { return (TempAssembly)_cache[new TempAssemblyCacheKey(ns, o)]; }
        }

        internal void Add(string ns, object o, TempAssembly assembly)
        {
            TempAssemblyCacheKey key = new TempAssemblyCacheKey(ns, o);
            lock (this)
            {
                if (_cache[key] == assembly) return;
                Hashtable clone = new Hashtable();
                foreach (object k in _cache.Keys)
                {
                    clone.Add(k, _cache[k]);
                }
                _cache = clone;
                _cache[key] = assembly;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""Custom database fields."""
from django.db import connection
from django.db.models import constants
from django.db.models.fields import SlugField
from django.utils.text import slugify

from resolwe.flow.exceptions import SlugError

MAX_SLUG_SEQUENCE_DIGITS = 9

class ResolweSlugField(SlugField):
    """Slug field."""

    def __init__(self, *args, **kwargs):
        """Initialize field."""
        self.populate_from = kwargs.pop("populate_from", None)

        # unique_with value can be string or tuple
        self.unique_with = kwargs.pop("unique_with", ())
        if isinstance(self.unique_with, str):
            self.unique_with = (self.unique_with,)

        if self.unique_with:
            # we will do "manual" granular check below
            kwargs["unique"] = False

        super().__init__(*args, **kwargs)

    def deconstruct(self):
        """Deconstruct method."""
        name, path, args, kwargs = super().deconstruct()

        if self.populate_from is not None:
            kwargs["populate_from"] = self.populate_from

        if self.unique_with != ():
            kwargs["unique_with"] = self.unique_with
            kwargs.pop("unique", None)

        return name, path, args, kwargs

    def _get_unique_constraints(self, instance):
        """Return SQL filter for filtering by fields in ``unique_with`` attribute.

        Filter is returned as tuple of two elements where first one is
        placeholder which is safe to insert into SQL query and second
        one may include potentially dangerous values and must be passed
        to SQL query in ``params`` attribute to make sure it is properly
        escaped.
        """
        constraints_expression = []
        constraints_values = {}
        for field_name in self.unique_with:
            if constants.LOOKUP_SEP in field_name:
                raise NotImplementedError(
                    "`unique_with` constraint does not support lookups by related models."
                )

            field = instance._meta.get_field(field_name)
            field_value = getattr(instance, field_name)

            # Convert value to the database representation.
            field_db_value = field.get_prep_value(field_value)

            constraint_key = "unique_" + field_name
            constraints_expression.append(
                "{} = %({})s".format(
                    connection.ops.quote_name(field.column), constraint_key
                )
            )
            constraints_values[constraint_key] = field_db_value

        if not constraints_expression:
            return "", []

        constraints_expression = "AND " + " AND ".join(constraints_expression)
        return constraints_expression, constraints_values

    def _get_populate_from_value(self, instance):
        """Get the value from ``populate_from`` attribute."""
        if hasattr(self.populate_from, "__call__"):
            # ResolweSlugField(populate_from=lambda instance: ...)
            return self.populate_from(instance)
        else:
            # ResolweSlugField(populate_from='foo')
            attr = getattr(instance, self.populate_from)
            return attr() if callable(attr) else attr

    def pre_save(self, instance, add):
        """Ensure slug uniqunes before save."""
        slug = self.value_from_object(instance)

        # We don't want to change slug defined by user.
        predefined_slug = bool(slug)

        if not slug and self.populate_from:
            slug = self._get_populate_from_value(instance)

        if slug:
            slug = slugify(slug)

        if not slug:
            slug = None

            if not self.blank:
                slug = instance._meta.model_name
            elif not self.null:
                slug = ""

        if slug:
            # Make sure that auto generated slug with added sequence
            # won't excede maximal length.
            # Validation of predefined slugs is handled by Django.
            if not predefined_slug:
                slug = slug[: (self.max_length - MAX_SLUG_SEQUENCE_DIGITS - 1)]

            constraints_placeholder, constraints_values = self._get_unique_constraints(
                instance
            )

            instance_pk_name = instance._meta.pk.name

            # Safe values - make sure that there is no chance of SQL injection.
            query_params = {
                "constraints_placeholder": constraints_placeholder,
                "slug_column": connection.ops.quote_name(self.column),
                "slug_len": len(slug),
                "table_name": connection.ops.quote_name(self.model._meta.db_table),
                "pk_neq_placeholder": "AND {} != %(instance_pk)s".format(
                    instance_pk_name
                )
                if instance.pk
                else "",
            }

            # SQL injection unsafe values - will be escaped.
            # Keys prefixed with `unique_` are reserved for `constraints_values` dict.
            query_escape_params = {
                "slug": slug,
                "slug_regex": "^{}(-[0-9]*)?$".format(slug),
            }
            query_escape_params.update(constraints_values)
            if instance.pk:
                query_escape_params["instance_pk"] = instance.pk

            with connection.cursor() as cursor:
                # TODO: Slowest part of this query is `MAX` function. It can
                #       be optimized by indexing slug column by slug sequence.
                #       https://www.postgresql.org/docs/9.4/static/indexes-expressional.html
                cursor.execute(
                    """
                    SELECT
                        CASE
                            WHEN (
                                EXISTS(
                                    SELECT 1 FROM {table_name} WHERE (
                                        {slug_column} = %(slug)s
                                        {pk_neq_placeholder}
                                        {constraints_placeholder}
                                    )
                                )
                            ) THEN MAX(slug_sequence) + 1
                            ELSE NULL
                        END
                    FROM (
                        SELECT COALESCE(
                            NULLIF(
                                RIGHT({slug_column}, -{slug_len}-1),
                                ''
                            ),
                            '1'
                        )::text::integer AS slug_sequence
                        FROM {table_name} WHERE (
                            {slug_column} ~ %(slug_regex)s
                            {pk_neq_placeholder}
                            {constraints_placeholder}
                        )
                    ) AS tmp
                    """.format(
                        **query_params
                    ),
                    params=query_escape_params,
                )
                result = cursor.fetchone()[0]

            if result is not None:
                if predefined_slug:
                    raise SlugError(
                        "Slug '{}' (version {}) is already taken.".format(
                            slug, instance.version
                        )
                    )

                if len(str(result)) > MAX_SLUG_SEQUENCE_DIGITS:
                    raise SlugError(
                        "Auto-generated slug sequence too long - please choose a different slug."
                    )

                slug = "{}-{}".format(slug, result)

            # Make the updated slug available as instance attribute.
            setattr(instance, self.name, slug)

        return slug


text:
<?php
$this->load->view('partials/head', ['title' => 'Ajax Posts']);
$this->load->view('partials/foot');
?>
<form style="display: none;" action="/posts/create" class="panel" id="form">

		Add<input class="panel-input" name="title" placeholder="Title">&#10008

		<textarea id="trigger" name="description" class="note" placeholder="Enter your note here."></textarea>

</form>
<?php
	foreach ($posts as $post){
		$this->load->view('partials/nav', ['title' => $post['title'], 'description' => $post['description'], 'id' => $post['id']]);
	}
	if (empty($posts)){
		echo "<button id='new' class='btn btn-primary'>New Note</button>";
	}
?>


text:
/**
 * gemini-scrollbar
 * @version 1.2.9
 * @link http://noeldelgado.github.io/gemini-scrollbar/
 * @license MIT
 */
(function() {
    var SCROLLBAR_WIDTH, CLASSNAMES, addClass, removeClass, getScrollbarWidth;

    CLASSNAMES = {
        element: 'gm-scrollbar-container',
        verticalScrollbar: 'gm-scrollbar -vertical',
        horizontalScrollbar: 'gm-scrollbar -horizontal',
        thumb: 'thumb',
        view: 'gm-scroll-view',
        autoshow: 'gm-autoshow',
        disable: 'gm-scrollbar-disable-selection',
        prevented: 'gm-prevented',
        scrollbarWidthTest: 'gm-test'
    };

    getScrollbarWidth = function getScrollbarWidth() {
        var scrollDiv = document.createElement("div");
        scrollDiv.className = CLASSNAMES.scrollbarWidthTest;
        document.body.appendChild(scrollDiv);

        var scrollbarWidth = (scrollDiv.offsetWidth - scrollDiv.clientWidth);
        document.body.removeChild(scrollDiv);

        return scrollbarWidth;
    };

    addClass = function addClass(el, classNames) {
        if (el.classList) {
            return classNames.forEach(function(cl) {
                el.classList.add(cl);
            });
        }

        el.className += ' ' + classNames.join(' ');
    };

    removeClass = function removeClass(el, classNames) {
        if (el.classList) {
            return classNames.forEach(function(cl) {
                el.classList.remove(cl);
            });
        }

        el.className = el.className.replace(new RegExp('(^|\\b)' + classNames.join('|') + '(\\b|$)', 'gi'), ' ');
    };

    function GeminiScrollbar(config) {
        this.element = null;
        this.autoshow = false;
        this.createElements = true;

        Object.keys(config || {}).forEach(function (propertyName) {
            this[propertyName] = config[propertyName];
        }, this);

        SCROLLBAR_WIDTH = getScrollbarWidth();

        this._cache = {events: {}};
        this._created = false;
        this._cursorDown = false;
        this._prevPageX = 0;
        this._prevPageY = 0;

        this._document = null;
        this._window = null;
        this._viewElement = this.element;
        this._scrollbarVerticalElement = null;
        this._thumbVerticalElement = null;
        this._scrollbarHorizontalElement = null;
        this._scrollbarHorizontalElement = null;
    }

    GeminiScrollbar.prototype.create = function create() {
        //if (SCROLLBAR_WIDTH === 0) {
        //    addClass(this.element, [CLASSNAMES.prevented]);
        //    return this;
        //}

        if (this._created === true) {
            console.warn('calling on a already-created object');
            return this;
        }

        if (this.autoshow) {
            addClass(this.element, [CLASSNAMES.autoshow]);
        }

        this._document = document;
        this._window = window;

        if (this.createElements === true) {
            this._viewElement = document.createElement('div');
            this._scrollbarVerticalElement = document.createElement('div');
            this._thumbVerticalElement = document.createElement('div');
            this._scrollbarHorizontalElement = document.createElement('div');
            this._thumbHorizontalElement = document.createElement('div');
            while(this.element.childNodes.length > 0) {
                this._viewElement.appendChild(this.element.childNodes[0]);
            }

            this._scrollbarVerticalElement.appendChild(this._thumbVerticalElement);
            this._scrollbarHorizontalElement.appendChild(this._thumbHorizontalElement);
            this.element.appendChild(this._scrollbarVerticalElement);
            this.element.appendChild(this._scrollbarHorizontalElement);
            this.element.appendChild(this._viewElement);
        } else {
            this._viewElement = this.element.querySelector('.' + CLASSNAMES.view);
            this._scrollbarVerticalElement = this.element.querySelector('.' + CLASSNAMES.verticalScrollbar.split(' ').join('.'));
            this._thumbVerticalElement = this._scrollbarVerticalElement.querySelector('.' + CLASSNAMES.thumb);
            this._scrollbarHorizontalElement = this.element.querySelector('.' + CLASSNAMES.horizontalScrollbar.split(' ').join('.'));
            this._thumbHorizontalElement = this._scrollbarHorizontalElement.querySelector('.' + CLASSNAMES.thumb);
        }

        addClass(this.element, [CLASSNAMES.element]);
        addClass(this._viewElement, [CLASSNAMES.view]);
        addClass(this._scrollbarVerticalElement, CLASSNAMES.verticalScrollbar.split(/\s/));
        addClass(this._scrollbarHorizontalElement, CLASSNAMES.horizontalScrollbar.split(/\s/));
        addClass(this._thumbVerticalElement, [CLASSNAMES.thumb]);
        addClass(this._thumbHorizontalElement, [CLASSNAMES.thumb]);

        this._scrollbarVerticalElement.style.display = '';
        this._scrollbarHorizontalElement.style.display = '';

        this._created = true;

        return this._bindEvents().update();
    };

    GeminiScrollbar.prototype.update = function update() {
        if (SCROLLBAR_WIDTH === 0) {
            return this;
        }

        if (this._created === false) {
            console.warn('calling on a not-yet-created object');
            return this;
        }

        var heightPercentage, widthPercentage;

        this._viewElement.style.width = ((this.element.offsetWidth + SCROLLBAR_WIDTH).toString() + 'px');
        this._viewElement.style.height = ((this.element.offsetHeight + SCROLLBAR_WIDTH).toString() + 'px');

        heightPercentage = (this._viewElement.clientHeight * 100 / this._viewElement.scrollHeight);
        widthPercentage = (this._viewElement.clientWidth * 100 / this._viewElement.scrollWidth);

        this._thumbVerticalElement.style.height = (heightPercentage < 100) ? (heightPercentage + '%') : '';
        this._thumbHorizontalElement.style.width = (widthPercentage < 100) ? (widthPercentage + '%') : '';

        this._scrollHandler();

        return this;
    };

    GeminiScrollbar.prototype.destroy = function destroy() {
        if (SCROLLBAR_WIDTH === 0) {
            return this;
        }

        if (this._created === false) {
            console.warn('calling on a not-yet-created object');
            return this;
        }

        this._unbinEvents();

        removeClass(this.element, [CLASSNAMES.element, CLASSNAMES.autoshow]);

        if (this.createElements === true) {
            this.element.removeChild(this._scrollbarVerticalElement);
            this.element.removeChild(this._scrollbarHorizontalElement);
            while(this._viewElement.childNodes.length > 0) {
                this.element.appendChild(this._viewElement.childNodes[0]);
            }
            this.element.removeChild(this._viewElement);
        } else {
            this._viewElement.style.width = '';
            this._viewElement.style.height = '';
            this._scrollbarVerticalElement.style.display = 'none';
            this._scrollbarHorizontalElement.style.display = 'none';
        }

        this._created = false;
        this._document = this._window = null;

        return null;
    };

    GeminiScrollbar.prototype.getViewElement = function() {
        return this._viewElement;
    };

    GeminiScrollbar.prototype._bindEvents = function() {
        this._cache.events.scrollHandler = this._scrollHandler.bind(this);
        this._cache.events.clickVerticalTrackHandler = this._clickVerticalTrackHandler.bind(this);
        this._cache.events.clickHorizontalTrackHandler = this._clickHorizontalTrackHandler.bind(this);
        this._cache.events.clickVerticalThumbHandler = this._clickVerticalThumbHandler.bind(this);
        this._cache.events.clickHorizontalThumbHandler = this._clickHorizontalThumbHandler.bind(this);
        this._cache.events.mouseUpDocumentHandler = this._mouseUpDocumentHandler.bind(this);
        this._cache.events.mouseMoveDocumentHandler = this._mouseMoveDocumentHandler.bind(this);
        this._cache.events.resizeWindowHandler = this.update.bind(this);

        this._viewElement.addEventListener('scroll', this._cache.events.scrollHandler);
        this._scrollbarVerticalElement.addEventListener('mousedown', this._cache.events.clickVerticalTrackHandler);
        this._scrollbarHorizontalElement.addEventListener('mousedown', this._cache.events.clickHorizontalTrackHandler);
        this._thumbVerticalElement.addEventListener('mousedown', this._cache.events.clickVerticalThumbHandler);
        this._thumbHorizontalElement.addEventListener('mousedown', this._cache.events.clickHorizontalThumbHandler);
        this._document.addEventListener('mouseup', this._cache.events.mouseUpDocumentHandler);
        this._window.addEventListener('resize', this._cache.events.resizeWindowHandler);

        return this;
    };

    GeminiScrollbar.prototype._unbinEvents = function() {
        this._viewElement.removeEventListener('scroll', this._cache.events.scrollHandler);
        this._scrollbarVerticalElement.removeEventListener('mousedown', this._cache.events.clickVerticalTrackHandler);
        this._scrollbarHorizontalElement.removeEventListener('mousedown', this._cache.events.clickHorizontalTrackHandler);
        this._thumbVerticalElement.removeEventListener('mousedown', this._cache.events.clickVerticalThumbHandler);
        this._thumbHorizontalElement.removeEventListener('mousedown', this._cache.events.clickHorizontalThumbHandler);
        this._document.removeEventListener('mouseup', this._cache.events.mouseUpDocumentHandler);
        this._document.removeEventListener('mousemove', this._cache.events.mouseMoveDocumentHandler);
        this._window.removeEventListener('resize', this._cache.events.resizeWindowHandler);

        return this;
    };

    GeminiScrollbar.prototype._scrollHandler = function() {
        var viewElement, x, y;

        viewElement = this._viewElement;
        y = ((viewElement.scrollTop * 100) / viewElement.clientHeight);
        x = ((viewElement.scrollLeft * 100) / viewElement.clientWidth);

        this._thumbVerticalElement.style.msTransform = 'translateY(' + y + '%)';
        this._thumbVerticalElement.style.webkitTransform = 'translateY(' + y + '%)';
        this._thumbVerticalElement.style.transform = 'translateY(' + y + '%)';

        this._thumbHorizontalElement.style.msTransform = 'translateX(' + x + '%)';
        this._thumbHorizontalElement.style.webkitTransform = 'translateX(' + x + '%)';
        this._thumbHorizontalElement.style.transform = 'translateX(' + x + '%)';
    };

    GeminiScrollbar.prototype._clickVerticalTrackHandler = function(e) {
        var offset = Math.abs(e.target.getBoundingClientRect().top - e.clientY);
        var thumbHalf = (this._thumbVerticalElement.offsetHeight / 2);
        var thumbPositionPercentage = ((offset - thumbHalf) * 100 / this._scrollbarVerticalElement.offsetHeight);

        this._viewElement.scrollTop = (thumbPositionPercentage * this._viewElement.scrollHeight / 100);
    };

    GeminiScrollbar.prototype._clickHorizontalTrackHandler = function(e) {
        var offset = Math.abs(e.target.getBoundingClientRect().left - e.clientX);
        var thumbHalf = (this._thumbHorizontalElement.offsetWidth / 2);
        var thumbPositionPercentage = ((offset - thumbHalf) * 100 / this._scrollbarHorizontalElement.offsetWidth);

        this._viewElement.scrollLeft = (thumbPositionPercentage * this._viewElement.scrollWidth / 100);
    };

    GeminiScrollbar.prototype._clickVerticalThumbHandler = function(e) {
        this._startDrag(e);
        this._prevPageY = (e.currentTarget.offsetHeight - (e.clientY - e.currentTarget.getBoundingClientRect().top));
    };

    GeminiScrollbar.prototype._clickHorizontalThumbHandler = function(e) {
        this._startDrag(e);
        this._prevPageX = (e.currentTarget.offsetWidth - (e.clientX - e.currentTarget.getBoundingClientRect().left));
    };

    GeminiScrollbar.prototype._startDrag = function(e) {
        e.stopImmediatePropagation();
        this._cursorDown = true;
        addClass(document.body, [CLASSNAMES.disable]);
        this._document.addEventListener('mousemove', this._cache.events.mouseMoveDocumentHandler);
        this._document.onselectstart = function() {return false;};
    };

    GeminiScrollbar.prototype._mouseUpDocumentHandler = function() {
        this._cursorDown = false;
        this._prevPageX = this._prevPageY = 0;
        removeClass(document.body, [CLASSNAMES.disable]);
        this._document.removeEventListener('mousemove', this._cache.events.mouseMoveDocumentHandler);
        this._document.onselectstart = null;
    };

    GeminiScrollbar.prototype._mouseMoveDocumentHandler = function(e) {
        if (this._cursorDown === false) {
            return void 0;
        }

        var offset, thumbClickPosition, thumbPositionPercentage;

        if (this._prevPageY) {
            offset = ((this._scrollbarVerticalElement.getBoundingClientRect().top - e.clientY) * -1);
            thumbClickPosition = (this._thumbVerticalElement.offsetHeight - this._prevPageY);
            thumbPositionPercentage = ((offset - thumbClickPosition) * 100 / this._scrollbarVerticalElement.offsetHeight);
            this._viewElement.scrollTop = (thumbPositionPercentage * this._viewElement.scrollHeight / 100);
            return void 0;
        }

        if (this._prevPageX) {
            offset = ((this._scrollbarHorizontalElement.getBoundingClientRect().left - e.clientX) * -1);
            thumbClickPosition = (this._thumbHorizontalElement.offsetWidth - this._prevPageX);
            thumbPositionPercentage = ((offset - thumbClickPosition) * 100 / this._scrollbarHorizontalElement.offsetWidth);
            this._viewElement.scrollLeft = (thumbPositionPercentage * this._viewElement.scrollWidth / 100);
        }
    };

    if (typeof exports === 'object') {
        module.exports = GeminiScrollbar;
    } else {
        window.GeminiScrollbar = GeminiScrollbar;
    }
})();


text:
from __future__ import absolute_import

__all__ = ["FeatureManager"]

from django.conf import settings

from sentry.plugins import plugins
from sentry.utils.safe import safe_execute

from .base import Feature
from .exceptions import FeatureNotRegistered

class FeatureManager(object):
    def __init__(self):
        self._registry = {}

    def all(self, feature_type=Feature):
        """
        Get a mapping of feature name -> feature class, optionally specific to a
        particular feature type.
        """
        return {k: v for k, v in self._registry.items() if v == feature_type}

    def add(self, name, cls=Feature):
        """
        Register a feature.

        The passed class is a Feature container object, this object can be used
        to encapsulate the context associated to a feature.

        >>> FeatureManager.has('my:feature', actor=request.user)
        """
        self._registry[name] = cls

    def get(self, name, *args, **kwargs):
        """
        Lookup a registered feature handler given the feature name.

        >>> FeatureManager.get('my:feature', actor=request.user)
        """
        try:
            cls = self._registry[name]
        except KeyError:
            raise FeatureNotRegistered(name)
        return cls(name, *args, **kwargs)

    def has(self, name, *args, **kwargs):
        """
        Determine if a feature is enabled.

        Features are checked in the following order:

        1. Execute Plugin feature handlers. Any plugin which returns a list of
           instantiated ``feature.handler.FeatureHandler`` objects will have
           each of their handlers executed in the order they are declared.

           When each handler is executed should the handler return None instead
           of True or False (feature enabled / disabled), the next registered
           plugin feature handler will be executed.

        2. The default configuration of the feature. This can be located in
           sentry.conf.server.SENTRY_FEATURES.

        Depending on the Feature class, additional arguments may need to be
        provided to assign organiation or project context to the feature.

        >>> FeatureManager.has('organizations:feature', organization, actor=request.user)
        """
        actor = kwargs.pop("actor", None)
        feature = self.get(name, *args, **kwargs)

        # Check plugin feature handlers
        rv = self._get_plugin_value(feature, actor)
        if rv is not None:
            return rv

        rv = settings.SENTRY_FEATURES.get(feature.name, False)
        if rv is not None:
            return rv

        # Features are by default disabled if no plugin or default enables them
        return False

    def _get_plugin_value(self, feature, actor):
        for plugin in plugins.all(version=2):
            handlers = safe_execute(plugin.get_feature_hooks, _with_transaction=False)
            for handler in handlers or ():
                rv = handler(feature, actor)
                if rv is not None:
                    return rv
        return None


text:
package alluxio.server.ft;

import alluxio.AlluxioTestDirectory;
import alluxio.Constants;
import alluxio.PropertyKey;
import alluxio.master.backcompat.BackwardsCompatibilityJournalGenerator;
import alluxio.master.backcompat.Journal;
import alluxio.master.backcompat.TestOp;
import alluxio.multi.process.Clients;
import alluxio.multi.process.MultiProcessCluster;
import alluxio.multi.process.MultiProcessCluster.Builder;
import alluxio.multi.process.PortCoordination;
import alluxio.security.LoginUser;
import alluxio.testutils.BaseIntegrationTest;

import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Assume;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Tests that the current version can read journals from previous versions, including the current
 * version.
 *
 * To cover many types of journal entries, the test runs a series of TestOps, each of which makes
 * some independent modification to master state, and has a method to verify that the change was
 * correctly applied. To add a new TestOp, implement the TestOp interface or extend FsTestOp, and
 * add your TestOp to the OPS list. Then either re-generate all journal artifacts from previous
 * versions (not easy at the moment, could add tooling for this later), or implement
 * TestOp#supportsVersion to only match the latest version and future versions.
 */
public final class BackwardsCompatibilityIntegrationTest extends BaseIntegrationTest {
  private static final Logger LOG =
      LoggerFactory.getLogger(BackwardsCompatibilityIntegrationTest.class);

  private MultiProcessCluster mCluster;

  @After
  public void after() throws Exception {
    if (mCluster != null) {
      mCluster.destroy();
    }
  }

  @Test
  public void currentCompatibility() throws Exception {
    // Tests that the operation checks pass before and after restart.
    mCluster = MultiProcessCluster.newBuilder(PortCoordination.BACKWARDS_COMPATIBILITY)
        .setClusterName("BackwardsCompatibility")
        .setNumMasters(1)
        .setNumWorkers(1)
        .build();
    mCluster.start();
    mCluster.waitForAllNodesRegistered(30 * Constants.SECOND_MS);
    Clients clients = mCluster.getClients();

    for (TestOp op : BackwardsCompatibilityJournalGenerator.OPS) {
      op.apply(clients);
      op.check(clients);
    }
    mCluster.stopMasters();
    mCluster.startMasters();
    for (TestOp op : BackwardsCompatibilityJournalGenerator.OPS) {
      op.check(clients);
    }
  }

  @Test
  public void readOldJournals() throws Exception {
    Assume.assumeTrue("Journals must be replayed by the same user that generated them, so this "
        + "test must be run as root", LoginUser.get().getName().equals("root"));
    // Starts a cluster from each old journal, and checks that all operation checks pass.
    List<Journal> journals = Arrays
        .asList(new File(BackwardsCompatibilityJournalGenerator.OLD_JOURNALS_RESOURCE).listFiles())
        .stream().map(f -> Journal.parse(f.getAbsolutePath()))
        .filter(Optional::isPresent)
        .map(o -> o.get())
        .collect(Collectors.toList());
    for (Journal journal : journals) {
      System.out.printf("Checking journal %s\n", journal.getDir());
      LOG.info("Checking journal %s\n", journal.getDir());
      Builder builder = MultiProcessCluster.newBuilder(PortCoordination.BACKWARDS_COMPATIBILITY)
          .setClusterName("BackwardsCompatibility")
          .setNumMasters(1)
          .setNumWorkers(1);
      if (journal.isBackup()) {
        builder.addProperty(PropertyKey.MASTER_JOURNAL_INIT_FROM_BACKUP, journal.getDir());
      } else {
        File journalDir =
            AlluxioTestDirectory.createTemporaryDirectory("backwardsCompatibility-journal");
        FileUtils.copyDirectory(new File(journal.getDir()), new File(journalDir.getAbsolutePath()));
        builder.setNoFormat(true);
        builder.addProperty(PropertyKey.MASTER_JOURNAL_FOLDER, journalDir.getAbsolutePath());
      }
      mCluster = builder.build();
      try {
        mCluster.start();
        mCluster.waitForAllNodesRegistered(30 * Constants.SECOND_MS);
        Clients clients = mCluster.getClients();
        for (TestOp op : BackwardsCompatibilityJournalGenerator.OPS) {
          if (op.supportsVersion(journal.getVersion())) {
            op.check(clients);
          }
        }
      } finally {
        mCluster.destroy();
      }
    }
  }
}


text:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF } from '@angular/common';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { routes } from './app.routes';

import { HomeModule } from './home/home.module';
import { SharedModule } from './shared/shared.module';
import { PlaylistModule } from './playlist/playlist.module';

@NgModule({
  imports: [BrowserModule,
    HttpModule,
    RouterModule.forRoot(routes),
    PlaylistModule,
    HomeModule,
    SharedModule.forRoot()],
  declarations: [AppComponent],
  providers: [{
    provide: APP_BASE_HREF,
    useValue: '<%= APP_BASE %>'
  }],
  bootstrap: [AppComponent]
})

export class AppModule { }


text:
/* $Id$ */

#import "CKTranslationUnit.h"

@interface CKTranslationUnit( Private )

- ( id )initWithPath: ( NSString * )path text: ( NSString * )text index: ( CKIndex * )index args: ( NSArray * )args;

@end


text:
package org.wildfly.swarm.opentracing.tracer;

import org.wildfly.swarm.spi.api.Fraction;
import org.wildfly.swarm.spi.api.annotations.DeploymentModule;

/**
 * @author Pavol Loffay
 */
@DeploymentModule(name = "org.wildfly.swarm.opentracing.tracer", slot = "deployment")
public class OpenTracingTracerResolverFraction implements Fraction<OpenTracingTracerResolverFraction> {

}


text:
package ru.sendto.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;

import lombok.AccessLevel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;

/**
 * Class for exceptions
 *
 * @author Lev Nadeinsky
 */
@Data
@EqualsAndHashCode(callSuper = false)
@JsonTypeName("ref")
public class RequestInfo extends Dto {
	@JsonProperty("r")
	Dto request;
}


text:
from django.apps import apps
from django.dispatch import Signal
from django.utils import six

class_prepared = Signal(providing_args=["class"])

class ModelSignal(Signal):
    """
    Signal subclass that allows the sender to be lazily specified as a string
    of the `app_label.ModelName` form.
    """

    def __init__(self, *args, **kwargs):
        super(ModelSignal, self).__init__(*args, **kwargs)
        self.unresolved_references = {}
        class_prepared.connect(self._resolve_references)

    def _resolve_references(self, sender, **kwargs):
        opts = sender._meta
        reference = (opts.app_label, opts.object_name)
        try:
            receivers = self.unresolved_references.pop(reference)
        except KeyError:
            pass
        else:
            for receiver, weak, dispatch_uid in receivers:
                super(ModelSignal, self).connect(
                    receiver, sender=sender, weak=weak, dispatch_uid=dispatch_uid
                )

    def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
        if isinstance(sender, six.string_types):
            try:
                app_label, model_name = sender.split('.')
            except ValueError:
                raise ValueError(
                    "Specified sender must either be a model or a "
                    "model name of the 'app_label.ModelName' form."
                )
            try:
                sender = apps.get_registered_model(app_label, model_name)
            except LookupError:
                ref = (app_label, model_name)
                refs = self.unresolved_references.setdefault(ref, [])
                refs.append((receiver, weak, dispatch_uid))
                return
        super(ModelSignal, self).connect(
            receiver, sender=sender, weak=weak, dispatch_uid=dispatch_uid
        )

pre_init = ModelSignal(providing_args=["instance", "args", "kwargs"], use_caching=True)
post_init = ModelSignal(providing_args=["instance"], use_caching=True)

pre_save = ModelSignal(providing_args=["instance", "raw", "using", "update_fields"],
                       use_caching=True)
post_save = ModelSignal(providing_args=["instance", "raw", "created", "using", "update_fields"], use_caching=True)

pre_delete = ModelSignal(providing_args=["instance", "using"], use_caching=True)
post_delete = ModelSignal(providing_args=["instance", "using"], use_caching=True)

m2m_changed = ModelSignal(
    providing_args=["action", "instance", "reverse", "model", "pk_set", "using"],
    use_caching=True,
)

pre_migrate = Signal(providing_args=["app_config", "verbosity", "interactive", "using"])
post_migrate = Signal(providing_args=["app_config", "verbosity", "interactive", "using"])

pre_syncdb = Signal(providing_args=["app", "create_models", "verbosity", "interactive", "db"])
post_syncdb = Signal(providing_args=["class", "app", "created_models", "verbosity", "interactive", "db"])


text:
package si.ox.smsforwarder;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class TextMessageReceiver extends BroadcastReceiver {
    public TextMessageReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // This method is called when the BroadcastReceiver is receiving

        Bundle bundle=intent.getExtras();

        Object[] messages=(Object[])bundle.get("pdus");
        SmsMessage[] sms=new SmsMessage[messages.length];

        for(int n=0;n<messages.length;n++){
            sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
        }

        for(SmsMessage msg:sms){

            //Toast.makeText(context, "SMS received", Toast.LENGTH_SHORT).show();

            forwardSMS(context, msg.getOriginatingAddress(), msg.getMessageBody());

        }
    }

    /**
     * Broadcasts debug message to the main activity.
     * It will be shown in the Debug section of settings dialog if it is currently open.
     * @param context
     * @param txt
     */
    public static void updateDebugBox(Context context, String txt){

        /*

        // broadcast the message to our main activity
        Intent intent2 = new Intent("debug");
        // You can also include some extra data.
        intent2.putExtra("txt", txt);
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent2);

        */

    }

    /**
     * Gets called for each received SMS by TextMessageReceiver.
     * Outputs that SMS to the debug window (if currently open) and
     * forwards it to the specified number if forwarding is enabled.
     * @param context
     * @param fromNumber
     * @param msgBody
     */
    public static void forwardSMS(Context context, String fromNumber, String msgBody)
    {

        // debug
        updateDebugBox(context, "\nFrom: " + fromNumber + "\n"+ "Message: "+msgBody+"\n");

        // sanity check
        if (msgBody.length() == 0){
            return;
        }

        // see if forwarding is enabled
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
        if (!sharedPref.getBoolean("enable_forwarding", false)) {
            return;
        }

        //Toast.makeText(context, "SMS received", Toast.LENGTH_SHORT).show();

        // format the body of the forwarded SMS
        msgBody = fromNumber + ": " + msgBody;

        // get and verify forwarding number
        String fwdToNumber = sharedPref.getString("forwarding_number", "");
        if (fwdToNumber.length() == 0){
            String errMsg = "SMS Forwarder error: forwarding number is not specified.";
            Toast.makeText(context, errMsg, Toast.LENGTH_LONG).show();
            updateDebugBox(context, errMsg);
            return;
        }

        // forward the message
        SmsManager.getDefault().sendTextMessage(fwdToNumber, null, msgBody, null, null);

    }

}


text:
package reforest.rf.feature

import org.junit.Assert.assertEquals
import reforest.rf.{RFCategoryInfo, RFCategoryInfoEmpty}
import reforest.rf.split.RFSplitter
import test.RFResourceFactory
import org.junit.{Assert, Test}

class RFFeatureSizerTest {
  private val numberBin = 32
  private val numClasses = 10
  private val splitter = RFResourceFactory.getSplitterRandomDefault(-23.5, 12.7, numberBin)
  private val sizer = splitter.generateRFSizer(numClasses)

  @Test
  def getSize(): Unit = {
    assertEquals((numberBin + 1) * numClasses, sizer.getSize(1))
  }

  @Test
  def shrinker(): Unit = {
    val sizer = new RFFeatureSizerSimpleModelSelection(32, 2, new RFCategoryInfoEmpty, 16)
    assertEquals(0, sizer.getShrinkedValue(1, 0))
    assertEquals(1, sizer.getShrinkedValue(1, -1))
    assertEquals(16, sizer.getShrinkedValue(1, 32))
    assertEquals(16, sizer.getShrinkedValue(1, 33))
    assertEquals(16, sizer.getShrinkedValue(1, 100))
  }

  @Test
  def shrinkerSpecialized(): Unit = {
    val splitNumberMap = Map(0 -> 4, 1 -> 8, 2 -> 7)
    val sizer = new RFFeatureSizerSpecializedModelSelection(splitNumberMap, 2, new RFCategoryInfoEmpty, 8, 32)

    assertEquals(5, sizer.getShrinkedValue(0, 5))
    assertEquals(4, sizer.getShrinkedValue(0, 4))
    assertEquals(1, sizer.getShrinkedValue(0, 1))
    assertEquals(0, sizer.getShrinkedValue(0, 0))
    assertEquals(0, sizer.getShrinkedValue(1, 0))
    assertEquals(1, sizer.getShrinkedValue(1, -1))
    assertEquals(8, sizer.getShrinkedValue(1, 32))
    assertEquals(8, sizer.getShrinkedValue(1, 33))
    assertEquals(8, sizer.getShrinkedValue(1, 100))
    assertEquals(8, sizer.getShrinkedValue(2, 8))
    assertEquals(7, sizer.getShrinkedValue(2, 7))
    assertEquals(6, sizer.getShrinkedValue(2, 6))
    assertEquals(2, sizer.getShrinkedValue(2, 2))
    assertEquals(1, sizer.getShrinkedValue(2, 1))
  }

  @Test
  def deShrinker(): Unit = {
    val sizer = new RFFeatureSizerSimpleModelSelection(32, 2, new RFCategoryInfoEmpty, 16)

    assertEquals(0, sizer.getDeShrinkedValue(0, 0))
    assertEquals(0, sizer.getDeShrinkedValue(1, 0))
    assertEquals(32, sizer.getDeShrinkedValue(1, 32))
    assertEquals(32, sizer.getDeShrinkedValue(1, 33))
    assertEquals(32, sizer.getDeShrinkedValue(1, 100))
  }

  @Test
  def deShrinkerSpecialized(): Unit = {
    val splitNumberMap = Map(0 -> 4, 1 -> 8, 2 -> 7)
    val sizer = new RFFeatureSizerSpecializedModelSelection(splitNumberMap, 2, new RFCategoryInfoEmpty, 8, 32)

    assertEquals(5, sizer.getDeShrinkedValue(0, 5))
    assertEquals(4, sizer.getDeShrinkedValue(0, 4))
    assertEquals(1, sizer.getDeShrinkedValue(0, 1))
    assertEquals(0, sizer.getDeShrinkedValue(0, 0))
    assertEquals(0, sizer.getDeShrinkedValue(1, 0))
    assertEquals(9, sizer.getDeShrinkedValue(1, 32))
    assertEquals(9, sizer.getDeShrinkedValue(1, 33))
    assertEquals(9, sizer.getDeShrinkedValue(1, 100))
    assertEquals(8, sizer.getDeShrinkedValue(2, 8))
    assertEquals(7, sizer.getDeShrinkedValue(2, 7))
    assertEquals(6, sizer.getDeShrinkedValue(2, 6))
    assertEquals(2, sizer.getDeShrinkedValue(2, 2))
    assertEquals(1, sizer.getDeShrinkedValue(2, 1))
  }
}


text:
#ifndef TENSORFLOW_LITE_EXPERIMENTAL_DELEGATES_COREML_BUILDERS_ACTIVATION_LAYER_BUILDER_H_
#define TENSORFLOW_LITE_EXPERIMENTAL_DELEGATES_COREML_BUILDERS_ACTIVATION_LAYER_BUILDER_H_

#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/experimental/delegates/coreml/builders/op_builder.h"

namespace tflite {
namespace delegates {
namespace coreml {

class ActivationLayerBuilder : public OpBuilder {
 public:
  explicit ActivationLayerBuilder(GraphBuilder* graph_builder)
      : OpBuilder(graph_builder) {}

  explicit ActivationLayerBuilder(GraphBuilder* graph_builder,
                                  TfLiteFusedActivation activation)
      : OpBuilder(graph_builder), activation_(activation) {}

  const char* DebugName() override;

  CoreML::Specification::NeuralNetworkLayer* Build() override;

  void SetActivation(TfLiteFusedActivation activation) {
    activation_ = activation;
  }

  void SetAlpha(float alpha) { alpha_ = alpha; }

  TfLiteStatus PopulateSubgraph(TfLiteContext* context) override;

  TfLiteStatus RegisterInputs(const TfLiteIntArray* inputs,
                              TfLiteContext* context) override;

  TfLiteStatus RegisterOutputs(const TfLiteIntArray* outputs,
                               TfLiteContext* context) override;

 private:
  TfLiteFusedActivation activation_;
  float alpha_ = 1.0f;
};

}  // namespace coreml
}  // namespace delegates
}  // namespace tflite
#endif  // TENSORFLOW_LITE_EXPERIMENTAL_DELEGATES_COREML_BUILDERS_ACTIVATION_LAYER_BUILDER_H_


text:
main()
{
int count, lim;
int sum;
printf("This program finds the sum of all the squares of the integers from 1 to any number\n");
printf("What is that number?\n");
scanf("%d",&lim);
count = 0;
sum = 0;
while (count++<lim)
    sum +=(count*count);
printf("I have added the squares of the numbers from 1 to %d and the sum is %d.\n",lim,sum);
}


text:
namespace peloton {
namespace brain {

// http://www.cs.princeton.edu/courses/archive/fall08/cos436/Duda/C/sk_means.htm
void Clusterer::ProcessSample(const Sample &sample) {
  // Figure out closest cluster
  oid_t closest_cluster = GetClosestCluster(sample);

  Sample distance = sample.GetDifference(means_[closest_cluster]);
  Sample mean_drift = distance * new_sample_weight_;

  // Update the cluster's mean
  means_[closest_cluster] = means_[closest_cluster] + mean_drift;
}

oid_t Clusterer::GetClosestCluster(const Sample &sample) {
  double min_dist = std::numeric_limits<double>::max();
  oid_t closest_cluster = START_OID;
  oid_t cluster_itr = START_OID;

  // Go over all the means and find closest cluster
  for (auto mean : means_) {
    auto dist = sample.GetDistance(mean);
    if (dist < min_dist) {
      closest_cluster = cluster_itr;
      min_dist = dist;
    }
    cluster_itr++;
  }

  closest_[closest_cluster]++;
  sample_count_++;

  return closest_cluster;
}

Sample Clusterer::GetCluster(oid_t cluster_offset) const {
  return means_[cluster_offset];
}

double Clusterer::GetFraction(oid_t cluster_offset) const {
  return ((double)closest_[cluster_offset]) / sample_count_;
}

column_map_type Clusterer::GetPartitioning(oid_t tile_count) const {
  assert(tile_count >= 1);
  assert(tile_count <= sample_column_count_);

  std::map<double, oid_t> frequencies;
  oid_t cluster_itr = START_OID;
  oid_t cluster_count;

  cluster_count = GetClusterCount();
  for (cluster_itr = 0; cluster_itr < cluster_count; cluster_itr++) {
    auto pair = std::make_pair(GetFraction(cluster_itr), cluster_itr);
    frequencies.insert(pair);
  }

  std::map<oid_t, oid_t> column_to_tile_map;
  oid_t tile_itr = START_OID;
  oid_t remaining_column_count = sample_column_count_;

  // look for most significant cluster
  for (auto entry = frequencies.rbegin(); entry != frequencies.rend();
       ++entry) {
    LOG_TRACE(" %lu :: %.3lf", entry->second, entry->first);

    // first, check if remaining columns less than tile count
    if (remaining_column_count <= tile_count) {
      oid_t column_itr;
      for (column_itr = 0; column_itr < sample_column_count_; column_itr++) {
        if (column_to_tile_map.count(column_itr) == 0) {
          column_to_tile_map[column_itr] = tile_itr;
          tile_itr++;
        }
      }
    }

    // otherwise, get its partitioning
    auto config = means_[entry->second];
    auto config_tile = config.GetEnabledColumns();

    for (auto column : config_tile) {
      if (column_to_tile_map.count(column) == 0) {
        column_to_tile_map[column] = tile_itr;
        remaining_column_count--;
      }
    }

    // check tile itr
    tile_itr++;
    if (tile_itr >= tile_count) tile_itr--;
  }

  // check if all columns are present in partitioning
  assert(column_to_tile_map.size() == sample_column_count_);

  // build partitioning
  column_map_type partitioning;
  std::map<oid_t, oid_t> tile_column_count_map;

  for (auto entry : column_to_tile_map) {
    auto column_id = entry.first;
    auto tile_id = entry.second;

    // figure out how many columns in given tile
    auto exists = tile_column_count_map.find(tile_id);
    if (exists == tile_column_count_map.end())
      tile_column_count_map[tile_id] = 0;
    else
      tile_column_count_map[tile_id] += 1;

    // create an entry for the partitioning map
    auto partition_entry =
        std::make_pair(tile_id, tile_column_count_map[tile_id]);
    partitioning[column_id] = partition_entry;
  }

  return partitioning;
}

const std::string Clusterer::GetInfo() const {
  std::ostringstream os;

  oid_t cluster_itr;
  oid_t cluster_count;

  cluster_count = GetClusterCount();
  for (cluster_itr = 0; cluster_itr < cluster_count; cluster_itr++)
    os << cluster_itr << " : " << GetFraction(cluster_itr)
       << " :: " << GetCluster(cluster_itr);

  return os.str();
}

}  // End brain namespace
}  // End peloton namespace


text:
package org.apache.commons.imaging.formats.psd.datareaders;

import net.windward.android.awt.image.BufferedImage;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.common.BinaryFileParser;
import org.apache.commons.imaging.common.BinaryFunctions;
import org.apache.commons.imaging.common.PackBits;
import org.apache.commons.imaging.common.mylzw.BitsToByteInputStream;
import org.apache.commons.imaging.common.mylzw.MyBitInputStream;
import org.apache.commons.imaging.formats.psd.ImageContents;
import org.apache.commons.imaging.formats.psd.PsdHeaderInfo;
import org.apache.commons.imaging.formats.psd.dataparsers.DataParser;
import org.apache.commons.imaging.util.IoUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteOrder;

public class CompressedDataReader extends DataReader {

    public CompressedDataReader(final DataParser fDataParser) {
        super(fDataParser);
    }

    @Override
    public void readData(final InputStream is, final BufferedImage bi,
            final ImageContents imageContents, final BinaryFileParser bfp)
            throws ImageReadException, IOException {
        final PsdHeaderInfo header = imageContents.header;
        final int width = header.columns;
        final int height = header.rows;

        // this.setDebug(true);
        final int scanlineCount = height * header.channels;
        final int[] scanlineBytecounts = new int[scanlineCount];
        for (int i = 0; i < scanlineCount; i++) {
            scanlineBytecounts[i] = BinaryFunctions.read2Bytes("scanline_bytecount[" + i
                    + "]", is, "PSD: bad Image Data", bfp.getByteOrder());
        }
        bfp.setDebug(false);
        // System.out.println("fImageContents.Compression: "
        // + imageContents.Compression);

        final int depth = header.depth;

        final int channelCount = dataParser.getBasicChannelsCount();
        final int[][][] data = new int[channelCount][height][];
        // channels[0] =
        for (int channel = 0; channel < channelCount; channel++) {
            for (int y = 0; y < height; y++) {
                final int index = channel * height + y;
                final byte[] packed = BinaryFunctions.readBytes("scanline",
                        is, scanlineBytecounts[index],
                        "PSD: Missing Image Data");

                final byte[] unpacked = new PackBits().decompress(packed, width);
                final InputStream bais = new ByteArrayInputStream(unpacked);
                final MyBitInputStream mbis = new MyBitInputStream(bais, ByteOrder.BIG_ENDIAN);
                BitsToByteInputStream bbis = null;
                boolean canThrow = false;
                try {
                    bbis = new BitsToByteInputStream(mbis, 8); // we want all samples to be bytes
                    final int[] scanline = bbis.readBitsArray(depth, width);
                    data[channel][y] = scanline;
                    canThrow = true;
                } finally {
                    IoUtils.closeQuietly(canThrow, bbis);
                }
            }
        }

        dataParser.parseData(data, bi, imageContents);

    }
}


text:
title: "D.C.Dennett, B.F.Skinner and H.P.Lovecraft"
excerpt: "Today was my last lecture in the 'Philosophical Foundations of Cognitive Science' class I took this semester with Dan Dennett."
modified: 2014-10-19
tags: [lovecraft, philosophy]
comments: true
header:
  image: features/skinnerdennetlovecraft.png
  caption: "Photo credit: WeGraphics, Wikimedia, nndb.com, news.stanford.com"
---

Today was my last lecture in the "Philosophical Foundations of Cognitive Science"
class I took this semester with Dan Dennett.

In class, Dennett posited the following frame theory (to the best of
my recollection): The mind, in a highly parallel fashion, is
constantly evaluating a multitude of stories (i.e., frames) to
determine which frame or combination of frames is most likely to
generalize to the current context, thus determining what one's
response should be in its current scenario.

I pointed out that this would likely run into similar problems to
Skinner's radical behaviorism; Skinner believed that behaviors were
generated in a stringent stimulus-response framework, and that any
observed behavior was thus the result of some reinforcement in the
agent's past. If an agent was presented with a novel (i.e., never
before experienced) stimulus, Skinner believed that the agent's
response was the result of reinforcement to *similar* responses to
*similar* stimuli.

Unfortunately, Skinner is *begging the question*, as any possible
behavior is explained in the same manner: Skinner has only to say
"It's reinforcement!" and be done with it. This  merely *explains
away* the question. I'm sure Karl Popper would be equally unconvinced
with this, as the approaches of Skinner and Dennett seem, at least at
first inspection, to be unfalsifiable.

Or are they?

Could one concoct a scenario to which there is no sufficiently similar
scenario experienced or heard of by the agent for which it to compare
to, meaning the agent would have no way of selecting any appropriate
behavior, as in Dennett's case it would not find any appropriate frame
with sufficient activation, and in Skinner's case would not find any
sufficiently reinforced response to execute?

This brings us to the third actor in our scene: H. P. Lovecraft.

In Lovecraft's stories, characters encounter indescribable horrors,
and go insane as a result. Viewed through the lens of Dennett's
theory, my intuition would be that as the beasts are inherently
indescribable, they could not possibly have been described in a
story. Viewed through the lens of Skinner's theory, the indescribable
aspect would similarly entail the lack of any sufficiently similar
scenario with which to compare the encounter with.

As no frame or response would be choosable by the agent, they would
have no way of responding to the encounter. In the world of
H. P. Lovecraft, this would result in a rending of the poor soul's
mind, rendering them insane.

Of course, one is unable to put this mapping to the test, as (to my
knowledge) there are no indescribable horrors lurking about for us to
present to subjects, and even if there were, the IRB for the
experiment would be a tough sell.


text:
`docker build -t quantscientist/pycuda -f Dockerfile.gpu3 .`

`nvidia-docker run -it -p 5555:5555 -p 7842:7842 -p 8787:8787 -p 8786:8786 -p 8788:8788 -v ~/db/Dropbox/dev2/:/root/sharedfolder  quantscientist/pycuda bash`

This repository includes utilities to build and run my NVIDIA Docker image for **the Deep Learning School**:
https://www.meetup.com/TensorFlow-Tel-Aviv/events/241762893/

NOTE: Building this image may take several hours since CMAKE is being built from source.
https://github.com/QuantScientist/deep-ml-meetups

Also available on docker hub (Build on docker hub usually failes because of the long build time):
https://hub.docker.com/r/quantscientist/deep-learning-boot-camp/

`docker pull quantscientist/deep-learning-boot-camp`

![cuda](cuda-test1.png)

Please be aware that this project is currently **experimental**.

### CUDA requirements

Running a CUDA container requires a machine with at least one CUDA-capable GPU and a driver compatible with the CUDA toolkit version you are using.

NVIDIA drivers are **backward-compatible** with CUDA toolkits versions:

CUDA toolkit version   | Minimum driver version
:---------------------:|:-----------------------:
  7.0                  | >= 346.46
  7.5                  | >= 352.39

** We use CUDA 8.0. **

### Get the toolkit:
`sudo apt-get install nvidia-cuda-toolkit`

### Get nsight IDE:
`sudo apt-get install nvidia-nsight`

### Install nvidia-docker and nvidia-docker-plugin
`wget -P /tmp https://github.com/NVIDIA/nvidia-docker/releases/download/v1.0.1/nvidia-docker_1.0.1-1_amd64.deb
sudo dpkg -i /tmp/nvidia-docker*.deb && rm /tmp/nvidia-docker*.deb`

#### Get nvidia docker (requires docker-engine **NOT** docker.io):
`nvidia-docker run --rm nvidia/cuda nvidia-smi`

# Image contents
On top of all the fancy deep learning libraries, this docker image contains:

Ubuntu 16.04
CUDA 8.0 (GPU version only)
cuDNN v5 (GPU version only)
Tensorflow
Theano
Keras
iPython/Jupyter Notebook
Numpy, SciPy, Pandas, Scikit Learn, Matplotlib
A few common libraries used for deep learning

* ArrayFire
* PyCUDA
* Python
* LLVM
* LLDB
* Snappy
* Numba

# Build the image
### GPU version
`docker build -t quantscientist/pycuda -f Dockerfile.gpu3 .`

### CPU version
`docker build -t quantscientist/pycuda -f Dockerfile.cpu .`

# Run the GPU image
`nvidia-docker run -it -p 5555:5555 -p 7842:7842 -p 8787:8787 -p 8786:8786 -p 8788:8788 -v ~/db/Dropbox/dev2/:/root/sharedfolder  quantscientist/pycuda bash`

# Run the GPU image
`docker run -it -p 5555:5555 -p 7842:7842 -p 8787:8787 -p 8786:8786 -p 8788:8788 -v /myhome/data-science/:/root/sharedfolder  --env="DISPLAY" quantscientist/pycuda bash`

# Run Jupyter
`chmod +x run_jupyter.sh
./run_jupyter.sh`

OR

`docker build -t quantscientist/gpu -f Dockerfile.gpu .`

# Issues and Contributing
* Please let us know by [filing a new issue](https://github.com/QuantScientist/Data-Science-ArrayFire-GPU/issues/new)
* You can contribute by opening a [pull request](https://help.github.com/articles/using-pull-requests/)
You will need to send a signed copy of the [Contributor License Agreement](CLA) to digits@nvidia.com before your change can be accepted.


text:
phpApps - loaders for PHP Desktop and other useful applications

PHP Desktop is an open source project founded by Czarek Tomczak:
<a href="http://github.com/cztomczak/phpdesktop">
    http://github.com/cztomczak/phpdesktop
</a>


text:
import fn from '../../setYear/index.js'
import convertToFP from '../_lib/convertToFP/index.js'

var setYear = convertToFP(fn, 2)

export default setYear


text:
// Code generated by go-swagger; DO NOT EDIT.

package constraint

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command

import (
	"net/http"

	"github.com/go-openapi/runtime/middleware"
)

// CreateConstraintHandlerFunc turns a function with the right signature into a create constraint handler
type CreateConstraintHandlerFunc func(CreateConstraintParams) middleware.Responder

// Handle executing the request and returning a response
func (fn CreateConstraintHandlerFunc) Handle(params CreateConstraintParams) middleware.Responder {
	return fn(params)
}

// CreateConstraintHandler interface for that can handle valid create constraint params
type CreateConstraintHandler interface {
	Handle(CreateConstraintParams) middleware.Responder
}

// NewCreateConstraint creates a new http.Handler for the create constraint operation
func NewCreateConstraint(ctx *middleware.Context, handler CreateConstraintHandler) *CreateConstraint {
	return &CreateConstraint{Context: ctx, Handler: handler}
}

/*
	CreateConstraint swagger:route POST /flags/{flagID}/segments/{segmentID}/constraints constraint createConstraint

CreateConstraint create constraint API
*/
type CreateConstraint struct {
	Context *middleware.Context
	Handler CreateConstraintHandler
}

func (o *CreateConstraint) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	route, rCtx, _ := o.Context.RouteInfo(r)
	if rCtx != nil {
		*r = *rCtx
	}
	var Params = NewCreateConstraintParams()
	if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
		o.Context.Respond(rw, r, route.Produces, route, err)
		return
	}

	res := o.Handler.Handle(Params) // actually handle the request
	o.Context.Respond(rw, r, route.Produces, route, res)

}


text:
using System;
using System.Linq;

namespace Slides
{
    class Program
    {
        static void Main()
        {
            // read dimensions
            string[] line = Console.ReadLine().Split(' ');
            int cuboidWidth = int.Parse(line[0]);
            int cuboidHeigth = int.Parse(line[1]);
            int cuboidDepth = int.Parse(line[2]);

            // read cuboid
            string[, ,] cuboid = new string[cuboidWidth, cuboidHeigth, cuboidDepth];
            for (int h = 0; h < cuboidHeigth; h++)
            {
                string[] row = Console.ReadLine().Split('|');
                for (int d = 0; d < cuboidDepth; d++)
                {
                    string[] cubes = row[d].Trim().Split(new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int w = 0; w < cuboidWidth; w++)
                    {
                        string cube = cubes[w];
                        cuboid[w, h, d] = cube;
                    }
                }
            }

            // read ball
            line = Console.ReadLine().Split(' ');
            int ballWidth = 0;
            int ballHeight = 0;
            int ballDepth = 0;

            // execute ball falling
            int nextWidth = int.Parse(line[0]);
            int nextHeight = 0;
            int nextDepth = int.Parse(line[1]);
            bool canDropo = true;
            string currentCube = "";
            while (canDropo)
            {
                if (nextHeight == cuboidHeigth)
                {
                    break;
                }

                if (0 > nextWidth || nextWidth > cuboidWidth - 1 ||
                    0 > nextDepth || nextDepth > cuboidDepth - 1)
                {
                    canDropo = false;
                    break;
                }

                ballWidth = nextWidth;
                ballHeight = nextHeight;
                ballDepth = nextDepth;

                // read current cube
                currentCube = cuboid[nextWidth, nextHeight, nextDepth];
                // execute current cube commnad
                // S X; T 1 1; B; E
                char command = currentCube[0];
                switch (command)
                {
                    case 'B': canDropo = false; break;
                    case 'E': nextHeight++; break;
                    case 'T': // "T 1 1"
                        int[] coord = currentCube.Substring(2).Split(' ')
                            .Select(x => int.Parse(x)).ToArray();
                        nextWidth = coord[0];
                        nextDepth = coord[1];
                        break;
                    case 'S': // S L; R; F; B; FL FL..
                        nextHeight++;
                        string dir = currentCube.Substring(2);
                        switch (dir)
                        {
                            case "L": nextWidth--; break;
                            case "R": nextWidth++; break;
                            case "F": nextDepth--; break;
                            case "B": nextDepth++; break;
                            case "FL": nextWidth--; nextDepth--; break;
                            case "FR": nextWidth++; nextDepth--; break;
                            case "BL": nextWidth--; nextDepth++; break;
                            case "BR": nextWidth++; nextDepth++; break;
                        }
                        break;
                }

            }

            // output
            Console.WriteLine(canDropo ? "Yes" : "No");
            Console.WriteLine("{0} {1} {2}", ballWidth, ballHeight, ballDepth);
        }
    }
}


text:
#include "info_defining_dialog.h"
#include "problem_definition_dialog.h"
#include "ui_problem_definition_dialog.h"

ProblemDefinitionDialog::ProblemDefinitionDialog(QWidget* parent, bool saveToFileAllowed) :
    QDialog(parent),
    ui_(new Ui::ProblemDefinitionDialog),
    infoDefiningDialog_(nullptr),
    saveToFileAllowed_(saveToFileAllowed)
{
    ui_->setupUi(this);
    ui_->pushButton_saveToFile->setEnabled(saveToFileAllowed);

    functionLabels_.at(0) = ui_->label_f0;
    functionLabels_.at(1) = ui_->label_f1;
    functionLabels_.at(2) = ui_->label_f2;
    functionLabels_.at(3) = ui_->label_f3;

    functionLineEdits_.at(0) = ui_->lineEdit_f0;
    functionLineEdits_.at(1) = ui_->lineEdit_f1;
    functionLineEdits_.at(2) = ui_->lineEdit_f2;
    functionLineEdits_.at(3) = ui_->lineEdit_f3;

    connect(ui_->pushButton_revert, &QPushButton::clicked,
            this, &ProblemDefinitionDialog::revertToFileStateRequested);
    connect(ui_->pushButton_saveTemporarily, &QPushButton::clicked,
            this, &ProblemDefinitionDialog::handleSaveButtonClicked);
    connect(ui_->pushButton_saveToFile, &QPushButton::clicked,
            this, &ProblemDefinitionDialog::handleSaveButtonClicked);

    connect(ui_->lineEdit_problemName, &QLineEdit::textEdited,
            this, &ProblemDefinitionDialog::enableSaveButtons);
    connect(ui_->lineEdit_f0, &QLineEdit::textEdited,
            this, &ProblemDefinitionDialog::enableSaveButtons);
    connect(ui_->lineEdit_f1, &QLineEdit::textEdited,
            this, &ProblemDefinitionDialog::enableSaveButtons);
    connect(ui_->lineEdit_f2, &QLineEdit::textEdited,
            this, &ProblemDefinitionDialog::enableSaveButtons);
    connect(ui_->lineEdit_f3, &QLineEdit::textEdited,
            this, &ProblemDefinitionDialog::enableSaveButtons);

    setWindowModality(Qt::ApplicationModal);
}

ProblemDefinitionDialog::~ProblemDefinitionDialog()
{
    delete ui_;
}

void ProblemDefinitionDialog::adaptTo(const QStringList& functionNames)
{
    unsigned int i = 0;
    for (const QString& funcName : functionNames)
    {
        functionLabels_.at(i)->setVisible(true);
        functionLineEdits_.at(i)->setVisible(true);
        functionLabels_.at(i)->setText(funcName + " = ");
        functionLineEdits_.at(i)->clear();
        i++;
    }

    for (unsigned int j = i; j < functionLabels_.size(); j++)
    {
        functionLabels_.at(j)->setVisible(false);
        functionLineEdits_.at(j)->setVisible(false);
    }
}

void ProblemDefinitionDialog::prepareEditing(const QString& currentProblemName,
                                             const QStringList& currentProblemFuncDefs,
                                             bool revertEnabled)
{
    setWindowTitle("Edit problem definition");
    oldName_ = currentProblemName;

    for (int i = 0; i < currentProblemFuncDefs.size(); ++i)
        functionLineEdits_.at(i)->setText(currentProblemFuncDefs.at(i));

    ui_->lineEdit_problemName->setText(currentProblemName);

    ui_->pushButton_saveTemporarily->setEnabled(false);
    ui_->pushButton_saveToFile->setEnabled(false);
    ui_->pushButton_revert->setEnabled(revertEnabled);

    lastOpenedForEditing_ = true;
}

void ProblemDefinitionDialog::prepareNewDefinition()
{
    setWindowTitle("Define a new problem");
    oldName_ = QString();

    ui_->pushButton_saveTemporarily->setEnabled(false);
    ui_->pushButton_saveToFile->setEnabled(false);
    ui_->pushButton_revert->setEnabled(false);

    for (unsigned int i = 0; i < functionLineEdits_.size(); ++i)
    {
        functionLineEdits_.at(i)->clear();
    }
    ui_->lineEdit_problemName->clear();

    lastOpenedForEditing_ = false;
}

void ProblemDefinitionDialog::enableSaveButtons()
{
    ui_->pushButton_saveTemporarily->setEnabled(true);
    if (saveToFileAllowed_)
        ui_->pushButton_saveToFile->setEnabled(true);
}

void ProblemDefinitionDialog::handleSaveButtonClicked() const
{
    bool overwrite = lastOpenedForEditing_;
    bool saveToFile = false;
    if (sender() == ui_->pushButton_saveToFile)
        saveToFile = true;

    QStringList newDefinitions;
    for (unsigned int i = 0; i < functionLineEdits_.size(); ++i)
    {
        QLineEdit* lineEdit = functionLineEdits_.at(i);
        if (lineEdit->isVisible())
            newDefinitions.append(lineEdit->text());
    }

    emit saveDefinitionRequested(overwrite, saveToFile, oldName_,
                                 ui_->lineEdit_problemName->text(),
                                 newDefinitions);
}

void ProblemDefinitionDialog::on_pushButton_cancel_clicked()
{
    close();
}

void ProblemDefinitionDialog::on_pushButton_help_clicked()
{
    if (!infoDefiningDialog_)
        infoDefiningDialog_ = new InfoDefiningDialog(this);

    infoDefiningDialog_->show();
}


text:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">

Turmas

        Id
        Nome

        <?php
        if (!isset($_SESSION)){session_start();}
            $conn=mysqli_connect("localhost","root","","proj");

            $instS="Select idTurma,DesignacaoTurma from turmas";
            $query = mysqli_query($conn,$instS);
            while ($row = mysqli_fetch_array ($query)){
            echo "
";
            echo "".$row['idTurma']."	 ";
            echo "".$row['DesignacaoTurma']."	";
                echo"	";
                ?>

                <a onClick="return confirm('Tem a certeza que deseja prosseguir?');" href="deleterowT.php?id=<?php echo $row['idTurma'];?>"> <button class='glyphicon glyphicon-remove' style='color:red;background-color:transparent;border: none;' ></button>

        <?php echo "
";
            }

        ?>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Adicionar Turma

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
namespace media {

// Represents a picture encoded (or to be encoded) with a video codec, such as
// VP8. Users of this class do not require knowledge of the codec format, or any
// codec-specific details related to the picture, but may otherwise need to pass
// or keep references to the picture, e.g. to keep a list of reference pictures
// required for a codec task valid until it is finished. Also used for storing
// non-codec-specific metadata.
class MEDIA_GPU_EXPORT CodecPicture
    : public base::RefCountedThreadSafe<CodecPicture> {
 public:
  CodecPicture();

  CodecPicture(const CodecPicture&) = delete;
  CodecPicture& operator=(const CodecPicture&) = delete;

  int32_t bitstream_id() const { return bitstream_id_; }
  void set_bitstream_id(int32_t bitstream_id) { bitstream_id_ = bitstream_id; }

  const gfx::Rect visible_rect() const { return visible_rect_; }
  void set_visible_rect(const gfx::Rect& rect) { visible_rect_ = rect; }

  // DecryptConfig returned by this method describes the decryption
  // configuration of the input stream for this picture. Returns null if it is
  // not encrypted.
  const DecryptConfig* decrypt_config() const { return decrypt_config_.get(); }
  void set_decrypt_config(std::unique_ptr<DecryptConfig> config) {
    decrypt_config_ = std::move(config);
  }

  // Populate with an unspecified colorspace by default.
  const VideoColorSpace& get_colorspace() const { return colorspace_; }
  void set_colorspace(const VideoColorSpace& colorspace) {
    colorspace_ = colorspace;
  }

 protected:
  friend class base::RefCountedThreadSafe<CodecPicture>;
  virtual ~CodecPicture();

 private:
  int32_t bitstream_id_ = -1;
  gfx::Rect visible_rect_;
  std::unique_ptr<DecryptConfig> decrypt_config_;
  VideoColorSpace colorspace_;
};

}  // namespace media

#endif  // MEDIA_GPU_CODEC_PICTURE_H_


text:
---
layout: post
title: "ES6 Promise API, Promise Pattern, Asynchronous Codes"
date: 2015-12-17 15:59:00 +08:00
categories: Web IT
tags: JavaScript ES6 AJAX
---

* content
{:toc}

### Notes about ES6 Promise API
* JavaScript execution model
    - single thread, each website
    - main thread maintains a queue, which has asynchronous tasks
    - HTML5 introduced web workers, which are the actual threads
* Asynchronous code
    - Event pattern. e.g. AJAX codes using ECMA script
    - Callback pattern. e.g. jQuery AJAX
    - Promise pattern - new in ES6
* Promise pattern pattern removes the common code issues that the event and callback pattern had below.
    - It is difficult to catch the exceptions, as we have to use multiple try and catch statements.
    - The code is harder to read, as it's difficult to follow the code flow due to the nested function calls.
    - It's difficult to maintain the state of the asynchronous operation.

### Examples
* [Promise API, resolve(), then()](https://eastmanjian.cn/js_demo/tiy.jsp?sample=es6%2Fpromise_resolve_then.html)
* [Combine one or more promises into new promises, Promise.all()](https://eastmanjian.cn/js_demo/tiy.jsp?sample=es6%2Fpromise_all.html)
* [Promise.race() - race between Promises and see which one finishes first](https://eastmanjian.cn/js_demo/tiy.jsp?sample=es6%2Fpromise_race.html)

* Project sample, using Promise API to wrap an AJAX REST request.

```javascript
/**
 * wrapper function for AJAX REST request.
 * @param params - The parameter object contains REST request parameters.
 *                  Including: type (method), url, contentType, accept, data.
 * @returns {Promise} - The promise object produced by an AJAX call.
 */
function ajaxRestReq(params) {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.onload = () => {
            if (xhr.status == 200) {
                resolve(xhr.responseText);
            } else {
                reject("Server Error: " + xhr.status);
            }
        }
        xhr.onerror = () => {
            reject("XMLHttpRequest Error:"  + xhr.status);
        }
        xhr.open(params.type, params.url, true);
        xhr.setRequestHeader("Content-type", params.contentType);
        xhr.setRequestHeader("Accept", params.accept);
        xhr.send(params.data);
    });
}

/**
 * Add a comment and store the data to the REST service.
 */
function addDelightalkComment() {
    let user = document.querySelector("#delightalkUserName").value;
    let userName = (user == "") ? "Anonymous" : user;
    let commentContent = document.querySelector("#delightalkCommentInput").value;
    if (commentContent == "") {
        document.querySelector("#delightalkCommentInput").focus();
        return;
    }
    let btnAddComment = document.querySelector("#addDelightalkCommentBtn")
    btnAddComment.innerText = "Publishing";
    btnAddComment.disabled = true;
    let commentItem = {
        pageURL: delightParams.pageUrlId,
        user: userName,
        comment: commentContent
    };
    ajaxRestReq({
        url: delightParams.restServiceUrl + delightParams.siteName + '/addComment/',    //remote server test
        type: 'POST',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(commentItem),
        accept: 'application/json',
    }).then(doneAddDelightalkComment, logErr);
}

/**
 * Get recent comments from REST service
 */
function getDelightalkRecentComments() {
    let requestData = {
        pageURL: delightParams.pageUrlId,
        lastN: delightParams.previousComments
    };
    ajaxRestReq({
        url: delightParams.restServiceUrl + delightParams.siteName + '/getRecentComments',  //remote server test
        type: 'PUT',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(requestData),
        accept: 'application/json',
    }).then(renderRecentComments, logErr);
}

/**
 * Callback function after a new comment is added successfully.
 */
function doneAddDelightalkComment() {
    let btnAddComment = document.querySelector("#addDelightalkCommentBtn")
    btnAddComment.innerText = "Published";
    document.querySelector("#delightalkCommentInput").value = "";
    setTimeout(function () {
        btnAddComment.innerText = " Publish ";
        btnAddComment.disabled = false;
    }, 1500);
    getDelightalkRecentComments();
}

/**
 * Render the REST returned json string into the recent comment section of the page.
 * @param jsonString the json format string contains the recent comment data.
 */
function renderRecentComments(jsonString) {
    let data = JSON.parse(jsonString);
    let htmlTxt = '';
    for (i = data.recentComments.length - 1; i >= 0; i--) {
        htmlTxt += '<div class="a-delightalk-comment">'
                +    '<header id="recentCmtHeader">'
                +      '<span id="delightalkCommentUser">'
                +        '<i class="fa fa-user comment-icon" aria-hidden="true"></i>'
                +        escapeHtml(data.recentComments[i].user + ' ')
                +      '</span>'
                +      '<span id="delightalkCommentDate">'
                +        '<i class="fa fa-clock-o comment-icon" aria-hidden="true"></i>'
                +        (new Date(data.recentComments[i].timestamp)).Format("yyyy-MM-dd hh:mm:ss")
                +      '</span>'
                +    '</header>'
                +    '<article  id="delightalkCommentContent">'
                +      escapeHtml(data.recentComments[i].comment)
                +    '</article>'
                +  '</div>';
    }
    document.querySelector("#recentDelightalkComments").innerHTML = htmlTxt;
}

/**
 * Callback function in case ajax request error.
 * @param reason - the error reason
 */
function logErr(reason) {
    console.log(reason);
}
```