text:
import hashlib

from django import template
from django.core.urlresolvers import reverse

from pennyblack.models import Link

register = template.Library()

class NewsletterstyleNode(template.Node):
    def __init__(self, key, style, request):
        self.key = key
        self.style = style
        self.request_var = template.Variable(request)

    def render(self, context):
        request = self.request_var.resolve(context)
        if not hasattr(request, '_pennyblack_newsletterstyle'):
            setattr(request, '_pennyblack_newsletterstyle', dict())
        request._pennyblack_newsletterstyle[str(self.key)] = self.style.render(context)
        return ''

def newsletterstyle(parser, token):
    """
    Stores the content in your context
    {% newsletterstyle request text_only_content %}
    """
    bits = list(token.split_contents())
    if len(bits) != 3:
        raise template.TemplateSyntaxError("%r expected format is 'newsletterstyle request stylename'" % bits[0])
    request = bits[1]
    key = parser.compile_filter(bits[2])
    style = parser.parse(('endnewsletterstyle',))
    parser.delete_first_token()
    return NewsletterstyleNode(key, style, request)
newsletterstyle = register.tag(newsletterstyle)

class NewsletterGetStyleNode(template.Node):
    def __init__(self, key, request):
        self.key = key
        self.request_var = template.Variable(request)

    def render(self, context):
        request = self.request_var.resolve(context)
        if not hasattr(request, '_pennyblack_newsletterstyle'):
            return ''
        if str(self.key) not in request._pennyblack_newsletterstyle.keys():
            return ''
        return request._pennyblack_newsletterstyle[str(self.key)]

def get_newsletterstyle(parser, token):
    """
    Loads a stored style and renders it
    """
    bits = list(token.split_contents())
    if len(bits) != 3:
        raise template.TemplateSyntaxError("%r expected format is 'newsletterstyle request stylename'" % bits[0])
    request = bits[1]
    key = parser.compile_filter(bits[2])
    return NewsletterGetStyleNode(key, request)
get_newsletterstyle = register.tag(get_newsletterstyle)

class NewsletterHeaderImageNode(template.Node):
    def __init__(self, extra_args={}):
        self.extra_args = extra_args

    def render(self, context):
        newsletter = context['newsletter']
        if context['webview']:
            if 'mail' in context:
                mail = context['mail']
                header_url = mail.get_header_url()
            else:
                header_url = ''
            header_image = newsletter.header_image.get_absolute_url()
        else:
            mail = context['mail']
            header_url = mail.get_header_url()
            header_image = newsletter.get_base_url() + reverse('pennyblack.ping', kwargs={'mail_hash': mail.mail_hash, 'filename': newsletter.header_image})
        return """""" % (header_url, header_image, ' '.join(self.extra_args))

@register.tag
def header_image(parser, token):
    """
    Renders the header image with tracking any extra args are given to the img tag

    {% header_image alt="Header" width="283" height="157" align="left" vspace="0" hspace="0" border="0" %}

    renders

    """
    bits = list(token.split_contents())
    extra_args = []
    for bit in bits:
        splitted = bit.split('=')
        if len(splitted) == 2:
            extra_args.append(bit)
    return NewsletterHeaderImageNode(extra_args=extra_args)

class NewsletterLinkUrlNode(template.Node):
    def __init__(self, identifier=None):
        self.identifier = identifier

    def render(self, context):
        from pennyblack.models import Newsletter
        if 'mail' not in context:
            return u'#'
        mail = context['mail']
        newsletter = mail.job.newsletter
        if newsletter.is_workflow():
            job = newsletter.get_default_job()
        else:
            job = mail.job
        try:
            link = job.links.get(identifier=self.identifier)
        except job.links.model.DoesNotExist:
            link = Newsletter.add_view_link_to_job(self.identifier, job)
        return context['base_url'] + reverse('pennyblack.redirect_link', args=(mail.mail_hash, link.link_hash))

@register.tag
def link_url(parser, token):
    """
    Renders a link wich is provided by the group object.
    """
    bits = list(token.split_contents())
    if len(bits) != 2:
        raise template.TemplateSyntaxError("%r expected format is 'link_url url_identifier'" % bits[0])
    return NewsletterLinkUrlNode(identifier=bits[1])

class ContentImageUrlNode(template.Node):
    def __init__(self, identifier=None):
        self.identifier = identifier

    def render(self, context):
        kwargs = {}
        if 'mail' in context:
            kwargs['context'] = context
        if self.identifier:
            kwargs['identifier'] = self.identifier
        return context['content'].get_image_url(**kwargs)

@register.tag
def content_image_url(parser, token):
    """
    Renders the link of the given content.
    """
    bits = list(token.split_contents())
    if len(bits) == 2:
        return ContentImageUrlNode(identifier=bits[1])
    return ContentImageUrlNode()

class LinkTagNode(template.Node):
    def __init__(self, target, token):
        self.target = target
        self.token = token

    def render(self, context):
        if isinstance(self.token, template.Variable):
            self.token = self.token.resolve(context)
        target = self.target.resolve(context)
        if 'mail' not in context:
            return "%s %s " % (target, self.token)
        mail = context['mail']
        link, created = Link.objects.get_or_create(token=self.token, job=mail.job)
        if created:
            link.link_target = target
            link.save()
        return context['base_url'] + reverse('pennyblack.redirect_link', args=(mail.mail_hash, link.link_hash))

@register.tag
def trackable_link(parser, token):
    """
    Renders a url that can be used to track links in a template outside the
    content types. Multiple links can be grouped together by giving a third
    parameter which identifies the link. This makes it possible to group links
    like in the following example:
    {% if random %}
        link
    {% else %}
        link
    {% endif %}
    The target link can contain template variables in the following form:
    link
    """
    bits = list(token.split_contents())
    if not 2 <= len(bits) <= 3:
        raise template.TemplateSyntaxError("%r expected format is 'tackable_link 'http://target_url''" % bits[0])
    if len(bits) == 2:
        template_loader, (position_start, position_end) = parser.command_stack[0][-1]
        link_token = hashlib.md5("%s%s" % (template_loader.loadname, position_start)).hexdigest()
    else:
        link_token = template.Variable(bits[2])
    return LinkTagNode(template.Variable(bits[1]), link_token)


text:
<?php
/**
 * BookingWindow
 *
 * PHP version 5
 *
 * @category Class
 * @package  Swagger\Client
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * MINDBODY Public API
 *
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * OpenAPI spec version: v6
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 * Swagger Codegen version: 2.4.6
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace Swagger\Client\Model;

use \ArrayAccess;
use \Swagger\Client\ObjectSerializer;

/**
 * BookingWindow Class Doc Comment
 *
 * @category Class
 * @description The booking window for registration
 * @package  Swagger\Client
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */
class BookingWindow implements ModelInterface, ArrayAccess
{
    const DISCRIMINATOR = null;

    /**
      * The original name of the model.
      *
      * @var string
      */
    protected static $swaggerModelName = 'BookingWindow';

    /**
      * Array of property to type mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerTypes = [
        'start_date_time' => '\DateTime',
        'end_date_time' => '\DateTime',
        'daily_start_time' => '\DateTime',
        'daily_end_time' => '\DateTime'
    ];

    /**
      * Array of property to format mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerFormats = [
        'start_date_time' => 'date-time',
        'end_date_time' => 'date-time',
        'daily_start_time' => 'date-time',
        'daily_end_time' => 'date-time'
    ];

    /**
     * Array of property to type mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerTypes()
    {
        return self::$swaggerTypes;
    }

    /**
     * Array of property to format mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerFormats()
    {
        return self::$swaggerFormats;
    }

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @var string[]
     */
    protected static $attributeMap = [
        'start_date_time' => 'StartDateTime',
        'end_date_time' => 'EndDateTime',
        'daily_start_time' => 'DailyStartTime',
        'daily_end_time' => 'DailyEndTime'
    ];

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @var string[]
     */
    protected static $setters = [
        'start_date_time' => 'setStartDateTime',
        'end_date_time' => 'setEndDateTime',
        'daily_start_time' => 'setDailyStartTime',
        'daily_end_time' => 'setDailyEndTime'
    ];

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @var string[]
     */
    protected static $getters = [
        'start_date_time' => 'getStartDateTime',
        'end_date_time' => 'getEndDateTime',
        'daily_start_time' => 'getDailyStartTime',
        'daily_end_time' => 'getDailyEndTime'
    ];

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @return array
     */
    public static function attributeMap()
    {
        return self::$attributeMap;
    }

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @return array
     */
    public static function setters()
    {
        return self::$setters;
    }

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @return array
     */
    public static function getters()
    {
        return self::$getters;
    }

    /**
     * The original name of the model.
     *
     * @return string
     */
    public function getModelName()
    {
        return self::$swaggerModelName;
    }

    /**
     * Associative array for storing property values
     *
     * @var mixed[]
     */
    protected $container = [];

    /**
     * Constructor
     *
     * @param mixed[] $data Associated array of property values
     *                      initializing the model
     */
    public function __construct(array $data = null)
    {
        $this->container['start_date_time'] = isset($data['start_date_time']) ? $data['start_date_time'] : null;
        $this->container['end_date_time'] = isset($data['end_date_time']) ? $data['end_date_time'] : null;
        $this->container['daily_start_time'] = isset($data['daily_start_time']) ? $data['daily_start_time'] : null;
        $this->container['daily_end_time'] = isset($data['daily_end_time']) ? $data['daily_end_time'] : null;
    }

    /**
     * Show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalidProperties = [];

        return $invalidProperties;
    }

    /**
     * Validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properties are valid
     */
    public function valid()
    {
        return count($this->listInvalidProperties()) === 0;
    }

    /**
     * Gets start_date_time
     *
     * @return \DateTime
     */
    public function getStartDateTime()
    {
        return $this->container['start_date_time'];
    }

    /**
     * Sets start_date_time
     *
     * @param \DateTime $start_date_time Date and time that the booking window opens; that is, the first day of sales.
     *
     * @return $this
     */
    public function setStartDateTime($start_date_time)
    {
        $this->container['start_date_time'] = $start_date_time;

        return $this;
    }

