text:
<?php

require_once($CFG->libdir.'/formslib.php');
require_once($CFG->libdir.'/datalib.php');

class user_bulk_action_form extends moodleform {
    function definition() {
        global $CFG;

        $mform =& $this->_form;

        $syscontext = context_system::instance();
        $actions = array(0=>get_string('choose').'...');
        if (has_capability('moodle/user:update', $syscontext)) {
            $actions[1] = get_string('confirm');
        }
        if (has_capability('moodle/site:readallmessages', $syscontext) && !empty($CFG->messaging)) {
            $actions[2] = get_string('messageselectadd');
        }
        if (has_capability('moodle/user:delete', $syscontext)) {
            $actions[3] = get_string('delete');
        }
        $actions[4] = get_string('displayonpage');
        if (has_capability('moodle/user:update', $syscontext)) {
            $actions[5] = get_string('download', 'admin');
        }
        if (has_capability('moodle/role:assign', $syscontext)){
             //TODO: MDL-24064
            //$actions[6] = get_string('enrolmultipleusers', 'admin');
        }
        if (has_capability('moodle/user:update', $syscontext)) {
            $actions[7] = get_string('forcepasswordchange');
        }
        if (has_capability('moodle/cohort:assign', $syscontext)) {
            $actions[8] = get_string('bulkadd', 'core_cohort');
        }
        $objs = array();
        $objs[] =& $mform->createElement('select', 'action', null, $actions);
        $objs[] =& $mform->createElement('submit', 'doaction', get_string('go'));
        $mform->addElement('group', 'actionsgrp', get_string('withselectedusers'), $objs, ' ', false);
    }
}

