text:
package pro.taskana;

import java.time.Instant;
import java.util.List;

import pro.taskana.exceptions.InvalidArgumentException;

/**
 * Interface for TaskSummary. This is a specific short model-object which only contains the most
 * important information.
 */
public interface TaskSummary {

  /**
   * Gets the id of the task.
   *
   * @return taskId
   */
  String getTaskId();

  /**
   * Gets the external id of the task.
   *
   * @return the external Id
   */
  String getExternalId();

  /**
   * Gets the name of the task-creator.
   *
   * @return creator
   */
  String getCreator();

  /**
   * Gets the time when the task was created.
   *
   * @return the created Instant
   */
  Instant getCreated();

  /**
   * Gets the time when the task was claimed.
   *
   * @return the claimed Instant
   */
  Instant getClaimed();

  /**
   * Gets the time when the task was completed.
   *
   * @return the completed Instant
   */
  Instant getCompleted();

  /**
   * Gets the time when the task was last modified.
   *
   * @return the last modified Instant
   */
  Instant getModified();

  /**
   * Gets the time when the task is planned to be executed.
   *
   * @return the planned Instant
   */
  Instant getPlanned();

  /**
   * Gets the time when the task is due.
   *
   * @return the due Instant
   */
  Instant getDue();

  /**
   * Gets the name of the task.
   *
   * @return the task's name
   */
  String getName();

  /**
   * Gets the note attached to the task.
   *
   * @return the task's note
   */
  String getNote();

  /**
   * Gets the priority of the task.
   *
   * @return the task's priority
   */
  int getPriority();

  /**
   * Gets the state of the task.
   *
   * @return the task's state
   */
  TaskState getState();

  /**
   * Gets the classification summary of the task.
   *
   * @return the task's classificationSummary
   */
  ClassificationSummary getClassificationSummary();

  /**
   * Gets the workbasket summary of the task.
   *
   * @return the task's workbasketSummary
   */
  WorkbasketSummary getWorkbasketSummary();

  /**
   * Gets the attachment summaries of the task.
   *
   * @return the task's attachment summaries
   */
  List<AttachmentSummary> getAttachmentSummaries();

  /**
   * Gets the domain of the task.
   *
   * @return the task's domain
   */
  String getDomain();

  /**
   * Gets the businessProcessId of the task.
   *
   * @return the task's businessProcessId
   */
  String getBusinessProcessId();

  /**
   * Gets the parentBusinessProcessId of the task.
   *
   * @return the task's parentBusinessProcessId
   */
  String getParentBusinessProcessId();

  /**
   * Gets the owner of the task.
   *
   * @return the task's owner
   */
  String getOwner();

  /**
   * Gets the primary ObjectReference of the task.
   *
   * @return the task's primary ObjectReference
   */
  ObjectReference getPrimaryObjRef();

  /**
   * Gets the isRead flag of the task.
   *
   * @return the task's isRead flag
   */
  boolean isRead();

  /**
   * Gets the isTransferred flag of the task.
   *
   * @return the task's isTransferred flag.
   */
  boolean isTransferred();

  /**
   * Gets the custom attribute number num of the task.
   *
   * @param num identifies which custom attribute is requested. Taskana concatenates "custom_" with
   *     num and the resulting String must match the name of the database column that contains the
   *     custom attribute. Valid values are "1", "2" .. "16"
   * @return the value of custom attribute number num
   * @throws InvalidArgumentException if num has not a value of "1", "2" ... "16"
   */
  String getCustomAttribute(String num) throws InvalidArgumentException;
}


text:
import os
import yaml
import shutil
import tempfile

# Import Salt Testing libs
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')

# Import salt libs
import integration