    /**
     * Gets end_date_time
     *
     * @return \DateTime
     */
    public function getEndDateTime()
    {
        return $this->container['end_date_time'];
    }

    /**
     * Sets end_date_time
     *
     * @param \DateTime $end_date_time Date and time that the booking window closes; that is, the last day of sales.
     *
     * @return $this
     */
    public function setEndDateTime($end_date_time)
    {
        $this->container['end_date_time'] = $end_date_time;

        return $this;
    }

    /**
     * Gets daily_start_time
     *
     * @return \DateTime
     */
    public function getDailyStartTime()
    {
        return $this->container['daily_start_time'];
    }

    /**
     * Sets daily_start_time
     *
     * @param \DateTime $daily_start_time The time that the booking window opens; that is, the time that the store opens.
     *
     * @return $this
     */
    public function setDailyStartTime($daily_start_time)
    {
        $this->container['daily_start_time'] = $daily_start_time;

        return $this;
    }

    /**
     * Gets daily_end_time
     *
     * @return \DateTime
     */
    public function getDailyEndTime()
    {
        return $this->container['daily_end_time'];
    }

    /**
     * Sets daily_end_time
     *
     * @param \DateTime $daily_end_time The time that the booking window closes; that is, the time that the store closes.
     *
     * @return $this
     */
    public function setDailyEndTime($daily_end_time)
    {
        $this->container['daily_end_time'] = $daily_end_time;

        return $this;
    }
    /**
     * Returns true if offset exists. False otherwise.
     *
     * @param integer $offset Offset
     *
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     *
     * @param integer $offset Offset
     *
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * Sets value based on offset.
     *
     * @param integer $offset Offset
     * @param mixed   $value  Value to be set
     *
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     *
     * @param integer $offset Offset
     *
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Gets the string presentation of the object
     *
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode(
                ObjectSerializer::sanitizeForSerialization($this),
                JSON_PRETTY_PRINT
            );
        }

        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
    ">

  <!--
       put all combinations of possible usages in this file so that XML->XSD converters
       (like trang) can generate a pretty good XSD.
  -->

  <camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
      <from uri="seda:a"/>
      <to uri="seda:b"/>
    </route>
    <route>
      <from uri="seda:a"/>
      <to uri="seda:b"/>
    </route>
    <route>
      <from ref="a"/>
      <to ref="b"/>
    </route>

    <route>
      <from uri="seda:a"/>
      <process ref="myProcessor"/>
    </route>

    <route>
      <from uri="seda:a"/>
      <filter>
        <predicate>
          <header name="foo"/>
          <isEqualTo value="bar"/>
        </predicate>
      </filter>
      <filter>
        <predicate>
          <header name="foo"/>
          <isEqualTo value="bar"/>
        </predicate>
      </filter>
      <process ref="#myProcessor"/>
    </route>

    <route>
      <from uri="seda:a"/>
      <intercept>
        <interceptor ref="interceptor1"/>
        <interceptor ref="#interceptor2"/>
      </intercept>
      <intercept>
        <interceptor ref="#interceptor1"/>
        <interceptor ref="interceptor2"/>
      </intercept>
      <to uri="seda:b"/>
    </route>

    <route>
      <from uri="seda:a"/>
      <choice>
        <when>
          <predicate>
            <header name="foo"/>
            <isEqualTo value="bar"/>
          </predicate>
          <to uri="seda:b"/>
        </when>
        <when>
          <predicate>
            <header name="foo"/>
            <isNotEqualTo value="cheese"/>
          </predicate>
          <to uri="seda:c"/>
        </when>
        <otherwise>
          <to uri="seda:d"/>
        </otherwise>
      </choice>
    </route>

    <route>
      <from uri="seda:a"/>
      <filter>
        <predicate>
          <header name="foo"/>
          <isEqualTo value="bar"/>
        </predicate>
      </filter>
      <to uri="seda:b"/>
    </route>

    <route>
      <from uri="seda:a"/>
      <to>
        <uri>seda:tap</uri>
        <uri>seda:a</uri>
      </to>
    </route>

    <route>
      <from uri="seda:a"/>
      <recipientList>
        <recipients>
          <header name=""/>
        </recipients>
      </recipientList>
    </route>

    <route>
      <from uri="seda:a"/>
      <recipientList>
        <recipients>
          <header name=""/>
          <tokenize token=","/>
        </recipients>
      </recipientList>
    </route>

    <route>
      <from uri="seda:a"/>
      <filter>
        <predicate>
          <body/>
          <isNotEqualTo value="none"/>
        </predicate>
      </filter>
      <recipientList>
        <recipients>
          <body/>
        </recipients>
      </recipientList>
    </route>

    <route>
      <from uri="seda:a"/>
      <split>
        <recipients>
          <bodyAs class="java.lang.String"/>
          <tokenize token="
"/>
        </recipients>
      </split>
      <to uri="seda:b"/>
    </route>

  </camelContext>

</beans>
        <!-- END SNIPPET: example -->


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.loicortola.controller">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:name="com.loicortola.controller.MyApplication">
        <activity
            android:name="com.loicortola.controller.ui.activity.DrawerActivity"
            android:label="@string/title_activity_drawer"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
import { addStrings } from 'meteor/vulcan:core';

addStrings('en', {
  "feeds.url": "Feed URL",
  "feeds.title": "Feed Title",
  "feeds.userId": "Feed User",
  "feeds.categories": "Feed Categories",
  "feeds.created_message": "Feed successfuly created!",
  "posts.feeds" : "Post Feeds",
  "posts.feeds.new" : " New Post Feeds",
});

addStrings('fr', {
  "feeds.url": "URL du flux RSS",
  "feeds.title": "Titre du flux RSS",
  "feeds.userId": "Auteur pour ce flux RSS",
  "feeds.categories": "Catégories du flux RSS",
});


text:
module Spec
  module Example
    # Lightweight representation of an example group. This is the object
    # that is passed to Spec::Runner::Formatter::BaseFormatter#add_example_group
    class ExampleGroupProxy

      def initialize(example_group) # :nodoc:
        @description         = example_group.description
        @nested_descriptions = example_group.nested_descriptions
        @examples            = example_group.example_proxies
        @location            = example_group.location
        @backtrace           = example_group.backtrace
      end

      # This is the docstring passed to the <tt>describe()</tt> method or any
      # of its aliases
      attr_reader :description

      # Used by Spec::Runner::Formatter::NestedTextFormatter to access the
      # docstrings for each example group in a nested group.
      attr_reader :nested_descriptions

      # A collection of ExampleGroupProxy instances, one for each example
      # declared in this group.
      attr_reader :examples

      # The file and line number at which the represented example group
      # was declared. This is extracted from <tt>caller</tt>, and is therefore
      # formatted as an individual line in a backtrace.
      attr_reader :location

      # Deprecated - use location() instead
      def backtrace
        @backtrace
      end

      # Returns the nested_descriptions collection with any descriptions
      # matching the submitted regexp removed.
      def filtered_description(regexp)
        build_description_from(
          *nested_descriptions.collect do |description|
            description =~ regexp ? $1 : description
          end
        )
      end

      def ==(other) # :nodoc:
        other.description == description
      end

    private

      # FIXME - this is duplicated from ExampleGroupMethods
      def build_description_from(*args)
        text = args.inject("") do |description, arg|
          description << " " unless (description == "" || arg.to_s =~ /^(\s|\.|#)/)
          description << arg.to_s
        end
        text == "" ? nil : text
      end
    end
  end
end


text:
export { default as TransactionLoading } from './TransactionLoading.js';
export { default as Processing } from './Processing.js'
export {default as InfoModal } from './InfoModal.js'
export {default as TermAndServices } from './TermAndServices.js'
export {default as QRCode } from './QRCode.js'


text:
/* Kernel.h - stalkware(1) kernel interface (for launcher)
 * stalkware - blah bleh - (C) 2013, Timo Buhrmester
 * See README for contact-, COPYING for license information.  */

#ifndef STALKWARE_KERNEL_H
#define STALKWARE_KERNEL_H 1

#if HAVE_CONFIG_H
# include <config.h>
#endif

#include "Module.h"

typedef Module* (*modfac_fp)();
template<typename T> Module* spawn() { return new T; }

struct modreg_s {
	const char *modnam_;
	modfac_fp modfac_;
	operator map<string, modfac_fp>::value_type() const {
		return map<string, modfac_fp>::value_type(modnam_, modfac_);
	}
};

#define REG(MOD) {#MOD, &spawn<MOD>}
// for each new module, add the include here:
#include "DummyModule.h"
#include "IRCModule.h"
#include "TWModule.h"

static struct modreg_s facarr[] = {
// and register here:
	REG(DummyModule),
	REG(IRCModule),
	REG(TWModule)
};

#undef REG

struct buddy {
	time_t tlast;
	string plast;
	string mlast;
	string ilast;
	bool ison;
	bool wason;
};

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

	bool run();
	void dump();
	void init(string const& stalkrc, string const& stalkstate,
			int spacing, bool colors, string const& logpath);
private:
	map<string, modfac_fp> facmap_;
	map<string, Module*> modmap_;
	map<Module*, map<string, cfgent>*> cfgmap_;
	map<Module*, vector<vector<string> > > stmap_;
	map<string, cfgent> kerncfg_;
	map<string, buddy> buddies_;

	int spc_;
	string statepath_;
	bool col_;
	string logpath_;

	void process_stalkrc(string const& path);
	void load_stalkstate(string const& path);
	void save_stalkstate(string const& path);
	void process_cfgline(const char *line);
	bool nextqtok(char *data, char **tokstart, char **tokend);
	void add_stalkee(const char *mname, vector<char*> const& user);
	void add_cfg(const char *mname, const char *sett, const char *val);
	void load_mod(const char *mname, const char *mclass);
	void display(time_t now);
};

#endif


text:
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
**********/
// "liveMedia"
// Copyright (c) 1996-2017 Live Networks, Inc.  All rights reserved.
// VP8 Video RTP Sources
// Implementation