class user_bulk_form extends moodleform {
    function definition() {

        $mform =& $this->_form;
        $acount =& $this->_customdata['acount'];
        $scount =& $this->_customdata['scount'];
        $ausers =& $this->_customdata['ausers'];
        $susers =& $this->_customdata['susers'];
        $total  =& $this->_customdata['total'];

        $achoices = array();
        $schoices = array();

        if (is_array($ausers)) {
            if ($total == $acount) {
                $achoices[0] = get_string('allusers', 'bulkusers', $total);
            } else {
                $a = new stdClass();
                $a->total  = $total;
                $a->count = $acount;
                $achoices[0] = get_string('allfilteredusers', 'bulkusers', $a);
            }
            $achoices = $achoices + $ausers;

            if ($acount > MAX_BULK_USERS) {
                $achoices[-1] = '...';
            }

        } else {
            $achoices[-1] = get_string('nofilteredusers', 'bulkusers', $total);
        }

        if (is_array($susers)) {
            $a = new stdClass();
            $a->total  = $total;
            $a->count = $scount;
            $schoices[0] = get_string('allselectedusers', 'bulkusers', $a);
            $schoices = $schoices + $susers;

            if ($scount > MAX_BULK_USERS) {
                $schoices[-1] = '...';
            }

        } else {
            $schoices[-1] = get_string('noselectedusers', 'bulkusers');
        }

        $mform->addElement('header', 'users', get_string('usersinlist', 'bulkusers'));

        $objs = array();
        $objs[0] =& $mform->createElement('select', 'ausers', get_string('available', 'bulkusers'), $achoices, 'size="15"');
        $objs[0]->setMultiple(true);
        $objs[1] =& $mform->createElement('select', 'susers', get_string('selected', 'bulkusers'), $schoices, 'size="15"');
        $objs[1]->setMultiple(true);

        $grp =& $mform->addElement('group', 'usersgrp', get_string('users', 'bulkusers'), $objs, ' ', false);
        $mform->addHelpButton('usersgrp', 'users', 'bulkusers');

        $mform->addElement('static', 'comment');

        $objs = array();
        $objs[] =& $mform->createElement('submit', 'addsel', get_string('addsel', 'bulkusers'));
        $objs[] =& $mform->createElement('submit', 'removesel', get_string('removesel', 'bulkusers'));
        $objs[] =& $mform->createElement('submit', 'addall', get_string('addall', 'bulkusers'));
        $objs[] =& $mform->createElement('submit', 'removeall', get_string('removeall', 'bulkusers'));
        $grp =& $mform->addElement('group', 'buttonsgrp', get_string('selectedlist', 'bulkusers'), $objs, array(' ', '
'), false);
        $mform->addHelpButton('buttonsgrp', 'selectedlist', 'bulkusers');

        $renderer =& $mform->defaultRenderer();
        $template = '{label} {element}';
        $renderer->setGroupElementTemplate($template, 'usersgrp');
    }
}


text:
using namespace std;

HistoryData::HistoryData(){
  symbol_amount = 0;
}

HistoryData::~HistoryData(){
  for(int i=0;i<symbol_amount;i++){
    free(bar_data[i]);
  }
}

int HistoryData::load(char *csv){
  fstream file;
  file.open(csv, ios::in | ios::binary);

  file.seekg(0, ios::end);
  streampos filesize = file.tellg();
  file.seekg(0, ios::beg);

  bar_data[symbol_amount] = (char *) malloc(filesize);
  file.read((char *)bar_data[symbol_amount], filesize);

  file.close();
  symbol_amount++;

  return (symbol_amount - 1);
}

void HistoryData::get(int index, unsigned long pos, int size, void* arg){
  memcpy(arg, bar_data[index] + pos, size);
  return;
}

// calcurate average from pos pointer and period
double HistoryData::moving_average(int index, unsigned long pos, int period){
  double price;
  double sum = 0;
  for(int i=0;i<period;i++){
    get(index, pos - i*44, 8, (void*)&price);
    sum += price;
  }
  return sum/period;
}

redpajama_set_name: RedPajamaGithub


text:
from datetime import datetime
from typing import Optional, List, Dict, Any

from dateutil import tz
from django.db import models
from django.urls import reverse

from mainapp.functions.minio import minio_client, minio_file_bucket
from .helper import DefaultFields
from .location import Location
from .person import Person

# Assumption: This is older than the oldest data
fallback_date = datetime(1995, 1, 1, 0, 0, 0, tzinfo=tz.tzlocal())

class File(DefaultFields):
    name = models.CharField(max_length=200)
    filename = models.CharField(max_length=200)
    # https://stackoverflow.com/a/643772/3549270#comment11618045_643772
    mime_type = models.CharField(max_length=255)
    legal_date = models.DateField(null=True, blank=True)
    sort_date = models.DateTimeField(default=fallback_date)
    filesize = models.IntegerField(null=True, blank=True)
    locations = models.ManyToManyField(Location, blank=True)
    mentioned_persons = models.ManyToManyField(Person, blank=True)
    page_count = models.IntegerField(null=True, blank=True)
    parsed_text = models.TextField(null=True, blank=True)
    # In case the license is different than the rest of the system, e.g. a CC-licensed picture
    license = models.CharField(max_length=200, null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    # Sometimes we need to delete file even if they were not deleted at the source
    manually_deleted = models.BooleanField(default=False)

    # Store these values for we might need them for a proxy
    oparl_access_url = models.CharField(max_length=512, null=True, blank=True)
    oparl_download_url = models.CharField(max_length=512, null=True, blank=True)

    def __str__(self):
        return self.filename or self.name

    def coordinates(self) -> List[Dict[str, Any]]:
        coordinates = []
        for location in self.locations.all():
            coordinate = location.coordinates()
            if coordinate:
                coordinates.append(coordinate)

        return coordinates

    def person_ids(self):
        return [person.id for person in self.mentioned_persons.all()]

    def get_default_link(self):
        return reverse("file", args=[self.id])

    def name_autocomplete(self):
        return self.name if len(self.name) > 0 else " "

    def get_oparl_url(self) -> Optional[str]:
        return self.oparl_download_url or self.oparl_access_url

    def manually_delete(self):
        """Sometimes we need to delete files even if they were not deleted at the source"""
        self.deleted = True
        self.manually_deleted = True
        self.save()
        minio_client().remove_object(minio_file_bucket, str(self.id))

    def get_assigned_meetings(self):
        from .meeting import Meeting

        return (
            self.meeting_auxiliary_files.all()
            | self.meeting_invitation.all()
            | self.meeting_auxiliary_files.all()
            | self.meeting_results_protocol.all()
            | self.meeting_verbatim_protocol.all()
            | Meeting.objects.filter(agendaitem__resolution_file=self)
        ).distinct()


text:
<?php

namespace WeAreArchitect\SharePoint;

class SPFolder extends SPListObject implements SPItemInterface
{
    use SPTimestampsTrait;

    /**
     * System Folder names
     *
     * @static
     * @access  public
     * @var     array
     */
    public static $systemFolders = [
        'forms',
    ];

    /**
     * SharePoint List GUID
     *
     * @access  protected
     * @var     string
     */
    protected $listGUID;

    /**
     * SharePoint List Title
     *
     * @access  protected
     * @var     string
     */
    protected $listTitle;

    /**
     * Folder Name
     *
     * @access  protected
     * @var     string
     */
    protected $name;

    /**
     * SharePoint Folder constructor
     *
     * @access  public
     * @param   SPSite $site     SharePoint Site
     * @param   array  $json     JSON response from the SharePoint REST API
     * @param   array  $settings Instantiation settings
     * @return  SPFolder
     */
    public function __construct(SPSite $site, array $json, array $settings = [])
    {
        $settings = array_replace_recursive([
            'fetch' => false, // fetch SharePoint Items (Folders/Files)?
        ], $settings, [
            'extra' => [],    // extra SharePoint Folder properties to map
            'items' => [],    // SharePoint Item instantiation settings
        ]);

        parent::__construct([
            'type'        => 'odata.type',
            'guid'        => 'UniqueId',
            'name'        => 'Name',
            'title'       => 'Name',
            'created'     => 'TimeCreated',
            'modified'    => 'TimeLastModified',
            'relativeUrl' => 'ServerRelativeUrl',
            'itemCount'   => 'ItemCount',

            // only available in sub Folders
            'listGUID'    => 'ListItemAllFields->ParentList->Id',

            // only available in the root Folder
            'listTitle'   => 'Properties->vti_x005f_listtitle',
        ], $settings['extra']);

        $this->site = $site;

        $this->hydrate($json);

        if ($settings['fetch'] && $this->itemCount > 0) {
            $this->getSPItems($settings['items']);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function toArray()
    {
        return [
            'type'         => $this->type,
            'guid'         => $this->guid,
            'title'        => $this->title,
            'name'         => $this->name,
            'created'      => $this->created,
            'modified'     => $this->modified,
            'relative_url' => $this->relativeUrl,
            'items'        => $this->items,
            'item_count'   => $this->itemCount,
            'extra'        => $this->extra,
        ];
    }

    /**
     * Get SharePoint Name
     *
     * @access  public
     * @return  string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Is this a root SharePoint Folder?
     *
     * @access  public
     * @return  bool
     */
    public function isRootFolder()
    {
        return ($this->listTitle !== null);
    }

    /**
     * {@inheritdoc}
     */
    public function isWritable($exception = false)
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function getUrl($path = null)
    {
        return $this->site->getHostname($this->getRelativeUrl($path));
    }

    /**
     * Check if a name matches a SharePoint System Folder
     *
     * @static
     * @access  public
     * @param   string $name SharePoint Folder name
     * @return  bool
     */
    public static function isSystemFolder($name)
    {
        $normalized = strtolower(basename($name));

        return in_array($normalized, static::$systemFolders);
    }

    /**
     * Get the SharePoint List of this Folder
     *
     * Depending if this is a root Folder,
     * retrieve the SharePoint List accordingly
     *
     * @access  public
     * @param   array  $settings Instantiation settings
     * @throws  SPException
     * @return  SPList
     */
    public function getSPList(array $settings = [])
    {
        if ($this->isRootFolder()) {
            return SPList::getByTitle($this->site, $this->listTitle, $settings);
        }

        return SPList::getByGUID($this->site, $this->listGUID, $settings);
    }

    /**
     * Get a SharePoint Folder by GUID
     *
     * @static
     * @access  public
     * @param   SPSite $site     SharePoint Site
     * @param   string $guid     SharePoint Folder GUID
     * @param   array  $settings Instantiation settings
     * @throws  SPException
     * @return  SPFolder
     */
    public static function getByGUID(SPSite $site, $guid, array $settings = [])
    {
        $json = $site->request("_api/web/GetFolderById('".$guid."')", [
            'headers' => [
                'Authorization' => 'Bearer '.$site->getSPAccessToken(),
                'Accept'        => 'application/json',
            ],

            'query'   => [
                '$expand' => 'ListItemAllFields/ParentList,Properties',
            ],
        ]);

        return new static($site, $json, $settings);
    }

    /**
     * Get a SharePoint Folder by Relative URL
     *
     * @static
     * @access  public
     * @param   SPSite $site        SharePoint Site
     * @param   string $relativeUrl SharePoint Folder relative URL
     * @param   array  $settings    Instantiation settings
     * @throws  SPException
     * @return  SPFolder
     */
    public static function getByRelativeUrl(SPSite $site, $relativeUrl, array $settings = [])
    {
        if (static::isSystemFolder($relativeUrl)) {
            throw new SPException('Trying to get a SharePoint System Folder');
        }

        $json = $site->request("_api/web/GetFolderByServerRelativeUrl('".$relativeUrl."')", [
            'headers' => [
                'Authorization' => 'Bearer '.$site->getSPAccessToken(),
                'Accept'        => 'application/json',
            ],

            'query'   => [
                '$expand' => 'ListItemAllFields/ParentList,Properties',
            ],
        ]);

        return new static($site, $json, $settings);
    }

    /**
     * Get SubFolders of a SharePoint Folder
     *
     * @static
     * @access  public
     * @param   SPSite $site        SharePoint Site
     * @param   string $relativeUrl SharePoint Folder relative URL
     * @param   array  $settings    Instantiation settings
     * @throws  SPException
     * @return  array
     */
    public static function getSubFolders(SPSite $site, $relativeUrl, array $settings = [])
    {
        $json = $site->request("_api/web/GetFolderByServerRelativeUrl('".$relativeUrl."')/Folders", [
            'headers' => [
                'Authorization' => 'Bearer '.$site->getSPAccessToken(),
                'Accept'        => 'application/json',
            ],

            'query'   => [
                '$expand' => 'ListItemAllFields/ParentList,Properties',
            ],
        ]);

        $folders = [];

        foreach ($json['value'] as $subFolder) {
            // skip System Folders
            if (! static::isSystemFolder($subFolder['Name'])) {
                $folders[$subFolder['UniqueId']] = new static($site, $subFolder, $settings);
            }
        }

        return $folders;
    }

    /**
     * Create a SharePoint Folder
     *
     * @static
     * @access  public
     * @param   SPFolderInterface $folder   Parent SharePoint Folder
     * @param   array             $name     SharePoint Folder name
     * @param   array             $settings Instantiation settings
     * @throws  SPException
     * @return  SPFolder
     */
    public static function create(SPFolderInterface $folder, $name, array $settings = [])
    {
        $folder->isWritable(true);

        $body = json_encode([
            'odata.type'        => 'SP.Folder',
            'ServerRelativeUrl' => $folder->getRelativeUrl($name),
        ]);

        $json = $folder->request('_api/web/Folders', [
            'headers' => [
                'Authorization'   => 'Bearer '.$folder->getSPAccessToken(),
                'Accept'          => 'application/json',
                'X-RequestDigest' => (string) $folder->getSPFormDigest(),
                'Content-type'    => 'application/json',
                'Content-length'  => strlen($body),
            ],

            'query'   => [
                '$expand' => 'ListItemAllFields/ParentList,Properties',
            ],

            'body'    => $body,
        ], 'POST');

        return new static($folder->getSPSite(), $json, $settings);
    }

    /**
     * Update a SharePoint Folder
     *
     * @access  public
     * @param   array  $properties SharePoint Folder properties (Name, ...)
     * @throws  SPException
     * @return  SPFolder
     */
    public function update(array $properties)
    {
        $properties = array_replace_recursive($properties, [
            'odata.type' => 'SP.Folder',
        ]);

        $body = json_encode($properties);

        $this->request("_api/web/GetFolderByServerRelativeUrl('".$this->relativeUrl."')", [
            'headers' => [
                'Authorization'   => 'Bearer '.$this->getSPAccessToken(),
                'Accept'          => 'application/json',
                'X-RequestDigest' => (string) $this->getSPFormDigest(),
                'X-HTTP-Method'   => 'MERGE',
                'IF-MATCH'        => '*',
                'Content-type'    => 'application/json',
                'Content-length'  => strlen($body),
            ],

            'query'   => [
                '$expand' => 'ListItemAllFields/ParentList,Properties',
            ],

            'body'    => $body,
        ], 'POST');

        // Rehydration is done using the $properties array,
        // since the SharePoint API doesn't return a response
        // on a successful update
        return $this->hydrate($properties, true);
    }

    /**
     * Delete a SharePoint Folder
     *
     * @access  public
     * @throws  SPException
     * @return  bool
     */
    public function delete()
    {
        $this->request("_api/web/GetFolderByServerRelativeUrl('".$this->relativeUrl."')", [
            'headers' => [
                'Authorization'   => 'Bearer '.$this->getSPAccessToken(),
                'X-RequestDigest' => (string) $this->getSPFormDigest(),
                'X-HTTP-Method'   => 'DELETE',
                'IF-MATCH'        => '*',
            ],
        ], 'POST');

        return true;
    }

    /**
     * Get the SharePoint Folder Item count (Folders and Files)
     *
     * @access  public
     * @throws  SPException
     * @return  int
     */
    public function getSPItemCount()
    {
        $json = $this->request("_api/web/GetFolderByServerRelativeUrl('".$this->relativeUrl."')/itemCount", [
            'headers' => [
                'Authorization' => 'Bearer '.$this->getSPAccessToken(),
                'Accept'        => 'application/json',
            ],
        ]);

        return $this->itemCount = $json['ItemCount'];
    }

    /**
     * Get all SharePoint Items (Folders/Files)
     *
     * @static
     * @access  public
     * @param   array  $settings Instantiation settings
     * @return  array
     */
    public function getSPItems(array $settings = [])
    {
        $settings = array_replace_recursive($settings, [
            'folders' => [
                'extra' => [], // extra SharePoint Folder properties to map
            ],

            'files' => [
                'extra' => [], // extra SharePoint File properties to map
            ],
        ]);

        $folders = static::getSubFolders($this->site, $this->relativeUrl, $settings['folders']);
        $files = SPFile::getAll($this, $settings['files']['extra']);

        $this->items = array_merge($folders, $files);

        return $this->items;
    }
}


text:
<?php
/**
 * File CacheWarmerTest.php
 *
 * @author Edward Pfremmer <epfremme@nerdery.com>
 */
namespace Pfrembot\RestProxyBundle\Tests\Cache;

use Pfrembot\RestProxyBundle\Builder\ProxyBuilder;
use Pfrembot\RestProxyBundle\Cache\CacheWarmer;
use Pfrembot\RestProxyBundle\Cache\ProxyCache;
use PhpParser\Builder;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;

/**
 * Class CacheWarmerTest
 *
 * @coversDefaultClass Pfrembot\RestProxyBundle\Cache\CacheWarmer
 *
 * @package Pfrembot\RestProxyBundle\Tests\Cache
 */
class CacheWarmerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Finder|\Mockery\MockInterface
     */
    private $finder;

    /**
     * @var ProxyBuilder|\Mockery\MockInterface
     */
    private $builder;

    /**
     * @var ProxyCache|\Mockery\MockInterface
     */
    private $cache;

    /**
     * @var CacheWarmer
     */
    private $cacheWarmer;

    /**
     * {@inheritdoc}
     */
    public function setUp()
    {
        $this->finder = \Mockery::mock(Finder::class);
        $this->builder = \Mockery::mock(ProxyBuilder::class);
        $this->cache = \Mockery::mock(ProxyCache::class);

        $this->cacheWarmer = new CacheWarmer($this->finder, $this->builder, $this->cache);
    }

    /**
     * @covers ::__construct
     */
    public function testConstruct()
    {
        $this->assertAttributeInstanceOf(Finder::class, 'finder', $this->cacheWarmer);
        $this->assertAttributeInstanceOf(ProxyBuilder::class, 'builder', $this->cacheWarmer);
        $this->assertAttributeInstanceOf(ProxyCache::class, 'cache', $this->cacheWarmer);
    }

    /**
     * @covers ::isOptional
     */
    public function testIsOptional()
    {
        $this->assertFalse($this->cacheWarmer->isOptional());
    }

    /**
     * @covers ::warmUp
     */
    public function testWarmUp()
    {
        $model = \Mockery::mock(Builder\Namespace_::class);

        $directory = str_replace('\\', '/', __NAMESPACE__);
        $classname = explode('\\', __CLASS__);

        $fileInfo = new SplFileInfo(__FILE__, $directory, end($classname));
        $iterator = new \ArrayIterator([$fileInfo]);

        $this->finder->shouldReceive('getIterator')->once()->withNoArgs()->andReturn($iterator);
        $this->builder->shouldReceive('build')->once()->with(\ReflectionClass::class)->andReturn($model);
        $this->cache->shouldReceive('write')->once()->with($model, self::class)->andReturnUndefined();

        $this->cacheWarmer->warmUp(__DIR__);
    }

    /**
     * @covers ::warmUp
     */
    public function testWarmUpWithNoAnnotation()
    {
        $directory = str_replace('\\', '/', __NAMESPACE__);
        $classname = explode('\\', __CLASS__);

        $fileInfo = new SplFileInfo(__FILE__, $directory, end($classname));
        $iterator = new \ArrayIterator([$fileInfo]);

        $this->finder->shouldReceive('getIterator')->once()->withNoArgs()->andReturn($iterator);
        $this->builder->shouldReceive('build')->once()->with(\ReflectionClass::class)->andReturn(false);
        $this->cache->shouldNotReceive('write');

        $this->cacheWarmer->warmUp(__DIR__);
    }
}


text:
package org.apache.kafka.common.config;

import org.apache.kafka.common.Configurable;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.config.types.Password;
import org.apache.kafka.common.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.kafka.common.config.provider.ConfigProvider;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * A convenient base class for configurations to extend.
 *

 * This class holds both the original configuration that was provided as well as the parsed
 */
public class AbstractConfig {

    private final Logger log = LoggerFactory.getLogger(getClass());

    /**
     * Configs for which values have been requested, used to detect unused configs.
     * This set must be concurrent modifiable and iterable. It will be modified
     * when directly accessed or as a result of RecordingMap access.
     */
    private final Set<String> used = ConcurrentHashMap.newKeySet();

    /* the original values passed in by the user */
    private final Map<String, ?> originals;

    /* the parsed values */
    private final Map<String, Object> values;

    private final ConfigDef definition;

    public static final String CONFIG_PROVIDERS_CONFIG = "config.providers";

    private static final String CONFIG_PROVIDERS_PARAM = ".param.";

    /**
     * Construct a configuration with a ConfigDef and the configuration properties, which can include properties
     * for zero or more {@link ConfigProvider} that will be used to resolve variables in configuration property
     * values.
     *
     * The originals is a name-value pair configuration properties and optional config provider configs. The
     * value of the configuration can be a variable as defined below or the actual value. This constructor will
     * first instantiate the ConfigProviders using the config provider configs, then it will find all the
     * variables in the values of the originals configurations, attempt to resolve the variables using the named
     * ConfigProviders, and then parse and validate the configurations.
     *
     * ConfigProvider configs can be passed either as configs in the originals map or in the separate
     * configProviderProps map. If config providers properties are passed in the configProviderProps any config
     * provider properties in originals map will be ignored. If ConfigProvider properties are not provided, the
     * constructor will skip the variable substitution step and will simply validate and parse the supplied
     * configuration.
     *
     * The "{@code config.providers}" configuration property and all configuration properties that begin with the
     * "{@code config.providers.}" prefix are reserved. The "{@code config.providers}" configuration property
     * specifies the names of the config providers, and properties that begin with the "{@code config.providers..}"
     * prefix correspond to the properties for that named provider. For example, the "{@code config.providers..class}"
     * property specifies the name of the {@link ConfigProvider} implementation class that should be used for
     * the provider.
     *
     * The keys for ConfigProvider configs in both originals and configProviderProps will start with the above
     * mentioned "{@code config.providers.}" prefix.
     *
     * Variables have the form "${providerName:[path:]key}", where "providerName" is the name of a ConfigProvider,
     * "path" is an optional string, and "key" is a required string. This variable is resolved by passing the "key"
     * and optional "path" to a ConfigProvider with the specified name, and the result from the ConfigProvider is
     * then used in place of the variable. Variables that cannot be resolved by the AbstractConfig constructor will
     * be left unchanged in the configuration.
     *
     *
     * @param definition the definition of the configurations; may not be null
     * @param originals the configuration properties plus any optional config provider properties;
     * @param configProviderProps the map of properties of config providers which will be instantiated by
     *        the constructor to resolve any variables in {@code originals}; may be null or empty
     * @param doLog whether the configurations should be logged
     */
    @SuppressWarnings("unchecked")
    public AbstractConfig(ConfigDef definition, Map<?, ?> originals,  Map<String, ?> configProviderProps, boolean doLog) {
        /* check that all the keys are really strings */
        for (Map.Entry<?, ?> entry : originals.entrySet())
            if (!(entry.getKey() instanceof String))
                throw new ConfigException(entry.getKey().toString(), entry.getValue(), "Key must be a string.");

        this.originals = resolveConfigVariables(configProviderProps, (Map<String, Object>) originals);
        this.values = definition.parse(this.originals);
        Map<String, Object> configUpdates = postProcessParsedConfig(Collections.unmodifiableMap(this.values));
        for (Map.Entry<String, Object> update : configUpdates.entrySet()) {
            this.values.put(update.getKey(), update.getValue());
        }
        definition.parse(this.values);
        this.definition = definition;
        if (doLog)
            logAll();
    }

    /**
     * Construct a configuration with a ConfigDef and the configuration properties,
     * which can include properties for zero or more {@link ConfigProvider}
     * that will be used to resolve variables in configuration property values.
     *
     * @param definition the definition of the configurations; may not be null
     * @param originals the configuration properties plus any optional config provider properties; may not be null
     */
    public AbstractConfig(ConfigDef definition, Map<?, ?> originals) {
        this(definition, originals, Collections.emptyMap(), true);
    }

    /**
     * Construct a configuration with a ConfigDef and the configuration properties,
     * which can include properties for zero or more {@link ConfigProvider}
     * that will be used to resolve variables in configuration property values.
     *
     * @param definition the definition of the configurations; may not be null
     * @param originals the configuration properties plus any optional config provider properties; may not be null
     * @param doLog whether the configurations should be logged
     */
    public AbstractConfig(ConfigDef definition, Map<?, ?> originals, boolean doLog) {
        this(definition, originals, Collections.emptyMap(), doLog);

    }

    /**
     * Called directly after user configs got parsed (and thus default values got set).
     * This allows to change default values for "secondary defaults" if required.
     *
     * @param parsedValues unmodifiable map of current configuration
     * @return a map of updates that should be applied to the configuration (will be validated to prevent bad updates)
     */
    protected Map<String, Object> postProcessParsedConfig(Map<String, Object> parsedValues) {
        return Collections.emptyMap();
    }

    protected Object get(String key) {
        if (!values.containsKey(key))
            throw new ConfigException(String.format("Unknown configuration '%s'", key));
        used.add(key);
        return values.get(key);
    }

    public void ignore(String key) {
        used.add(key);
    }

    public Short getShort(String key) {
        return (Short) get(key);
    }

    public Integer getInt(String key) {
        return (Integer) get(key);
    }

    public Long getLong(String key) {
        return (Long) get(key);
    }

    public Double getDouble(String key) {
        return (Double) get(key);
    }

    @SuppressWarnings("unchecked")
    public List<String> getList(String key) {
        return (List<String>) get(key);
    }

    public Boolean getBoolean(String key) {
        return (Boolean) get(key);
    }

    public String getString(String key) {
        return (String) get(key);
    }

    public ConfigDef.Type typeOf(String key) {
        ConfigDef.ConfigKey configKey = definition.configKeys().get(key);
        if (configKey == null)
            return null;
        return configKey.type;
    }

    public String documentationOf(String key) {
        ConfigDef.ConfigKey configKey = definition.configKeys().get(key);
        if (configKey == null)
            return null;
        return configKey.documentation;
    }

    public Password getPassword(String key) {
        return (Password) get(key);
    }

    public Class<?> getClass(String key) {
        return (Class<?>) get(key);
    }

    public Set<String> unused() {
        Set<String> keys = new HashSet<>(originals.keySet());
        keys.removeAll(used);
        return keys;
    }

    public Map<String, Object> originals() {
        Map<String, Object> copy = new RecordingMap<>();
        copy.putAll(originals);
        return copy;
    }

    public Map<String, Object> originals(Map<String, Object> configOverrides) {
        Map<String, Object> copy = new RecordingMap<>();
        copy.putAll(originals);
        copy.putAll(configOverrides);
        return copy;
    }

    /**
     * Get all the original settings, ensuring that all values are of type String.
     * @return the original settings
     * @throws ClassCastException if any of the values are not strings
     */
    public Map<String, String> originalsStrings() {
        Map<String, String> copy = new RecordingMap<>();
        for (Map.Entry<String, ?> entry : originals.entrySet()) {
            if (!(entry.getValue() instanceof String))
                throw new ClassCastException("Non-string value found in original settings for key " + entry.getKey() +
                        ": " + (entry.getValue() == null ? null : entry.getValue().getClass().getName()));
            copy.put(entry.getKey(), (String) entry.getValue());
        }
        return copy;
    }

    /**
     * Gets all original settings with the given prefix, stripping the prefix before adding it to the output.
     *
     * @param prefix the prefix to use as a filter
     * @return a Map containing the settings with the prefix
     */
    public Map<String, Object> originalsWithPrefix(String prefix) {
        return originalsWithPrefix(prefix, true);
    }

    /**
     * Gets all original settings with the given prefix.
     *
     * @param prefix the prefix to use as a filter
     * @param strip strip the prefix before adding to the output if set true
     * @return a Map containing the settings with the prefix
     */
    public Map<String, Object> originalsWithPrefix(String prefix, boolean strip) {
        Map<String, Object> result = new RecordingMap<>(prefix, false);
        for (Map.Entry<String, ?> entry : originals.entrySet()) {
            if (entry.getKey().startsWith(prefix) && entry.getKey().length() > prefix.length()) {
                if (strip)
                    result.put(entry.getKey().substring(prefix.length()), entry.getValue());
                else
                    result.put(entry.getKey(), entry.getValue());
            }
        }
        return result;
    }

    /**
     * Put all keys that do not start with {@code prefix} and their parsed values in the result map and then
     * put all the remaining keys with the prefix stripped and their parsed values in the result map.
     *
     * This is useful if one wants to allow prefixed configs to override default ones.
     *

     * Two forms of prefixes are supported:
     *

     *
listener.name.{listenerName}.some.prop: If the provided prefix is `listener.name.{listenerName}.`,
     *         the key `some.prop` with the value parsed using the definition of `some.prop` is returned.

     *
listener.name.{listenerName}.{mechanism}.some.prop: If the provided prefix is `listener.name.{listenerName}.`,
     *         the key `{mechanism}.some.prop` with the value parsed using the definition of `some.prop` is returned.
     *          This is used to provide per-mechanism configs for a broker listener (e.g sasl.jaas.config)

     *

     *

     */
    public Map<String, Object> valuesWithPrefixOverride(String prefix) {
        Map<String, Object> result = new RecordingMap<>(values(), prefix, true);
        for (Map.Entry<String, ?> entry : originals.entrySet()) {
            if (entry.getKey().startsWith(prefix) && entry.getKey().length() > prefix.length()) {
                String keyWithNoPrefix = entry.getKey().substring(prefix.length());
                ConfigDef.ConfigKey configKey = definition.configKeys().get(keyWithNoPrefix);
                if (configKey != null)
                    result.put(keyWithNoPrefix, definition.parseValue(configKey, entry.getValue(), true));
                else {
                    String keyWithNoSecondaryPrefix = keyWithNoPrefix.substring(keyWithNoPrefix.indexOf('.') + 1);
                    configKey = definition.configKeys().get(keyWithNoSecondaryPrefix);
                    if (configKey != null)
                        result.put(keyWithNoPrefix, definition.parseValue(configKey, entry.getValue(), true));
                }
            }
        }
        return result;
    }

    /**
     * If at least one key with {@code prefix} exists, all prefixed values will be parsed and put into map.
     * If no value with {@code prefix} exists all unprefixed values will be returned.
     *
     * This is useful if one wants to allow prefixed configs to override default ones, but wants to use either
     * only prefixed configs or only regular configs, but not mix them.
     */
    public Map<String, Object> valuesWithPrefixAllOrNothing(String prefix) {
        Map<String, Object> withPrefix = originalsWithPrefix(prefix, true);

        if (withPrefix.isEmpty()) {
            return new RecordingMap<>(values(), "", true);
        } else {
            Map<String, Object> result = new RecordingMap<>(prefix, true);

            for (Map.Entry<String, ?> entry : withPrefix.entrySet()) {
                ConfigDef.ConfigKey configKey = definition.configKeys().get(entry.getKey());
                if (configKey != null)
                    result.put(entry.getKey(), definition.parseValue(configKey, entry.getValue(), true));
            }

            return result;
        }
    }

    public Map<String, ?> values() {
        return new RecordingMap<>(values);
    }

    public Map<String, ?> nonInternalValues() {
        Map<String, Object> nonInternalConfigs = new RecordingMap<>();
        values.forEach((key, value) -> {
            ConfigDef.ConfigKey configKey = definition.configKeys().get(key);
            if (configKey == null || !configKey.internalConfig) {
                nonInternalConfigs.put(key, value);
            }
        });
        return nonInternalConfigs;
    }

    private void logAll() {
        StringBuilder b = new StringBuilder();
        b.append(getClass().getSimpleName());
        b.append(" values: ");
        b.append(Utils.NL);

        for (Map.Entry<String, Object> entry : new TreeMap<>(this.values).entrySet()) {
            b.append('\t');
            b.append(entry.getKey());
            b.append(" = ");
            b.append(entry.getValue());
            b.append(Utils.NL);
        }
        log.info(b.toString());
    }

    /**
     * Log warnings for any unused configurations
     */
    public void logUnused() {
        for (String key : unused())
            log.warn("The configuration '{}' was supplied but isn't a known config.", key);
    }

    private <T> T getConfiguredInstance(Object klass, Class<T> t, Map<String, Object> configPairs) {
        if (klass == null)
            return null;

        Object o;
        if (klass instanceof String) {
            try {
                o = Utils.newInstance((String) klass, t);
            } catch (ClassNotFoundException e) {
                throw new KafkaException("Class " + klass + " cannot be found", e);
            }
        } else if (klass instanceof Class<?>) {
            o = Utils.newInstance((Class<?>) klass);
        } else
            throw new KafkaException("Unexpected element of type " + klass.getClass().getName() + ", expected String or Class");
        if (!t.isInstance(o))
            throw new KafkaException(klass + " is not an instance of " + t.getName());
        if (o instanceof Configurable)
            ((Configurable) o).configure(configPairs);

        return t.cast(o);
    }

    /**
     * Get a configured instance of the give class specified by the given configuration key. If the object implements
     * Configurable configure it using the configuration.
     *
     * @param key The configuration key for the class
     * @param t The interface the class should implement
     * @return A configured instance of the class
     */
    public <T> T getConfiguredInstance(String key, Class<T> t) {
        return getConfiguredInstance(key, t, Collections.emptyMap());
    }

    /**
     * Get a configured instance of the give class specified by the given configuration key. If the object implements
     * Configurable configure it using the configuration.
     *
     * @param key The configuration key for the class
     * @param t The interface the class should implement
     * @param configOverrides override origin configs
     * @return A configured instance of the class
     */
    public <T> T getConfiguredInstance(String key, Class<T> t, Map<String, Object> configOverrides) {
        Class<?> c = getClass(key);

        return getConfiguredInstance(c, t, originals(configOverrides));
    }

    /**
     * Get a list of configured instances of the given class specified by the given configuration key. The configuration
     * may specify either null or an empty string to indicate no configured instances. In both cases, this method
     * returns an empty list to indicate no configured instances.
     * @param key The configuration key for the class
     * @param t The interface the class should implement
     * @return The list of configured instances
     */
    public <T> List<T> getConfiguredInstances(String key, Class<T> t) {
        return getConfiguredInstances(key, t, Collections.emptyMap());
    }

    /**
     * Get a list of configured instances of the given class specified by the given configuration key. The configuration
     * may specify either null or an empty string to indicate no configured instances. In both cases, this method
     * returns an empty list to indicate no configured instances.
     * @param key The configuration key for the class
     * @param t The interface the class should implement
     * @param configOverrides Configuration overrides to use.
     * @return The list of configured instances
     */
    public <T> List<T> getConfiguredInstances(String key, Class<T> t, Map<String, Object> configOverrides) {
        return getConfiguredInstances(getList(key), t, configOverrides);
    }

    /**
     * Get a list of configured instances of the given class specified by the given configuration key. The configuration
     * may specify either null or an empty string to indicate no configured instances. In both cases, this method
     * returns an empty list to indicate no configured instances.
     * @param classNames The list of class names of the instances to create
     * @param t The interface the class should implement
     * @param configOverrides Configuration overrides to use.
     * @return The list of configured instances
     */
    public <T> List<T> getConfiguredInstances(List<String> classNames, Class<T> t, Map<String, Object> configOverrides) {
        List<T> objects = new ArrayList<>();
        if (classNames == null)
            return objects;
        Map<String, Object> configPairs = originals();
        configPairs.putAll(configOverrides);
        for (Object klass : classNames) {
            Object o = getConfiguredInstance(klass, t, configPairs);
            objects.add(t.cast(o));
        }
        return objects;
    }

    private Map<String, String> extractPotentialVariables(Map<?, ?>  configMap) {
        // Variables are tuples of the form "${providerName:[path:]key}". From the configMap we extract the subset of configs with string
        // values as potential variables.
        Map<String, String> configMapAsString = new HashMap<>();
        for (Map.Entry<?, ?> entry : configMap.entrySet()) {
            if (entry.getValue() instanceof String)
                configMapAsString.put((String) entry.getKey(), (String) entry.getValue());
        }

        return configMapAsString;
    }

    /**
     * Instantiates given list of config providers and fetches the actual values of config variables from the config providers.
     * returns a map of config key and resolved values.
     * @param configProviderProps The map of config provider configs
     * @param originals The map of raw configs.
     * @return map of resolved config variable.
     */
    @SuppressWarnings("unchecked")
    private  Map<String, ?> resolveConfigVariables(Map<String, ?> configProviderProps, Map<String, Object> originals) {
        Map<String, String> providerConfigString;
        Map<String, ?> configProperties;
        Map<String, Object> resolvedOriginals = new HashMap<>();
        // As variable configs are strings, parse the originals and obtain the potential variable configs.
        Map<String, String> indirectVariables = extractPotentialVariables(originals);

        resolvedOriginals.putAll(originals);
        if (configProviderProps == null || configProviderProps.isEmpty()) {
            providerConfigString = indirectVariables;
            configProperties = originals;
        } else {
            providerConfigString = extractPotentialVariables(configProviderProps);
            configProperties = configProviderProps;
        }
        Map<String, ConfigProvider> providers = instantiateConfigProviders(providerConfigString, configProperties);

        if (!providers.isEmpty()) {
            ConfigTransformer configTransformer = new ConfigTransformer(providers);
            ConfigTransformerResult result = configTransformer.transform(indirectVariables);
            if (!result.data().isEmpty()) {
                resolvedOriginals.putAll(result.data());
            }
        }
        providers.values().forEach(x -> Utils.closeQuietly(x, "config provider"));

        return new ResolvingMap<>(resolvedOriginals, originals);
    }

    private Map<String, Object> configProviderProperties(String configProviderPrefix, Map<String, ?> providerConfigProperties) {
        Map<String, Object> result = new HashMap<>();
        for (Map.Entry<String, ?> entry : providerConfigProperties.entrySet()) {
            String key = entry.getKey();
            if (key.startsWith(configProviderPrefix) && key.length() > configProviderPrefix.length()) {
                result.put(key.substring(configProviderPrefix.length()), entry.getValue());
            }
        }
        return result;
    }

    /**
     * Instantiates and configures the ConfigProviders. The config providers configs are defined as follows:
     * config.providers : A comma-separated list of names for providers.
     * config.providers.{name}.class : The Java class name for a provider.
     * config.providers.{name}.param.{param-name} : A parameter to be passed to the above Java class on initialization.
     * returns a map of config provider name and its instance.
     * @param indirectConfigs The map of potential variable configs
     * @param providerConfigProperties The map of config provider configs
     * @return map map of config provider name and its instance.
     */
    private Map<String, ConfigProvider> instantiateConfigProviders(Map<String, String> indirectConfigs, Map<String, ?> providerConfigProperties) {
        final String configProviders = indirectConfigs.get(CONFIG_PROVIDERS_CONFIG);

        if (configProviders == null || configProviders.isEmpty()) {
            return Collections.emptyMap();
        }

        Map<String, String> providerMap = new HashMap<>();

        for (String provider: configProviders.split(",")) {
            String providerClass = providerClassProperty(provider);
            if (indirectConfigs.containsKey(providerClass))
                providerMap.put(provider, indirectConfigs.get(providerClass));

        }
        // Instantiate Config Providers
        Map<String, ConfigProvider> configProviderInstances = new HashMap<>();
        for (Map.Entry<String, String> entry : providerMap.entrySet()) {
            try {
                String prefix = CONFIG_PROVIDERS_CONFIG + "." + entry.getKey() + CONFIG_PROVIDERS_PARAM;
                Map<String, ?> configProperties = configProviderProperties(prefix, providerConfigProperties);
                ConfigProvider provider = Utils.newInstance(entry.getValue(), ConfigProvider.class);
                provider.configure(configProperties);
                configProviderInstances.put(entry.getKey(), provider);
            } catch (ClassNotFoundException e) {
                log.error("Could not load config provider class " + entry.getValue(), e);
                throw new ConfigException(providerClassProperty(entry.getKey()), entry.getValue(), "Could not load config provider class or one of its dependencies");
            }
        }

        return configProviderInstances;
    }

    private static String providerClassProperty(String providerName) {
        return String.format("%s.%s.class", CONFIG_PROVIDERS_CONFIG, providerName);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        AbstractConfig that = (AbstractConfig) o;

        return originals.equals(that.originals);
    }

    @Override
    public int hashCode() {
        return originals.hashCode();
    }

    /**
     * Marks keys retrieved via `get` as used. This is needed because `Configurable.configure` takes a `Map` instead
     * of an `AbstractConfig` and we can't change that without breaking public API like `Partitioner`.
     */
    private class RecordingMap<V> extends HashMap<String, V> {

        private final String prefix;
        private final boolean withIgnoreFallback;

        RecordingMap() {
            this("", false);
        }

        RecordingMap(String prefix, boolean withIgnoreFallback) {
            this.prefix = prefix;
            this.withIgnoreFallback = withIgnoreFallback;
        }

        RecordingMap(Map<String, ? extends V> m) {
            this(m, "", false);
        }

        RecordingMap(Map<String, ? extends V> m, String prefix, boolean withIgnoreFallback) {
            super(m);
            this.prefix = prefix;
            this.withIgnoreFallback = withIgnoreFallback;
        }

        @Override
        public V get(Object key) {
            if (key instanceof String) {
                String stringKey = (String) key;
                String keyWithPrefix;
                if (prefix.isEmpty()) {
                    keyWithPrefix = stringKey;
                } else {
                    keyWithPrefix = prefix + stringKey;
                }
                ignore(keyWithPrefix);
                if (withIgnoreFallback)
                    ignore(stringKey);
            }
            return super.get(key);
        }
    }

    /**
     * ResolvingMap keeps a track of the original map instance and the resolved configs.
     * The originals are tracked in a separate nested map and may be a `RecordingMap`; thus
     * any access to a value for a key needs to be recorded on the originals map.
     * The resolved configs are kept in the inherited map and are therefore mutable, though any
     * mutations are not applied to the originals.
     */
    private static class ResolvingMap<V> extends HashMap<String, V> {

        private final Map<String, ?> originals;

        ResolvingMap(Map<String, ? extends V> resolved, Map<String, ?> originals) {
            super(resolved);
            this.originals = Collections.unmodifiableMap(originals);
        }

        @Override
        public V get(Object key) {
            if (key instanceof String && originals.containsKey(key)) {
                // Intentionally ignore the result; call just to mark the original entry as used
                originals.get(key);
            }
            // But always use the resolved entry
            return super.get(key);
        }
    }
}


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

public partial class ModuleWeaver
{
    public void ProcessType(TypeDefinition typeDefinition)
    {
        if (!IncludeCompilerGenerated && IsCompilerGenerated(typeDefinition.CustomAttributes))
        {
            return;
        }
        if (typeDefinition.IsNotPublic || (!typeDefinition.IsPublic))
        {
            if (typeDefinition.IsNested)
            {
                typeDefinition.IsNestedPublic = true;
            }
            else
            {
                typeDefinition.IsPublic = true;
            }
            AddEditorBrowsableAttribute(typeDefinition.CustomAttributes);
        }
        if (typeDefinition.IsInterface)
        {
            return;
        }

        foreach (var method in typeDefinition.Methods)
        {
            ProcessMethod(method);
        }
        foreach (var field in typeDefinition.Fields)
        {
            ProcessField(field);
        }
    }

    void ProcessField(FieldDefinition field)
    {
        if (!IncludeCompilerGenerated && IsCompilerGenerated(field.CustomAttributes))
        {
            return;
        }
        if (field.IsPublic)
        {
            return;
        }
        var requiresPublicize = false;
        if (field.IsAssembly)
        {
            field.IsAssembly = false;
            requiresPublicize = true;
        }
        if (field.IsPrivate)
        {
            field.IsPrivate = false;
            requiresPublicize = true;
        }
        if (requiresPublicize)
        {
            field.IsPublic = true;
            AddEditorBrowsableAttribute(field.CustomAttributes);
        }
    }

    static bool IsCompilerGenerated(IEnumerable<CustomAttribute> customAttributes)
    {
        return customAttributes.Any(x=>x.AttributeType.Name == "CompilerGeneratedAttribute");
    }

    void ProcessMethod(MethodDefinition method)
    {
        var requiresPublicize = false;
        if (method.IsPublic)
        {
            return;
        }
        if (method.IsAssembly)
        {
            method.IsAssembly = false;
            requiresPublicize = true;
        }
        if (method.IsHideBySig)
        {
            method.IsHideBySig = false;
            requiresPublicize = true;
        }
        if (method.IsPrivate)
        {
            method.IsPrivate = false;
            requiresPublicize = true;
        }

        if (requiresPublicize)
        {
            method.IsPublic = true;
            AddEditorBrowsableAttribute(method.CustomAttributes);
        }
    }

    void AddEditorBrowsableAttribute(Collection<CustomAttribute> customAttributes)
    {
        if (customAttributes.Any(x=>x.AttributeType.Name == "EditorBrowsableAttribute"))
        {
            return;
        }
        var customAttribute = new CustomAttribute(EditorBrowsableConstructor);
        customAttribute.ConstructorArguments.Add(new CustomAttributeArgument(EditorBrowsableStateType, AdvancedStateConstant));
        customAttributes.Add(customAttribute);
    }
}


text:
#ifndef INCLUDE_blob_h__
#define INCLUDE_blob_h__

#include "git2/blob.h"
#include "repository.h"
#include "odb.h"
#include "fileops.h"

struct git_blob {
	git_object object;
	git_odb_object *odb_object;
};

void git_blob__free(git_blob *blob);
int git_blob__parse(git_blob *blob, git_odb_object *obj);
int git_blob__getbuf(git_buf *buffer, git_blob *blob);

#endif


text:
require 'spec_helper'

describe Models::Three do

  it 'return self if a straight was found' do
    cards = %w(5C 5C 5C 3C 4C).map{ |v| Models::Card.new(v) }
    expect{described_class.new(cards)}.not_to raise_exception
  end

end


text:
<?php
    $p = 'upload_excel.';
?>

@extends('layouts.mainPanel')

    @section('panel-headLinks')
        <link href="{{ asset('/plugins/fontawesome/css/font-awesome.css') }}" rel="stylesheet" type="text/css"/>
        <link href="{{ asset('plugins/faloading/jquery.faloading.min.css') }}" rel="stylesheet">
        <link href={{asset('css/uploadExcel/uploadExcelPage.css')}} rel="stylesheet" type="text/css">
        <link href={{asset('css/uploadExcel/dropzone.css')}} rel="stylesheet" type="text/css">
        <link href="{{ asset('css/records/validation_errors.css') }}" rel="stylesheet" type="text/css">
    @stop

    @section('panel-title')
        @lang($p.'upload_excel')
    @stop

    @section('main-window-content')
        {{-- Dropzone --}}

                    <form action="{{url('new-benefiter/uploadCSV')}}" id="dropzone" class="dropzone margin-5per custom-style relPos">

@lang($p.'upload_here')

                                    @lang($p.'choose-file')

                        {{ csrf_field() }}
                    </form>

            {{-- Progress Bar (NOT FOR NOW) --}}
            {{--
--}}
                {{--
--}}
                    {{--
--}}
                    <?php
                         // $percent = 100;
                        //  echo '
';
                        //  echo $percent.'% Complete (success)';
                        //  echo '
';
                      ?>
                    {{--
--}}
                {{--
--}}
            {{--
--}}

            {{-- Status messages --}}

                @lang($p.'success_upload')

                @lang($p.'unsuccess_upload')

            {{-- Refresh button --}}

                    <button class="importButton btn btn-warning" onclick="refreshPage()">@lang($p.'add-another')</button>

            {{-- Imported files info --}}
            @if(count($importedCSVFiles_basic_info) != 0)
            <?php
                $datesHelper = new \App\Services\DatesHelper();
            ?>

@lang($p.'already-uploaded')

                              Α/Α
                              @lang($p.'filename')
                              @lang($p.'import-date')

                          @for($i=0 ; $i<count($importedCSVFiles_basic_info) ; $i++)

                                  {{ $i+1 }}
                                  {{ $importedCSVFiles_basic_info[$i]['csv_name'] }}
                                  {{ $datesHelper->getFinelyFormattedStringDateFromDBDate($importedCSVFiles_basic_info[$i]['created_at']) }}

                          @endfor

            @endif

    @stop

    @section('panel-scripts')

    @stop


text:
from collections import Sequence
from importlib import import_module
from wsgiref.simple_server import make_server

from .http import Request
from .dispatch import dispatch, compile_url_conf
from ._logging import make_logger

STATUS = "{code} {message}"

class Application(object):
    def __init__(self, settings_module: str):
        settings = import_module(settings_module)
        make_logger(settings.LOGGING)
        url = import_module(settings.URL_CONF)
        self.registry, self.url_conf = compile_url_conf(url.patterns)

    def __call__(self, environ, start_response) -> Sequence:
        response = dispatch(Request(environ), self.url_conf, self.registry)
        start_response(STATUS.format(code=response["status_code"],
                                     message=response["status_message"]),
                       response["headers"])
        return (data for data in response["data"])

    def run(self, host='127.0.0.1', port=8000):
        try:
            host, port = host.split(':')
            port = int(port)
        except ValueError:
            pass
        make_server(host, port, app=self)


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>GrPPI: pack_traits.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

GrPPI
    0.3.1

Generic and Reusable Parallel Pattern Interface

Main Page

Related Pages

Modules

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

include

common

Namespaces |
Typedefs

pack_traits.h File Reference

This graph shows which files directly or indirectly include this file:

<map name="pack__traits_8hdep" id="pack__traits_8hdep">
<area shape="rect" id="node2" href="sequential__execution_8h.html" title="sequential_execution.h" alt="" coords="5,80,160,107"/>
<area shape="rect" id="node3" href="dynamic__execution_8h.html" title="dynamic_execution.h" alt="" coords="10,244,155,271"/>
<area shape="rect" id="node5" href="parallel__execution__omp_8h.html" title="parallel_execution\l_omp.h" alt="" coords="70,155,197,196"/>
<area shape="rect" id="node4" href="grppi_8h.html" title="grppi.h" alt="" coords="52,319,113,345"/>
</map>

Go to the source code of this file.

Namespaces

  	grppi

  	grppi::internal

Typedefs

template<int Index, typename... T>

using 	grppi::internal::requires_index_last = std::enable_if_t<(Index==(sizeof...(T)-1)), int >

template<int Index, typename... T>

using 	grppi::internal::requires_index_not_last = std::enable_if_t<(Index< sizeof...(T)-1), int >

<address class="footer">
Generated by

 1.8.11
</address>


text:
package org.apache.sling.event.jobs;

import java.util.Date;

import aQute.bnd.annotation.ProviderType;

/**
 * Scheduling information.
 * @since 1.3
 */
@ProviderType
public interface ScheduleInfo {

    enum ScheduleType {
        DATE,         // scheduled for a date
        HOURLY,       // scheduled hourly
        DAILY,        // scheduled once a day
        WEEKLY,       // scheduled once a week
        MONTHLY,      // scheduled once a month
        YEARLY,       // scheduled once a year,
        CRON          // scheduled according to the cron expression
    }

    /**
     * Return the scheduling type
     * @return The scheduling type
     */
    ScheduleType getType();

    /**
     * Return the scheduled execution date for a schedule of type date.
     */
    Date getAt();

    /**
     * If the schedule is a cron expression, return the expression.
     * @return The cron expression or null
     */
    String getExpression();

    /**
     * If the job is scheduled yearly, returns the month of the year
     * @return The day of the year (from 1 to 12) or -1
     */
    int getMonthOfYear();

    /**
     * If the job is scheduled monthly, returns the day of the month
     * @return The day of the month (from 1 to 28) or -1
     */
    int getDayOfMonth();

    /**
     * If the job is scheduled weekly, returns the day of the week
     * @return The day of the week (from 1 to 7) or -1
     */
    int getDayOfWeek();

    /**
     * Return the hour of the day for daily and weekly scheduled jobs
     * @return The hour of the day (from 0 to 23) or -1
     */
    int getHourOfDay();

    /**
     * Return the minute of the hour for daily, weekly and hourly scheduled jobs.
     * @return The minute of the hour (from 0 to 59) or -1
     */
    int getMinuteOfHour();
}


text:
.. _build-app:

=======================================================
    Building a Tangelo Web Application from Scratch
=======================================================

This tutorial will go through the steps of building a working, albeit simple,
Tangelo application from the ground up.  Most Tangelo applications consist of
(at least) three parts:  an HTML document presenting the form of the application
as a web page, a JavaScript file to drive dynamic content and behavior within
the web page, and a Python service to perform serverside processing.  The
tutorial application will have one of each to demonstrate how they will fit
together.

String Reverser
===============

The tutorial application will be a *string reverser*.  The user will see a form
where a word can be entered, and a button to submit the word.  The word will
then make a trip to the server, where it will be reversed and returned to the
client.  The reversed word will then be displayed in the web page.

Preparing the Stage
-------------------

Tangelo will need to be running in order for the application to work.  The
quickstart instructions will be sufficient (see :ref:`quickstart`): ::

    tangelo

This should launch Tangelo on *localhost*, port 8080 (also known as
http://localhost:8080/).

First we need a place to put the files for the application.  We will serve the
application out of a specialized directory to contain several Tangelo
applications. It is a good practice to house each application in its own
subdirectory - this keeps things organized, and allows for easy development of
web applications in source control systems such as GitHub: ::

    cd ~
    mkdir tangelo_apps
    cd tangelo_apps
    mkdir reverser

Next, we need to serve this directory to the web.  We'd also like to be able to
see the directory contents and Python source as we edit our application, since
we're in "developer mode": ::

    tangelo --list-dir --show-py

By default, Tangelo serves files from the current directory.  It would also be
possible to use the web root option by adding ``--root ~/tangelo_apps`` to make the
desired root directory explicit.

Visiting http://localhost:8080/reverser in a web browser should at this point
show you a directory listing of no entries.  Let's fix that by creating some
content.

HTML
----

The first step is to create a web page.  In a text editor, open a file called
``index.html`` and copy in the following:

.. code-block:: html
    :linenos:

    <!DOCTYPE html>
    <title>Reverser</title>

Reverser

        <input id=text type=text>
        <button id=go class="btn btn-class">Go

This is a very simple page, containing a text field (with ID ``text``), a button
(ID ``go``), and an empty div element (ID ``output``).  Feel free to reload the
page in your browser to see if everything worked properly.

Next we need to attach some behaviors to these elements.

JavaScript
----------

We want to be able to read the text from the input element, send it to the
server, and do something with the result.  We would like to do this whenever the
"Go" button is clicked.  The JavaScript to accomplish this follows - place this
in a file named ``myapp.js`` (to reflect the script tag in line 9 of
``index.html``):

.. code-block:: javascript
    :linenos:

    $(function () {
        $("#go").click(function () {
            var text = $("#text").val();
            $.getJSON("myservice?text=" + encodeURIComponent(text), function (data) {
                $("#output").text(data.reversed);
            });
        });
    });

Several things are happening in this short bit of code, so let's examine them
one by one.  Line 1 simply makes use of the jQuery ``$()`` function, which takes
a single argument:  a function to invoke with no arguments when the page content
is loaded and ready.

Line 2 uses the "CSS selector" variant of the ``$()`` function to select an
element by ID - in this case, the "go" button - and attach a behavior to its
"click" callback.

Line 3 - the first line of the function executed on button click - causes the
contents of of the text input field to be read out into the variable ``text``.

Line 4 uses the jQuery convenience function ``$.getJSON()`` to initiate an ajax
request to the URL http://localhost:8080/reverser/myservice, passing in the text
field contents as a query argument.  When the server has a response prepared,
the function passed as the second argument to ``$.getJSON()`` will be called,
with the response as the argument.

Line 5 makes use of this response data to place some text in the blank div.
Because ``$.getJSON()`` converts the server response to a JSON object
automatically, we can simply get the reversed word we are looking for in
``data.reversed``.  The output div in the webpage should now be displaying the
reversed word.

The final component of this application is the server side processing itself,
the service named ``myservice``.

Python
------

The Python web service will perform a reversal of its input.  The following
Python code accomplishes this (save it in a file named ``myservice.py``, again,
to reflect the usage of that name in the ``myapp.js`` above):

.. code-block:: python

    def run(text=""):
        return {"reversed": text[::-1]}

This short Python function uses a terse array idiom to reverse the order of the
letters in a string.  Note that a string goes into this function from the client
(i.e., the call to ``$.getJSON`` is line 4 of ``myapp.js``), and a Python dict
comes out.  The dict is automatically converted to JSON-encoded text, which the
``$.getJSON()`` function automatically converts to a JavaScript object, which is
finally passed to the anonymous function on line 4 of ``myapp.js``.

Tying it All Together
---------------------

The application is now complete.  Once more refresh the page at
http://localhost:8080/reverser/, type in your favorite word, and click the "Go"
button.  If all goes well, you should see your favorite word, reversed, below
the text input field!

Discussion
----------

Of course, we did not need to bring the server into this particular example,
since JavaScript is perfectly suited to reversing words should the need arise.
However, this example was meant to demonstrate how the three pieces - content,
dynamic clientside behavior, and serverside processing - come together to
implement a full, working web application.

Now imagine that instead of reversing the word, you wanted to use the word as a
search index in a database, or to direct the construction of a complex object,
or to kick off a large, parallel processing job on a computation engine, or that
you simply want to use some Python library that has no equivalent in the
JavaScript world.  Each of these cases represents some action that is difficult
or impossible to achieve using clientside JavaScript.  By writing Tangelo web
services you can enrich your application by bringing in the versatility and
power of Python and its libraries.


text:
layout: post
title: "Advanced Tricks in Pandas"
subtitle: "Pandas functions that I wish I knew when I started"
tags: ["pandas", "data wrangling"]
published: true
---

> Pandas is a data manipulation and analysis library for python.
> It is heavily used by the Machine Learning community to clean, transform, and analyze structured data.

# Why should you read this post?

I've been using pandas for working with structured data like Electronic Health Records (EHR), insurance claims, sensory data from wearables, etc. Pandas is a powerful data manipulation library that I've been consistently under-utilizing. In this post, I describe a list of pandas functions that I wish I knew about when I started with Data Science. If you are someone who works with data for a living you might find this useful.

## Select features from file

Sometimes csv files contain too much information. Too many irrelevant columns.
I used to read the whole file into memory and then get rid of the irrelevant columns.
Instead, we could read only the useful columns from the file.

Consider the example of Melbourne housing prices data.
Say we are interested in the following features:

- Suburb
- Rooms
- Landsize
- BuildingArea
- YearBuilt
- Price

![](/img/pandas/excel-screenshot.png)

`usecols` option `read_csv` allows us to specify which columns we are interested in.

{% highlight python %}
pd.read_csv("melb_data.csv",
            usecols=["Suburb", "Rooms", "Landsize", "BuildingArea", "YearBuilt", "Date", "Price"])
{% endhighlight %}

![](/img/pandas/read_csv.png)

## Parse Date as datetime data type

pandas by default parses columns containing date as the generic "object" type.
We could take control of how it is parsed by using the `parse_date` option in `read_csv`.

{% highlight python %}
df = pd.read_csv("melb_data.csv",
                   usecols=["Suburb", "Rooms", "Landsize", "BuildingArea", "YearBuilt", "Date", "Price"],
                    parse_dates=["Date"], dayfirst=True)
df.dtypes
{% endhighlight %}

![](/img/pandas/parse_date.png)

## Dealing with Missing values

You may have noticed several NaN (missing) values in the data frame.
We can decide to remove the rows with missing data or fill them in depending on the situation.
There are many ways to fill in the missing values.
We could fill in with average (mean, median) or most likely values (mode).
Or we could use the values from the neighboring rows.
Back-fill `bfill` fills in using the value from the next rows.
Forward-fill `ffill` fills in using the value from the previous rows.

{% highlight python %}
df.BuildingArea.fillna(method="ffill")
{% endhighlight %}
![](/img/pandas/ffill.png)

{% highlight python %}
df.BuildingArea.fillna(method="bfill")
{% endhighlight %}
![](/img/pandas/bfill.png)

{% highlight python %}
df.BuildingArea.fillna(df.BuildingArea.mean().item())
{% endhighlight %}
![](/img/pandas/meanfill.png)

## Filtering data

Almost every time I perform data analysis, I use conditions to filter out rows.
Often I end up having to use multiple conditions leading to long, awkward lines of code.

{% highlight python %}
df[(df.BuildingArea < 150) & (df.YearBuilt > 2000.) & (df.Rooms == 1)]
{% endhighlight %}

Alternatively, we could use `df.query` and enter our conditions as a string.

{% highlight python %}
df.query("BuildingArea < 150. & YearBuilt > 2000. & Rooms == 1")
{% endhighlight %}
![](/img/pandas/query.png)

{% highlight python %}
df.query("BuildingArea == Landsize").head()
{% endhighlight %}
![](/img/pandas/query1.png)

## Is it in my list?

Here is another one that I use a lot.
Let us say we are interested in a limited list of suburbs.
How do we filter out the rest of the suburbs?

{% highlight python %}
df[df.Suburb.isin(["Ashwood", "Altona North", "Coburg"])]
{% endhighlight %}
![](/img/pandas/isin.png)

## String Operations

pandas offers string-specific functionalities using a `str` accessor.
There are methods equivalent to python's string manipulation methods like lower, upper, strip, isalpha, find, index, split, and regex-based functions like match, search, and extractall (equivalent to `re.findall`).
You can find a lit of string methods supported by pandas [here](https://pandas.pydata.org/docs/user_guide/text.html#method-summary).

{% highlight python %}
df[df.Suburb.str.startswith("A")]
{% endhighlight %}
![](/img/pandas/str.png)

## Date operations

pandas allows you to work with Date type objects using the `dt` accessor.
`pandas.Series.dt` can be used to access date, hour, day, month, year, etc, from a Datetime object.
It also supports many operations on Datetime objects like `floor`, `ceil`, `normalize` etc,.

{% highlight python %}
df[df.Date.dt.year == 2016]
{% endhighlight %}
![](/img/pandas/dt.png)

## Group and Summarize

Groupby splits the data into different groups given a column.
Using multiple columns to group will create a hierarchy of groups.
The example below groups the data by "Regionname" and "Suburb" and summarizes the "Landsize" values within these groups.

{% highlight python %}
df.groupby(["Regionname", "Suburb", ])[["Landsize"]].sum()
{% endhighlight %}
![](/img/pandas/gb.png)

## Ranking and Sorting

During data analysis, we'll be interested in ranking entries in the data frame based on a variable of our choice.
Looking at the extremes in the housing market might reveal interesting patterns.
In the example below, we rank the housing entries based on their market price.

{% highlight python %}
df["RankByPrice"] = df["Price"].rank(method="max")
{% endhighlight %}
![](/img/pandas/rank.png)

Instead, we could just sort the entries based on one or more columns.

{% highlight python %}
df_sane.sort_values(by=["BuildingArea", "Landsize"], ascending=False)
{% endhighlight %}
![](/img/pandas/sort.png)

## Correlation

pandas has a handy function to calculate pair-wise correlation between variables. The correlation matrix is a good indicator of which features are useful (strong correlation with target variable) and which features are correlated with each other.

{% highlight python %}
import seaborn as sns

corr = df.corr()
sns.heatmap(corr, cmap="Blues", annot=True);
{% endhighlight %}
![](/img/pandas/corr.png)

## Combining data

When working with data from multiple sources, there is a need to combine them after cleaning and transformation.
Pandas has functions to merge, join, append and concat data.
merge and join are different ways of doing the same thing.
merge performs a database-style join on data frames.
concat and append perform concatenation of data frames along a particular axis.

In the code below,
{% highlight python %}
land_size = df.groupby(["Regionname", "Suburb", ])[["Landsize"]].sum()
building_area = df.groupby(["Regionname", "Suburb",])[["BuildingArea"]].sum()
pd.merge(land_size, building_area, left_index=True, right_index=True)
{% endhighlight %}
![](/img/pandas/merge_index-index.png)

`reset_index` removes "Regionname" and "Suburb" as indices.
Now to perform merge we need to explicitly include column names.
The merge operation removes the indexes from the resulting data frame.
Doing a merge on two unindexed data frames gives the same result.

{% highlight python %}
pd.merge(land_size, building_area.reset_index(),
         left_index=True,
         right_on=["Regionname", "Suburb"])
pd.merge(land_size.reset_index(), building_area.reset_index(),
         on=["Regionname", "Suburb"])
{% endhighlight %}
![](/img/pandas/merge_index-on.png)

We can do sql-like merges using left, right, inner and outer methods.

{% highlight python %}
pd.merge(land_size.reset_index(),
         building_area.reset_index().head(),
         how="left")
{% endhighlight %}
![](/img/pandas/merge-left.png)

{% highlight python %}
pd.merge(land_size.reset_index().head(),
         building_area.reset_index(),
         how="inner")
{% endhighlight %}
![](/img/pandas/merge-inner.png)

Setting `indicator=True` lets us know how each row was merged.
{% highlight python %}
pd.merge(land_size.reset_index().head(),
         building_area.reset_index().tail(),
         how="outer", indicator=True)
{% endhighlight %}
![](/img/pandas/merge-outer_indicator.png)

Concatenation is a simpler operation that combines two or more data frames row-wise or column-wise.

{% highlight python %}
pd.concat([land_size, building_area])
{% endhighlight %}
![](/img/pandas/concat.png)

Concatenation work along the column axis using `axis=1`.

{% highlight python %}
pd.concat([land_size, building_area], axis=1)
{% endhighlight %}
![](/img/pandas/concat1.png)

## Contigency Tables

`pd.crosstab` takes an index and a list of columns as inputs and creates a simple cross tabulation between two or more factors.
It creates a frequency table of factors.
The frequency can be replaced by a different kind of summary by specifying a summarization function.

{% highlight python %}
pd.crosstab(df.Suburb, [df.Rooms])
{% endhighlight %}
![](/img/pandas/crosstab.png)

## Multi-level data frames

It might be useful to group our entries based on, say the source of the data if we are acquiring and integrating data from different sources.
Grouping like that creates a multi-level data frame.

{% highlight python %}
pd.concat([land_size.reset_index(), building_area.reset_index()],
        keys=["land", "building"])
{% endhighlight %}
![](/img/pandas/mlm.png)

## Profiling

`pandas_profiling` is an external package that generates a detailed report on a pandas data frame. It generates a html report which includes tons of useful information such as global data statistics, variable statistics, missing value count, interaction between variables, correlation between variables, etc.

{% highlight python %}
from pandas_profiling import ProfileReport

prof = ProfileReport(df)
prof.to_file(output_file='output.html')
{% endhighlight %}

![](/img/pandas/profiling/1.png)
![](/img/pandas/profiling/2.png)
![](/img/pandas/profiling/3.png)
![](/img/pandas/profiling/4.png)
![](/img/pandas/profiling/5.png)

`pandas` is an incredibly powerful, flexible, and intuitive tool for working with structured data.
I'm thinking of writing a follow-up blog that covers SQL-like functions in pandas and compares SQL queries with pandas functions.

That's it for now.
I hope one of these tricks helps you improve your workflow.
See you soon with more.

If you got something to say leave a comment below.


text:
#pragma once
#include <aws/nimble/NimbleStudio_EXPORTS.h>
#include <aws/nimble/model/StudioComponent.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace NimbleStudio
{
namespace Model
{
  class AWS_NIMBLESTUDIO_API DeleteStudioComponentResult
  {
  public:
    DeleteStudioComponentResult();
    DeleteStudioComponentResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    DeleteStudioComponentResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
Information about the studio component.

     */
    inline const StudioComponent& GetStudioComponent() const{ return m_studioComponent; }

    /**
     *
Information about the studio component.

     */
    inline void SetStudioComponent(const StudioComponent& value) { m_studioComponent = value; }

    /**
     *
Information about the studio component.

     */
    inline void SetStudioComponent(StudioComponent&& value) { m_studioComponent = std::move(value); }

    /**
     *
Information about the studio component.

     */
    inline DeleteStudioComponentResult& WithStudioComponent(const StudioComponent& value) { SetStudioComponent(value); return *this;}

    /**
     *
Information about the studio component.

     */
    inline DeleteStudioComponentResult& WithStudioComponent(StudioComponent&& value) { SetStudioComponent(std::move(value)); return *this;}

  private:

    StudioComponent m_studioComponent;
  };

} // namespace Model
} // namespace NimbleStudio
} // namespace Aws


text:
package com.thoughtworks.sulabh.activity;

import android.content.Intent;
import android.os.Bundle;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

import static junit.framework.Assert.assertEquals;
import static org.mockito.Mockito.*;

@RunWith(RobolectricTestRunner.class)
public class DetailsActivityTest {
	private DetailsActivity detailsActivity;
	private Intent intent;

	@Before
	public void setUp() throws Exception {
		detailsActivity = spy(new DetailsActivity());
		doNothing().when(detailsActivity).onCreate(null);
		intent = mock(Intent.class);
		Bundle bundle = new Bundle();
		when(intent.getExtras()).thenReturn(bundle);
		when(detailsActivity.getIntent()).thenReturn(intent);
	}

	@Test
	public void mapsTrueToYes() {
		String actual = detailsActivity.mapValues("true");
		String expected = "Yes";
		assertEquals(expected, actual);
	}

	@Test
	public void mapsFalseToNo() {
		String actual = detailsActivity.mapValues("false");
		String expected = "No";
		assertEquals(expected, actual);
	}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2017-07-03
 * Time: 12:12
 */

namespace app\src\qqav\action;

use app\src\base\action\BaseAction;
use app\src\base\helper\PageHelper;
use app\src\qqav\logic\VideoLogic;

class VideoAction extends BaseAction
{
    /**
     *
     * @param $entity
     * @return array
     */
    public function create($entity){
        if(isset($entity['create_time'])) $entity['create_time'] = time();
        if(isset($entity['update_time'])) $entity['update_time'] = time();

        return (new VideoLogic())->add($entity);
    }

    public function query($map,PageHelper $pageHelper,$order=false,$params=false){
        return (new VideoLogic())->query($map,$pageHelper->queryParam(),$order,$params);
    }
}