class MatchTest(integration.ShellCase, integration.ShellCaseCommonTestsMixIn):
    '''
    Test salt matchers
    '''
    _call_binary_ = 'salt'

    def test_list(self):
        '''
        test salt -L matcher
        '''
        data = self.run_salt('-L minion test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertNotIn('sub_minion', data)
        data = self.run_salt('-L minion,sub_minion test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertIn('sub_minion', data)

    def test_compound(self):
        '''
        test salt compound matcher
        '''
        data = self.run_salt('-C "min* and G@test_grain:cheese" test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertNotIn('sub_minion', data)
        data = self.run_salt('-C "min* and not G@test_grain:foo" test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertNotIn('sub_minion', data)
        data = self.run_salt('-C "min* not G@test_grain:foo" test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertNotIn('sub_minion', data)
        match = 'P@test_grain:^cheese$ and * and G@test_grain:cheese'
        data = self.run_salt('-t 1 -C \'{0}\' test.ping'.format(match))
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertNotIn('sub_minion', data)
        match = 'L@sub_minion and E@.*'
        data = self.run_salt('-t 1 -C "{0}" test.ping'.format(match))
        data = '\n'.join(data)
        self.assertIn('sub_minion', data)
        self.assertNotIn('minion', data.replace('sub_minion', 'stub'))

    def test_glob(self):
        '''
        test salt glob matcher
        '''
        data = self.run_salt('minion test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertNotIn('sub_minion', data)
        data = self.run_salt('"*" test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertIn('sub_minion', data)

    def test_regex(self):
        '''
        test salt regex matcher
        '''
        data = self.run_salt('-E "^minion$" test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertNotIn('sub_minion', data)
        data = self.run_salt('-E ".*" test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertIn('sub_minion', data)

    def test_grain(self):
        '''
        test salt grain matcher
        '''
        # First-level grain (string value)
        data = self.run_salt('-t 1 -G "test_grain:cheese" test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertNotIn('sub_minion', data)
        data = self.run_salt('-G "test_grain:spam" test.ping')
        data = '\n'.join(data)
        self.assertIn('sub_minion', data)
        self.assertNotIn('minion', data.replace('sub_minion', 'stub'))
        # First-level grain (list member)
        data = self.run_salt('-t 1 -G "planets:earth" test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertNotIn('sub_minion', data)
        data = self.run_salt('-G "planets:saturn" test.ping')
        data = '\n'.join(data)
        self.assertIn('sub_minion', data)
        self.assertNotIn('minion', data.replace('sub_minion', 'stub'))
        data = self.run_salt('-G "planets:pluto" test.ping')
        self.assertEqual(
            ''.join(data),
            'No minions matched the target. No command was sent, no jid was '
            'assigned.'
        )
        # Nested grain (string value)
        data = self.run_salt('-t 1 -G "level1:level2:foo" test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertNotIn('sub_minion', data)
        data = self.run_salt('-G "level1:level2:bar" test.ping')
        data = '\n'.join(data)
        self.assertIn('sub_minion', data)
        self.assertNotIn('minion', data.replace('sub_minion', 'stub'))
        # Nested grain (list member)
        data = self.run_salt('-t 1 -G "companions:one:ian" test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertNotIn('sub_minion', data)
        data = self.run_salt('-G "companions:two:jamie" test.ping')
        data = '\n'.join(data)
        self.assertIn('sub_minion', data)
        self.assertNotIn('minion', data.replace('sub_minion', 'stub'))

    def test_regrain(self):
        '''
        test salt grain matcher
        '''
        data = self.run_salt(
            '-t 1 --grain-pcre "test_grain:^cheese$" test.ping'
        )
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertNotIn('sub_minion', data)
        data = self.run_salt('--grain-pcre "test_grain:.*am$" test.ping')
        data = '\n'.join(data)
        self.assertIn('sub_minion', data)
        self.assertNotIn('minion', data.replace('sub_minion', 'stub'))

    def test_pillar(self):
        '''
        test pillar matcher
        '''
        # First-level pillar (string value)
        data = self.run_salt('-I "monty:python" test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertIn('sub_minion', data)
        # First-level pillar (string value, only in sub_minion)
        data = self.run_salt('-I "sub:sub_minion" test.ping')
        data = '\n'.join(data)
        self.assertIn('sub_minion', data)
        self.assertNotIn('minion', data.replace('sub_minion', 'stub'))
        # First-level pillar (list member)
        data = self.run_salt('-I "knights:Bedevere" test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertIn('sub_minion', data)
        # Nested pillar (string value)
        data = self.run_salt('-I "level1:level2:foo" test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertIn('sub_minion', data)
        # Nested pillar (list member)
        data = self.run_salt('-I "companions:three:sarah jane" test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertIn('sub_minion', data)

    def test_exsel(self):
        data = self.run_salt('-X test.ping test.ping')
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertIn('sub_minion', data)

    def test_ipcidr(self):
        subnets_data = self.run_salt('--out yaml \'*\' network.subnets')
        yaml_data = yaml.load('\n'.join(subnets_data))

        # We're just after the first defined subnet from 'minion'
        subnet = yaml_data['minion'][0]

        data = self.run_salt('-S {0} test.ping'.format(subnet))
        data = '\n'.join(data)
        self.assertIn('minion', data)
        self.assertIn('sub_minion', data)

    def test_static(self):
        '''
        test salt static call
        '''
        data = self.run_salt('minion test.ping --static')
        data = '\n'.join(data)
        self.assertIn('minion', data)

    def test_salt_documentation(self):
        '''
        Test to see if we're supporting --doc
        '''
        data = self.run_salt('-d \* user')
        self.assertIn('user.add:', data)

    def test_salt_documentation_arguments_not_assumed(self):
        '''
        Test to see if we're not auto-adding '*' and 'sys.doc' to the call
        '''
        data = self.run_salt('-d')
        self.assertIn('user.add:', data)
        data = self.run_salt('\'*\' -d')
        self.assertIn('user.add:', data)
        data = self.run_salt('\'*\' -d user')
        self.assertIn('user.add:', data)
        data = self.run_salt('\'*\' sys.doc -d user')
        self.assertIn('user.add:', data)
        data = self.run_salt('\'*\' sys.doc user')
        self.assertIn('user.add:', data)

    def test_issue_7754(self):
        old_cwd = os.getcwd()
        config_dir = os.path.join(integration.TMP, 'issue-7754')
        if not os.path.isdir(config_dir):
            os.makedirs(config_dir)

        os.chdir(config_dir)

        config_file_name = 'master'
        config = yaml.load(
            open(self.get_config_file_path(config_file_name), 'r').read()
        )
        config['log_file'] = 'file:///dev/log/LOG_LOCAL3'
        open(os.path.join(config_dir, config_file_name), 'w').write(
            yaml.dump(config, default_flow_style=False)
        )
        ret = self.run_script(
            self._call_binary_,
            '--config-dir {0} minion test.ping'.format(
                config_dir
            ),
            timeout=15
        )
        try:
            self.assertIn('minion', '\n'.join(ret))
            self.assertFalse(os.path.isdir(os.path.join(config_dir, 'file:')))
        finally:
            os.chdir(old_cwd)
            if os.path.isdir(config_dir):
                shutil.rmtree(config_dir)

if __name__ == '__main__':
    from integration import run_tests
    run_tests(MatchTest)

redpajama_set_name: RedPajamaGithub


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

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Error 404 Kitten: I'm sorry, I tried really hard to find it.</title>
	<meta name="generator" content="TextMate http://macromates.com/">
	<meta name="author" content="Aral Balkan">

		Photo by Vannessa.


text:
class CreateBuckets < ActiveRecord::Migration
  def change
    create_table :buckets do |t|
      t.string   :serial, :null => false
      t.string   :token,  :null => false
      t.string   :secret, :null => false
      t.string   :max_id, :null => false, :default => '0'
      t.integer  :page, :default => 0
      t.integer  :destroy_count, :default => 0
      t.datetime :reset_at
      t.integer  :auth_failed_count, :default => 0

      t.timestamps
    end
    add_index :buckets, :serial, :unique => true
  end
end


text:
package org.xander.katas;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;

public class OneHundredDoorsTest {
    OneHundredDoors oneHundredDoors = new OneHundredDoors();

    @Test
    public void basic() {
        assertNotNull(oneHundredDoors);
    }

    @Test
    public void allAreClosedInitially() {
        for (Boolean door : oneHundredDoors.checkAllDoors()) {
            assertFalse(door);
        }
    }

    @Test
    public void firstGo() {
        oneHundredDoors.go(1);

        for (Boolean door : oneHundredDoors.checkAllDoors()) {
            assertTrue(door);
        }
    }

    @Test
    public void secondGo() {
        int second = 2;
        oneHundredDoors.go(second);
        boolean[] currentList = oneHundredDoors.checkAllDoors();

        for (int i = 0; i < currentList.length ; i = i + second) {
            assertTrue(currentList[i]);
        }
    }

    @Test
    public void thirdGo() {
        int third = 3;
        oneHundredDoors.go(third);
        boolean[] currentList = oneHundredDoors.checkAllDoors();

        for (int i = 0; i < currentList.length ; i = i + third) {
            assertTrue(currentList[i]);
        }
    }

    @Test
    public void allGoes() {
        for (int goNumber = 1; goNumber < 100; goNumber++) {
            oneHundredDoors.go(goNumber);
        }
        outputDoorsStates();
    }

    private void outputDoorsStates() {
        List<Boolean> positiveNumbers = new ArrayList<>();
        List<Boolean> negativeNumbers = new ArrayList<>();

        for (Boolean element : oneHundredDoors.checkAllDoors()) {
            if (element.booleanValue()) {
                positiveNumbers.add(element);
            } else {
                negativeNumbers.add(element);
            }
        }

        System.out.println("There are " + positiveNumbers.size() + " positive numbers ");
        System.out.print("and " + negativeNumbers.size() + " negative numbers ");
        System.out.println("\nHere are they respectively: ");

        System.out.println("\nPositive : ");
        boolean[] listOfDoors = oneHundredDoors.checkAllDoors();
        for (int i = 0 ; i < listOfDoors.length ; i++) {
            if (listOfDoors[i])
                System.out.print(i + ", ");

        }
        System.out.println("\nNegative : ");

        for (int i = 0 ; i < listOfDoors.length ; i++) {
            if (!listOfDoors[i])
                System.out.print(i + ", ");
        }
    }
}


text:
package org.onvif.ver10.device.wsdl;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.cxf.xjc.runtime.JAXBToStringStyle;
import org.onvif.ver10.schema.BinaryData;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="CertificateID" type="{http://www.w3.org/2001/XMLSchema}token"/>
 *         <element name="Subject" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="Attributes" type="{http://www.onvif.org/ver10/schema}BinaryData" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "certificateID",
    "subject",
    "attributes"
})
@XmlRootElement(name = "GetPkcs10Request")
public class GetPkcs10Request {

    @XmlElement(name = "CertificateID", required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "token")
    protected String certificateID;
    @XmlElement(name = "Subject")
    protected String subject;
    @XmlElement(name = "Attributes")
    protected BinaryData attributes;

    /**
     * Gets the value of the certificateID property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getCertificateID() {
        return certificateID;
    }

    /**
     * Sets the value of the certificateID property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setCertificateID(String value) {
        this.certificateID = value;
    }

    /**
     * Gets the value of the subject property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSubject() {
        return subject;
    }

    /**
     * Sets the value of the subject property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSubject(String value) {
        this.subject = value;
    }

    /**
     * Gets the value of the attributes property.
     *
     * @return
     *     possible object is
     *     {@link BinaryData }
     *
     */
    public BinaryData getAttributes() {
        return attributes;
    }

    /**
     * Sets the value of the attributes property.
     *
     * @param value
     *     allowed object is
     *     {@link BinaryData }
     *
     */
    public void setAttributes(BinaryData value) {
        this.attributes = value;
    }

    /**
     * Generates a String representation of the contents of this type.
     * This is an extension method, produced by the 'ts' xjc plugin
     *
     */
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, JAXBToStringStyle.DEFAULT_STYLE);
    }

}


text:
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'isthatanearthquake.views.home', name='home'),
    # url(r'^isthatanearthquake/', include('isthatanearthquake.foo.urls')),

    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),

    url(r'^', include('quakes.urls')),
)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/01. Views.iml" filepath="$PROJECT_DIR$/.idea/01. Views.iml" />
    </modules>
  </component>
</project>


text:
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE DeriveGeneric #-}

module Models.FeaturedCharacter (FeaturedCharacter(..)) where

import BasicPrelude

import Data.Aeson (FromJSON(..), ToJSON(..))
import GHC.Generics (Generic)

import Models.Ids (CharacterId)
import Models.Image (Image)

data FeaturedCharacter = FeaturedCharacter
  { id :: CharacterId
  , name :: Text
  , thumbnail :: Image
  } deriving (Show, Generic)

instance FromJSON FeaturedCharacter
instance ToJSON FeaturedCharacter


text:
#ifndef ICARUS_GENERATE_H
#define ICARUS_GENERATE_H

#include "../../parse/data/decl.h"
#include "../../parse/data/field.h"

/* the ic_generate type is created for every function we want to be generated
 * many of these will be generated by the backend (such as constructors),
 * some may be generated within icarus itself
 *
 * FIXME TODO how do we differentiate between these two?
 *  print can be expressed in icarus
 *  cons cannot
 *
 */

enum ic_generate_tag {
    ic_generate_tag_cons_struct,
    ic_generate_tag_cons_union,
    ic_generate_tag_print,
    /* FIXME TODO once we have generics we can replace println with
     *  fn println[T](t::T)
     *      print(t)
     *      println()
     *  end
     */
    ic_generate_tag_println,
};

struct ic_generate {
    enum ic_generate_tag tag;
    /* the fdecl created to represent this function
     * currently a blank (with name set, but no body)
     */
    struct ic_decl_func *fdecl;
    /* the type that triggered this generation */
    struct ic_decl_type *tdecl;
    /* fields only used by subset of generate_tag */
    union {
        struct ic_field *union_field;
    } u;
};

/* allocate and initalise a new ic_generate
 *
 * returns * on success
 * returns 0 on failure
 */
struct ic_generate *ic_generate_new(enum ic_generate_tag tag, struct ic_decl_func *fdecl, struct ic_decl_type *tdecl);

/* initialise an existing ic_generate
 *
 * returns 1 on success
 * returns 0 on failure
 */
unsigned int ic_generate_init(struct ic_generate *gen, enum ic_generate_tag tag, struct ic_decl_func *fdecl, struct ic_decl_type *tdecl);

/* destroy an ic_generate
 *
 * will only free gen is `free_gen` is truthy
 *
 * will free fdecl if set
 * will not free other fields (as they are not owned)
 *
 * returns 1 on success
 * returns 0 on failure
 */
unsigned int ic_generate_destroy(struct ic_generate *gen, unsigned int free_gen);

/* get fdecl field
 *
 * returns * on success
 * returns 0 on failure
 */
struct ic_decl_func *ic_generate_get_fdecl(struct ic_generate *gen);

/* get tdecl field
 *
 * returns * on success
 * returns 0 on failure
 */
struct ic_decl_type *ic_generate_get_tdecl(struct ic_generate *gen);

/* get union_field
 *
 * only legal if tag is cons_union
 *
 * returns * on success
 * returns 0 on failure
 */

struct ic_field *ic_generate_get_union_field(struct ic_generate *gen);

/* set union_field
 *
 * only legal if tag is cons_union
 * only legal if union_field not already set
 *
 * returns 1 on success
 * returns 0 on failure
 */

unsigned int ic_generate_set_union_field(struct ic_generate *gen, struct ic_field *union_field);

#endif // ICARUS_GENERATE_H


text:
<?php

namespace App\Classes;

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Session;
use Config;
use App;

class EtuUTT
{
    /**
     * Call an endpoit on EtuUTT API and renew token if expired
     *
     * @return array
     */
    public function call($path, $params = [])
    {
        $client = new \GuzzleHttp\Client([
            'base_uri' => Config::get('services.etuutt.baseuri.api'),
            'auth' => [
                Config::get('services.etuutt.client.id'),
                Config::get('services.etuutt.client.secret')
            ]
        ]);

        try {
            $response = $client->get($path.'?access_token=' . Auth::user()->etuutt_access_token.'&'.http_build_query($params));
        } catch (\GuzzleHttp\Exception\ClientException $e) {
            if ($e->hasResponse()) {
                $json = json_decode($e->getResponse()->getBody()->getContents(), true);
                if ($json) {

                    // Catch token expiration
                    if (isset($json['error']) && $json['error'] == 'expired_token') {
                        // Refresh token
                        $params = [
                            'grant_type'         => 'refresh_token',
                            'refresh_token' => Auth::user()->etuutt_refresh_token
                        ];
                        try {
                            $response = $client->post('/api/oauth/token', ['form_params' => $params]);
                        } catch (\GuzzleHttp\Exception\GuzzleException $e) {
                            // An error 400 from the server is usual when the authorization_code
                            // has expired. We force deconnexion to let hom renew his token
                            if ($e->hasResponse() && $e->getResponse()->getStatusCode() === 400) {
                                Session::flush();
                            }
                            App::abort(500);
                        }

                        $json = json_decode($response->getBody()->getContents(), true);
                        $student = Auth::user();
                        $student->etuutt_access_token = $json['access_token'];
                        $student->etuutt_refresh_token = $json['refresh_token'];
                        $student->save();

                        return $this->call($path, $params);
                    } else {
                        $json['http_code'] = $e->getCode();
                        return $json;
                    }
                }
            }
            return [
                'http_code' => $e->getCode(),
                'error' => $e->getCode(),
                'error_message' => $e->getResponse()->getReasonPhrase(),
            ];
        } catch (\GuzzleHttp\Exception\GuzzleException $e) {
            App::abort(500);
        }

        $json = json_decode($response->getBody()->getContents(), true);

        return $json;
    }

    /**
     * Find and update or create user from etuutt user data
     * @param   $json          Etuutt user dat
     * @param   $access_token  EtuUTT Access token
     * @param   $refresh_token EtuUTT Refresh token
     * @return                 found or created user
     */
    public function updateOrCreateUser($json, $access_token, $refresh_token)
    {
        // If the user is new, import some values from the API response.
        $student = User::where('etuutt_login', $json['login'])->first();
        if ($student === null) {
            // Fallback on student_id auth
            $student = User::where('student_id', $json['studentId'])->first();
        }

        if ($student === null) {
            $student = new User([
                'student_id'    => $json['studentId'],
                'first_name'    => $json['firstName'],
                'last_name'     => $json['lastName'],
                'surname'       => $json['surname'],
                'email'         => $json['email'],
                'facebook'      => $json['facebook'],
                'phone'         => ($json['phonePrivacy'] == 'public') ? $json['phone'] : null,
                'branch'        => $json['branch'],
                'level'         => $json['level']
            ]);
            $student->etuutt_access_token = $access_token;
            $student->etuutt_refresh_token = $refresh_token;
            $student->etuutt_login = $json['login'];

            // Error here a ignored, we just keep user without a picture if we cannot download it
            $picture = @file_get_contents('https://local-sig.utt.fr/Pub/trombi/individu/' . $student->student_id . '.jpg');
            @file_put_contents(public_path() . '/uploads/students-trombi/' . $student->student_id . '.jpg', $picture);

            if ($json['sex'] == 'male') {
                $student->sex = User::SEX_MALE;
            } elseif ($json['sex'] == 'female') {
                $student->sex = User::SEX_FEMALE;
            }

            $student->last_login = new \DateTime();
            $student->save();
        }
        // Account was created by another person, update it with personnal informations
        elseif (empty($student->etuutt_refresh_token)) {
            $student->last_login = new \DateTime();
            $student->etuutt_access_token = $access_token;
            $student->etuutt_refresh_token = $refresh_token;
            $student->phone = ($json['phonePrivacy'] == 'public') ? $json['phone'] : null;
            if ($json['sex'] == 'male') {
                $student->sex = User::SEX_MALE;
            } elseif ($json['sex'] == 'female') {
                $student->sex = User::SEX_FEMALE;
            }
            $student->save();
        }
        // Else only update login datetime
        else {
            $student->last_login = new \DateTime();
            $student->etuutt_access_token = $access_token;
            $student->etuutt_refresh_token = $refresh_token;
            $student->etuutt_login = $json['login'];
            $student->student_id = $json['studentId'];
            $student->first_name = $json['firstName'];
            $student->last_name = $json['lastName'];
            $student->save();
        }

        return $student;
    }

    /**
     * Import user from EtuUTT to the db
     * @param  string $login User etuutt login
     * @return The user entity if created or found existing
     */
    function importUser($login) {
        // If the user is new, import some values from the API response.
        $json = EtuUTT::call('/api/public/users/'.$login)['data'];
        $user = User::where([ 'etuutt_login' => $json['login'] ])->first();
        if ($user === null) {
            $user = new User([
                'student_id'    => $json['studentId'],
                'first_name'    => $json['firstName'],
                'last_name'     => $json['lastName'],
                'surname'       => $json['surname'],
                'email'         => $json['email'],
                'facebook'      => $json['facebook'],
                'branch'        => $json['branch'],
                'level'         => $json['level'],
            ]);
            $user->etuutt_login = $json['login'];
            $user->save();

            // Error here a ignored, we just keep user without a picture if we cannot download it
            $picture = @file_get_contents('https://local-sig.utt.fr/Pub/trombi/individu/' . $json['studentId'] . '.jpg');
            @file_put_contents(public_path() . '/uploads/students-trombi/' . $json['studentId'] . '.jpg', $picture);
        }

        return $user;
    }
}


text:
require 'spec_helper'

module AWS
  class SimpleDB
    describe Request do

      it_should_behave_like "an authorize v2 request"

      it_should_behave_like "an aws query request"

    end
  end
end


text:
using System;
using HOLMS.Platform.Types;
using HOLMS.Types.Extensions;
using HOLMS.Types.Extensions.Support;
using HOLMS.Types.Primitive;
using HOLMS.Platform.Support.DTOExtensions.Primitive;

namespace HOLMS.Types.IAM {
    public partial class StaffMember : EntityDTO<StaffMemberIndicator> {
        public StaffMember(StaffMemberIndicator s, string userid, string password,
            string displayName, string emergencyContactPhone, bool isPhoneDisplayable,
            DateTime dateHired, bool isActive,
            DepartmentIndicator dept, string deptName, ContactInformation contact,bool isIncluded = false) {
            EntityId = s;
            UserId = userid;

            if (password != null) {
                Password = password;
            }

            DisplayName = displayName;
            EmergencyContactPhoneNumber = emergencyContactPhone;
            IsPhoneDataDisplayable = isPhoneDisplayable;
            DateHired = dateHired.ToTS();
            IsActive = isActive;
			IsIncluded = isIncluded;
            Department = dept;
            DepartmentName = deptName;
            ContactInfo = contact;
        }

        public override StaffMemberIndicator GetIndicator() => EntityId;

        public string NameFamilyGiven => ContactInfo.GetNameFamilyGiven();

        public string NameGivenFamily => ContactInfo.GetNameGivenFamily();

    }
}


text:
using System;
using Raksha.Utilities.Date;

namespace Raksha.Pkix
{
    public class CertStatus
    {
        public const int Unrevoked = 11;

        public const int Undetermined = 12;

        private int status = Unrevoked;

        DateTimeObject revocationDate = null;

        /// <summary>
        /// Returns the revocationDate.
        /// </summary>
         public DateTimeObject RevocationDate
        {
            get { return revocationDate; }
            set { this.revocationDate = value; }
        }

		/// <summary>
        /// Returns the certStatus.
        /// </summary>
        public int Status
        {
            get { return status; }
            set { this.status = value; }
        }
    }
}


text:
module Incite
  class Inline < Incite::Citation

    def to_html
      "(#{formatted_contributors(:authors)}. #{source.year}, #{formatted_pages})"
    end

  end
end


text:
package com.snowplowanalytics.snowplow.internal.globalcontexts;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.snowplowanalytics.snowplow.globalcontexts.GlobalContext;

import java.util.Set;

public interface GlobalContextsConfigurationInterface {

    /**
     * @return Set of tags associated to added GlobalContexts.
     */
    @NonNull
    Set<String> getTags();

    /**
     * Add a GlobalContext generator to the configuration of the tracker.
     * @param tag The label identifying the generator in the tracker.
     * @param contextGenerator The GlobalContext generator.
     * @return Whether the adding operation has succeeded.
     */
    boolean add(@NonNull String tag, @NonNull GlobalContext contextGenerator);

    /**
     * Remove a GlobalContext generator from the configuration of the tracker.
     * @param tag The label identifying the generator in the tracker.
     * @return Whether the removing operation has succeded.
     */
    @Nullable
    GlobalContext remove(@NonNull String tag);
}


text:
<?php
    class Home extends CI_Controller {
        public function __construct() {
            parent::__construct();
            $this->load->helper('url');
        }

        public function index($post_id = FALSE) {

            $this->load->model('pmodel');
            $data['posts'] = $this->pmodel->get_post();
            $this->load->view('post/index',$data);
            $this->load->view('footer');

        }

        public function article($post_id = FALSE) {

            if ($post_id === FALSE) {
                redirect('/');
            }

            $this->load->model('pmodel');
            $data['posts'] = $this->pmodel->get_post($post_id);
            $this->load->view('header');
            $this->load->view('post/article',$data);
            $this->load->view('footer');
        }

        public function create() {
            $this->load->model('pmodel');
            $this->load->helper('url');
            $this->load->helper('form');
            $this->load->library('form_validation');

            if(!$this->session->userdata('logged_in')) {
                redirect('/');
            }

            $this->form_validation->set_rules('title','Title','required');
            $this->form_validation->set_rules('artist','Artist','required');
            $this->form_validation->set_rules('content','Content','required');

            if ($this->form_validation->run() == FALSE) {
                $this->load->view('header');
                $this->load->view('admin/create');
                $this->load->view('footer');
            } else {
                $this->pmodel->insert_post();
                redirect('/');
            }
        }

        public function about() {
            $this->load->view('header');
            $this->load->view('about');
            $this->load->view('footer');
        }
    }
 ?>


text:
"""
Common parameter types for validating request Body.

"""

import re
import unicodedata

def _is_printable(char):
    """determine if a unicode code point is printable.

    This checks if the character is either "other" (mostly control
    codes), or a non-horizontal space. All characters that don't match
    those criteria are considered printable; that is: letters;
    combining marks; numbers; punctuation; symbols; (horizontal) space
    separators.
    """
    category = unicodedata.category(char)
    return (not category.startswith("C") and
            (not category.startswith("Z") or category == "Zs"))

def _get_all_chars():
    for i in range(0xFFFF):
        yield chr(i)

# build a regex that matches all printable characters. This allows
# spaces in the middle of the name. Also note that the regexp below
# deliberately allows the empty string. This is so only the constraint
# which enforces a minimum length for the name is triggered when an
# empty string is tested. Otherwise it is not deterministic which
# constraint fails and this causes issues for some unittests when
# PYTHONHASHSEED is set randomly.

def _build_regex_range(ws=True, invert=False, exclude=None):
    """Build a range regex for a set of characters in utf8.

    This builds a valid range regex for characters in utf8 by
    iterating the entire space and building up a set of x-y ranges for
    all the characters we find which are valid.

    :param ws: should we include whitespace in this range.
    :param invert: invert the logic
    :param exclude: any characters we want to exclude

    The inversion is useful when we want to generate a set of ranges
    which is everything that's not a certain class. For instance,
    produce all all the non printable characters as a set of ranges.
    """
    if exclude is None:
        exclude = []
    regex = ""
    # are we currently in a range
    in_range = False
    # last character we found, for closing ranges
    last = None
    # last character we added to the regex, this lets us know that we
    # already have B in the range, which means we don't need to close
    # it out with B-B. While the later seems to work, it's kind of bad form.
    last_added = None

    def valid_char(char):
        if char in exclude:
            result = False
        elif ws:
            result = _is_printable(char)
        else:
            # Zs is the unicode class for space characters, of which
            # there are about 10 in this range.
            result = (_is_printable(char) and
                      unicodedata.category(char) != "Zs")
        if invert is True:
            return not result
        return result

    # iterate through the entire character range. in_
    for c in _get_all_chars():
        if valid_char(c):
            if not in_range:
                regex += re.escape(c)
                last_added = c
            in_range = True
        else:
            if in_range and last != last_added:
                regex += "-" + re.escape(last)
            in_range = False
        last = c
    else:
        if in_range:
            regex += "-" + re.escape(c)
    return regex

valid_description_regex_base = '^[%s]*$'

valid_description_regex = valid_description_regex_base % (
    _build_regex_range())

keyvalue_pairs = {
    'type': 'object',
    'patternProperties': {
        '^[a-zA-Z0-9-_:. /]{1,1024}$': {
            'anyOf': [
                {'type': 'array'},
                {'type': 'string', 'maxLength': 1024},
                {'type': 'object'},
                {'type': 'null'},
                {'type': 'boolean'},
                {'type': 'number'}
            ]
        }
    },
    'additionalProperties': False
}

keyvalue_pairs_no_length_limit = {
    'type': 'object',
    'patternProperties': {
        '^[a-zA-Z0-9-_:. /]+$': {
            'anyOf': [
                {'type': 'array'},
                {'type': 'string'},
                {'type': 'object'},
                {'type': 'null'},
                {'type': 'boolean'},
                {'type': 'number'}
            ]
        }
    },
    'additionalProperties': False
}

description = {
    'type': 'string', 'minLength': 0, 'maxLength': 1024,
    'pattern': valid_description_regex,
}

uuid = {
    'type': 'string', 'format': 'uuid'
}

name_allow_zero_min_length = {
    'type': 'string', 'minLength': 0, 'maxLength': 255
}

ip_address = {
    'type': 'string',
    'oneOf': [
        {'format': 'ipv4'},
        {'format': 'ipv6'}
    ]
}

positive_integer = {
    'type': ['integer', 'string'],
    'pattern': '^[0-9]*$', 'minimum': 1, 'minLength': 1
}

identifier = {
    'type': 'string', 'minLength': 1, 'maxLength': 255
}

identifier_in_vim = {
    'type': 'string', 'minLength': 1, 'maxLength': 255
}

identifier_in_vnfd = {
    'type': 'string', 'minLength': 1, 'maxLength': 255
}

identifier_in_vnf = {
    'type': 'string', 'minLength': 1, 'maxLength': 255
}

mac_address_or_none = {
    'type': 'string', 'format': 'mac_address_or_none'
}


text:
<?php
namespace Mtasuandi\Tiket\Services;

use Mtasuandi\Tiket\Exceptions\TiketException;
use Mtasuandi\Tiket\Util\Config;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Psr7\Request;

/**
 * Super class for all services
 *
 * @package 	Services
 * @author 		M Teguh A Suandi
 */
abstract class BaseService
{
	/**
	 * Helper function to return required headers for making an HTTP request with Tiket.com
	 * @return 	array - authorization headers
	 */
	private static function getHeaders()
	{
		return [
			'twh' => Config::get( 'settings.user_agent' )
		];
	}

	/**
	 * GuzzleHTTP Client Implementation to use for HTTP requests
	 * @var 	Client
	 */
	private $client;

	/**
	 * Token for the application
	 * @var 	string
	 */
	private $token;

	/**
	 * Constructor with the option to supply an alternative rest client to be used
	 * @param 	string $token - Tiket.com Token
	 */
	public function __construct( $token )
	{
		$this->token 	= $token;
		$this->client = new Client( $this->getHeaders() );
	}

	/**
	 * Get the rest client being used by the service
	 * @return 	Client - GuzzleHTTP Client
	 */
	protected function getClient()
	{
		return $this->client;
	}

	/**
	 * Create send request for the API Calls
	 */
	protected function send( $method, $baseUrl, $params = [] )
	{
		$params['query']['token'] = $this->token;
		$response = $this->client->request( $method, $baseUrl, $params );
		return $response->getBody()->getContents();
	}

	/**
   * Turns a ClientException into a TiketException - like magic.
   * @param 	ClientException $exception - Guzzle ClientException
   * @return 	TiketException
   */
  protected function convertException( $exception )
  {
    $tiketException = new TiketException( $exception->getResponse()->getReasonPhrase(), $exception->getCode() );
    $tiketException->setUrl( $exception->getResponse()->getEffectiveUrl() );
    $tiketException->setErrors( json_decode( $exception->getResponse()->getBody()->getContents() ) );
    return $tiketException;
  }
}


text:
package Google::Ads::AdWords::v201809::ImageAsset;
use strict;
use warnings;

__PACKAGE__->_set_element_form_qualified(1);

sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201809' };

our $XML_ATTRIBUTE_CLASS;
undef $XML_ATTRIBUTE_CLASS;

sub __get_attr_class {
    return $XML_ATTRIBUTE_CLASS;
}

use base qw(Google::Ads::AdWords::v201809::Asset);
# Variety: sequence
use Class::Std::Fast::Storable constructor => 'none';
use base qw(Google::Ads::SOAP::Typelib::ComplexType);

{ # BLOCK to scope variables

my %assetId_of :ATTR(:get<assetId>);
my %assetName_of :ATTR(:get<assetName>);
my %assetSubtype_of :ATTR(:get<assetSubtype>);
my %assetStatus_of :ATTR(:get<assetStatus>);
my %Asset__Type_of :ATTR(:get<Asset__Type>);
my %imageData_of :ATTR(:get<imageData>);
my %imageFileSize_of :ATTR(:get<imageFileSize>);
my %imageMimeType_of :ATTR(:get<imageMimeType>);
my %fullSizeInfo_of :ATTR(:get<fullSizeInfo>);

__PACKAGE__->_factory(
    [ qw(        assetId
        assetName
        assetSubtype
        assetStatus
        Asset__Type
        imageData
        imageFileSize
        imageMimeType
        fullSizeInfo

    ) ],
    {
        'assetId' => \%assetId_of,
        'assetName' => \%assetName_of,
        'assetSubtype' => \%assetSubtype_of,
        'assetStatus' => \%assetStatus_of,
        'Asset__Type' => \%Asset__Type_of,
        'imageData' => \%imageData_of,
        'imageFileSize' => \%imageFileSize_of,
        'imageMimeType' => \%imageMimeType_of,
        'fullSizeInfo' => \%fullSizeInfo_of,
    },
    {
        'assetId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long',
        'assetName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
        'assetSubtype' => 'Google::Ads::AdWords::v201809::Asset::Type',
        'assetStatus' => 'Google::Ads::AdWords::v201809::AssetStatus',
        'Asset__Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
        'imageData' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary',
        'imageFileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long',
        'imageMimeType' => 'Google::Ads::AdWords::v201809::MediaMimeType',
        'fullSizeInfo' => 'Google::Ads::AdWords::v201809::ImageDimensionInfo',
    },
    {

        'assetId' => 'assetId',
        'assetName' => 'assetName',
        'assetSubtype' => 'assetSubtype',
        'assetStatus' => 'assetStatus',
        'Asset__Type' => 'Asset.Type',
        'imageData' => 'imageData',
        'imageFileSize' => 'imageFileSize',
        'imageMimeType' => 'imageMimeType',
        'fullSizeInfo' => 'fullSizeInfo',
    }
);

} # end BLOCK

1;

=pod

=head1 NAME

Google::Ads::AdWords::v201809::ImageAsset

=head1 DESCRIPTION

Perl data type class for the XML Schema defined complexType
ImageAsset from the namespace https://adwords.google.com/api/adwords/cm/v201809.

Represents an image asset.

=head2 PROPERTIES

The following properties may be accessed using get_PROPERTY / set_PROPERTY
methods:

=over

=item * imageData

=item * imageFileSize

=item * imageMimeType

=item * fullSizeInfo

=back

=head1 METHODS

=head2 new

Constructor. The following data structure may be passed to new():

=head1 AUTHOR

Generated by SOAP::WSDL

=cut


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/wearables/jacket/shared_jacket_s03.iff"
	result.attribute_template_id = 11
	result.stfName("wearables_name","jacket_s03")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
package org.shopkeeper.subjects.subjecttypes;

/**
 * This class contains all the subjects types that are currently available. When asked, please make sure you use these
 * types.
 */
public class SubjectTypes {

    public static final int ITEM = 0;
    public static final int CATEGORY = 1;
    public static final int CUSTOMER = 2;
}


text:
using VweCore.Geometry;

namespace VweCore.Abstractions
{
    public interface IRelativelyPositionable : IMovable
    {
        Point2D Offset { get; set; }
    }
}


text:
require 'spec_helper'

describe "sections/show" do
  before(:each) do
    @section = assign(:section, stub_model(Section,
      :name => "Name"
    ))
  end

  it "renders attributes in <p>" do
    render
    # Run the generator again with the --webrat flag if you want to use webrat matchers
    rendered.should match(/Name/)
  end
end


text:
package com.heima.mobilesafe.engine;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.xmlpull.v1.XmlSerializer;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.SystemClock;
import android.util.Xml;
import android.widget.ProgressBar;

/**
 * ¶ÌÐű¸·ÝµÄÒµÎñÀ࣬½«¶ÌÐű¸·Ý³Éxml¸ñʽ
 * @author lenovo
 */
public class SmsEngine {

	//1.´´½¨Ë¢×Ó(»Øµ÷½Ó¿Ú)
	public interface ShowProgress{
		//ÉèÖÃ×î´ó½ø¶È
		public void setMax(int max);
		//ÉèÖõ±Ç°½ø¶È
		public void setProgress(int progress);
	}

	//2.¸øµ÷ÓÃÕßË¢×Ó,²¢×¢²á»Øµ÷½Ó¿Ú
	public static void getAllSms(Context context,ShowProgress showProgress){
		//1.»ñÈ¡¶ÌÐÅ
		//1.1»ñÈ¡¶ÌÐŵÄÄÚÈݽâÎöÕß
		ContentResolver contentResolver = context.getContentResolver();
		//1.2»ñÈ¡ÄÚÈÝÌṩÕߵĵØÖ·   sms,sms±íµÄµØַΪ null
		//1.3»ñÈ¡²éѯ·¾¶
		Uri uri = Uri.parse("content://sms");
		//1.4²éѯ²Ù×÷
		Cursor cursor = contentResolver.query(uri, new String[]{"address","date","type","body"}, null, null, null);
		int count = cursor.getCount();
		showProgress.setMax(count);//ÉèÖÃ×î´ó½ø¶È
		//ÉèÖõ±Ç°½ø¶È
		int progress =0;

		//2.±¸·Ý¶ÌÐÅ
		//2.1»ñÈ¡xmlÐòÁÐÆ÷
		XmlSerializer xmlSerializer = Xml.newSerializer();
		try {
			//2.2±£´æxmlÎļþµÄ±£´æµÄ·¾¶
			xmlSerializer.setOutput(new FileOutputStream(new File("storage/sdcard1/backupsms.xml")), "utf-8");
			//2.3ÉèÖÃÍ·ÐÅÏ¢
			xmlSerializer.startDocument("utf-8", true);
			//2.4ÉèÖøù±êÇ©
			xmlSerializer.startTag(null, "smss");
			//1.5½âÎöcursor
			while(cursor.moveToNext()){
				SystemClock.sleep(1000);
				//2.5ÉèÖöÌÐŵıêÇ©
				xmlSerializer.startTag(null, "sms");

				//2.6ÉèÖÃÎı¾ÄÚÈݵıêÇ©
				xmlSerializer.startTag(null, "address");
				String address = cursor.getString(0);
				xmlSerializer.text(address);
				xmlSerializer.endTag(null, "address");

				xmlSerializer.startTag(null, "date");
				String date = cursor.getString(1);
				xmlSerializer.text(date);
				xmlSerializer.endTag(null, "date");

				xmlSerializer.startTag(null, "type");
				String type = cursor.getString(2);
				xmlSerializer.text(type);
				xmlSerializer.endTag(null, "type");

				xmlSerializer.startTag(null, "body");
				String body = cursor.getString(3);
				xmlSerializer.text(body);
				xmlSerializer.endTag(null, "body");

				xmlSerializer.endTag(null, "sms");
//				System.out.println("address:"+address+" date:"+date+" type:"+type+" body:"+body);
				//ÉèÖýø¶ÈÌõµÄµ±Ç°½ø¶È
				progress++;
				showProgress.setProgress(progress);
			}
			xmlSerializer.endTag(null, "smss");
			xmlSerializer.endDocument();
			//½«Êý¾Ýˢе½ÎļþÖÐ
			xmlSerializer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


text:
import json
import urllib.parse

from django.http import HttpResponse
from django.views import View

from people.factories import create_authenticate_interactor

class ViewWrapper(View):

    view_creator_func = None
    upload_picture_name = None

    def get(self, request, *args, **kwargs):
        kwargs.update(request.GET.dict())

        logged_person_id = self.authenticate(request, **kwargs)
        kwargs.update({'logged_person_id': logged_person_id})

        body, status = self.view_creator_func(request, **kwargs).get(**kwargs)
        return HttpResponse(json.dumps(body), status=status, content_type='application/json')

    def post(self, request, *args, **kwargs):
        kwargs.update(request.POST.dict())

        logged_person_id = self.authenticate(request, **kwargs)
        kwargs.update({'logged_person_id': logged_person_id})

        if self.upload_picture_name is not None:
            picture = request.FILES[self.upload_picture_name]
            body, status = self.view_creator_func(request, **kwargs).post(picture, **kwargs)
        else:
            body, status = self.view_creator_func(request, **kwargs).post(**kwargs)
        return HttpResponse(json.dumps(body), status=status, content_type='application/json')

    def patch(self, request, *args, **kwargs):
        data = dict(urllib.parse.parse_qsl(request.body.decode("utf-8"), keep_blank_values=True))
        kwargs.update(data)

        logged_person_id = self.authenticate(request, **kwargs)
        kwargs.update({'logged_person_id': logged_person_id})

        if self.upload_picture_name is not None:
            picture = request.FILES[self.upload_picture_name]
            body, status = self.view_creator_func(request, **kwargs).patch(picture, **kwargs)
        else:
            body, status = self.view_creator_func(request, **kwargs).patch(**kwargs)
        return HttpResponse(json.dumps(body), status=status, content_type='application/json')

    def delete(self, request, *args, **kwargs):
        data = dict(urllib.parse.parse_qsl(request.body.decode("utf-8"), keep_blank_values=True))
        kwargs.update(data)

        logged_person_id = self.authenticate(request, **kwargs)
        kwargs.update({'logged_person_id': logged_person_id})

        body, status = self.view_creator_func(request, **kwargs).delete(**kwargs)
        content = json.dumps(body) if body is not None else ''
        return HttpResponse(content, status=status, content_type='application/json')

    def authenticate(self, request, **kwargs):
        authentication_header = request.META.get('HTTP_AUTHORIZATION')
        if authentication_header is None:
            return None

        access_token = authentication_header.replace('Token ', '')
        return create_authenticate_interactor().set_params(access_token=access_token).execute()


text:
import { FETCH_USER, ERROR_RESPONSE } from '../actions/types';

const INITIAL_STATE = { profile: {}, message: '', error: '' };

export default function (state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_USER:
      return { ...state, profile: action.payload.user };
    case ERROR_RESPONSE:
      return { ...state, error: action.payload };
  }

  return state;
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;

namespace Nohros.Data
{
  public class FieldNameLookup
  {
    readonly string[] fields_;
    readonly CompareInfo compare_info_;
    readonly Dictionary<string, int> lookup_;

    public FieldNameLookup(IDataReader reader) {
      int field_count = reader.FieldCount;
      fields_ = new string[field_count];
      lookup_ = new Dictionary<string, int>();

      for (int i = 0; i < field_count; i++) {
        string name = reader.GetName(i);
        fields_[i] = name;
        lookup_[name] = i;
      }

      compare_info_ = CultureInfo.InvariantCulture.CompareInfo;
    }

    public int GetOrdinal(string name) {
      if (name == null) {
        throw new ArgumentNullException("name");
      }
      int index = IndexOf(name);
      if (index == -1) {
        throw new IndexOutOfRangeException(name);
      }
      return index;
    }

    public int IndexOf(string name) {
      int index;
      if (lookup_.TryGetValue(name, out index)) {
        return index;
      }
      index = LinearIndexOf(name, CompareOptions.IgnoreCase);
      if (index == -1) {
        return LinearIndexOf(name,
          CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType |
            CompareOptions.IgnoreCase);
      }
      return index;
    }

    int LinearIndexOf(string name, CompareOptions compare_options) {
      int length = fields_.Length;
      for (int i = 0; i < length; i++) {
        if (compare_info_.Compare(name, fields_[i], compare_options) == 0) {
          lookup_[name] = i;
          return i;
        }
      }
      return -1;
    }
  }
}


text:
package nl.myndocs.database.migrator.integration.tools;

import nl.myndocs.database.migrator.MigrationScript;
import nl.myndocs.database.migrator.definition.Migration;

import java.util.function.Consumer;

public class SimpleMigrationScript implements MigrationScript {
    private final String migrationId;
    private final Consumer<Migration> migrationConsumer;

    public SimpleMigrationScript(String migrationId, Consumer<Migration> migrationConsumer) {
        this.migrationId = migrationId;
        this.migrationConsumer = migrationConsumer;
    }

    @Override
    public String migrationId() {
        return migrationId;
    }

    @Override
    public void migrate(Migration migration) {
        migrationConsumer.accept(migration);
    }
}


text:
class GURL;

namespace content {
class BrowserContext;
}

namespace extensions {

struct ExtensionInfo;

namespace util {

// TODO(tmdiep): Move functions from
// chrome/browser/extensions/extension_util.h/cc that are only dependent on
// extensions/ here.

// Returns true if |extension_id| identifies an extension that is installed
// permanently and not ephemerally.
bool IsExtensionInstalledPermanently(const std::string& extension_id,
                                     content::BrowserContext* context);

// Returns true if |extension_id| identifies an ephemeral app.
bool IsEphemeralApp(const std::string& extension_id,
                    content::BrowserContext* context);

// Returns true if the extension has isolated storage.
bool HasIsolatedStorage(const ExtensionInfo& info);

// Returns true if the site URL corresponds to an extension or app and has
// isolated storage.
bool SiteHasIsolatedStorage(const GURL& extension_site_url,
                            content::BrowserContext* context);

}  // namespace util
}  // namespace extensions

#endif  // EXTENSIONS_BROWSER_EXTENSION_UTIL_H_


text:
package com.gigamole.sample.screens;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.gigamole.infinitecycleviewpager.VerticalInfiniteCycleViewPager;
import com.gigamole.sample.R;
import com.gigamole.sample.adapters.VerticalPagerAdapter;

/**
 * Created by GIGAMOLE on 8/18/16.
 */
public class VerticalPagerFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_vertical, container, false);
    }

    @Override
    public void onViewCreated(final View view, @Nullable final Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        final VerticalInfiniteCycleViewPager verticalInfiniteCycleViewPager =
                (VerticalInfiniteCycleViewPager) view.findViewById(R.id.vicvp);
        verticalInfiniteCycleViewPager.setAdapter(new VerticalPagerAdapter(getContext()));

        verticalInfiniteCycleViewPager.setScrollDuration(1000);
        verticalInfiniteCycleViewPager.startAutoScroll(true);
    }
}


text:
#import <Foundation/Foundation.h>
#import "PF_FBPlacePickerViewController.h"
#import "PF_FBRequest.h"
#import "PF_FBGraphObjectTableDataSource.h"
#import "PF_FBSession.h"

// This is the cache identity used by both the view controller and cache descriptor objects
extern NSString *const PF_FBPlacePickerCacheIdentity;

extern const NSInteger PF_defaultResultsLimit;
extern const NSInteger PF_defaultRadius;

@interface PF_FBPlacePickerViewController (Internal)

+ (PF_FBRequest*)requestForPlacesSearchAtCoordinate:(CLLocationCoordinate2D)coordinate
                                  radiusInMeters:(NSInteger)radius
                                    resultsLimit:(NSInteger)resultsLimit
                                      searchText:(NSString*)searchText
                                          fields:(NSSet*)fieldsForRequest
                                      datasource:(PF_FBGraphObjectTableDataSource*)datasource
                                         session:(PF_FBSession*)session;
@end


text:
package com.radiostream.di.components;

import com.radiostream.Settings;
import com.radiostream.javascript.bridge.PlayerEventsEmitter;
import com.radiostream.javascript.proxy.PlayerJsProxy;

import javax.inject.Singleton;

import dagger.Component;

@Component(modules = {})
@Singleton
public interface ApplicationComponent {
  void inject(PlayerJsProxy service);
  Settings provideSettings();
  PlayerEventsEmitter providePlayerEventsEmitter();
}


text:
@interface ZFTestModel : ZFBaseModel
@property(nonatomic,copy)NSString *name;
@property(nonatomic,assign)int age;
@end


text:
'use strict'

const vfs = require('vinyl-fs')
const hashSum = require('hash-sum')
const loadConfig = require('./config').loadConfig
const Cache = require('./cache')
const DepResolver = require('./dep-resolver')
const taskStream = require('./task-stream')
const cacheStream = require('./cache-stream')
const createWatcher = require('./externals/watcher')
const WatchLogger = require('./loggers/watch-logger')
const util = require('./util')

/**
 * The top level function to start the watcher for incremental build.
 * The 1st parameter can accept the following options:
 *
 * config - Path to a houl config file
 * cache - Path to a houl cache file
 * dot - Include dot files in output
 *
 * The 2nd parameter is meant to be used for internal,
 * so the users should not use it.
 *
 * The return value is a chokidar watcher object
 * which the user can use to execute any further processing.
 */
function watch(options, debug) {
  debug = debug || { cb: util.noop }

  const config = loadConfig(options.config)

  const cache = new Cache(hashSum)
  const depResolver = DepResolver.create(config)

  // Restore cache data
  if (options.cache) {
    const cacheData = util.readFileSync(options.cache)

    if (cacheData) {
      const json = JSON.parse(cacheData)

      // Restore cache data
      cache.deserialize(json.cache)

      // Restore deps data
      depResolver.deserialize(json.deps)
    }
  }

  // Logger
  const logger = new WatchLogger(config, {
    console: debug.console
  })

  stream(config.vinylInput).on('finish', debug.cb)
  return createWatcher(config, depResolver, (name, files, origin) => {
    if (name === 'add') {
      logger.addFile(origin)
    } else if (name === 'change') {
      logger.updateFile(origin)
    }

    const filtered = files.filter(f => !config.isExclude(f))
    if (filtered.length === 0) return

    stream(filtered)
      .on('data', file => {
        logger.writeFile(file.path)
      })
      .on('finish', debug.cb)
  }).on('ready', () => {
    logger.startWatching()
  })

  function stream(sources) {
    return vfs
      .src(sources, { nodir: true, dot: options.dot, base: config.input })
      .pipe(cacheStream(cache, depResolver, util.readFileSync))
      .pipe(taskStream(config))
      .pipe(vfs.dest(config.output))
      .on('finish', () => {
        if (!options.cache) return

        const serialized = JSON.stringify({
          cache: cache.serialize(),
          deps: depResolver.serialize()
        })
        util.writeFileSync(options.cache, serialized)
      })
  }
}

exports.watch = watch


text:
<!DOCTYPE HTML>

  <title>Flutter Test Browser Host</title>


text:
<!doctype html>

  <meta name="generator" content="JSDoc 3">
  <meta charset="utf-8">
  <title>Class: SparseVector</title>
  <link rel="stylesheet" href="https://brick.a.ssl.fastly.net/Karla:400,400i,700,700i" type="text/css">
  <link rel="stylesheet" href="https://brick.a.ssl.fastly.net/Noto+Serif:400,400i,700,700i" type="text/css">
  <link rel="stylesheet" href="https://brick.a.ssl.fastly.net/Inconsolata:500" type="text/css">
  <link href="css/baseline.css" rel="stylesheet">

        Home

class static
la.<wbr>SparseVector

Source: ladoc.<wbr>js:456

Represents a sparse vector.

Properties

dim

nnz

Methods

at(idx)

full()

idxVec()

inner(arg)

multiply(num)

norm()

normalize()

print()

put(idx, num)

sum()

toString()

valVec()

new SparseVector([arg][, dim])

Sparse Vector

            Example

// import la module
var la = require('qminer').la;
// create new sparse vector with arrays
var spVec = new la.SparseVector([[0, 1], [2, 3], [3, 6]]); // sparse vector [1, 0, 3, 6]
// create new sparse vector with dim
var spVec2 = new la.SparseVector([[0, 1], [2, 3], [3, 6]], 5); // largest index (zero based) is 4

Parameters

                    Name
                    Type
                    Optional
                    Description

arg

(Array of Array of number or module:la.SparseVector)

Yes

Constructor arguments. There are two ways of constructing:

1. Nested array of vector elements. Example: [[0, 2],[2, 3]] has two nonzero values, first value is 2 at position 0, second value is 3 at position 2.

2. A sparse vector (copy constructor).

dim

number

Yes

Maximal length of sparse vector. It is only in combinantion with nested array of vector elements.

Properties

dim

Returns the dimension of sparse vector.

Returns

number Dimension of sparse vector.

nnz

Returns the number of nonzero values.

Returns

number Number of nonzero values.

Methods

at(idx) →  number

Returns an element of the sparse vector.

            Example

// import la module
var la = require('qminer').la;
// create a sparse vector
var vec = new la.SparseVector([[0, 1], [3, 2], [4, -5]]);
// get the value at the position 3
vec.at(3); // returns the value 2

Parameter

                      Name
                      Type
                      Optional
                      Description

idx

number

Index (zero based).

Returns

number Sparse vector element.

full() →  module:la.Vector

Returns the dense vector representation of the sparse vector.

Returns

module:la.Vector The dense vector representation.

idxVec() →  module:la.Vector

Returns a dense vector of indices (zero based) of nonzero elements of sparse vector.

Returns

module:la.Vector A dense vector of indeces.

inner(arg) →  number

Returns the inner product of the parameter and the sparse vector.

            Example

// import la module
var la = require('qminer').la;
// create two vectors, one sparse and one dense
var sparse = new la.SparseVector([[0, 1], [3, 2], [4, -5]]);
var dense = new la.Vector([3, -4, 2, 0.5, -1]);
// get the inner product of the vectors
sparse.inner(dense); // returns the value 9

Parameter

                      Name
                      Type
                      Optional
                      Description

arg

(module:la.Vector or module:la.SparseVector)

The inner product input.

Returns

number The inner product of the two vectors.

multiply(num) →  module:la.SparseVector

Multiplies the sparse vector with a scalar.

            Example

// import la module
var la = require('qminer').la;
// create a new sparse vector
var spVec = new la.SparseVector([[0, 1], [2, 3], [3, 6]]);
// multiply sparse vector with scalar 3.14
var spVec2 = spVec.multiply(3.14); // returns sparse vector [3.14, 0, 9.42, 18.84]

Parameter

                      Name
                      Type
                      Optional
                      Description

num

number

The scalar.

Returns

module:la.SparseVector The product of num and sparse vector.

norm() →  number

Returns the norm of sparse vector.

Returns

number Norm of sparse vector.

normalize() →  module:la.SparseVector

Normalizes the sparse vector.

Returns

module:la.SparseVector Self. The vector is normalized.

print()

Prints the sparse vector on-screen.

            Example

// import la module
var la = require('qminer').la;
// create a new sparse vector
var spVec = new la.SparseVector([[0, 1], [2, 3]]);
// print sparse vector
spVec.print(); // shows on-screen [(0, 1), (2, 3)]

put(idx, num) →  module:la.SparseVector

Puts a new element in sparse vector.

            Example

// import la module
var la = require('qminer').la;
// create a new sparse vector
var vec = new la.SparseVector([[0, 1], [3, 2], [4, -5]]);
// set the new values at position 2
vec.put(2, -4);

Parameters

                      Name
                      Type
                      Optional
                      Description

idx

number

Index (zero based).

num

number

Input value.

Returns

module:la.SparseVector Self. It puts/changes the values with the index idx to the value num.

sum() →  number

Returns the sum of all values in sparse vector.

            Example

// import la module
var la = require('qminer').la;
// create a new sparse vector
var vec = new la.SparseVector([[0, 1], [3, 2], [4, -5]]);
// get the sum of the values in the vector
vec.sum(); // returns -2

Returns

number The sum of all values in sparse vector.

toString() →  string

Returns the string representation.

            Example

// import la module
var la = require('qminer').la;
// create a new sparse vector
var spVec = new la.SparseVector([[0, 1], [2, 3]]);
// get the string representation of the vector
spVec.toString(); // returns the string '[(0, 1), (2, 3)]'

Returns

string The string representation of the sparse vector.

valVec() →  module:la.Vector

Returns a dense vector of values of nonzero elements of sparse vector.

Returns

module:la.Vector A dense vector of values.


text:
#include "pillarScatter.h"
#include <cstring>

using namespace nvinfer1;
using nvinfer1::plugin::PillarScatterPlugin;
using nvinfer1::plugin::PillarScatterPluginCreator;

static const char* PLUGIN_VERSION{"1"};
static const char* PLUGIN_NAME{"PillarScatterPlugin"};

// Static class fields initialization
PluginFieldCollection PillarScatterPluginCreator::mFC{};
std::vector<PluginField> PillarScatterPluginCreator::mPluginAttributes;

// Helper function for serializing plugin
template <typename T>
void writeToBuffer(char*& buffer, const T& val)
{
    *reinterpret_cast<T*>(buffer) = val;
    buffer += sizeof(T);
}

// Helper function for deserializing plugin
template <typename T>
T readFromBuffer(const char*& buffer)
{
    T val = *reinterpret_cast<const T*>(buffer);
    buffer += sizeof(T);
    return val;
}

PillarScatterPlugin::PillarScatterPlugin(size_t h, size_t w)
    : feature_y_size_(h)
    , feature_x_size_(w)
{
}

PillarScatterPlugin::PillarScatterPlugin(const void* data, size_t length)
{
    const char* d = reinterpret_cast<const char*>(data);
    feature_y_size_ = readFromBuffer<size_t>(d);
    feature_x_size_ = readFromBuffer<size_t>(d);
}

nvinfer1::IPluginV2DynamicExt* PillarScatterPlugin::clone() const noexcept
{
    try
    {
        auto* plugin = new PillarScatterPlugin(feature_y_size_, feature_x_size_);
        plugin->setPluginNamespace(mNamespace.c_str());
        return plugin;
    }
    catch (std::exception const& e)
    {
        caughtError(e);
    }
    return nullptr;
}

nvinfer1::DimsExprs PillarScatterPlugin::getOutputDimensions(
    int outputIndex, const nvinfer1::DimsExprs* inputs, int nbInputs, nvinfer1::IExprBuilder& exprBuilder) noexcept
{
    PLUGIN_ASSERT(outputIndex == 0);
    nvinfer1::DimsExprs output;
    auto batch_size = inputs[0].d[0];
    output.nbDims = 4;
    output.d[0] = batch_size;
    output.d[1] = inputs[0].d[2];
    output.d[2] = exprBuilder.constant(feature_y_size_);
    output.d[3] = exprBuilder.constant(feature_x_size_);
    return output;
}

bool PillarScatterPlugin::supportsFormatCombination(
    int pos, const nvinfer1::PluginTensorDesc* inOut, int nbInputs, int nbOutputs) noexcept
{
    PLUGIN_ASSERT(nbInputs == 3);
    PLUGIN_ASSERT(nbOutputs == 1);
    const PluginTensorDesc& in = inOut[pos];
    if (pos == 0)
    {
        return (in.type == nvinfer1::DataType::kFLOAT || in.type == nvinfer1::DataType::kHALF) && (in.format == TensorFormat::kLINEAR);
    }
    if (pos == 1)
    {
        return (in.type == nvinfer1::DataType::kINT32) && (in.format == TensorFormat::kLINEAR);
    }
    if (pos == 2)
    {
        return (in.type == nvinfer1::DataType::kINT32) && (in.format == TensorFormat::kLINEAR);
    }
    if (pos == 3)
    {
        return (in.type == inOut[0].type) && (in.format == TensorFormat::kLINEAR || in.format == TensorFormat::kHWC8);
    }
    return false;
}

void PillarScatterPlugin::configurePlugin(const nvinfer1::DynamicPluginTensorDesc* in, int nbInputs,
    const nvinfer1::DynamicPluginTensorDesc* out, int nbOutputs) noexcept
{
    return;
}

size_t PillarScatterPlugin::getWorkspaceSize(const nvinfer1::PluginTensorDesc* inputs, int nbInputs,
    const nvinfer1::PluginTensorDesc* outputs, int nbOutputs) const noexcept
{
    return 0;
}
int PillarScatterPlugin::enqueue(const nvinfer1::PluginTensorDesc* inputDesc,
    const nvinfer1::PluginTensorDesc* outputDesc, const void* const* inputs, void* const* outputs, void* workspace,
    cudaStream_t stream) noexcept
{
    try
    {
        int batchSize = inputDesc[0].dims.d[0];
        int maxPillarNum = inputDesc[0].dims.d[1];
        int numFeatures = inputDesc[0].dims.d[2];

        nvinfer1::DataType inputType = inputDesc[0].type;

        auto coords_data = static_cast<const unsigned int *>(inputs[1]);
        auto params_data = static_cast<const unsigned int *>(inputs[2]);

        unsigned int featureY = feature_y_size_;
        unsigned int featureX = feature_x_size_;

        int status = -1;

        if(inputType == nvinfer1::DataType::kHALF){
            auto pillar_features_data = static_cast<const half *>(inputs[0]);
            auto spatial_feature_data = static_cast<half *>(outputs[0]);
            cudaMemsetAsync(spatial_feature_data, 0, batchSize*numFeatures*featureY*featureX * sizeof(half), stream);
            status = pillarScatterKernelLaunch<half>(
                batchSize,
                maxPillarNum,
                numFeatures,
                pillar_features_data,
                coords_data,
                params_data,
                featureX,
                featureY,
                spatial_feature_data,
                stream
                );
            PLUGIN_ASSERT(status == STATUS_SUCCESS);
            return status;
        }
        else if(inputType == nvinfer1::DataType::kFLOAT){
            auto pillar_features_data = static_cast<const float *>(inputs[0]);
            auto spatial_feature_data = static_cast<float *>(outputs[0]);
            cudaMemsetAsync(spatial_feature_data, 0, batchSize*numFeatures*featureY*featureX * sizeof(float), stream);
            status = pillarScatterKernelLaunch<float>(
                batchSize,
                maxPillarNum,
                numFeatures,
                pillar_features_data,
                coords_data,
                params_data,
                featureX,
                featureY,
                spatial_feature_data,
                stream
                );
            PLUGIN_ASSERT(status == STATUS_SUCCESS);
            return status;
        }
        else{
            PLUGIN_ASSERT(status == STATUS_SUCCESS);
            return status;
        }
    }
    catch (const std::exception& e)
    {
        caughtError(e);
    }
    return -1;
}

nvinfer1::DataType PillarScatterPlugin::getOutputDataType(
    int index, const nvinfer1::DataType* inputTypes, int nbInputs) const noexcept
{
    return inputTypes[0];
}

const char* PillarScatterPlugin::getPluginType() const noexcept
{
    return PLUGIN_NAME;
}

const char* PillarScatterPlugin::getPluginVersion() const noexcept
{
    return PLUGIN_VERSION;
}

int PillarScatterPlugin::getNbOutputs() const noexcept
{
    return 1;
}

int PillarScatterPlugin::initialize() noexcept
{
    return 0;
}

void PillarScatterPlugin::terminate() noexcept
{
}

size_t PillarScatterPlugin::getSerializationSize() const noexcept
{
    return 3 * sizeof(size_t);
}

void PillarScatterPlugin::serialize(void* buffer) const noexcept
{
    char* d = reinterpret_cast<char*>(buffer);
    writeToBuffer<size_t>(d, feature_y_size_);
    writeToBuffer<size_t>(d, feature_x_size_);
}

void PillarScatterPlugin::destroy() noexcept
{
    delete this;
}

void PillarScatterPlugin::setPluginNamespace(const char* libNamespace) noexcept
{
    mNamespace = libNamespace;
}

const char* PillarScatterPlugin::getPluginNamespace() const noexcept
{
    return mNamespace.c_str();
}

PillarScatterPluginCreator::PillarScatterPluginCreator()
{
    mPluginAttributes.clear();
    mPluginAttributes.emplace_back(PluginField("dense_shape", nullptr, PluginFieldType::kINT32, 1));
    mFC.nbFields = mPluginAttributes.size();
    mFC.fields = mPluginAttributes.data();
}

const char* PillarScatterPluginCreator::getPluginName() const noexcept
{
    return PLUGIN_NAME;
}

const char* PillarScatterPluginCreator::getPluginVersion() const noexcept
{
    return PLUGIN_VERSION;
}

const PluginFieldCollection* PillarScatterPluginCreator::getFieldNames() noexcept
{
    return &mFC;
}

IPluginV2* PillarScatterPluginCreator::createPlugin(const char* name, const PluginFieldCollection* fc) noexcept
{
    try
    {
        const PluginField* fields = fc->fields;
        int32_t nbFields = fc->nbFields;
        int32_t targetH = 0;
        int32_t targetW = 0;
        plugin::validateRequiredAttributesExist({"dense_shape"}, fc);
        for (int32_t i = 0; i < nbFields; ++i)
        {
            if (!strcmp(fields[i].name, "dense_shape"))
            {
                int32_t const* ts = static_cast<int32_t const*>(fields[i].data);
                targetH = ts[0];
                targetW = ts[1];
                PLUGIN_VALIDATE(targetH > 0 && targetW > 0);
            }
        }
        IPluginV2* plugin = new PillarScatterPlugin(targetH, targetW);
        return plugin;
    }
    catch (std::exception const& e)
    {
        caughtError(e);
    }
    return nullptr;
}

IPluginV2* PillarScatterPluginCreator::deserializePlugin(
    const char* name, const void* serialData, size_t serialLength) noexcept
{
    try
    {
        // This object will be deleted when the network is destroyed,
        IPluginV2* plugin = new PillarScatterPlugin(serialData, serialLength);
        return plugin;
    }
    catch (std::exception const& e)
    {
        caughtError(e);
    }
    return nullptr;
}

void PillarScatterPluginCreator::setPluginNamespace(const char* libNamespace) noexcept
{
    mNamespace = libNamespace;
}

const char* PillarScatterPluginCreator::getPluginNamespace() const noexcept
{
    return mNamespace.c_str();
}


text:
const fs = require('fs');
const assert = require('assert');

const libDetectorSource = fs.readFileSync(__dirname + '/../library/libraries.js', 'utf8');

console.log('💻 Evaluating libraries.js...');
eval(libDetectorSource);

const libraryDetectorEntries = d41d8cd98f00b204e9800998ecf8427e_LibraryDetectorTests;
assert.ok(libraryDetectorEntries);

console.log('🔍 Asserting entries look correct...');
const libIds = new Set();

for (const [libName, entry] of Object.entries(libraryDetectorEntries)) {
    assert.ok(libName, `Entry doesn't have a name. Impossible.`);

    /**
     * Validate no duplicate `id`s
     */
    if (libIds.has(entry.id)) {
        assert.fail(`[${libName}] \`id\` is a duplicate`);
    } else {
        libIds.add(entry.id);
    }

    /**
     * Validate each library has its required components
     */
    // id
    assert.equal(typeof entry.id, 'string', `[${libName}] \`id\` isn't a string`);
    assert.ok(entry.id.length, `[${libName}] \`id\` string isn't defined.`);

    // icon
    assert.equal(typeof entry.icon, 'string', `[${libName}] \`icon\` isn't a string`);
    assert.ok(entry.icon.length, `[${libName}] \`icon\` string isn't defined`);
    const iconFileExists = fs.existsSync(`${__dirname}/../icons/${entry.icon}.png`);
    assert.ok(iconFileExists, `[${libName}] \`icon\` file not found in ./icons`);

    const stat = fs.statSync(`${__dirname}/../icons/${entry.icon}.png`);
    assert.ok(stat.size, `[${libName}] \`icon\` file is empty`);

    // url
    assert.equal(typeof entry.url, 'string', `[${libName}] \`url\` isn't a string`);
    assert.ok(entry.url.startsWith('http'), `[${libName}] \`url\` doesn't look like a URL`);
    assert.ok(new URL(entry.url), `[${libName}] \`url\` is an invalid URL`);

    // npm
    // TODO: determine if `npm` is required or not
    if ('npm' in entry) {
        assert.ok(entry.npm === null || entry.npm.length, `[${libName}] \`npm\` should be either null or a string.`)
    }

    // test
    assert.equal(typeof entry.test, 'function', `[${libName}] \`test\` method is not a function`);
}

console.log('\n✅ Tests pass!\n');


text:
package net.mollywhite.mbta;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.db.DataSourceFactory;
import io.dropwizard.jdbi.DBIFactory;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import net.mollywhite.mbta.client.MbtaClient;
import net.mollywhite.mbta.client.TweetConsumer;
import net.mollywhite.mbta.client.TwitterClient;
import net.mollywhite.mbta.dao.TweetDAO;
import net.mollywhite.mbta.health.TwitterHealthCheck;
import net.mollywhite.mbta.resources.AllResource;
import net.mollywhite.mbta.resources.BranchResource;
import net.mollywhite.mbta.resources.LineResource;
import net.mollywhite.mbta.resources.MaintenanceResource;
import net.mollywhite.mbta.resources.StationResource;
import net.mollywhite.mbta.services.TwitterClientManager;
import org.skife.jdbi.v2.DBI;

import java.sql.Connection;
import java.sql.DriverManager;

public class MbtaApplication extends Application<MbtaConfiguration> {
  private DBI dbi;

  public static void main(String[] args) throws Exception {
    new MbtaApplication().run(args);
  }

  @Override
  public String getName() {
    return "mbta";
  }

  @Override
  public void initialize(Bootstrap bootstrap) {
//    bootstrap.addBundle(new AssetsBundle("/assets", "/", "index.html"));
  }

  @Override
  public void run(MbtaConfiguration config, Environment environment) throws Exception {
    final DataSourceFactory dsf = config.getDataSourceFactory();
    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(environment, dsf, "postgresql");
    final TweetDAO tweetDAO = jdbi.onDemand(TweetDAO.class);

    final TwitterClient twitterClient = new TwitterClient(config.getTwitterConsumerKey(), config.getTwitterConsumerSecret(), config.getTwitterToken(), config.getTwitterSecret());
    final TwitterHealthCheck twitterHealthCheck = new TwitterHealthCheck(twitterClient);
    final ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    final Connection connection = DriverManager.getConnection(dsf.getUrl(), dsf.getUser(), dsf.getPassword());
    final MbtaClient mbtaClient = new MbtaClient(mapper, config.getMbtaApiKey());
    final TweetConsumer tweetConsumer = new TweetConsumer(twitterClient, mapper, tweetDAO, connection, mbtaClient);
    TwitterClientManager twitterClientManager = new TwitterClientManager(tweetConsumer);

    environment.healthChecks().register("Twitter healthcheck", twitterHealthCheck);
    environment.jersey().register(new AllResource(tweetDAO));
    environment.jersey().register(new BranchResource(tweetDAO));
    environment.jersey().register(new LineResource(tweetDAO));
    environment.jersey().register(new StationResource(tweetDAO));
    environment.jersey().register(new MaintenanceResource(tweetDAO));
    environment.lifecycle().manage(twitterClientManager);
  }
}