#include "VP8VideoRTPSource.hh"

VP8VideoRTPSource*
VP8VideoRTPSource::createNew(UsageEnvironment& env, Groupsock* RTPgs,
			      unsigned char rtpPayloadFormat,
			      unsigned rtpTimestampFrequency) {
  return new VP8VideoRTPSource(env, RTPgs, rtpPayloadFormat,
			       rtpTimestampFrequency);
}

VP8VideoRTPSource
::VP8VideoRTPSource(UsageEnvironment& env, Groupsock* RTPgs,
		     unsigned char rtpPayloadFormat,
		     unsigned rtpTimestampFrequency)
  : MultiFramedRTPSource(env, RTPgs, rtpPayloadFormat, rtpTimestampFrequency) {
}

VP8VideoRTPSource::~VP8VideoRTPSource() {
}

#define incrHeader do { ++resultSpecialHeaderSize; ++headerStart; if (--packetSize == 0) return False; } while (0)

Boolean VP8VideoRTPSource
::processSpecialHeader(BufferedPacket* packet,
                       unsigned& resultSpecialHeaderSize) {
  unsigned char* headerStart = packet->data();
  unsigned packetSize = packet->dataSize();

  // The special header is from 1 to 6 bytes long.
  if (packetSize == 0) return False; // error
  resultSpecialHeaderSize = 1; // unless we learn otherwise

  u_int8_t const byte1 = *headerStart;
  Boolean const X = (byte1&0x80) != 0;
  Boolean const S = (byte1&0x10) != 0;
  u_int8_t const PartID = byte1&0x0F;

  fCurrentPacketBeginsFrame = S && PartID == 0;
  fCurrentPacketCompletesFrame = packet->rtpMarkerBit(); // RTP header's "M" bit

  if (X) {
    incrHeader;

    u_int8_t const byte2 = *headerStart;
    Boolean const I = (byte2&0x80) != 0;
    Boolean const L = (byte2&0x40) != 0;
    Boolean const T = (byte2&0x20) != 0;
    Boolean const K = (byte2&0x10) != 0;

    if (I) {
      incrHeader;
      if ((*headerStart)&0x80) { // extension flag in the PictureID is set
	incrHeader;
      }
    }

    if (L) incrHeader;
    if (T||K) incrHeader;
  }

  return True;
}

char const* VP8VideoRTPSource::MIMEtype() const {
  return "video/VP8";
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto

package com.google.cloud.compute.v1;

public interface ExchangedPeeringRouteOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.ExchangedPeeringRoute)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * The destination range of the route.
   *

   *
   * optional string dest_range = 381327712;
   *
   * @return Whether the destRange field is set.
   */
  boolean hasDestRange();
  /**
   *
   *
   *

   * The destination range of the route.
   *

   *
   * optional string dest_range = 381327712;
   *
   * @return The destRange.
   */
  java.lang.String getDestRange();
  /**
   *
   *
   *

   * The destination range of the route.
   *

   *
   * optional string dest_range = 381327712;
   *
   * @return The bytes for destRange.
   */
  com.google.protobuf.ByteString getDestRangeBytes();

  /**
   *
   *
   *

   * True if the peering route has been imported from a peer. The actual import happens if the field networkPeering.importCustomRoutes is true for this network, and networkPeering.exportCustomRoutes is true for the peer network, and the import does not result in a route conflict.
   *

   *
   * optional bool imported = 114502404;
   *
   * @return Whether the imported field is set.
   */
  boolean hasImported();
  /**
   *
   *
   *

   * True if the peering route has been imported from a peer. The actual import happens if the field networkPeering.importCustomRoutes is true for this network, and networkPeering.exportCustomRoutes is true for the peer network, and the import does not result in a route conflict.
   *

   *
   * optional bool imported = 114502404;
   *
   * @return The imported.
   */
  boolean getImported();

  /**
   *
   *
   *

   * The region of peering route next hop, only applies to dynamic routes.
   *

   *
   * optional string next_hop_region = 122577014;
   *
   * @return Whether the nextHopRegion field is set.
   */
  boolean hasNextHopRegion();
  /**
   *
   *
   *

   * The region of peering route next hop, only applies to dynamic routes.
   *

   *
   * optional string next_hop_region = 122577014;
   *
   * @return The nextHopRegion.
   */
  java.lang.String getNextHopRegion();
  /**
   *
   *
   *

   * The region of peering route next hop, only applies to dynamic routes.
   *

   *
   * optional string next_hop_region = 122577014;
   *
   * @return The bytes for nextHopRegion.
   */
  com.google.protobuf.ByteString getNextHopRegionBytes();

  /**
   *
   *
   *

   * The priority of the peering route.
   *

   *
   * optional uint32 priority = 445151652;
   *
   * @return Whether the priority field is set.
   */
  boolean hasPriority();
  /**
   *
   *
   *

   * The priority of the peering route.
   *

   *
   * optional uint32 priority = 445151652;
   *
   * @return The priority.
   */
  int getPriority();

  /**
   *
   *
   *

   * The type of the peering route.
   * Check the Type enum for the list of possible values.
   *

   *
   * optional string type = 3575610;
   *
   * @return Whether the type field is set.
   */
  boolean hasType();
  /**
   *
   *
   *

   * The type of the peering route.
   * Check the Type enum for the list of possible values.
   *

   *
   * optional string type = 3575610;
   *
   * @return The type.
   */
  java.lang.String getType();
  /**
   *
   *
   *

   * The type of the peering route.
   * Check the Type enum for the list of possible values.
   *

   *
   * optional string type = 3575610;
   *
   * @return The bytes for type.
   */
  com.google.protobuf.ByteString getTypeBytes();
}


text:
import os

import pytest

from pandas import read_csv, read_table

class BaseParser:
    engine = None
    low_memory = True
    float_precision_choices = []

    def update_kwargs(self, kwargs):
        kwargs = kwargs.copy()
        kwargs.update(dict(engine=self.engine, low_memory=self.low_memory))

        return kwargs

    def read_csv(self, *args, **kwargs):
        kwargs = self.update_kwargs(kwargs)
        return read_csv(*args, **kwargs)

    def read_table(self, *args, **kwargs):
        kwargs = self.update_kwargs(kwargs)
        return read_table(*args, **kwargs)

class CParser(BaseParser):
    engine = "c"
    float_precision_choices = [None, "high", "round_trip"]

class CParserHighMemory(CParser):
    low_memory = False

class CParserLowMemory(CParser):
    low_memory = True

class PythonParser(BaseParser):
    engine = "python"
    float_precision_choices = [None]

@pytest.fixture
def csv_dir_path(datapath):
    return datapath("io", "parser", "data")

@pytest.fixture
def csv1(csv_dir_path):
    return os.path.join(csv_dir_path, "test1.csv")

_cParserHighMemory = CParserHighMemory()
_cParserLowMemory = CParserLowMemory()
_pythonParser = PythonParser()

_py_parsers_only = [_pythonParser]
_c_parsers_only = [_cParserHighMemory, _cParserLowMemory]
_all_parsers = _c_parsers_only + _py_parsers_only

_py_parser_ids = ["python"]
_c_parser_ids = ["c_high", "c_low"]
_all_parser_ids = _c_parser_ids + _py_parser_ids

@pytest.fixture(params=_all_parsers, ids=_all_parser_ids)
def all_parsers(request):
    return request.param

@pytest.fixture(params=_c_parsers_only, ids=_c_parser_ids)
def c_parser_only(request):
    return request.param

@pytest.fixture(params=_py_parsers_only, ids=_py_parser_ids)
def python_parser_only(request):
    return request.param


text:
<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="mainActivityButtonStyle">
        <item name="android:background">@color/backViewColor</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">@android:color/holo_green_dark</item>
        <item name="android:textSize">18sp</item>
        <item name="android:textAlignment">center</item>
        <item name="android:layout_gravity">center_horizontal|left</item>
    </style>

    <style name="programNameTextView">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">39dp</item>
        <item name="android:textSize">29sp</item>
        <item name="android:textColor">@color/textColorGreenOrOrangeAllActivities</item>
        <item name="android:text">@string/program_name</item>
        <item name="android:textStyle">normal</item>
        <item name="android:gravity">center_vertical|center_horizontal</item>
        <item name="android:layout_marginTop">10dp</item>
    </style>

    <style name="textViewLoginActivityStandart">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">@color/textViewLoginPasswordApplyColorLoginActivity</item>
        <item name="android:textSize">22sp</item>
    </style>

    <style name="editTextLoginActivityStandart">
        <item name="android:layout_width">120dp</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">@color/editTextStringInsideColorAllActivities</item>
    </style>

    <style name="buttonLoginActivityStandart">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">37dp</item>
        <item name="android:textSize">18sp</item>
        <item name="android:textColor">#FFFFFF</item>
        <item name="android:background">@color/textColorGreenOrOrangeAllActivities</item>
    </style>

    <style name="imageViewAppIconAllActivities">
        <item name="android:layout_height">210dp</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:src">@drawable/tyt</item>
        <item name="android:scaleType">fitCenter</item>
    </style>

    <style name="editTextLoginAndRegistrationActivities">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textSize">17sp</item>
        <item name="android:textColor">@color/editTextStringInsideColorAllActivities</item>
        <item name="android:textAllCaps">false</item>
    </style>

    <style name="textViewLoginAndRegistrationActivities">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_marginTop">7dp</item>
        <item name="android:textColor">@color/textColorGreenOrOrangeAllActivities</item>
        <item name="android:textAllCaps">false</item>
        <item name="android:textSize">18sp</item>
    </style>

    <style name="firstLaunchTextViewGeneral">
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:textSize">16sp</item>
        <item name="android:textColor">@color/frontViewColor</item>

    </style>
</resources>


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.plugin.pinot;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.airlift.log.Logger;
import io.trino.plugin.base.expression.AggregateFunctionRewriter;
import io.trino.plugin.base.expression.AggregateFunctionRule;
import io.trino.plugin.pinot.client.PinotClient;
import io.trino.plugin.pinot.query.DynamicTable;
import io.trino.plugin.pinot.query.DynamicTableBuilder;
import io.trino.plugin.pinot.query.aggregation.ImplementApproxDistinct;
import io.trino.plugin.pinot.query.aggregation.ImplementAvg;
import io.trino.plugin.pinot.query.aggregation.ImplementCountAll;
import io.trino.plugin.pinot.query.aggregation.ImplementCountDistinct;
import io.trino.plugin.pinot.query.aggregation.ImplementMinMax;
import io.trino.plugin.pinot.query.aggregation.ImplementSum;
import io.trino.spi.connector.AggregateFunction;
import io.trino.spi.connector.AggregationApplicationResult;
import io.trino.spi.connector.Assignment;
import io.trino.spi.connector.ColumnHandle;
import io.trino.spi.connector.ColumnMetadata;
import io.trino.spi.connector.ColumnNotFoundException;
import io.trino.spi.connector.ConnectorMetadata;
import io.trino.spi.connector.ConnectorSession;
import io.trino.spi.connector.ConnectorTableHandle;
import io.trino.spi.connector.ConnectorTableMetadata;
import io.trino.spi.connector.ConnectorTableProperties;
import io.trino.spi.connector.Constraint;
import io.trino.spi.connector.ConstraintApplicationResult;
import io.trino.spi.connector.LimitApplicationResult;
import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.connector.SchemaTablePrefix;
import io.trino.spi.connector.TableNotFoundException;
import io.trino.spi.expression.ConnectorExpression;
import io.trino.spi.expression.Variable;
import io.trino.spi.predicate.Domain;
import io.trino.spi.predicate.TupleDomain;
import io.trino.spi.type.ArrayType;
import org.apache.pinot.spi.data.Schema;

import javax.inject.Inject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Verify.verify;
import static com.google.common.cache.CacheLoader.asyncReloading;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Iterables.getOnlyElement;
import static io.trino.plugin.pinot.PinotColumn.getPinotColumnsForPinotSchema;
import static io.trino.plugin.pinot.PinotSessionProperties.isAggregationPushdownEnabled;
import static java.util.Locale.ENGLISH;
import static java.util.Objects.requireNonNull;
import static java.util.function.UnaryOperator.identity;

public class PinotMetadata
        implements ConnectorMetadata
{
    private static final Logger log = Logger.get(PinotMetadata.class);

    private static final Object ALL_TABLES_CACHE_KEY = new Object();
    private static final String SCHEMA_NAME = "default";
    private static final String PINOT_COLUMN_NAME_PROPERTY = "pinotColumnName";

    private final LoadingCache<String, List<PinotColumn>> pinotTableColumnCache;
    private final LoadingCache<Object, List<String>> allTablesCache;
    private final int maxRowsPerBrokerQuery;
    private final AggregateFunctionRewriter aggregateFunctionRewriter;
    private final ImplementCountDistinct implementCountDistinct;

    @Inject
    public PinotMetadata(
            PinotClient pinotClient,
            PinotConfig pinotConfig,
            @ForPinot Executor executor)
    {
        requireNonNull(pinotConfig, "pinot config");
        long metadataCacheExpiryMillis = pinotConfig.getMetadataCacheExpiry().roundTo(TimeUnit.MILLISECONDS);
        this.allTablesCache = CacheBuilder.newBuilder()
                .refreshAfterWrite(metadataCacheExpiryMillis, TimeUnit.MILLISECONDS)
                .build(asyncReloading(CacheLoader.from(pinotClient::getAllTables), executor));
        this.pinotTableColumnCache =
                CacheBuilder.newBuilder()
                        .refreshAfterWrite(metadataCacheExpiryMillis, TimeUnit.MILLISECONDS)
                        .build(asyncReloading(new CacheLoader<>()
                        {
                            @Override
                            public List<PinotColumn> load(String tableName)
                                    throws Exception
                            {
                                Schema tablePinotSchema = pinotClient.getTableSchema(tableName);
                                return getPinotColumnsForPinotSchema(tablePinotSchema);
                            }
                        }, executor));

        executor.execute(() -> this.allTablesCache.refresh(ALL_TABLES_CACHE_KEY));
        this.maxRowsPerBrokerQuery = pinotConfig.getMaxRowsForBrokerQueries();
        this.implementCountDistinct = new ImplementCountDistinct();
        this.aggregateFunctionRewriter = new AggregateFunctionRewriter(identity(), ImmutableSet.<AggregateFunctionRule>builder()
                .add(new ImplementCountAll())
                .add(new ImplementAvg())
                .add(new ImplementMinMax())
                .add(new ImplementSum())
                .add(new ImplementApproxDistinct())
                .add(implementCountDistinct)
                .build());
    }

    @Override
    public List<String> listSchemaNames(ConnectorSession session)
    {
        return ImmutableList.of(SCHEMA_NAME);
    }

    @Override
    public PinotTableHandle getTableHandle(ConnectorSession session, SchemaTableName tableName)
    {
        if (tableName.getTableName().trim().startsWith("select ")) {
            DynamicTable dynamicTable = DynamicTableBuilder.buildFromPql(this, tableName);
            return new PinotTableHandle(tableName.getSchemaName(), dynamicTable.getTableName(), TupleDomain.all(), OptionalLong.empty(), Optional.of(dynamicTable));
        }

        try {
            String pinotTableName = getPinotTableNameFromTrinoTableName(tableName.getTableName());
            return new PinotTableHandle(tableName.getSchemaName(), pinotTableName);
        }
        catch (TableNotFoundException e) {
            log.debug(e, "Table not found: %s", tableName);
            return null;
        }
    }

    @Override
    public ConnectorTableMetadata getTableMetadata(ConnectorSession session, ConnectorTableHandle table)
    {
        PinotTableHandle pinotTableHandle = (PinotTableHandle) table;
        if (pinotTableHandle.getQuery().isPresent()) {
            DynamicTable dynamicTable = pinotTableHandle.getQuery().get();
            Map<String, ColumnHandle> columnHandles = getColumnHandles(session, table);
            ImmutableList.Builder<ColumnMetadata> columnMetadataBuilder = ImmutableList.builder();
            for (String columnName : dynamicTable.getSelections()) {
                PinotColumnHandle pinotColumnHandle = (PinotColumnHandle) columnHandles.get(columnName.toLowerCase(ENGLISH));
                columnMetadataBuilder.add(pinotColumnHandle.getColumnMetadata());
            }

            for (String columnName : dynamicTable.getGroupingColumns()) {
                PinotColumnHandle pinotColumnHandle = (PinotColumnHandle) columnHandles.get(columnName.toLowerCase(ENGLISH));
                columnMetadataBuilder.add(pinotColumnHandle.getColumnMetadata());
            }
            dynamicTable.getAggregateColumns().forEach(handle -> columnMetadataBuilder.add(handle.getColumnMetadata()));
            SchemaTableName schemaTableName = new SchemaTableName(pinotTableHandle.getSchemaName(), dynamicTable.getTableName());
            return new ConnectorTableMetadata(schemaTableName, columnMetadataBuilder.build());
        }
        SchemaTableName tableName = new SchemaTableName(pinotTableHandle.getSchemaName(), pinotTableHandle.getTableName());

        return getTableMetadata(tableName);
    }

    @Override
    public List<SchemaTableName> listTables(ConnectorSession session, Optional<String> schemaNameOrNull)
    {
        ImmutableList.Builder<SchemaTableName> builder = ImmutableList.builder();
        for (String table : getPinotTableNames()) {
            builder.add(new SchemaTableName(SCHEMA_NAME, table));
        }
        return builder.build();
    }

    @Override
    public Map<String, ColumnHandle> getColumnHandles(ConnectorSession session, ConnectorTableHandle tableHandle)
    {
        PinotTableHandle pinotTableHandle = (PinotTableHandle) tableHandle;
        if (pinotTableHandle.getQuery().isPresent()) {
            return getDynamicTableColumnHandles(pinotTableHandle);
        }
        return getPinotColumnHandles(pinotTableHandle.getTableName());
    }

    public Map<String, ColumnHandle> getPinotColumnHandles(String tableName)
    {
        ImmutableMap.Builder<String, ColumnHandle> columnHandlesBuilder = ImmutableMap.builder();
        for (ColumnMetadata columnMetadata : getColumnsMetadata(tableName)) {
            columnHandlesBuilder.put(columnMetadata.getName(),
                    new PinotColumnHandle(getPinotColumnName(columnMetadata), columnMetadata.getType()));
        }
        return columnHandlesBuilder.build();
    }

    private static String getPinotColumnName(ColumnMetadata columnMetadata)
    {
        Object pinotColumnName = requireNonNull(columnMetadata.getProperties().get(PINOT_COLUMN_NAME_PROPERTY), "Pinot column name is missing");
        return pinotColumnName.toString();
    }

    @Override
    public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix)
    {
        requireNonNull(prefix, "prefix is null");
        ImmutableMap.Builder<SchemaTableName, List<ColumnMetadata>> columns = ImmutableMap.builder();
        for (SchemaTableName tableName : listTables(session, prefix)) {
            ConnectorTableMetadata tableMetadata = getTableMetadata(tableName);
            // table can disappear during listing operation
            if (tableMetadata != null) {
                columns.put(tableName, tableMetadata.getColumns());
            }
        }
        return columns.build();
    }

    @Override
    public ColumnMetadata getColumnMetadata(
            ConnectorSession session,
            ConnectorTableHandle tableHandle,
            ColumnHandle columnHandle)
    {
        return ((PinotColumnHandle) columnHandle).getColumnMetadata();
    }

    @Override
    public Optional<Object> getInfo(ConnectorTableHandle table)
    {
        return Optional.empty();
    }

    @Override
    public ConnectorTableProperties getTableProperties(ConnectorSession session, ConnectorTableHandle table)
    {
        return new ConnectorTableProperties();
    }

    @Override
    public Optional<LimitApplicationResult<ConnectorTableHandle>> applyLimit(ConnectorSession session, ConnectorTableHandle table, long limit)
    {
        PinotTableHandle handle = (PinotTableHandle) table;
        if (handle.getLimit().isPresent() && handle.getLimit().getAsLong() <= limit) {
            return Optional.empty();
        }
        Optional<DynamicTable> dynamicTable = handle.getQuery();
        if (dynamicTable.isPresent() &&
                (dynamicTable.get().getLimit().isEmpty() || dynamicTable.get().getLimit().getAsLong() > limit)) {
            dynamicTable = Optional.of(new DynamicTable(dynamicTable.get().getTableName(),
                    dynamicTable.get().getSuffix(),
                    dynamicTable.get().getSelections(),
                    dynamicTable.get().getFilter(),
                    dynamicTable.get().getGroupingColumns(),
                    dynamicTable.get().getAggregateColumns(),
                    dynamicTable.get().getOrderBy(),
                    OptionalLong.of(limit),
                    dynamicTable.get().getOffset(),
                    dynamicTable.get().getQuery()));
        }

        handle = new PinotTableHandle(
                handle.getSchemaName(),
                handle.getTableName(),
                handle.getConstraint(),
                OptionalLong.of(limit),
                dynamicTable);
        boolean singleSplit = dynamicTable.isPresent();
        return Optional.of(new LimitApplicationResult<>(handle, singleSplit, false));
    }

    @Override
    public Optional<ConstraintApplicationResult<ConnectorTableHandle>> applyFilter(ConnectorSession session, ConnectorTableHandle table, Constraint constraint)
    {
        PinotTableHandle handle = (PinotTableHandle) table;
        TupleDomain<ColumnHandle> oldDomain = handle.getConstraint();

        TupleDomain<ColumnHandle> newDomain = oldDomain.intersect(constraint.getSummary());
        TupleDomain<ColumnHandle> remainingFilter;
        if (newDomain.isNone()) {
            remainingFilter = TupleDomain.all();
        }
        else {
            Map<ColumnHandle, Domain> domains = newDomain.getDomains().orElseThrow();

            Map<ColumnHandle, Domain> supported = new HashMap<>();
            Map<ColumnHandle, Domain> unsupported = new HashMap<>();
            for (Map.Entry<ColumnHandle, Domain> entry : domains.entrySet()) {
                // Pinot does not support array literals
                if (((PinotColumnHandle) entry.getKey()).getDataType() instanceof ArrayType) {
                    unsupported.put(entry.getKey(), entry.getValue());
                }
                else {
                    supported.put(entry.getKey(), entry.getValue());
                }
            }
            newDomain = TupleDomain.withColumnDomains(supported);
            remainingFilter = TupleDomain.withColumnDomains(unsupported);
        }

        if (oldDomain.equals(newDomain)) {
            return Optional.empty();
        }

        handle = new PinotTableHandle(
                handle.getSchemaName(),
                handle.getTableName(),
                newDomain,
                handle.getLimit(),
                handle.getQuery());
        return Optional.of(new ConstraintApplicationResult<>(handle, remainingFilter, false));
    }

    @Override
    public Optional<AggregationApplicationResult<ConnectorTableHandle>> applyAggregation(
            ConnectorSession session,
            ConnectorTableHandle handle,
            List<AggregateFunction> aggregates,
            Map<String, ColumnHandle> assignments,
            List<List<ColumnHandle>> groupingSets)
    {
        if (!isAggregationPushdownEnabled(session)) {
            return Optional.empty();
        }

        // Global aggregation is represented by [[]]
        verify(!groupingSets.isEmpty(), "No grouping sets provided");

        // Pinot currently only supports simple GROUP BY clauses with a single grouping set
        if (groupingSets.size() != 1) {
            return Optional.empty();
        }

        PinotTableHandle tableHandle = (PinotTableHandle) handle;
        // If aggregate are present than no further aggregations
        // can be pushed down: there are currently no subqueries in pinot
        if (tableHandle.getQuery().isPresent() &&
                !tableHandle.getQuery().get().getAggregateColumns().isEmpty()) {
            return Optional.empty();
        }

        ImmutableList.Builder<ConnectorExpression> projections = ImmutableList.builder();
        ImmutableList.Builder<Assignment> resultAssignments = ImmutableList.builder();
        ImmutableList.Builder<PinotColumnHandle> aggregationExpressions = ImmutableList.builder();

        for (AggregateFunction aggregate : aggregates) {
            Optional<PinotColumnHandle> rewriteResult = aggregateFunctionRewriter.rewrite(session, aggregate, assignments);
            rewriteResult = applyCountDistinct(session, aggregate, assignments, tableHandle, rewriteResult);
            if (rewriteResult.isEmpty()) {
                return Optional.empty();
            }
            PinotColumnHandle pinotColumnHandle = rewriteResult.get();
            aggregationExpressions.add(pinotColumnHandle);
            projections.add(new Variable(pinotColumnHandle.getColumnName(), pinotColumnHandle.getDataType()));
            resultAssignments.add(new Assignment(pinotColumnHandle.getColumnName(), pinotColumnHandle, pinotColumnHandle.getDataType()));
        }
        List<String> groupingColumns = getOnlyElement(groupingSets).stream()
                .map(PinotColumnHandle.class::cast)
                .map(PinotColumnHandle::getColumnName)
                .collect(toImmutableList());
        OptionalLong limitForDynamicTable = OptionalLong.empty();
        // Ensure that pinot default limit of 10 rows is not used
        // By setting the limit to maxRowsPerBrokerQuery + 1 the connector will
        // know when the limit was exceeded and throw an error
        if (tableHandle.getLimit().isEmpty() && !groupingColumns.isEmpty()) {
            limitForDynamicTable = OptionalLong.of(maxRowsPerBrokerQuery + 1);
        }
        DynamicTable dynamicTable = new DynamicTable(
                tableHandle.getTableName(),
                Optional.empty(),
                ImmutableList.of(),
                tableHandle.getQuery().flatMap(DynamicTable::getFilter),
                groupingColumns,
                aggregationExpressions.build(),
                ImmutableList.of(),
                limitForDynamicTable,
                OptionalLong.empty(),
                "");
        tableHandle = new PinotTableHandle(tableHandle.getSchemaName(), tableHandle.getTableName(), tableHandle.getConstraint(), tableHandle.getLimit(), Optional.of(dynamicTable));

        return Optional.of(new AggregationApplicationResult<>(tableHandle, projections.build(), resultAssignments.build(), ImmutableMap.of(), false));
    }

    private Optional<PinotColumnHandle> applyCountDistinct(ConnectorSession session, AggregateFunction aggregate, Map<String, ColumnHandle> assignments, PinotTableHandle tableHandle, Optional<PinotColumnHandle> rewriteResult)
    {
        AggregateFunctionRule.RewriteContext context = new AggregateFunctionRule.RewriteContext()
        {
            @Override
            public Map<String, ColumnHandle> getAssignments()
            {
                return assignments;
            }

            @Override
            public Function<String, String> getIdentifierQuote()
            {
                return identity();
            }

            @Override
            public ConnectorSession getSession()
            {
                return session;
            }
        };

        if (implementCountDistinct.getPattern().matches(aggregate, context)) {
            Variable input = (Variable) getOnlyElement(aggregate.getInputs());
            // If this is the second pass to applyAggregation for count distinct then
            // the first pass will have added the distinct column to the grouping columns,
            // otherwise do not push down the aggregation.
            // This is to avoid count(column_name) being pushed into pinot, which is currently unsupported.
            // Currently Pinot treats count(column_name) as count(*), i.e. it counts nulls.
            if (tableHandle.getQuery().isEmpty() || !tableHandle.getQuery().get().getGroupingColumns().contains(input.getName())) {
                return Optional.empty();
            }
        }
        return rewriteResult;
    }

    @Override
    public boolean usesLegacyTableLayouts()
    {
        return false;
    }

    @VisibleForTesting
    public List<PinotColumn> getPinotColumns(String tableName)
    {
        String pinotTableName = getPinotTableNameFromTrinoTableName(tableName);
        return getFromCache(pinotTableColumnCache, pinotTableName);
    }

    private List<String> getPinotTableNames()
    {
        return getFromCache(allTablesCache, ALL_TABLES_CACHE_KEY);
    }

    private static <K, V> V getFromCache(LoadingCache<K, V> cache, K key)
    {
        V value = cache.getIfPresent(key);
        if (value != null) {
            return value;
        }
        try {
            return cache.get(key);
        }
        catch (ExecutionException e) {
            throw new PinotException(PinotErrorCode.PINOT_UNCLASSIFIED_ERROR, Optional.empty(), "Cannot fetch from cache " + key, e.getCause());
        }
    }

    private String getPinotTableNameFromTrinoTableName(String trinoTableName)
    {
        List<String> allTables = getPinotTableNames();
        String pinotTableName = null;
        for (String candidate : allTables) {
            if (trinoTableName.equalsIgnoreCase(candidate)) {
                pinotTableName = candidate;
                break;
            }
        }
        if (pinotTableName == null) {
            throw new TableNotFoundException(new SchemaTableName(SCHEMA_NAME, trinoTableName));
        }
        return pinotTableName;
    }

    private Map<String, ColumnHandle> getDynamicTableColumnHandles(PinotTableHandle pinotTableHandle)
    {
        checkState(pinotTableHandle.getQuery().isPresent(), "dynamic table not present");
        String schemaName = pinotTableHandle.getSchemaName();
        DynamicTable dynamicTable = pinotTableHandle.getQuery().get();

        Map<String, ColumnHandle> columnHandles = getPinotColumnHandles(dynamicTable.getTableName());
        ImmutableMap.Builder<String, ColumnHandle> columnHandlesBuilder = ImmutableMap.builder();
        for (String columnName : dynamicTable.getSelections()) {
            PinotColumnHandle columnHandle = (PinotColumnHandle) columnHandles.get(columnName.toLowerCase(ENGLISH));
            if (columnHandle == null) {
                throw new ColumnNotFoundException(new SchemaTableName(schemaName, dynamicTable.getTableName()), columnName);
            }
            columnHandlesBuilder.put(columnName.toLowerCase(ENGLISH), columnHandle);
        }

        for (String columnName : dynamicTable.getGroupingColumns()) {
            PinotColumnHandle columnHandle = (PinotColumnHandle) columnHandles.get(columnName.toLowerCase(ENGLISH));
            if (columnHandle == null) {
                throw new ColumnNotFoundException(new SchemaTableName(schemaName, dynamicTable.getTableName()), columnName);
            }
            columnHandlesBuilder.put(columnName.toLowerCase(ENGLISH), columnHandle);
        }
        dynamicTable.getAggregateColumns()
                .forEach(handle -> columnHandlesBuilder.put(handle.getColumnName().toLowerCase(ENGLISH), handle));
        return columnHandlesBuilder.build();
    }

    private ConnectorTableMetadata getTableMetadata(SchemaTableName tableName)
    {
        return new ConnectorTableMetadata(tableName, getColumnsMetadata(tableName.getTableName()));
    }

    private List<ColumnMetadata> getColumnsMetadata(String tableName)
    {
        List<PinotColumn> columns = getPinotColumns(tableName);
        return columns.stream()
                .map(PinotMetadata::createPinotColumnMetadata)
                .collect(toImmutableList());
    }

    private static ColumnMetadata createPinotColumnMetadata(PinotColumn pinotColumn)
    {
        return ColumnMetadata.builder()
                .setName(pinotColumn.getName().toLowerCase(ENGLISH))
                .setType(pinotColumn.getType())
                .setProperties(ImmutableMap.<String, Object>builder()
                        .put(PINOT_COLUMN_NAME_PROPERTY, pinotColumn.getName())
                        .build())
                .build();
    }

    private List<SchemaTableName> listTables(ConnectorSession session, SchemaTablePrefix prefix)
    {
        if (prefix.getSchema().isEmpty() || prefix.getTable().isEmpty()) {
            return listTables(session, Optional.empty());
        }
        return ImmutableList.of(new SchemaTableName(prefix.getSchema().get(), prefix.getTable().get()));
    }
}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "dia".
 *
 * @property integer $dia_id
 * @property string $descripcion
 * @property string $created
 * @property string $updated
 * @property integer $createby
 * @property integer $updateby
 * @property string $active
 *
 * @property Horario[] $horarios
 */
class Dia extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'dia';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['dia_id'], 'required'],
            [['dia_id', 'createby', 'updateby'], 'integer'],
            [['created', 'updated'], 'safe'],
            [['descripcion'], 'string', 'max' => 45],
            [['active'], 'string', 'max' => 1],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'dia_id' => 'Dia ID',
            'descripcion' => 'Descripcion',
            'created' => 'Created',
            'updated' => 'Updated',
            'createby' => 'Createby',
            'updateby' => 'Updateby',
            'active' => 'Active',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getHorarios()
    {
        return $this->hasMany(Horario::className(), ['dia_id' => 'dia_id']);
    }
}


text:
int allocated_chunks = 0;
bool logging_enabled;
bool init = false;
pthread_mutex_t memory_mutex;
pthread_mutex_t logging_mutex;

void * safe_malloc(int size) {
	if (!init) {
		init = true;
		logging_enabled = ENABLE_LOG;
		pthread_mutex_init(&memory_mutex, NULL);
		pthread_mutex_init(&logging_mutex, NULL);
	}

	void * chunk = malloc(size);
	if (chunk == NULL) {
		printf("ERROR: memory allocation failed, exit\n");
		exit(1);
	}

	// increment number of created chunks
	pthread_mutex_lock(&memory_mutex);
	allocated_chunks++;
	pthread_mutex_unlock(&memory_mutex);

	// Set the memory chunk values to 0;
	memset(chunk, 0, size);

	return chunk;
}

void safe_free(void * chunk) {
	if (!init) {
		init = true;
		logging_enabled = ENABLE_LOG;
		pthread_mutex_init(&memory_mutex, NULL);
		pthread_mutex_init(&logging_mutex, NULL);
	}

	if (chunk != NULL) {
		free(chunk);
		chunk = NULL;

		// decrement number of created chunks
		pthread_mutex_lock(&memory_mutex);
		allocated_chunks--;
		pthread_mutex_unlock(&memory_mutex);
	}
}

FILE * safe_fopen(const char * file_name, const char * mode) {
	FILE * stream = fopen(file_name, mode);
	if (stream == NULL) {
		printf("ERROR: loading file at %s\n", file_name);
		exit(1);
	}

	return stream;
}

void safe_fread(void * buffer, int size, FILE * stream) {
	fread(buffer, size, 1, stream);
	if (buffer == NULL) {
		fclose(stream);
		exit(1);
	}
}

char * safe_strdup(const char * str) {
	if (!init) {
		init = true;
		logging_enabled = ENABLE_LOG;
		pthread_mutex_init(&memory_mutex, NULL);
		pthread_mutex_init(&logging_mutex, NULL);
	}

	char * dup = strdup(str);
	if (dup == NULL) {
		printf("ERROR: duplicating string %s\n", str);
		exit(1);
	}

	// increment number of created chunks
	pthread_mutex_lock(&memory_mutex);
	allocated_chunks++;
	pthread_mutex_unlock(&memory_mutex);

	return dup;
}

void safe_pthread_create(pthread_t * thread, const pthread_attr_t * attr, void * (*start_routine) (void *), void *arg) {
	int rv = pthread_create(thread, attr, start_routine, arg);
	if (rv != 0) {
		printf("ERROR: unable to create new thread.\n");
		exit(1);
	}
}

void write_log2(const char * msg, ...) {
	if (!init) {
		init = true;
		logging_enabled = ENABLE_LOG;
		pthread_mutex_init(&memory_mutex, NULL);
		pthread_mutex_init(&logging_mutex, NULL);
	}

	if (!logging_enabled) {
		return;
	}

	char buffer[MAX_LOG_LINE];
	va_list format_args;
	FILE * file_stream;

	// Format input message
	va_start(format_args, msg);
	vsprintf(buffer, msg, format_args);
	va_end(format_args);

	pthread_mutex_lock(&logging_mutex);
	file_stream = safe_fopen("log.txt", "a");
	fprintf(file_stream, buffer);
	fclose(file_stream);
	pthread_mutex_unlock(&logging_mutex);
}

void write_log1(const char * func, const char * msg, ...) {
	if (!init) {
		init = true;
		logging_enabled = ENABLE_LOG;
		pthread_mutex_init(&memory_mutex, NULL);
		pthread_mutex_init(&logging_mutex, NULL);
	}

	if (!logging_enabled) {
		return;
	}

	char buffer1[MAX_LOG_LINE];
	char buffer2[MAX_LOG_LINE];
	va_list format_args;
	FILE * file_stream;

	// Format input message
	va_start(format_args, msg);
	vsprintf(buffer1, msg, format_args);
	va_end(format_args);

	// Format time
	sprintf(buffer2, "[%s] %s\n", func, buffer1);

	pthread_mutex_lock(&logging_mutex);
	file_stream = safe_fopen("log.txt", "a");
	fprintf(file_stream, buffer2);
	fclose(file_stream);
	pthread_mutex_unlock(&logging_mutex);
}


text:
package ${package};

import org.knime.core.node.defaultnodesettings.DefaultNodeSettingsPane;
import org.knime.core.node.defaultnodesettings.DialogComponentNumber;
import org.knime.core.node.defaultnodesettings.SettingsModelIntegerBounded;

/**
 * NodeDialog for the "${node}" Node.
 *
 * This node dialog derives from {@link DefaultNodeSettingsPane} which allows
 * creation of a simple dialog with standard components. If you need a more
 * complex dialog please derive directly from
 * {@link org.knime.core.node.NodeDialogPane}.
 */
public class ${node}Dialog extends DefaultNodeSettingsPane {

    /**
     * New pane for configuring ${node} node dialog.
     * This is just a suggestion to demonstrate possible default dialog
     * components.
     */
    protected ${node}Dialog() {
        super();

        addDialogComponent(new DialogComponentNumber(
                new SettingsModelIntegerBounded(
                    ${node}Model.CFGKEY_COUNT,
                    ${node}Model.DEFAULT_COUNT,
                    Integer.MIN_VALUE, Integer.MAX_VALUE),
                    "Counter:", /*step*/ 1, /*componentwidth*/ 5));

    }
}


text:
> Extend an object with the properties of other objects, but only if they don't already exist.

**How is this different than `extend` or `assign`?**

* [extend][] and `assign`: "last one wins" - properties are updated or overwritten by new values.
* `defaults`: "first one wins" -  only new properties are filled in.

## Install

Install with [npm](https://www.npmjs.com/)

```sh
$ npm i defaults-shallow --save
```

## Usage

```js
var defaults = require('defaults-shallow');

defaults({a: 'b'}, {c: 'd'});
//=> {a: 'b', c: 'd'}

defaults({a: 'b'}, {a: 'c'});
//=> {a: 'b'}
```

To shallow clone you can use an empty object as the first argument:

```js
var options = defaults({}, {a: 'b'}, {c: 'd'}, {a: 'f'});
//=> {a: 'b', c: 'd'}
```

## Related projects

* [defaults-deep](https://www.npmjs.com/package/defaults-deep): Like `extend` but recursively copies only the missing properties/values to the target object. | [homepage](https://github.com/jonschlinkert/defaults-deep)
* [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow)
* [merge-deep](https://www.npmjs.com/package/merge-deep): Recursively merge values in a javascript object. | [homepage](https://github.com/jonschlinkert/merge-deep)
* [mixin-deep](https://www.npmjs.com/package/mixin-deep): Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. | [homepage](https://github.com/jonschlinkert/mixin-deep)

## Running tests

Install dev dependencies:

```sh
$ npm i -d && npm test
```

## Contributing

Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/defaults-shallow/issues/new).

## Author

**Jon Schlinkert**

+ [github/jonschlinkert](https://github.com/jonschlinkert)
+ [twitter/jonschlinkert](http://twitter.com/jonschlinkert)

## License

Copyright © 2015 Jon Schlinkert
Released under the MIT license.

***

_This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on October 04, 2015._


text:
require 'spec_helper'

describe IttfPoints do
  context '`weight` arguments' do
    describe 'default value' do
      let(:p1) { IttfPoints::Player.new(rating_points: 2572) }
      it { expect(p1.weight).to eq(:r2) }
    end

    describe 'not :r2 but :w2 (alias)' do
      let(:p1) { IttfPoints::Player.new(rating_points: 2572, weight: :W2) }
      before do
        p1.
          win(1412, '2029').
          lose([2145, 2189, '2447'])
      end

      describe '#new_rating_points' do
        it { expect(p1.new_rating_points).to eq 2517 }
      end
    end
  end

  # cf. 9/2015 Ito Mima
  let(:player) { IttfPoints::Player.new(rating_points: 2572, weight: :R2) }

  context 'when player won' do
    before do
      player.win(1412).win('2029')
    end

    describe '#points_difference' do
      it { expect(player.points_difference).to eq [1160, 543] }
    end

    describe '#gained_rating_points' do
      it { expect(player.gained_rating_points).to eq [0, 2] }
    end

    describe '#lost_rating_points' do
      it { expect(player.lost_rating_points).to be_nil }
    end

    describe '#new_added_rating_points' do
      it { expect(player.new_added_rating_points).to eq 2 }
    end
  end

  context 'when player lost' do
    before do
      player.lose(2145).lose(2189).lose('2447')
    end

    describe '#points_difference' do
      it { expect(player.points_difference).to eq [427, 383, 125] }
    end

    describe '#gained_rating_points' do
      it { expect(player.gained_rating_points).to be_nil }
    end

    describe '#lost_rating_points' do
      it { expect(player.lost_rating_points).to eq [24, 21, 12] }
    end

    describe '#new_added_rating_points' do
      it { expect(player.new_added_rating_points).to eq(-57) }
    end
  end

  context 'when player won & lost' do
    before do
      player.
        win(1412, '2029').
        lose([2145, 2189, '2447'])
    end

    describe '#points_difference' do
      it { expect(player.points_difference).to eq [1160, 543, 427, 383, 125] }
    end

    describe '#gained_rating_points' do
      it { expect(player.gained_rating_points).to eq [0, 2] }
    end

    describe '#lost_rating_points' do
      it { expect(player.lost_rating_points).to eq [24, 21, 12] }
    end

    describe '#new_added_rating_points' do
      it { expect(player.new_added_rating_points).to eq(-55) }
    end

    describe '#new_rating_points' do
      it { expect(player.new_rating_points).to eq 2517 }
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace DotVVM.VS2015Extension.DothtmlEditorExtensions.Completions.Dothtml.Base
{
    public enum TriggerPoint
    {
        None,
        DirectiveName,
        DirectiveValue,
        TagName,
        TagAttributeName,
        TagAttributeValue,
        BindingName,
        BindingValue
    }
}


text:
using System.Collections.Generic;

namespace QuizDuell.Json
{
    public class User
    {
        // current_user_games
        public string user_id { get; set; }
        public string name { get; set; }
        public bool qc { get; set; }
        public List<Game> games { get; set; }
        public int q_reviewer { get; set; }
        public List<Friend> friends { get; set; }
        public string email { get; set; }
        public string avatar_code { get; set; }
        public List<object> blocked { get; set; }

        // find_user
        public string facebook_id { get; set; }
        //public string user_id { get; set; }
        //public string name { get; set; }
        //public object avatar_code { get; set; }

        // top_list_rating
        public object key { get; set; }
        public int rating { get; set; }
        //public string name { get; set; }
        //public string avatar_code { get; set; }

        // top_list_writers
        public int n_approved_questions { get; set; }
        //public string name { get; set; }
        //public string avatar_code { get; set; }
    }
}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>CSS Grid Layout Test: Minimum size of grid items</title>
<link rel="author" title="Manuel Rego Casasnovas" href="mailto:rego@igalia.com">
<link rel="help" href="http://www.w3.org/TR/css-grid-1/#min-size-auto" title="6.5. Implied Minimum Size of Grid Items">
<link rel="match" href="../../reference/ref-filled-green-100px-square.xht">
<meta name="assert" content="Checks that automatic minimum size is clamped even if the track has an 'auto' min track sizing function as the max track sizing function is fixed.">

Test passes if there is a filled green square and no red.


text:
@interface UIImageView (HUWebImage)

- (void)hu_setImageWithURL:(NSURL *)url;
- (void)hu_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder;
- (void)hu_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(void(^)(UIImage *image, NSError *error, NSURL *imageUrl))completed;

@end


text:
import copy
import re
from typing import List, Optional, Sequence

from .settings import DEFAULT_CONFIG, Config
from .wrap_modes import WrapModes as Modes
from .wrap_modes import formatter_from_string

def import_statement(
    import_start: str,
    from_imports: List[str],
    comments: Sequence[str] = (),
    line_separator: str = "\n",
    config: Config = DEFAULT_CONFIG,
    multi_line_output: Optional[Modes] = None,
) -> str:
    """Returns a multi-line wrapped form of the provided from import statement."""
    formatter = formatter_from_string((multi_line_output or config.multi_line_output).name)
    dynamic_indent = " " * (len(import_start) + 1)
    indent = config.indent
    line_length = config.wrap_length or config.line_length
    statement = formatter(
        statement=import_start,
        imports=copy.copy(from_imports),
        white_space=dynamic_indent,
        indent=indent,
        line_length=line_length,
        comments=comments,
        line_separator=line_separator,
        comment_prefix=config.comment_prefix,
        include_trailing_comma=config.include_trailing_comma,
        remove_comments=config.ignore_comments,
    )
    if config.balanced_wrapping:
        lines = statement.split(line_separator)
        line_count = len(lines)
        if len(lines) > 1:
            minimum_length = min(len(line) for line in lines[:-1])
        else:
            minimum_length = 0
        new_import_statement = statement
        while len(lines[-1]) < minimum_length and len(lines) == line_count and line_length > 10:
            statement = new_import_statement
            line_length -= 1
            new_import_statement = formatter(
                statement=import_start,
                imports=copy.copy(from_imports),
                white_space=dynamic_indent,
                indent=indent,
                line_length=line_length,
                comments=comments,
                line_separator=line_separator,
                comment_prefix=config.comment_prefix,
                include_trailing_comma=config.include_trailing_comma,
                remove_comments=config.ignore_comments,
            )
            lines = new_import_statement.split(line_separator)
    if statement.count(line_separator) == 0:
        return _wrap_line(statement, line_separator, config)
    return statement

def line(content: str, line_separator: str, config: Config = DEFAULT_CONFIG) -> str:
    """Returns a line wrapped to the specified line-length, if possible."""
    wrap_mode = config.multi_line_output
    if len(content) > config.line_length and wrap_mode != Modes.NOQA:  # type: ignore
        line_without_comment = content
        comment = None
        if "#" in content:
            line_without_comment, comment = content.split("#", 1)
        for splitter in ("import ", ".", "as "):
            exp = r"\b" + re.escape(splitter) + r"\b"
            if re.search(exp, line_without_comment) and not line_without_comment.strip().startswith(
                splitter
            ):
                line_parts = re.split(exp, line_without_comment)
                if comment and not (config.use_parentheses and "noqa" in comment):
                    _comma_maybe = (
                        "," if (config.include_trailing_comma and config.use_parentheses) else ""
                    )
                    line_parts[
                        -1
                    ] = f"{line_parts[-1].strip()}{_comma_maybe}{config.comment_prefix}{comment}"
                next_line = []
                while (len(content) + 2) > (
                    config.wrap_length or config.line_length
                ) and line_parts:
                    next_line.append(line_parts.pop())
                    content = splitter.join(line_parts)
                if not content:
                    content = next_line.pop()

                cont_line = _wrap_line(
                    config.indent + splitter.join(next_line).lstrip(), line_separator, config
                )
                if config.use_parentheses:
                    if splitter == "as ":
                        output = f"{content}{splitter}{cont_line.lstrip()}"
                    else:
                        _comma = "," if config.include_trailing_comma and not comment else ""
                        if wrap_mode in (
                            Modes.VERTICAL_HANGING_INDENT,  # type: ignore
                            Modes.VERTICAL_GRID_GROUPED,  # type: ignore
                        ):
                            _separator = line_separator
                        else:
                            _separator = ""
                        _comment = ""
                        if comment and "noqa" in comment:
                            _comment = f"{config.comment_prefix}{comment}"
                            cont_line = cont_line.rstrip()
                            _comma = "," if config.include_trailing_comma else ""
                        output = (
                            f"{content}{splitter}({_comment}"
                            f"{line_separator}{cont_line}{_comma}{_separator})"
                        )
                    lines = output.split(line_separator)
                    if config.comment_prefix in lines[-1] and lines[-1].endswith(")"):
                        content, comment = lines[-1].split(config.comment_prefix, 1)
                        lines[-1] = content + ")" + config.comment_prefix + comment[:-1]
                    return line_separator.join(lines)
                return f"{content}{splitter}\\{line_separator}{cont_line}"
    elif len(content) > config.line_length and wrap_mode == Modes.NOQA:  # type: ignore
        if "# NOQA" not in content:
            return f"{content}{config.comment_prefix} NOQA"

    return content

_wrap_line = line


text:
// This file is included by other files and is not in itself syntactically
// correct.

// void mkn::kul::Process::run() KTHROW(mkn::kul::proc::Exception){

SECURITY_ATTRIBUTES sa;
ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES));
// Set the bInheritHandle flag so pipe handles are inherited.
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;

std::stringstream ss;
ss << this;

const ULONG &pipeID = PIPE_ID();
std::string pipeOut = "\\\\.\\Pipe\\kul_proc_out." + std::to_string(this_proc::id()) + "." +
                      ss.str() + "." + std::to_string(pipeID);
std::string pipeErr = "\\\\.\\Pipe\\kul_proc_err." + std::to_string(this_proc::id()) + "." +
                      ss.str() + "." + std::to_string(pipeID);
std::string pipeIn = "\\\\.\\Pipe\\kul_proc_in." + std::to_string(this_proc::id()) + "." +
                     ss.str() + "." + std::to_string(pipeID);

LPSTR lPipeOut = _strdup(pipeOut.c_str());
g_hChildStd_OUT_Wr = ::CreateNamedPipeA(lPipeOut, PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
                                        PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1,
                                        __MKN_KUL_PROCESS_BUFFER__, __MKN_KUL_PROCESS_BUFFER__, 0, &sa);
if (!g_hChildStd_OUT_Wr) error(__LINE__, "CreatePipe failed");
g_hChildStd_OUT_Rd = ::CreateFileA(lPipeOut, GENERIC_READ, 0, &sa, OPEN_EXISTING,
                                   FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0);
if (!g_hChildStd_OUT_Rd) error(__LINE__, "CreatePipe failed");
if (!SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0))
  error(__LINE__, "SetHandleInformation failed");

LPSTR lPipeErr = _strdup(pipeErr.c_str());
g_hChildStd_ERR_Wr = ::CreateNamedPipeA(lPipeErr, PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
                                        PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1,
                                        __MKN_KUL_PROCESS_BUFFER__, __MKN_KUL_PROCESS_BUFFER__, 0, &sa);
if (!g_hChildStd_ERR_Wr) error(__LINE__, "CreatePipe failed");
g_hChildStd_ERR_Rd = ::CreateFileA(lPipeErr, GENERIC_READ, 0, &sa, OPEN_EXISTING,
                                   FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0);
if (!g_hChildStd_ERR_Rd) error(__LINE__, "CreatePipe failed");
if (!SetHandleInformation(g_hChildStd_ERR_Rd, HANDLE_FLAG_INHERIT, 0))
  error(__LINE__, "SetHandleInformation failed");

bool bSuccess = FALSE;

PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;

ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));

siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.dwFlags = STARTF_USESTDHANDLES;
siStartInfo.hStdError = g_hChildStd_ERR_Wr;
siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
siStartInfo.wShowWindow = SW_HIDE;
siStartInfo.lpDesktop = NULL;
siStartInfo.lpReserved = NULL;
siStartInfo.lpTitle = NULL;
siStartInfo.cbReserved2 = 0;
siStartInfo.lpReserved2 = NULL;

unsigned flags = CREATE_UNICODE_ENVIRONMENT;
HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
                         FILE_ATTRIBUTE_NORMAL, NULL);
if (cons == INVALID_HANDLE_VALUE) {
  flags |= DETACHED_PROCESS;
} else {
  CloseHandle(cons);
}

preStart();

LPTSTR lpszVariable;
LPCH lpvEnv = GetEnvironmentStrings();
if (lpvEnv == NULL) error(__LINE__, "GetEnvironmentStrings() failed.");
kul::hash::map::S2S env;
for (lpszVariable = (LPTSTR)lpvEnv; *lpszVariable; lpszVariable++) {
  std::stringstream ss;
  while (*lpszVariable) ss << *lpszVariable++;
  std::string var = ss.str();
  if (var.find("=") != std::string::npos)
    env.insert(var.substr(0, var.find("=")), var.substr(var.find("=") + 1));
}
if (FreeEnvironmentStrings(lpvEnv) == 0) error(__LINE__, "FreeEnvironmentStrings() failed");

char const *dir = directory().empty() ? 0 : directory().c_str();
std::string cmd(toString());

expand(cmd);
LPSTR szCmdline = _strdup(cmd.c_str());

if (vars().size()) {
  std::wstring newEnv;

  for (auto &evs : vars()) env[evs.first] = evs.second;

  for (auto &evs : env) {
    std::string name = evs.first;
    std::string var(name + "=" + evs.second);
    newEnv += std::wstring(var.begin(), var.end());
    newEnv.push_back('\0');
  }
  // may not work
  bSuccess = CreateProcess(NULL, szCmdline, NULL, NULL, TRUE, flags, (LPVOID)newEnv.c_str(), dir,
                           &siStartInfo, &piProcInfo);
} else
  bSuccess =
      CreateProcess(NULL, szCmdline, NULL, NULL, TRUE, flags, NULL, dir, &siStartInfo, &piProcInfo);

if (!bSuccess) error(__LINE__, "CreateProcess failed with last error: " + GetLastError());

pid(piProcInfo.dwProcessId);

CloseHandle(g_hChildStd_OUT_Wr);
CloseHandle(g_hChildStd_ERR_Wr);

if (this->waitForExit()) {
  OVERLAPPED il = {0};
  memset(&il, 0, sizeof(il));
  il.hEvent = revent;
  OVERLAPPED ol = {0};
  memset(&ol, 0, sizeof(ol));
  ol.hEvent = revent;
  OVERLAPPED el = {0};
  memset(&el, 0, sizeof(el));
  el.hEvent = revent;

  DWORD dwRead;
  CHAR chBuf[__MKN_KUL_PROCESS_BUFFER__ + 1];
  bSuccess = FALSE;
  bool alive = true;
  do {
#if defined(_MKN_KUL_PROC_LOOP_NSLEEP_) && (_MKN_KUL_PROC_LOOP_NSLEEP_ > 0)
    mkn::kul::this_thread::nSleep(_MKN_KUL_PROC_LOOP_NSLEEP_);
#endif
    alive = WaitForSingleObject(piProcInfo.hProcess, 11) == WAIT_TIMEOUT;
    for (;;) {
      dwRead = 0;
      bSuccess = ::ReadFile(g_hChildStd_OUT_Rd, chBuf, __MKN_KUL_PROCESS_BUFFER__, &dwRead, &ol);
      while (!bSuccess &&
             (GetLastError() == ERROR_IO_PENDING || GetLastError() == ERROR_IO_INCOMPLETE)) {
        WaitForSingleObject(ol.hEvent, 11);
        bSuccess = GetOverlappedResult(g_hChildStd_OUT_Rd, &ol, &dwRead, 0);
      }
      if (!bSuccess || dwRead == 0) break;
      chBuf[dwRead] = '\0';
      out(std::string(chBuf, dwRead));
    }
    for (;;) {
      dwRead = 0;
      bSuccess = ::ReadFile(g_hChildStd_ERR_Rd, chBuf, __MKN_KUL_PROCESS_BUFFER__, &dwRead, &el);
      if (GetLastError() == ERROR_IO_PENDING) {
        WaitForSingleObject(el.hEvent, 11);
        bSuccess = GetOverlappedResult(g_hChildStd_OUT_Rd, &el, &dwRead, 0);
      }
      if (!bSuccess || dwRead == 0) break;
      chBuf[dwRead] = '\0';
      err(std::string(chBuf, dwRead));
    }
  } while (alive);
}
tearDown();
if (this->waitForExit()) {
  DWORD ec = 0;
  if (FALSE == GetExitCodeProcess(piProcInfo.hProcess, &ec))
    KEXCEPT(mkn::kul::proc::Exception, "GetExitCodeProcess failure");
  exitCode(ec);
  finish();
  setFinished();
}
CloseHandle(piProcInfo.hThread);
CloseHandle(piProcInfo.hProcess);

// }


text:
<?php

namespace Gopro\InventarioBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;

class ServicioAdmin extends Admin
{

    private $securityContext;

    /**
     * Orden Predeterminado del datagrid
     *
     * @var array
     */
    protected $datagridValues = array(
        '_page' => 1,
        '_sort_order' => 'DESC',
        '_sort_by' => 'tiempo'
    );

    public function setSecurityContext($securityContext) {
        $this->securityContext = $securityContext;
    }

    public function getSecurityContext() {
        return $this->securityContext;
    }

    /**
     * Default Entity values
     *
     */
    public function getNewInstance()
    {
        $instance = parent::getNewInstance();
        $instance->setUser($this->getSecurityContext()->getToken()->getUser());

        return $instance;
    }

    /**
     * @param DatagridMapper $datagridMapper
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('id')
            ->add('item')
            ->add('tiempo', null, array('label' => 'Solicitado en', 'format' => 'Y-m-d hh:mm'))
            ->add('servicioestado', null, array('label' => 'Estado'))
            ->add('serviciotipo', null, array('label' => 'Tipo'))
            ->add('descripcion', null, array('label' => 'Descripción'))
            ->add('user', null, array('label' => 'Solicitado a'))
        ;
    }

    /**
     * @param ListMapper $listMapper
     */
    protected function configureListFields(ListMapper $listMapper)
    {

        $listMapper
            ->add('id')
            ->add('item')
            ->add('tiempo', null, array('label' => 'Solicitado en', 'format' => 'Y-m-d h:i'))
            ->add('servicioestado', null, array('label' => 'Estado'))
            ->add('serviciotipo', null, array('label' => 'Tipo'))
            ->add('descripcion', null, array('label' => 'Descripción', 'editable' => true))
            ->add('user', null, array('label' => 'Solicitado a'))
            ->add('_action', 'actions', array(
                'actions' => array(
                    'show' => array(),
                    'edit' => array(),
                    'delete' => array(),
                )
            ))
        ;
    }

    /**
     * @param FormMapper $formMapper
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('item')
            ->add('tiempo', 'sonata_type_datetime_picker', array('label' => 'Solicitado en'))
            ->add('servicioestado', null, array('label' => 'Estado'))
            ->add('serviciotipo', null, array('label' => 'Tipo'))
            ->add('descripcion', null, array('label' => 'Descripción'))
            ->add('user', null, array('label' => 'Solicitado a'))
            ->add('servicioacciones','sonata_type_collection', array(
                'label' => 'Acciones',
                'by_reference' => false),array(
                    'edit' => 'inline',
                    'inline' => 'table'
                )
            )
        ;
    }

    /**
     * @param ShowMapper $showMapper
     */
    protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->add('id')
            ->add('item')
            ->add('tiempo', null, array('label' => 'Solicitado en', 'format' => 'Y-m-d h:i'))
            ->add('servicioestado', null, array('label' => 'Estado'))
            ->add('serviciotipo', null, array('label' => 'Tipo'))
            ->add('descripcion', null, array('label' => 'Descripción'))
            ->add('user', null, array('label' => 'Solicitado a'))
            ->add('servicioacciones', null, array('label' => 'Acciones'))
        ;
    }
}