text:
use std::io::{Write, Seek, SeekFrom};
use std::fs::File;
use std::mem;
use std::slice;
use std::cell::RefCell;
use std::collections::{HashSet, HashMap};

use uuid::Uuid;
use xz2::write::XzEncoder;
use tempfile::tempfile;
use console::{style, StyledObject};
use indicatif::{ProgressBar, ProgressStyle};

use super::types::{IndexItem, StoredSlice, MemDbHeader, IndexedUuid};
use super::super::Result;
use super::super::sdk::{SdkInfo, DumpOptions, Objects};
use super::super::dsym::{Object, Variant};
use super::super::utils::{file_size_format, copy_with_progress};

struct MemDbBuilder<W> {
    writer: RefCell<W>,
    tempfile: Option<RefCell<File>>,
    info: SdkInfo,
    symbols: Vec<String>,
    symbols_map: HashMap<String, u32>,
    object_names: Vec<String>,
    object_names_map: HashMap<String, u16>,
    object_uuid_mapping: Vec<(String, Uuid)>,
    variant_uuids: Vec<IndexedUuid>,
    variant_uuids_seen: HashSet<Uuid>,
    variants: Vec<Vec<IndexItem>>,
    symbol_count: usize,
    options: DumpOptions,
}

fn format_step(step: usize, opts: &DumpOptions) -> StyledObject<String> {
    let steps = if opts.compress {
        6
    } else {
        5
    };
    style(format!("[{}/{}]", step, steps)).dim()
}

trait WriteSeek : Write + Seek {}
impl<T: Write+Seek> WriteSeek for T {}

impl<W: Write + Seek> MemDbBuilder<W> {

    pub fn new(writer: W, info: &SdkInfo, opts: DumpOptions)
        -> Result<MemDbBuilder<W>>
    {
        let rv = MemDbBuilder {
            writer: RefCell::new(writer),
            tempfile: if opts.compress {
                Some(RefCell::new(tempfile()?))
            } else {
                None
            },
            info: info.clone(),
            symbols: vec![],
            symbols_map: HashMap::new(),
            object_names: vec![],
            object_names_map: HashMap::new(),
            object_uuid_mapping: vec![],
            variant_uuids: vec![],
            variant_uuids_seen: HashSet::new(),
            variants: vec![],
            symbol_count: 0,
            options: opts,
        };
        let header = MemDbHeader { ..Default::default() };
        rv.write(&header)?;
        Ok(rv)
    }

    fn with_file<T, F: FnOnce(&mut WriteSeek) -> T>(&self, f: F) -> T {
        if self.options.compress {
            f(&mut *self.tempfile.as_ref().unwrap().borrow_mut() as &mut WriteSeek)
        } else {
            f(&mut *self.writer.borrow_mut() as &mut WriteSeek)
        }
    }

    fn write_bytes(&self, x: &[u8]) -> Result<usize> {
        self.with_file(|w| {
            w.write_all(x)?;
            Ok(x.len())
        })
    }

    fn write<T>(&self, x: &T) -> Result<usize> {
        unsafe {
            let bytes : *const u8 = mem::transmute(x);
            let size = mem::size_of_val(x);
            self.with_file(|w| {
                w.write_all(slice::from_raw_parts(bytes, size))?;
                Ok(size)
            })
        }
    }

    fn seek(&self, new_pos: usize) -> Result<()> {
        self.with_file(|w| {
            w.seek(SeekFrom::Start(new_pos as u64))?;
            Ok(())
        })
    }

    fn tell(&self) -> Result<usize> {
        self.with_file(|w| {
            Ok(w.seek(SeekFrom::Current(0))? as usize)
        })
    }

    fn add_symbol(&mut self, sym: &str) -> u32 {
        if let Some(&sym_id) = self.symbols_map.get(sym) {
            return sym_id as u32;
        }
        let symbol_count = self.symbols.len();
        self.symbols.push(sym.to_string());
        self.symbols_map.insert(sym.to_string(), symbol_count as u32);
        symbol_count as u32
    }

    fn add_object_name(&mut self, src: &str) -> u16 {
        if let Some(&src_id) = self.object_names_map.get(src) {
            return src_id as u16;
        }
        let object_count = self.object_names.len();
        self.object_names.push(src.to_string());
        self.object_names_map.insert(src.to_string(), object_count as u16);
        object_count as u16
    }

    pub fn write_object(&mut self, obj: &Object, filename: Option<&str>) -> Result<()> {
        for variant in obj.variants() {
            let src = variant.name().or(filename).unwrap();
            if let Some(uuid) = variant.uuid() {
                self.write_object_variant(&obj, &variant, &uuid, src)?;
            }
        }
        Ok(())
    }

    fn write_object_variant(&mut self, obj: &Object, var: &Variant,
                            uuid: &Uuid, src: &str) -> Result<bool> {
        self.object_uuid_mapping.push((
            format!("{}:{}", src, var.arch()),
            *uuid
        ));

        if self.variant_uuids_seen.contains(uuid) {
            return Ok(false);
        }
        self.variant_uuids_seen.insert(*uuid);

        let mut symbols = obj.symbols(var.arch())?;
        let src_id = self.add_object_name(src);

        // build symbol index
        let mut index = vec![];
        for (addr, sym) in symbols.iter() {
            let sym_id = self.add_symbol(sym);
            index.push(IndexItem::new(addr - var.vmaddr(), src_id, Some(sym_id)));
            self.symbol_count += 1;
        }

        // write an end marker if we know the image size
        if var.vmsize() > 0 {
            index.push(IndexItem::new(var.vmsize(), src_id, None));
            self.symbol_count += 1;
        }

        index.sort_by_key(|item| item.addr());

        // register variant and uuid
        self.variant_uuids.push(IndexedUuid::new(uuid, self.variants.len()));
        self.variants.push(index);

        Ok(true)
    }

    fn make_string_slices(&self, strings: &[String], _try_compress: bool) -> Result<Vec<StoredSlice>> {
        let mut slices = vec![];
        let pb = ProgressBar::new(strings.len() as u64);
        pb.set_style(ProgressStyle::default_bar()
            .template("{wide_msg:.dim}\n{wide_bar} {pos:>5}/{len}"));
        for string in strings.iter() {
            let offset = self.tell()?;
            pb.set_message(&string);
            let len = self.write_bytes(string.as_bytes())?;
            slices.push(StoredSlice::new(offset, len, false));
            pb.inc(1);
        }
        pb.finish_and_clear();
        Ok(slices)
    }

    fn write_slices(&self, slices: &[StoredSlice], start: &mut u32, len: &mut u32) -> Result<()> {
        *start = self.tell()? as u32;
        let pb = ProgressBar::new(slices.len() as u64);
        for item in slices.iter() {
            self.write(item)?;
            pb.inc(1);
        }
        *len = slices.len() as u32;
        pb.finish_and_clear();
        Ok(())
    }

    pub fn flush(&mut self) -> Result<()> {
        println!("      Found {} symbols", style(self.symbol_count).cyan());
        let mut header = MemDbHeader { ..Default::default() };
        header.version = 2;
        header.sdk_info.set_from_sdk_info(&self.info);

        println!("{} Writing metadata", format_step(2, &self.options));
        // start by writing out the index of the variants and record the slices.
        let mut slices = vec![];
        let pb = ProgressBar::new(self.variants.iter().map(|x| x.iter().count()).sum::<usize>() as u64);
        pb.set_style(ProgressStyle::default_bar()
            .template("{wide_msg:.dim}\n{wide_bar} {pos:>5}/{len}"));
        for variant in self.variants.iter() {
            let offset = self.tell()?;
            for index_item in variant {
                pb.set_message(&self.object_uuid_mapping[index_item.src_id() as usize].0);
                self.write(index_item)?;
                pb.inc(1);
            }
            slices.push(StoredSlice::new(offset, (self.tell()? - offset), false));
        }
        pb.finish_and_clear();
        self.write_slices(&slices[..], &mut header.variants_start,
                          &mut header.variants_count)?;

        // next write out the UUIDs.  Since these are fixed length we do not
        // need to use slices here.
        header.uuids_start = self.tell()? as u32;
        header.uuids_count = self.variant_uuids.len() as u32;
        self.variant_uuids.sort_by_key(|x| x.uuid);
        for indexed_uuid in self.variant_uuids.iter() {
            self.write(indexed_uuid)?;
        }

        // next we write out the name + arch -> uuid index mapping.  We also sort
        // this by uuid so that the index matches up.
        header.tagged_object_names_start = self.tell()? as u32;
        self.object_uuid_mapping.sort_by_key(|&(_, b)| b);
        for &(ref tagged_object, _) in self.object_uuid_mapping.iter() {
            self.write_bytes(format!("{}\x00", tagged_object).as_bytes())?;
        }
        header.tagged_object_names_end = self.tell()? as u32;

        // now write out all the object name sources
        let slices = self.make_string_slices(&self.object_names[..], true)?;
        self.write_slices(&slices[..], &mut header.object_names_start,
                          &mut header.object_names_count)?;

        println!("{} Writing symbol strings", format_step(3, &self.options));

        // now write out all the symbols
        let slices = self.make_string_slices(&self.symbols[..], true)?;
        println!("{} Writing symbol index", format_step(4, &self.options));
        self.write_slices(&slices[..], &mut header.symbols_start,
                          &mut header.symbols_count)?;

        println!("{} Writing headers", format_step(5, &self.options));

        let file_size = self.tell()?;

        // write the updated header
        self.seek(0)?;
        self.write(&header)?;

        println!("      Indexed {} variants",
                 style(self.variant_uuids.len()).cyan());

        // compress if necessary
        if self.options.compress {
            println!("{} Compressing", format_step(6, &self.options));
            let pb = ProgressBar::new(file_size as u64);
            pb.set_style(ProgressStyle::default_bar()
                .template("{wide_bar} {bytes}/{total_bytes}"));
            self.seek(0)?;
            let mut reader = self.tempfile.as_ref().unwrap().borrow_mut();
            let mut writer = self.writer.borrow_mut();
            {
                let mut zwriter = XzEncoder::new(&mut *writer, 9);
                copy_with_progress(&pb, &mut *reader, &mut zwriter)?;
            }
            let compressed_file_size = writer.seek(SeekFrom::Current(0))? as usize;
            let pct = (compressed_file_size * 100) / file_size;
            pb.finish_and_clear();
            println!(
                "      Compressed from {} to {} ({}% of original size)",
                file_size_format(file_size),
                file_size_format(compressed_file_size),
                pct);
        }

        Ok(())
    }
}

/// Dumps objects into a writer
pub fn dump_memdb<W: Write + Seek>(writer: W, info: &SdkInfo,
                                   opts: DumpOptions, objects: Objects)
    -> Result<()>
{
    println!("{} Processing {} files", format_step(1, &opts),
             style(objects.file_count()).cyan());
    let mut builder = MemDbBuilder::new(writer, info, opts)?;
    let pb = ProgressBar::new(objects.file_count() as u64);
    pb.set_style(ProgressStyle::default_bar()
        .template("{wide_msg:.dim}\n{wide_bar} {pos:>5}/{len}"));
    for obj_res in objects {
        let (offset, filename, obj) = obj_res?;
        pb.set_message(&filename);
        builder.write_object(&obj, Some(&filename))?;
        pb.inc(offset as u64);
    }
    pb.finish_and_clear();
    builder.flush()?;
    Ok(())
}


text:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { PipesFunctionsComponent } from './pipes-functions.component';

const routes: Routes = [
    { path: 'pipes-functions', component: PipesFunctionsComponent }
];

@NgModule({
    imports: [ RouterModule.forChild(routes) ],
    exports: [ RouterModule ]
})
export class PipesFunctionsRoutingModule {
    static components = [
        PipesFunctionsComponent
    ]
}

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"github.com/pseudomuto/protokit"

	"log"
	"os"

	gendoc "github.com/pseudomuto/protoc-gen-doc"
	_ "github.com/pseudomuto/protoc-gen-doc/extensions/google_api_http" // imported for side effects
	_ "github.com/pseudomuto/protoc-gen-doc/extensions/lyft_validate"   // imported for side effects
	_ "github.com/pseudomuto/protoc-gen-doc/extensions/validator_field" // imported for side effects
)

func main() {
	if flags := ParseFlags(os.Stdout, os.Args); HandleFlags(flags) {
		os.Exit(flags.Code())
	}

	if err := protokit.RunPlugin(new(gendoc.Plugin)); err != nil {
		log.Fatal(err)
	}
}

// HandleFlags checks if there's a match and returns true if it was "handled"
func HandleFlags(f *Flags) bool {
	if !f.HasMatch() {
		return false
	}

	if f.ShowHelp() {
		f.PrintHelp()
	}

	if f.ShowVersion() {
		f.PrintVersion()
	}

	return true
}


text:
'use strict';

/* Controllers */

angular.module('myApp.controllers', [])
  .controller('SearchController', ['$rootScope', '$scope', 'instagram','$location', function($rootScope, $scope, instagram, $location) {

      $scope.getResults = function() {
          var hasError = false;
          var formSubmitted = false;
          var $fieldsToValidate = $("#search-form .has-validator");
          // instagram url to be contructed by input, default is popular
          var instagramUrl = 'https://api.instagram.com/v1/media/popular?client_id=599289ce136242f98cb101527d18360d&callback=JSON_CALLBACK';
          // make sure results view is shown
          $location.path('results');

          // prevent double submits before page load finishes
          if (formSubmitted) {
              return false;
          }

          if(!$scope.username && !$scope.hashtag) {
              var hasError = true;
              console.log(hasError);
          }
          if($scope.username && !$scope.hashtag) {
              // run search for all instagram images with hastag
              $rootScope.searchterm = 'username '+$scope.username;

              instagramUrl = 'https://api.instagram.com/v1/users/search?q=' + $scope.username + '&client_id=599289ce136242f98cb101527d18360d&callback=JSON_CALLBACK';

              $rootScope.userResults = [];

              // call instagram service
              instagram.fetchImages(instagramUrl, function(data) {
                $rootScope.userResults = data;
                console.log(data);
              });

              // clear input text
              $scope.clearInput();
              //clear results
              $rootScope.userResults = [];
              $rootScope.hashtagResults = []

          }
          if(!$scope.username && $scope.hashtag) {
              // run search for instagram hashtag
              $rootScope.searchterm = '#'+$scope.hashtag;

              instagramUrl = 'https://api.instagram.com/v1/tags/' + $scope.hashtag + '/media/recent?client_id=599289ce136242f98cb101527d18360d&callback=JSON_CALLBACK';

              $rootScope.hashtagResults = [];

              // call instagram service
              instagram.fetchImages(instagramUrl, function(data){
                $rootScope.hashtagResults = data;
              });

              // clear input text
              $scope.clearInput();
              //clear results
              $rootScope.userResults = [];
              $rootScope.hashtagResults = []

              /* what is called from the service
              $http.jsonp(instagramUrl).
                success(function(response){
                  $rootScope.results = response.data;
                  console.log($rootScope.results);
                }).
                error(function(response) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                console.log('Server error!');
              });
              */
          } else if($scope.username || $scope.hashtag) {
              var hasError = false;
          }

          if (!hasError) {
              $("#sidebar-search .alert").html('').hide();
              // hide keyboard on mobile
              $('input#submit').blur();
              formSubmitted = true;
              return true;
          } else {
             $("#sidebar-search .alert").html('You must fill out one of the fields with a search term.').show();
             hasError = false;
             return false;
          }
      };

      $scope.clearResults = function(){
        //clear results
        $rootScope.userResults = [];
        $rootScope.hashtagResults = []
        $rootScope.searchterm = '';
      };

      $scope.clearInput = function(){
        // clear input text
        $scope.username = '';
        $scope.hashtag = '';
      };

  }]);


text:
/**
 * @author Aleksey Ignatenko
 * @version $Revision: 1.0 $
 */

package org.apache.harmony.test.reliability.vm.classloading;

import org.apache.harmony.test.reliability.share.Test;
import java.lang.reflect.Method;
import java.io.IOException;
import java.io.InputStream;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Goal: check that class loading and unloading work without OOME or other unexpected
 *       problems when classes are loaded by user-defined classloader from binary file
 *       in numerous threads in parallel.
 *
 * The test does:
 *    1. Reads parameters, which are:
 *       param[0] - path to classes/ directory, relatively to which auxilliary
 *                  class TestUnloadingClass.class can be found.
 *       param[1] - number of classes to load via custom class loader in each thread
 *       param[2] - number of classloading threads
 *
 *    2. Starts param[2] of classloading threads. Each thread:
 *       a. Runs param[1] iterations. On each iteration:
 *       b. New instance of custom classloader (class CustomLoader) is created.
 *       c. Loading of some class (represented by org.apache....TestUnloadingClass.class)
 *          by the new instance of the loader is initiated.
 *       d. After the class is loaded, it is checked that classes' loader (as returned
 *          by Class.getClassLoader()) is definitely instance of the used custom loder.
 *       e. Then, some method of the loaded class is invoked.
 *       f. Finally, reference to the class, custom classloader which loaded the class
 *          are null-ed, expecting that it will allow to unload the class and custom loader.
 */

public class ClassUnloadingTest extends Test {

    static int NUMBER_OF_CLASSES_TO_LOAD = 100;

    static int NUMBER_OF_THREADS_TO_START = 100;

    static String CLASS_DIR = "";

    static String pckgName = "org.apache.harmony.test.reliability.vm.classloading";

    static String testedClassName = "TestUnloadingClass";

    volatile Boolean failed = false;

    public static void main(String[] args){
        System.exit(new ClassUnloadingTest().test(args));
    }

    public int test(String[] args){

        parseParams(args);
        failed = false;

        Thread thrds[] = new Thread[NUMBER_OF_THREADS_TO_START];
        for (int i = 0; i < thrds.length; i++){
            thrds[i] = new LoadingThread(this);
            thrds[i].run();
        }

        for (int i = 0; i < thrds.length; i++){
            try {
                thrds[i].join();
            } catch (InterruptedException e) {
                failed = true;
                log.add("InterruptedException was thrown: " + e.getMessage());
            }
        }
        if (failed){
            return fail("");
        }
        return pass("OK");
    }

    public void parseParams(String[] params) {
        if (params.length >= 1) {
            CLASS_DIR = params[0];
        }
        if (params.length >= 2) {
            NUMBER_OF_CLASSES_TO_LOAD = Integer.parseInt(params[1]);
        }
        if (params.length >= 3) {
            NUMBER_OF_THREADS_TO_START = Integer.parseInt(params[2]);
        }
    }

    String getTestedClassURI() {
        String s = pckgName + "." + testedClassName;
        return (s.replace('.', '/') + ".class");
    }

}

class LoadingThread extends Thread {

    ClassUnloadingTest base;

    LoadingThread (ClassUnloadingTest base) {
        this.base = base;
    }

    public void run() {

        for (int i = 0; i < base.NUMBER_OF_CLASSES_TO_LOAD; i++) {
            CustomLoader cl = new CustomLoader(base);
            try {
                String className = base.pckgName + "." + base.testedClassName;
                String classFileName = base.testedClassName + ".class";
                Class cls = cl.loadClass(className, classFileName);

                if (cls == null){
                    base.failed = true;
                    continue;
                }
                if (cls.getClassLoader() != cl) {
                    base.log.add("getClassLoader() returned not the custom classloader");
                    base.failed = true;
                    continue;
                }

                Object obj = cls.newInstance();
                Method meth = cls.getMethod("test", new Class[0]);
                meth.invoke(obj, new Object[0]);

                // Force unloading
                meth = null;
                obj   = null;
                cls = null;
                cl = null;
            } catch (Throwable t) {
                base.log.add("Thread " + this.getId() + ": unexpected exception was thrown: " + t.getMessage());
                base.failed = true;
            }
        }
    }
}

class CustomLoader extends ClassLoader {

    ClassUnloadingTest base;

    CustomLoader(ClassUnloadingTest base) {
        this.base = base;
    }

    protected URL findResource(String name){
        URL ret = null;
        try {
            File workDir = new File(base.CLASS_DIR);
            ret = new URL(workDir.toURI().toString() + "/" + base.getTestedClassURI());
        } catch (MalformedURLException e) {
            throw new Error(e);
        }
        return ret;
    }

    public Class loadClass(String cname, String fname) {

        InputStream is = getResourceAsStream(fname);

        if (is == null) {
            throw new RuntimeException("Couldn't find resource: " + fname);
        }

        byte[] data = new byte[0];
        byte[] piece = new byte[512];
        int len;
        try {
            while ((len = is.read(piece)) != -1) {
                byte[] tmp = data;
                data = new byte[tmp.length + len];
                System.arraycopy(tmp, 0, data, 0, tmp.length);
                System.arraycopy(piece, 0, data, tmp.length, len);
                tmp = null;
            }
        } catch (IOException ex) {
            throw new Error(ex);
        }

        try {
            is.close();
        } catch (IOException ex) {
            throw new Error(ex);
        }
        return defineClass(cname, data, 0, data.length);
    }
}


text:
package org.gradle.buildinit.plugins.internal.maven;

import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
import org.apache.maven.project.MavenProject;
import org.gradle.internal.io.StreamByteBuffer;

import java.io.IOException;
import java.util.Set;

public class MavenProjectXmlWriter {

    //TODO this class attempts to mimic the behavior of the output of mvn help:effective-pom
    //instead of this class we should walk the maven project object model (instead of parsing the xml!)

    String toXml(Set<MavenProject> projects) {
        assert !projects.isEmpty() : "Cannot prepare the Maven projects effective XML because provided projects set is empty.";

        if (projects.size() == 1) {
            return toXml(projects.iterator().next());
        }

        StringBuilder out = new StringBuilder("<projects>");
        for (MavenProject project : projects) {
            out.append(toXml(project));
        }
        return out.append("</projects>").toString();
    }

    private String toXml(MavenProject project) {
        StreamByteBuffer out = new StreamByteBuffer();
        try {
            new MavenXpp3Writer().write(out.getOutputStream(), project.getModel());
        } catch (IOException e) {
            throw new RuntimeException("Unable to serialize Maven model to XML. Maven project: " + project, e);
        }
        return prepareXml(out.readAsString());
    }

    String prepareXml(String xml) {
        return xml.replaceFirst("^<\\?xml.+?\\?>", "");
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bot. Gaz. 9: 188 (1884)

#### Original name
Puccinia tenuis (Schwein.) Burrill

### Remarks
null


text:
<?php
namespace Concrete\Core\Api\Fractal\Transformer;

use Concrete\Core\Page\Collection\Version\Version;
use League\Fractal\TransformerAbstract;

class CollectionVersionTransformer extends TransformerAbstract
{

    public function transform(Version $version)
    {
        $data = [];
        $data['id'] = $version->getVersionID();
        $data['is_approved'] = $version->isApproved();
        $data['date_created'] = $version->getVersionDateCreated();
        $data['date_approved'] = $version->getVersionDateApproved();
        $data['publish_end_date'] = $version->getPublishEndDate();
        return $data;
    }

}


text:
using Quasar.Utilities;

namespace Quasar.HabboHotel.Rewards
{
    public class Reward
    {
        public double RewardStart { get; set; }
        public double RewardEnd { get; set; }
        public RewardType Type { get; set; }
        public string RewardData { get; set; }
        public string Message { get; set; }
        public Reward(double Start, double End, string Type, string RewardData, string Message)
        {
            this.RewardStart = Start;
            this.RewardEnd = End;
            this.Type = RewardTypeUtility.GetType(Type);
            this.RewardData = RewardData;
            this.Message = Message;
        }

        public bool isActive()
        {
            double Now = UnixTimestamp.GetNow();
            return (Now >= RewardStart && Now <= RewardEnd);
        }
    }
}


text:
package info.u250.c2d.engine;

import com.badlogic.gdx.InputProcessor;

/**
 * Scene is the main render loop drawable . Such as : main scene, game scene, help scene etc.
 * Many time , only one mainScene allowed besides the transitionScene.
 * The game logic can be put in {@link #update(float)} and draw the game in {@link #render(float)} so when you pause the game, the logic is no effect to the game.
 * another important method is {@link #getInputProcessor()} , which supply a user defined input process .
 *
 * @author xjjdog
 */
public interface Scene {
    /**
     * all the game scene logic show be here if you want
     */
    void update(float delta);

    /**
     * draw the game objects that on this scene
     */
    void render(float delta);

    /**
     * the show method was called when the transition scene reach the screen
     */
    void show();

    /**
     * the hide method was called when the transition scene  hide the scene1 , it can be used to dispose some resources if you want
     */
    void hide();

    /**
     * supply a user defined inputProcess to handle all user events in the scene
     */
    InputProcessor getInputProcessor();
}


text:
    <form class="form-horizontal" role="form" ng-submit="saveItem(item)">

            Name

                <input type="text" ng-model="item.name" class="form-control"/>

                <crud-Buttons></crud-Buttons>

    </form>


text:
package mezz.jei.util;

import javax.annotation.Nullable;

import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;

import mezz.jei.api.helpers.IStackHelper;
import mezz.jei.api.ingredients.subtypes.ISubtypeManager;

public class StackHelper implements IStackHelper {
	private final ISubtypeManager subtypeManager;

	public StackHelper(ISubtypeManager subtypeManager) {
		this.subtypeManager = subtypeManager;
	}

	/**
	 * Similar to ItemStack.areItemStacksEqual but ignores NBT on items without subtypes, and uses the {@link ISubtypeManager}
	 */
	@Override
	public boolean isEquivalent(@Nullable ItemStack lhs, @Nullable ItemStack rhs) {
		if (lhs == rhs) {
			return true;
		}

		if (lhs == null || rhs == null) {
			return false;
		}

		if (lhs.getItem() != rhs.getItem()) {
			return false;
		}

		String keyLhs = getUniqueIdentifierForStack(lhs, UidMode.NORMAL);
		String keyRhs = getUniqueIdentifierForStack(rhs, UidMode.NORMAL);
		return keyLhs.equals(keyRhs);
	}

	public String getUniqueIdentifierForStack(ItemStack stack) {
		return getUniqueIdentifierForStack(stack, UidMode.NORMAL);
	}

	public String getUniqueIdentifierForStack(ItemStack stack, UidMode mode) {
		ErrorUtil.checkNotEmpty(stack, "stack");

		Item item = stack.getItem();
		ResourceLocation registryName = item.getRegistryName();
		if (registryName == null) {
			String stackInfo = ErrorUtil.getItemStackInfo(stack);
			throw new IllegalStateException("Item has no registry name: " + stackInfo);
		}

		String result = registryName.toString();
		if (mode == UidMode.NORMAL) {
			String subtypeInfo = subtypeManager.getSubtypeInfo(stack);
			if (subtypeInfo != null && !subtypeInfo.isEmpty()) {
				result = result + ':' + subtypeInfo;
			}
		}
		return result;
	}

	public enum UidMode {
		NORMAL, WILDCARD
	}
}


text:
if [ -z "$1" ]
then
   DEPLOY_DIR="../../deploy"
else
   DEPLOY_DIR="$1"
fi
CONFIG_PATH="$DEPLOY_DIR/config.yaml"
HELPERS_PATH="$DEPLOY_DIR/helpers.sh"
MEMORY="256MB"
TIMEOUT="540"

source "$HELPERS_PATH"
eval "$(parse_yaml $CONFIG_PATH)"

INBOUND_TOPIC_NAME="$ENQUEUE_TASK_TOPIC"

SUB=$(cat $CONFIG_PATH |  grep -P ENQUEUE_TASK_TOPIC)
PREFIX="$DEPLOYMENT_NAME.$SOLUTION_PREFIX"
echo "$PREFIX"
echo "$SUB"

INBOUND_TOPIC_NAME=$PREFIX.$INBOUND_TOPIC_NAME

create_pubsub_topic "$INBOUND_TOPIC_NAME"

CFG_FILE=$(cat $CONFIG_PATH > ./__config.yaml)

gcloud functions deploy "$DEPLOYMENT_NAME""_""$SOLUTION_PREFIX""_long_running_task_writer" \
   --runtime python38 \
   --entry-point main \
   --trigger-resource "$INBOUND_TOPIC_NAME" \
   --trigger-event google.pubsub.topic.publish \
   --memory "$MEMORY" \
   --timeout "$TIMEOUT" \
   --project "$DEFAULT_GCP_PROJECT" \
   --region "$DEFAULT_GCP_REGION" \
   --service-account "$SERVICE_ACCOUNT" \
   --env-vars-file ./__config.yaml \
   --no-allow-unauthenticated \
   --format "none"

rm ./__config.yaml


text:
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using Azure.Core;

namespace Azure.Analytics.Synapse.Artifacts.Models
{
    [JsonConverter(typeof(ShopifySourceConverter))]
    public partial class ShopifySource : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Query))
            {
                writer.WritePropertyName("query");
                writer.WriteObjectValue(Query);
            }
            if (Optional.IsDefined(QueryTimeout))
            {
                writer.WritePropertyName("queryTimeout");
                writer.WriteObjectValue(QueryTimeout);
            }
            if (Optional.IsDefined(AdditionalColumns))
            {
                writer.WritePropertyName("additionalColumns");
                writer.WriteObjectValue(AdditionalColumns);
            }
            writer.WritePropertyName("type");
            writer.WriteStringValue(Type);
            if (Optional.IsDefined(SourceRetryCount))
            {
                writer.WritePropertyName("sourceRetryCount");
                writer.WriteObjectValue(SourceRetryCount);
            }
            if (Optional.IsDefined(SourceRetryWait))
            {
                writer.WritePropertyName("sourceRetryWait");
                writer.WriteObjectValue(SourceRetryWait);
            }
            if (Optional.IsDefined(MaxConcurrentConnections))
            {
                writer.WritePropertyName("maxConcurrentConnections");
                writer.WriteObjectValue(MaxConcurrentConnections);
            }
            foreach (var item in AdditionalProperties)
            {
                writer.WritePropertyName(item.Key);
                writer.WriteObjectValue(item.Value);
            }
            writer.WriteEndObject();
        }

        internal static ShopifySource DeserializeShopifySource(JsonElement element)
        {
            Optional<object> query = default;
            Optional<object> queryTimeout = default;
            Optional<object> additionalColumns = default;
            string type = default;
            Optional<object> sourceRetryCount = default;
            Optional<object> sourceRetryWait = default;
            Optional<object> maxConcurrentConnections = default;
            IDictionary<string, object> additionalProperties = default;
            Dictionary<string, object> additionalPropertiesDictionary = new Dictionary<string, object>();
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("query"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    query = property.Value.GetObject();
                    continue;
                }
                if (property.NameEquals("queryTimeout"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    queryTimeout = property.Value.GetObject();
                    continue;
                }
                if (property.NameEquals("additionalColumns"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    additionalColumns = property.Value.GetObject();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("sourceRetryCount"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    sourceRetryCount = property.Value.GetObject();
                    continue;
                }
                if (property.NameEquals("sourceRetryWait"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    sourceRetryWait = property.Value.GetObject();
                    continue;
                }
                if (property.NameEquals("maxConcurrentConnections"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    maxConcurrentConnections = property.Value.GetObject();
                    continue;
                }
                additionalPropertiesDictionary.Add(property.Name, property.Value.GetObject());
            }
            additionalProperties = additionalPropertiesDictionary;
            return new ShopifySource(type, sourceRetryCount.Value, sourceRetryWait.Value, maxConcurrentConnections.Value, additionalProperties, queryTimeout.Value, additionalColumns.Value, query.Value);
        }

        internal partial class ShopifySourceConverter : JsonConverter<ShopifySource>
        {
            public override void Write(Utf8JsonWriter writer, ShopifySource model, JsonSerializerOptions options)
            {
                writer.WriteObjectValue(model);
            }
            public override ShopifySource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                using var document = JsonDocument.ParseValue(ref reader);
                return DeserializeShopifySource(document.RootElement);
            }
        }
    }
}


text:
package com.twu.biblioteca;

import java.util.Arrays;
import java.util.Scanner;

public class Menu {

    private static Scanner sc = new Scanner(System.in);
    private Library library = new Library();
    public static final String[] OPTIONS = {"1. List Books", "2.Print User Info", "3. Return a Book", "4. Checkout a Book", "5. List Movies", "6. Return a Movie", "7. Checkout a Movie", "8. Quit"};
    UserAccount userAccount = new UserAccount();

    public void runMenu() {
        displayOptions();
        actOnChoice(getUserMenuOption(), library);
    }

    public String launchApp() {
        String welcomeText = "Welcome to the Bangalore Public Library!\n";
        System.out.println(welcomeText);
        return welcomeText;
    }

    public String displayOptions() {
        System.out.println("What would you like to do next?");
        System.out.println(Arrays.toString(OPTIONS));

        return Arrays.toString(OPTIONS);
    }

    private int getUserMenuOption() {
        System.out.println("Enter a number for your choice: \n <<");
        int choice = sc.nextInt();
        return choice;
    }

    public void actOnChoice(int choice, Library library) {

        switch (choice) {
            case 1:
                library.listAvailableBooks();
                break;
            case 2:
                userAccount.printUserInformation();
                break;
            case 3:
                System.out.println("You are about to return a book.");
                library.returnBook();
                break;
            case 4:
                System.out.println("You are about to checkout a book.");
                library.checkoutBook();
                break;
            case 5:
                library.listAvailableMovies();
                break;
            case 6:
                System.out.println("You are about to return a movie.");
                library.returnMovie();
                break;
            case 7:
                System.out.println("You are about to checkout a movie.");
                library.checkoutMovie();
                break;
            case 8:
                System.out.println("Good bye!");
                return;
            default:
                System.out.println("Select a valid option!");
        }
        runMenu();
    }

}


text:
package com.ircclouds.irc.api.om;

import com.ircclouds.irc.api.domain.messages.*;

public class ChanPartBuilder implements IBuilder<ChannelPart>
{
	// //:aae!aaf@bot.lebane.se PART #botcode :aSS

    public ChannelPart build(AbstractMessage aMessage) {
        return new ChannelPart(aMessage);
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

  <title>Theming - Semantic</title>
  <link rel="stylesheet" type="text/css" href="../../dist/components/reset.css">
  <link rel="stylesheet" type="text/css" href="../../dist/components/site.css">
  <link rel="stylesheet" type="text/css" href="../../dist/components/grid.css">

Heading 1

Heading 2

Heading 3

Heading 4

Heading 5

Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nullam id dolor id nibh ultricies vehicula.

Example body text

Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nullam id dolor id nibh ultricies vehicula.

This line of text is meant to be treated as fine print.

The following snippet of text is rendered as bold text.

The following snippet of text is rendered as italicized text.

An abbreviation of the word attribute is attr.

Red

Orange

Yellow

Olive

Green

Teal

Blue

Violet

Purple

Pink

Brown

Grey

Black


text:
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<link href="http://search.cpan.org/s/style.css" rel="stylesheet" type="text/css">
<title>Planimeter(1)</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:root@localhost" />

NAME

Planimeter -- compute the area of geodesic polygons

SYNOPSIS

Planimeter [ -r ] [ -s ] [ -l ] [ -e a f ] [ -p prec ] [ -G | -E | -Q | -R ] [ --comment-delimiter commentdelim ] [ --version | -h | --help ] [ --input-file infile | --input-string instring ] [ --line-separator linesep ] [ --output-file outfile ]

DESCRIPTION

Measure the area of a geodesic polygon. Reads polygon vertices from standard input, one per line. Vertices may be given as latitude and longitude, UTM/UPS, or MGRS coordinates, interpreted in the same way as GeoConvert(1). (MGRS coordinates signify the center of the corresponding MGRS square.) The end of input, a blank line, or a line which can't be interpreted as a vertex signals the end of one polygon and the start of the next. For each polygon print a summary line with the number of points, the perimeter (in meters), and the area (in meters^2).

The edges of the polygon are given by the shortest geodesic between consecutive vertices. In certain cases, there may be two or many such shortest geodesics, and in that case, the polygon is not uniquely specified by its vertices. This only happens with very long edges (for the WGS84 ellipsoid, any edge shorter than 19970 km is uniquely specified by its end points). In such cases, insert an additional vertex near the middle of the long edge to define the boundary of the polygon.

By default, polygons traversed in a counter-clockwise direction return a positive area and those traversed in a clockwise direction return a negative area. This sign convention is reversed if the -r option is given.

Of course, encircling an area in the clockwise direction is equivalent to encircling the rest of the ellipsoid in the counter-clockwise direction. The default interpretation used by Planimeter is the one that results in a smaller magnitude of area; i.e., the magnitude of the area is less than or equal to one half the total area of the ellipsoid. If the -s option is given, then the interpretation used is the one that results in a positive area; i.e., the area is positive and less than the total area of the ellipsoid.

Only simple (i.e., non-self-intersecting) polygons are supported for the area computation. Polygons may include one or both poles. There is no need to close the polygon.

OPTIONS

-r

toggle whether counter-clockwise traversal of the polygon returns a positive (the default) or negative result.

-s

toggle whether to return a signed result (the default) or not.

-l

toggle whether the vertices represent a polygon (the default) or a polyline. For a polyline, the number of points and the length of the path joining them is returned; the path is not closed and the area is not reported.

-e

specify the ellipsoid via a f; the equatorial radius is a and the flattening is f. Setting f = 0 results in a sphere. Specify f < 0 for a prolate ellipsoid. A simple fraction, e.g., 1/297, is allowed for f. (Also, if f > 1, the flattening is set to 1/f.) By default, the WGS84 ellipsoid is used, a = 6378137 m, f = 1/298.257223563. If entering vertices as UTM/UPS or MGRS coordinates, use the default ellipsoid, since the conversion of these coordinates to latitude and longitude always uses the WGS84 parameters.

-p

set the output precision to prec (default 6); the perimeter is given (in meters) with prec digits after the decimal point; the area is given (in meters^2) with (prec - 5) digits after the decimal point.

-G

use the series formulation for the geodesics. This is the default option and is recommended for terrestrial applications. This option, -G, and the following three options, -E, -Q, and -R, are mutually exclusive.

-E

use "exact" algorithms (based on elliptic integrals) for the geodesic calculations. These are more accurate than the (default) series expansions for |f| > 0.02. (But note that the implementation of areas in GeodesicExact uses a high order series and this is only accurate for modest flattenings.)

-Q

perform the calculation on the authalic sphere. The area calculation is accurate even if the flattening is large, provided the edges are sufficiently short. The perimeter calculation is not accurate.

-R

The lines joining the vertices are rhumb lines instead of geodesics.

--comment-delimiter

set the comment delimiter to commentdelim (e.g., "#" or "//"). If set, the input lines will be scanned for this delimiter and, if found, the delimiter and the rest of the line will be removed prior to processing. For a given polygon, the last such string found will be appended to the output line (separated by a space).

--version

print version and exit.

-h

print usage and exit.

--help

print full documentation and exit.

--input-file

read input from the file infile instead of from standard input; a file name of "-" stands for standard input.

--input-string

read input from the string instring instead of from standard input. All occurrences of the line separator character (default is a semicolon) in instring are converted to newlines before the reading begins.

--line-separator

set the line separator character to linesep. By default this is a semicolon.

--output-file

write output to the file outfile instead of to standard output; a file name of "-" stands for standard output.

EXAMPLES

Example (the area of the 100km MGRS square 18SWK)

   Planimeter <<EOF
   18n 500000 4400000
   18n 600000 4400000
   18n 600000 4500000
   18n 500000 4500000
   EOF
   => 4 400139.53295860 10007388597.1913

The following code takes the output from gdalinfo and reports the area covered by the data (assuming the edges of the image are geodesics).

   #! /bin/sh
   egrep '^((Upper|Lower) (Left|Right)|Center) ' |
   sed -e 's/d /d/g' -e "s/' /'/g" | tr -s '(),\r\t' ' ' | awk '{
       if ($1 $2 == "UpperLeft")
           ul = $6 " " $5;
       else if ($1 $2 == "LowerLeft")
           ll = $6 " " $5;
       else if ($1 $2 == "UpperRight")
           ur = $6 " " $5;
       else if ($1 $2 == "LowerRight")
           lr = $6 " " $5;
       else if ($1 == "Center") {
           printf "%s\n%s\n%s\n%s\n\n", ul, ll, lr, ur;
           ul = ll = ur = lr = "";
       }
   }
   ' | Planimeter | cut -f3 -d' '

SEE ALSO

GeoConvert(1), GeodSolve(1).

An online version of this utility is availbable at http://geographiclib.sourceforge.net/cgi-bin/Planimeter.

The algorithm for the area of geodesic polygon is given in Section 6 of C. F. F. Karney, Algorithms for geodesics, J. Geodesy 87, 43-55 (2013); DOI https://dx.doi.org/10.1007/s00190-012-0578-z; addenda: http://geographiclib.sf.net/geod-addenda.html.

AUTHOR

Planimeter was written by Charles Karney.

HISTORY

Planimeter was added to GeographicLib, http://geographiclib.sf.net, in version 1.4.


text:
title: Advanced
---

### Keyed each blocks

Associating a *key* with a block allows Svelte to be smarter about how it adds and removes items to and from a list. To do so, add an `(expression)` that uniquely identifies each member of the list:

```html
<!-- { repl: false } -->
{#each people as person (person.name)}
	<div>{person.name}</div>
{/each}
```

It's easier to show the effect of this than to describe it. Open the following example in the REPL:

```html
<!-- { title: 'Keyed each blocks' } -->
<button on:click="update()">update</button>

<section>
	<h2>Keyed</h2>
	{#each people as person (person.name)}
		<div transition:slide>{person.name}</div>
	{/each}
</section>

<section>
	<h2>Non-keyed</h2>
	{#each people as person}
		<div transition:slide>{person.name}</div>
	{/each}
</section>

<style>
	button {
		display: block;
	}

	section {
		width: 10em;
		float: left;
	}
</style>

<script>
	import { slide } from 'svelte-transitions';

	var people = ['Alice', 'Barry', 'Cecilia', 'Douglas', 'Eleanor', 'Felix', 'Grace', 'Horatio', 'Isabelle'];

	function random() {
		return people
			.filter(() => Math.random() < 0.5)
			.map(name => ({ name }))
	}

	export default {
		data() {
			return { people: random() };
		},

		methods: {
			update() {
				this.set({ people: random() });
			}
		},

		transitions: { slide }
	};
</script>
```

### Hydration

If you're using [server-side rendering](guide#server-side-rendering), it's likely that you'll need to create a client-side version of your app *on top of* the server-rendered version. A naive way to do that would involve removing all the existing DOM and rendering the client-side app in its place:

```js
import App from './App.html';

const target = document.querySelector('#element-with-server-rendered-html');

// avoid doing this!
target.innerHTML = '';
new App({
	target
});
```

Ideally, we want to reuse the existing DOM instead. This process is called *hydration*. First, we need to tell the compiler to include the code necessary for hydration to work by passing the `hydratable: true` option:

```js
const { js } = svelte.compile(source, {
	hydratable: true
});
```

(Most likely, you'll be passing this option to [rollup-plugin-svelte](https://github.com/rollup/rollup-plugin-svelte) or [svelte-loader](https://github.com/sveltejs/svelte-loader).)

Then, when we instantiate the client-side component, we tell it to use the existing DOM with `hydrate: true`:

```js
import App from './App.html';

const target = document.querySelector('#element-with-server-rendered-html');

new App({
	target,
	hydrate: true
});
```

> It doesn't matter if the client-side app doesn't perfectly match the server-rendered HTML — Svelte will repair the DOM as it goes.

### Immutable

Because arrays and objects are *mutable*, Svelte must err on the side of caution when deciding whether or not to update things that refer to them.

But if all your data is [immutable](https://en.wikipedia.org/wiki/Immutable_object), you can use the `{ immutable: true }` compiler option to use strict object comparison (using `===`) everywhere in your app. If you have one component that uses immutable data you can set it to use the strict comparison for just that component.

In the example below, `searchResults` would normally be recalculated whenever `items` *might* have changed, but with `immutable: true` it will only update when `items` has *definitely* changed. This can improve the performance of your app.

```html
<!-- { repl: false } -->
{#each searchResults as item}
	<div>{item.name}</div>
{/each}

<script>
	import FuzzySearch from 'fuzzy-search';

	export default {
		immutable: true,

		computed: {
			searchResults: ({ searchString, items }) => {
				if (!searchString) return items;

				const searcher = new FuzzySearch(items, ['name', 'location']);
				return searcher.search(searchString);
			}
		}
	}
</script>
```

[Here's a live example](repl?demo=immutable) showing the effect of `immutable: true`.


text:
//
// @author raver119@gmail.com
//

#include <ops/BroadcastBoolOpsTuple.h>
#include <ops/declarable/headers/broadcastable.h>
#if NOT_EXCLUDED(OP_equals)

namespace sd {
namespace ops {
BROADCASTABLE_BOOL_OP_IMPL(equals, 0, 0) {
  auto x = INPUT_VARIABLE(0);
  auto y = INPUT_VARIABLE(1);
  auto z = OUTPUT_VARIABLE(0);

  BROADCAST_CHECK_EMPTY(x, y, z);

  auto tZ = BroadcastHelper::broadcastApply(
      BroadcastBoolOpsTuple::custom(scalar::EqualTo, pairwise::EqualTo, broadcast::EqualTo), x, y, z);
  if (tZ == nullptr)
    return sd::Status::KERNEL_FAILURE;
  else if (tZ != z) {
    OVERWRITE_RESULT(tZ);
  }

  return sd::Status::OK;
}

DECLARE_SYN(equal, equals);

DECLARE_TYPES(equals) {
  getOpDescriptor()
      ->setAllowedInputTypes(0, DataType::ANY)
      ->setAllowedInputTypes(1, DataType::ANY)
      ->setAllowedOutputTypes(0, DataType::BOOL);
}
}  // namespace ops
}  // namespace sd

#endif


text:
package com.amazonaws.services.codeartifact.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Details about the package origin configuration of a package.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PackageOriginConfiguration implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * A PackageOriginRestrictions object that contains information about the upstream and publish package
     * origin configuration for the package.
     *

     */
    private PackageOriginRestrictions restrictions;

    /**
     *

     * A PackageOriginRestrictions object that contains information about the upstream and publish package
     * origin configuration for the package.
     *

     *
     * @param restrictions
     *        A PackageOriginRestrictions object that contains information about the upstream and publish
     *        package origin configuration for the package.
     */

    public void setRestrictions(PackageOriginRestrictions restrictions) {
        this.restrictions = restrictions;
    }

    /**
     *

     * A PackageOriginRestrictions object that contains information about the upstream and publish package
     * origin configuration for the package.
     *

     *
     * @return A PackageOriginRestrictions object that contains information about the upstream and publish
     *         package origin configuration for the package.
     */

    public PackageOriginRestrictions getRestrictions() {
        return this.restrictions;
    }

    /**
     *

     * A PackageOriginRestrictions object that contains information about the upstream and publish package
     * origin configuration for the package.
     *

     *
     * @param restrictions
     *        A PackageOriginRestrictions object that contains information about the upstream and publish
     *        package origin configuration for the package.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PackageOriginConfiguration withRestrictions(PackageOriginRestrictions restrictions) {
        setRestrictions(restrictions);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getRestrictions() != null)
            sb.append("Restrictions: ").append(getRestrictions());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof PackageOriginConfiguration == false)
            return false;
        PackageOriginConfiguration other = (PackageOriginConfiguration) obj;
        if (other.getRestrictions() == null ^ this.getRestrictions() == null)
            return false;
        if (other.getRestrictions() != null && other.getRestrictions().equals(this.getRestrictions()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getRestrictions() == null) ? 0 : getRestrictions().hashCode());
        return hashCode;
    }

    @Override
    public PackageOriginConfiguration clone() {
        try {
            return (PackageOriginConfiguration) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.codeartifact.model.transform.PackageOriginConfigurationMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
<?php

namespace Piplin\Bus\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification as BaseNotification;
use NotificationChannels\Webhook\WebhookChannel;
use Piplin\Bus\Notifications\Channels\DingtalkChannel;
use Piplin\Models\Hook;

/**
 * Notification class.
 */
abstract class Notification extends BaseNotification implements ShouldQueue
{
    use Queueable;

    /**
     * Get the notification's delivery hooks.
     *
     * @param  Hook  $hook
     * @return array
     */
    public function via(Hook $hook)
    {
        if ($hook->type === Hook::WEBHOOK) {
            return [WebhookChannel::class];
        } elseif ($hook->type === Hook::DINGTALK) {
            return [DingtalkChannel::class];
        }

        return [$hook->type];
    }
}


text:
<?php

declare(strict_types=1);

namespace Biplane\YandexDirect\Api\V5\Contract;

use AllowDynamicProperties;

/**
 * Auto-generated code.
 */
#[AllowDynamicProperties]
class Callout
{
    protected $CalloutText = null;

    /**
     * @return static
     */
    public static function create()
    {
        return new static();
    }

    public function getCalloutText(): string
    {
        return $this->CalloutText;
    }

    /**
     * @return $this
     */
    public function setCalloutText(string $value)
    {
        $this->CalloutText = $value;

        return $this;
    }
}


text:
<list model="hr.leave">
    <field name="number"/>
    <field name="date"/>
    <field name="employee_id"/>
    <field name="start_date"/>
    <field name="end_date"/>
    <field name="leave_type_id"/>
    <field name="period_id"/>
    <field name="days_requested"/>
    <field name="days_remaining"/>
    <field name="state"/>
</list>


text:
// File Name: xXXXMessage.h
//
// Written By: Danny Kent (jaus AT dannykent DOT com), Tom Galluzzo
//
// Version: 3.3.0b
//
// Date: 09/08/09
//
// Description: This file defines the attributes of a XxXxMessage

#ifndef XXXX_MESSAGE_H
#define XXXX_MESSAGE_H

#include "jaus.h"

typedef struct
{
	// Include all parameters from a JausMessage structure:
	// Header Properties
	struct
	{
		// Properties by bit fields
		#ifdef JAUS_BIG_ENDIAN
			JausUnsignedShort reserved:2;
			JausUnsignedShort version:6;
			JausUnsignedShort expFlag:1;
			JausUnsignedShort scFlag:1;
			JausUnsignedShort ackNak:2;
			JausUnsignedShort priority:4;
		#elif JAUS_LITTLE_ENDIAN
			JausUnsignedShort priority:4;
			JausUnsignedShort ackNak:2;
			JausUnsignedShort scFlag:1;
			JausUnsignedShort expFlag:1;
			JausUnsignedShort version:6;
			JausUnsignedShort reserved:2;
		#else
			#error "Please define system endianess (see jaus.h)"
		#endif
	}properties;

	JausUnsignedShort commandCode;

	JausAddress destination;

	JausAddress source;

	JausUnsignedInteger dataSize;

	JausUnsignedInteger dataFlag;

	JausUnsignedShort sequenceNumber;

	// MESSAGE DATA MEMBERS GO HERE

	// Example from ReportGlobalPoseMessage
	//
	//	JausUnsignedShort presenceVector;
	//	JausDouble latitudeDegrees;				// Scaled Int (-90, 90)
	//	JausDouble longitudeDegrees;			// Scaled Int (-180, 180)
	//	JausDouble elevationMeters;				// Scaled Int (-10000, 35000)
	//	JausDouble positionRmsMeters;			// Scaled UInt (0, 100)
	//	JausDouble rollRadians;					// Scaled Short (-JAUS_PI, JAUS_PI)
	//	JausDouble pitchRadians;				// Scaled Short (-JAUS_PI, JAUS_PI)
	//	JausDouble yawRadians;					// Scaled Short (-JAUS_PI, JAUS_PI)
	//	JausDouble attitudeRmsRadians;			// Scaled Short (0, JAUS_PI)
	//	JausUnsignedInteger timeStamp;

}XxXxMessageStruct;

typedef XxXxMessageStruct* XxXxMessage;

JAUS_EXPORT XxXxMessage xXXXMessageCreate(void);
JAUS_EXPORT void xXXXMessageDestroy(XxXxMessage);

JAUS_EXPORT JausBoolean xXXXMessageFromBuffer(XxXxMessage message, unsigned char* buffer, unsigned int bufferSizeBytes);
JAUS_EXPORT JausBoolean xXXXMessageToBuffer(XxXxMessage message, unsigned char *buffer, unsigned int bufferSizeBytes);

JAUS_EXPORT XxXxMessage xXXXMessageFromJausMessage(JausMessage jausMessage);
JAUS_EXPORT JausMessage xXXXMessageToJausMessage(XxXxMessage message);

JAUS_EXPORT unsigned int xXXXMessageSize(XxXxMessage message);

JAUS_EXPORT char* xXXXMessageToString(XxXxMessage message);
#endif // XXXX_MESSAGE_H


text:
package org.apache.solr.search.json;

import org.apache.lucene.util.LuceneTestCase;
import org.apache.solr.JSONTestUtil;
import org.apache.solr.SolrTestCaseHS;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

@LuceneTestCase.SuppressCodecs({"Lucene3x","Lucene40","Lucene41","Lucene42","Lucene45","Appending"})
public class TestJsonRequest extends SolrTestCaseHS {

  private static SolrInstances servers;  // for distributed testing

  @BeforeClass
  public static void beforeTests() throws Exception {
    JSONTestUtil.failRepeatedKeys = true;
    initCore("solrconfig-tlog.xml","schema_latest.xml");
  }

  public static void initServers() throws Exception {
    if (servers == null) {
      servers = new SolrInstances(3, "solrconfig-tlog.xml","schema_latest.xml");
    }
  }

  @AfterClass
  public static void afterTests() throws Exception {
    JSONTestUtil.failRepeatedKeys = false;
    if (servers != null) {
      servers.stop();
      servers = null;
    }
  }

  @Test
  public void testLocalJsonRequest() throws Exception {
    doJsonRequest(Client.localClient);
  }

  @Test
  public void testDistribJsonRequest() throws Exception {
    initServers();
    initServers();
    Client client = servers.getClient( random().nextInt() );
    client.queryDefaults().set( "shards", servers.getShards() );
    doJsonRequest(client);
  }

  public static void doJsonRequest(Client client) throws Exception {
    client.deleteByQuery("*:*", null);
    client.add(sdoc("id", "1", "cat_s", "A", "where_s", "NY"), null);
    client.add(sdoc("id", "2", "cat_s", "B", "where_s", "NJ"), null);
    client.add(sdoc("id", "3"), null);
    client.commit();
    client.add(sdoc("id", "4", "cat_s", "A", "where_s", "NJ"), null);
    client.add(sdoc("id", "5", "cat_s", "B", "where_s", "NJ"), null);
    client.commit();
    client.add(sdoc("id", "6", "cat_s", "B", "where_s", "NY"), null);
    client.commit();

    // test json param
    client.testJQ( params("json","{query:'cat_s:A'}")
        , "response/numFound==2"
    );

    // test multiple json params
    client.testJQ( params("json","{query:'cat_s:A'}", "json","{filter:'where_s:NY'}")
        , "response/numFound==1"
    );

    // test multiple json params with one being zero length
    client.testJQ( params("json","{query:'cat_s:A'}", "json","{filter:'where_s:NY'}", "json","")
        , "response/numFound==1"
    );

    // test multiple json params with one being a comment
    client.testJQ( params("json","{query:'cat_s:A'}", "json","{filter:'where_s:NY'}", "json","/* */")
        , "response/numFound==1"
    );

    // test merging multi-valued params into list
    client.testJQ( params("json","{query:'*:*'}", "json","{filter:'where_s:NY'}", "json","{filter:'cat_s:A'}")
        , "response/numFound==1"
    );

    // test merging multi-valued params into list, second value is already list
    client.testJQ( params("json","{query:'*:*'}", "json","{filter:'where_s:NY'}", "json","{filter:['cat_s:A']}")
        , "response/numFound==1"
    );

    // test merging multi-valued params into list, first value is already list
    client.testJQ( params("json","{query:'*:*'}", "json","{filter:['where_s:NY']}", "json","{filter:'cat_s:A'}")
        , "response/numFound==1"
    );

    // test merging multi-valued params into list, both values are already list
    client.testJQ( params("json","{query:'*:*'}", "json","{filter:['where_s:NY']}", "json","{filter:['cat_s:A']}")
        , "response/numFound==1"
    );

    // test inserting and merging with paths
    client.testJQ( params("json.query","'*:*'", "json.filter","'where_s:NY'", "json.filter","'cat_s:A'")
        , "response/numFound==1"
    );

    // test inserting and merging with paths with an empty string and a comment
    client.testJQ( params("json.query","'*:*'", "json.filter","'where_s:NY'", "json.filter","'cat_s:A'", "json.filter","", "json.filter","/* */")
        , "response/numFound==1"
    );

    // test overwriting of non-multivalued params
    client.testJQ( params("json.query","'foo_s:NONE'", "json.filter","'where_s:NY'", "json.filter","'cat_s:A'", "json.query","'*:*'")
        , "response/numFound==1"
    );

    // normal parameter specified in the params block, including numeric params cast back to string
    client.testJQ( params("json","{params:{q:'*:*', fq:['cat_s:A','where_s:NY'], start:0, rows:5, fl:id}}")
        , "response/docs==[{id:'1'}]"
    );
    client.testJQ( params("json","{params:{q:'*:*', fq:['cat_s:A','where_s:(NY OR NJ)'], start:0, rows:1, fl:id, sort:'where_s asc'}}")
        , "response/numFound==2"
        , "response/docs==[{id:'4'}]"
    );
    client.testJQ( params("json","{params:{q:'*:*', fq:['cat_s:A','where_s:(NY OR NJ)'], start:0, rows:1, fl:[id,'x:5.5'], sort:'where_s asc'}}")
        , "response/numFound==2"
        , "response/docs==[{id:'4', x:5.5}]"
    );
    // test merge params
    client.testJQ( params("json","{params:{q:'*:*'}}", "json","{params:{fq:['cat_s:A','where_s:(NY OR NJ)'], start:0, rows:1, fl:[id,'x:5.5']}}", "json","{params:{sort:'where_s asc'}}")
        , "response/numFound==2"
        , "response/docs==[{id:'4', x:5.5}]"
    );

    // test offset/limit/sort/fields
    client.testJQ( params("json.query","'*:*'",  "json.offset","1", "json.limit","2", "json.sort","'id desc'", "json.fields","'id'")
        , "response/docs==[{id:'5'},{id:'4'}]"
    );
    // test offset/limit/sort/fields, multi-valued json.fields
    client.testJQ( params("json.query","'*:*'",  "json.offset","1", "json.limit","2", "json.sort","'id desc'", "json.fields","'id'", "json.fields","'x:5.5'")
        , "response/docs==[{id:'5', x:5.5},{id:'4', x:5.5}]"
    );
    // test offset/limit/sort/fields, overwriting non-multivalued params
    client.testJQ( params("json.query","'*:*'",  "json.offset","17", "json.offset","1", "json.limit","42", "json.limit","2", "json.sort","'id asc'", "json.sort","'id desc'", "json.fields","'id'", "json.fields","'x:5.5'")
        , "response/docs==[{id:'5', x:5.5},{id:'4', x:5.5}]"
    );

    // test templating before parsing JSON
    client.testJQ( params("json","${OPENBRACE} query:'cat_s:A' ${CLOSEBRACE}", "json","${OPENBRACE} filter:'where_s:NY'${CLOSEBRACE}",  "OPENBRACE","{", "CLOSEBRACE","}")
        , "response/numFound==1"
    );

    // test templating with params defined in the JSON itself!  Do we want to keep this functionality?
    client.testJQ( params("json","{params:{V1:A,V2:NY}, query:'cat_s:${V1}'}", "json","{filter:'where_s:${V2}'}")
        , "response/numFound==1"
    );

    //
    // with body
    //
    client.testJQ(params("stream.body", "{query:'cat_s:A'}", "stream.contentType", "application/json")
        , "response/numFound==2"
    );

    // test body in conjunction with query params
    client.testJQ(params("stream.body", "{query:'cat_s:A'}", "stream.contentType", "application/json", "json.filter", "'where_s:NY'")
        , "response/numFound==1"
    );

    // test that json body in params come "after" (will overwrite)
    client.testJQ(params("stream.body", "{query:'*:*', filter:'where_s:NY'}", "stream.contentType", "application/json", "json","{query:'cat_s:A'}")
        , "response/numFound==1"
    );

    // test that json.x params come after body
    client.testJQ(params("stream.body", "{query:'*:*', filter:'where_s:NY'}", "stream.contentType", "application/json", "json.query","'cat_s:A'")
        , "response/numFound==1"
    );

    // test facet with json body
    client.testJQ(params("stream.body", "{query:'*:*', facet:{x:'unique(where_s)'}}", "stream.contentType", "application/json")
        , "facets=={count:6,x:2}"
    );

    // test facet with json body, insert additional facets via query parameter
    client.testJQ(params("stream.body", "{query:'*:*', facet:{x:'unique(where_s)'}}", "stream.contentType", "application/json", "json.facet.y","{terms:{field:where_s}}", "json.facet.z","'unique(where_s)'")
        , "facets=={count:6,x:2, y:{buckets:[{val:NJ,count:3},{val:NY,count:2}]}, z:2}"
    );

    // test debug
    client.testJQ( params("json","{query:'cat_s:A'}", "json.filter","'where_s:NY'", "debug","true")
        , "debug/json=={query:'cat_s:A', filter:'where_s:NY'}"
    );

    try {
      // test failure on unknown parameter
      client.testJQ(params("json", "{query:'cat_s:A', foobar_ignore_exception:5}")
          , "response/numFound==2"
      );
      fail();
    } catch (Exception e) {
      assertTrue(e.getMessage().contains("foobar"));
    }

  }

}


text:
package co.mindie.cindy.webservice.responsewriter;

import co.mindie.cindy.core.annotation.Load;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;

@Load(creationPriority = -1)
public class JsonResponseWriter implements IResponseWriter {

	// //////////////////////
	// VARIABLES
	// //////////////

	private boolean indentEnabled;
	private ObjectMapper mapper;

	// //////////////////////
	// CONSTRUCTORS
	// //////////////

	public JsonResponseWriter() {
		this.mapper = new ObjectMapper();

		this.mapper.registerModule(new ObjectIdJsonModule());
		this.mapper.registerModule(new JodaModule());
		this.mapper.registerModule(new JsonOrgModule());

		this.mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
		this.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		this.mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

		this.mapper.setSerializationInclusion(Include.NON_NULL);

		this.mapper.setDateFormat(new ISO8601DateFormat());
	}

	// //////////////////////
	// METHODS
	// //////////////

	@Override
	public void writeResponse(Object response, OutputStream outputStream) throws IOException {
		if (response == null) {
			response = new HashMap<>();
		}

		this.getObjectMapper().writeValue(outputStream, response);
	}

	// //////////////////////
	// METHODS
	// //////////////

	// //////////////////////
	// GETTERS/SETTERS
	// //////////////

	public boolean isIndentEnabled() {
		return this.indentEnabled;
	}

	public void setIndentEnabled(boolean indentEnabled) {
		this.indentEnabled = indentEnabled;
		if (indentEnabled) {
			this.mapper.enable(SerializationFeature.INDENT_OUTPUT);
		} else {
			this.mapper.disable(SerializationFeature.INDENT_OUTPUT);
		}
	}

	@Override
	public String getContentType() {
		return "application/json";
	}

	@Override
	public Long getContentLength(Object response) {
		return null;
	}

	public ObjectMapper getObjectMapper() {
		return this.mapper;
	}
}


text:
class ISteamClient;
class ISteamUser;
class ISteamGameServer;
class ISteamFriends;
class ISteamUtils;
class ISteamMatchmaking;
class ISteamContentServer;
class ISteamMasterServerUpdater;
class ISteamMatchmakingServers;
class ISteam2Bridge;
class ISteamUserStats;
class ISteamApps;
class ISteamBilling;
class IVAC;
class ISteamNetworking;
class ISteamRemoteStorage;
class ISteamGameServerItems;
class ISteamGameServerStats;
class ISteamHTTP;

#define CLIENTENGINE_INTERFACE_VERSION "CLIENTENGINE_INTERFACE_VERSION001"

#define STEAMCLIENT_INTERFACE_VERSION_006		"SteamClient006"
#define STEAMCLIENT_INTERFACE_VERSION_007		"SteamClient007"
#define STEAMCLIENT_INTERFACE_VERSION_008		"SteamClient008"
#define STEAMCLIENT_INTERFACE_VERSION_009		"SteamClient009"
#define STEAMCLIENT_INTERFACE_VERSION_010		"SteamClient010"
#define STEAMCLIENT_INTERFACE_VERSION_011		"SteamClient011"

#endif


text:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <dirent.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include <arpa/nameser.h>
#include "relay.h"
#include "server.h"
#include "configuration.h"
#include "handle_session.h"
#include "parser.h"

#define RELAY_EVERY            2 /* seconds. */
#define MESSAGE_EXTENSION      ".eml"
#define MAX_MESSAGES_PER_BURST 10

#define SMTP_DEFAULT_PORT      25

extern server_t server;
extern configuration_t conf;
extern configuration_t mime_types;
extern dnscache_t dnscache;

relay_t relay;

static void stop (int nsignal);
static void handle_alarm (int nsignal);

static int relay_init (relay_t *relay);
static void relay_free (relay_t *relay);

static int do_relay (relay_t *relay);
static int read_pre_header (input_stream_t *input_stream, mail_transaction_t *mail_transaction, off_t *offset);
static void remove_session (relay_t *relay, int client);
static int send_messages (relay_t *relay);

void relay_loop (void)
{
	struct sigaction act;
	struct itimerval interval;

	if (relay_init (&relay) < 0) {
		domainlist_free (&server.domainlist);

		configuration_free (&conf);
		configuration_free (&mime_types);

		fprintf (stderr, "Couldn't create relay.\n");
		exit (-1);
	}

	/* Install signal handlers. */
	sigemptyset (&act.sa_mask);
	act.sa_flags = 0;

	act.sa_handler = stop;
	sigaction (SIGINT, &act, NULL);
	sigaction (SIGTERM, &act, NULL);

	act.sa_handler = handle_alarm;
	sigaction (SIGALRM, &act, NULL);

	/* Set alarm every second. */
	interval.it_interval.tv_sec = 1;
	interval.it_interval.tv_usec = 0;
	interval.it_value.tv_sec = 1;
	interval.it_value.tv_usec = 0;
	if (setitimer (ITIMER_REAL, &interval, NULL) < 0) {
		perror ("setitimer");

		domainlist_free (&server.domainlist);

		configuration_free (&mime_types);
		configuration_free (&conf);

		exit (-1);
	}

	server.running = 1;

	do {
		if (do_relay (&relay) < 0) {
			break;
		}

		sleep (RELAY_EVERY);

		if (server.running) {
			/* If the parent process is not alive... */
			if (kill (server.delivery_pid, 0) < 0) {
				break;
			}
		} else {
			break;
		}
	} while (1);

	relay_free (&relay);
	dnscache_free (&dnscache);

	domainlist_free (&server.domainlist);

	configuration_free (&conf);
	configuration_free (&mime_types);

	exit (0);
}

void stop (int nsignal)
{
	printf ("Relay process received signal %d.\nStopping...\n", nsignal);

	server.running = 0;
}

void handle_alarm (int nsignal)
{
	server.handle_alarm = 1;
}

int relay_init (relay_t *relay)
{
	input_stream_t *input_stream;
	struct rlimit rlim;
	size_t size;
	int i;

	relay->epoll_fd = -1;
	relay->nfds = 0;
	relay->index = NULL;
	relay->events = NULL;
	relay->sessions = NULL;
	relay->interrupted_sessions = NULL;
	relay->number_interrupted_sessions = 0;

	input_stream = &relay->input_stream;
	input_stream->fd = -1;
	input_stream->buf_base = NULL;
	input_stream->buf_end = NULL;
	input_stream->size = 0;

	input_stream->read_ptr = NULL;
	input_stream->read_end = NULL;

	input_stream->end_of_file = 0;
	input_stream->error = 0;

	/* Get the hard limit of the maximum number of file descriptors. */
	if (getrlimit (RLIMIT_NOFILE, &rlim) < 0) {
		perror ("getrlimit");
		return -1;
	}

	relay->max_file_descriptors = rlim.rlim_max;

	/* Open epoll file descriptor. */
	if ((relay->epoll_fd = epoll_create (relay->max_file_descriptors)) < 0) {
		perror ("epoll_create");
		return -1;
	}

	/* Allocate memory for index. */
	relay->index = (int *) malloc (relay->max_file_descriptors * sizeof (int));
	if (!relay->index) {
		close (relay->epoll_fd);
		relay->epoll_fd = -1;

		fprintf (stderr, "Couldn't allocate memory for index.\n");
		return -1;
	}

	/* Allocate memory for epoll events. */
	relay->events = (struct epoll_event *) malloc (relay->max_file_descriptors * sizeof (struct epoll_event));
	if (!relay->events) {
		free (relay->index);
		relay->index = NULL;

		close (relay->epoll_fd);
		relay->epoll_fd = -1;

		fprintf (stderr, "Couldn't allocate memory for epoll events.\n");
		return -1;
	}

	/* Allocate memory for sessions. */
	relay->sessions = (session_t *) malloc (relay->max_file_descriptors * sizeof (session_t));
	if (!relay->sessions) {
		free (relay->events);
		relay->events = NULL;

		free (relay->index);
		relay->index = NULL;

		close (relay->epoll_fd);
		relay->epoll_fd = -1;

		fprintf (stderr, "Couldn't allocate memory for connections.\n");
		return -1;
	}

	/* Allocate memory for interrupted sessions. */
	relay->interrupted_sessions = (session_t **) malloc (relay->max_file_descriptors * sizeof (session_t *));
	if (!relay->interrupted_sessions) {
		free (relay->sessions);
		relay->sessions = NULL;

		free (relay->events);
		relay->events = NULL;

		free (relay->index);
		relay->index = NULL;

		close (relay->epoll_fd);
		relay->epoll_fd = -1;

		fprintf (stderr, "Couldn't allocate memory for interrupted sessions.\n");
		return -1;
	}

	/* Allocate memory for input stream. */
	size = TEXT_LINE_MAXLEN + 1;
	input_stream->buf_base = (unsigned char *) malloc (size);
	if (!input_stream->buf_base) {
		free (relay->interrupted_sessions);
		relay->interrupted_sessions = NULL;

		free (relay->sessions);
		relay->sessions = NULL;

		free (relay->events);
		relay->events = NULL;

		free (relay->index);
		relay->index = NULL;

		close (relay->epoll_fd);
		relay->epoll_fd = -1;

		fprintf (stderr, "Couldn't allocate memory for input stream.\n");
		return -1;
	}

	input_stream->buf_end = input_stream->buf_base + size;
	input_stream->size = size;

	input_stream->read_ptr = input_stream->buf_base;
	input_stream->read_end = input_stream->buf_base;

	/* Initialize sessions. */
	for (i = 0; i < relay->max_file_descriptors; i++) {
		session_init (&(relay->sessions[i]));
	}

	return 0;
}

void relay_free (relay_t *relay)
{
	input_stream_t *input_stream;
	int i;

	if (relay->epoll_fd != -1) {
		close (relay->epoll_fd);
		relay->epoll_fd = -1;
	}

	relay->nfds = 0;

	if (relay->index) {
		free (relay->index);
		relay->index = NULL;
	}

	if (relay->events) {
		free (relay->events);
		relay->events = NULL;
	}

	if (relay->sessions) {
		for (i = 0; i < relay->max_file_descriptors; i++) {
			session_free (&(relay->sessions[i]));
		}

		free (relay->sessions);
		relay->sessions = NULL;
	}

	if (relay->interrupted_sessions) {
		free (relay->interrupted_sessions);
		relay->interrupted_sessions = NULL;
	}

	relay->number_interrupted_sessions = 0;

	input_stream = &relay->input_stream;
	if (input_stream->buf_base) {
		free (input_stream->buf_base);
		input_stream->buf_base = NULL;
	}

	input_stream->fd = -1;
	input_stream->buf_end = NULL;
	input_stream->size = 0;

	input_stream->read_ptr = NULL;
	input_stream->read_end = NULL;

	input_stream->end_of_file = 0;
	input_stream->error = 0;
}

int do_relay (relay_t *relay)
{
	DIR *relay_directory;
	struct dirent *mail;
	stringlist_t files;
	size_t nmessages;
	char oldpath[PATH_MAX + 1];
	char newpath[PATH_MAX + 1];
	input_stream_t *input_stream;
	mail_transaction_t mail_transaction;
	off_t offset;
	off_t filesize;
	domainlist_t *forward_paths;
	domain_t *domain;
	char *data;
	off_t index;
	session_t *session;
	transaction_list_t *transaction_list;
	transaction_t *transaction;
	eDnsStatus status;
	struct epoll_event ev;
	size_t len;
	int fd;
	int sd;
	size_t i, j, k;
	int already_connected;

	/* Open directory where are the messages to relay. */
	relay_directory = opendir (server.relay_directory);
	if (!relay_directory) {
		fprintf (stderr, "Couldn't open relay directory %s.\n", server.relay_directory);
		return -1;
	}

	stringlist_init (&files);
	nmessages = 0;

	/* Build a list of messages to relay. */
	while (((mail = readdir (relay_directory)) != NULL) && (nmessages < MAX_MESSAGES_PER_BURST)) {
		if (mail->d_name[0] == '.') {
			continue;
		}

		/* If not a message... */
		len = strlen (mail->d_name);
		if ((len < sizeof (MESSAGE_EXTENSION)) || (strcmp (mail->d_name + len - (sizeof (MESSAGE_EXTENSION) - 1), MESSAGE_EXTENSION) != 0)) {
			continue;
		}

		snprintf (oldpath, sizeof (oldpath), "%s/%s", server.relay_directory, mail->d_name);
		fd = open (oldpath, O_RDONLY);
		if (fd < 0) {
			continue;
		}

		if (stringlist_insert_string (&files, mail->d_name, fd) < 0) {
			close (fd);
			for (i = 0; i < files.used; i++) {
				close (files.strings[i].data);
			}

			stringlist_free (&files);

			closedir (relay_directory);

			return -1;
		}

		nmessages++;
	}

	closedir (relay_directory);

	if (!nmessages) {
		return 0;
	}

	input_stream = &relay->input_stream;

	mail_transaction_init (&mail_transaction);

	/* Save current time. */
	server.current_time = time (NULL);
	gmtime_r (&server.current_time, &server.stm);

	/* For each message to relay... */
	for (i = 0; i < nmessages; i++) {
		input_stream->fd = files.strings[i].data;
		input_stream->read_ptr = input_stream->buf_base;
		input_stream->read_end = input_stream->buf_base;

		input_stream->end_of_file = 0;
		input_stream->error = 0;

		if (read_pre_header (&relay->input_stream, &mail_transaction, &offset) < 0) {
			mail_transaction_free (&mail_transaction);
			close (relay->input_stream.fd);

			/* Move mail to error directory. */
			snprintf (oldpath, sizeof (oldpath), "%s/%.*s", server.relay_directory, files.strings[i].len, files.data + files.strings[i].string);
			snprintf (newpath, sizeof (newpath), "%s/%.*s", server.error_directory, files.strings[i].len, files.data + files.strings[i].string);
			rename (oldpath, newpath);

			/* Mark file as closed. */
			files.strings[i].data = -1;

			continue;
		}

		/* Get filesize. */
		filesize = lseek (relay->input_stream.fd, 0, SEEK_END);

		forward_paths = &mail_transaction.forward_paths;
		data = forward_paths->data.data;

		/* For each domain... */
		for (j = 0; j < forward_paths->used; j++) {
			domain = &(forward_paths->records[j]);

			/* Resolve DNS. */
			status = dnscache_lookup (&dnscache, data + domain->domain_name, T_MX, MAX_HOSTS, &index, server.current_time);
			if ((status == DNS_HOST_NOT_FOUND) || (status == DNS_NO_DATA)) {
				status = dnscache_lookup (&dnscache, data + domain->domain_name, T_A, MAX_HOSTS, &index, server.current_time);
			}

			if (status != DNS_SUCCESS) {
				/* The domain is unreachable. */
				continue;
			}

			/* We might be already connected to this SMTP server. */
			already_connected = 0;
			for (k = 0; k < relay->nfds; k++) {
				if (relay->sessions[relay->index[k]].dnscache == index) {
					already_connected = 1;
					break;
				}
			}

			/* If we weren't already connected... */
			if (!already_connected) {
				/* Connect to SMTP server. */
				if ((sd = connect_to_smtp_server (&(dnscache.records[index]))) < 0) {
					/* The domain is unreachable. */
					continue;
				}

				/* Add connection to epoll descriptor. */
				ev.events = EPOLLOUT;
				ev.data.u64 = 0;
				ev.data.fd = sd;
				if (epoll_ctl (relay->epoll_fd, EPOLL_CTL_ADD, sd, &ev) < 0) {
					perror ("epoll_ctl");

					close (sd);

					break;
				}

				session = &(relay->sessions[sd]);

				/* Save domain. */
				if (buffer_append_string (&session->domain, data + domain->domain_name) < 0) {
					buffer_free (&session->domain);

					/* Remove connection from epoll descriptor. */
					ev.events = 0;
					ev.data.u64 = 0;
					ev.data.fd = sd;
					epoll_ctl (relay->epoll_fd, EPOLL_CTL_DEL, sd, &ev);

					close (sd);

					break;
				}

				session->index = relay->nfds;
				session->sd = sd;
				session->dnscache = index;
			} else {
				session = &(relay->sessions[relay->index[k]]);
			}

			if (session_allocate_transactions (session) < 0) {
				session_free_transactions (session);
				buffer_free (&session->domain);

				session->dnscache = -1;

				/* Remove connection from epoll descriptor. */
				ev.events = 0;
				ev.data.u64 = 0;
				ev.data.fd = session->sd;
				epoll_ctl (relay->epoll_fd, EPOLL_CTL_DEL, session->sd, &ev);

				close (session->sd);
				session->sd = -1;

				session->index = -1;

				break;
			}

			transaction_list = &session->transaction_list;
			transaction = &(transaction_list->transactions[transaction_list->used]);

			buffer_init (&transaction->reverse_path, 32);
			if (buffer_append_string (&transaction->reverse_path, mail_transaction.reverse_path) < 0) {
				buffer_free (&transaction->reverse_path);
				session_free_transactions (session);
				buffer_free (&session->domain);

				session->dnscache = -1;

				/* Remove connection from epoll descriptor. */
				ev.events = 0;
				ev.data.u64 = 0;
				ev.data.fd = session->sd;
				epoll_ctl (relay->epoll_fd, EPOLL_CTL_DEL, session->sd, &ev);

				close (session->sd);
				session->sd = -1;

				session->index = -1;

				break;
			}

			/* For each forward path... */
			stringlist_init (&transaction->forward_paths);
			for (k = 0; k < domain->used; k++) {
				if (stringlist_insert_string (&transaction->forward_paths, data + domain->local_parts[k], 0) < 0) {
					stringlist_free (&transaction->forward_paths);
					buffer_free (&transaction->reverse_path);
					session_free_transactions (session);
					buffer_free (&session->domain);

					session->dnscache = -1;

					/* Remove connection from epoll descriptor. */
					ev.events = 0;
					ev.data.u64 = 0;
					ev.data.fd = session->sd;
					epoll_ctl (relay->epoll_fd, EPOLL_CTL_DEL, session->sd, &ev);

					close (session->sd);
					session->sd = -1;

					session->index = -1;

					break;
				}
			}

			/* If we couldn't allocate memory... */
			if (k != domain->used) {
				break;
			}

			transaction->fd = files.strings[i].data;
			transaction->message_offset = offset;
			transaction->offset = offset;
			transaction->filesize = filesize;

			transaction_list->used++;

			if (!already_connected) {
				session->last_read_write = server.current_time;

				relay->index[relay->nfds++] = session->sd;
			}
		}

		if (j != forward_paths->used) {
			mail_transaction_free (&mail_transaction);

			/* Remove sessions.*/
			for (j = 0; j < relay->nfds;) {
				remove_session (relay, relay->index[j]);
			}

			/* Close files. */
			for (j = 0; j < files.used; j++) {
				if (files.strings[j].data != -1) {
					close (files.strings[j].data);
				}
			}

			stringlist_free (&files);

			return -1;
		}

		mail_transaction_free (&mail_transaction);
	}

	if (relay->nfds > 0) {
		send_messages (relay);
	}

	/* TODO: Send a message to the reverse-path(s) in case we couldn't send some of the message(s). */

	/* Close and remove files. */
	for (i = 0; i < files.used; i++) {
		if (files.strings[i].data != -1) {
			close (files.strings[i].data);

			snprintf (oldpath, sizeof (oldpath), "%s/%.*s", server.relay_directory, files.strings[i].len, files.data + files.strings[i].string);
			unlink (oldpath);
		}
	}

	stringlist_free (&files);

	return 0;
}

int read_pre_header (input_stream_t *input_stream, mail_transaction_t *mail_transaction, off_t *offset)
{
	unsigned char *argument;
	unsigned char *local_part;
	size_t local_part_len;
	unsigned char *domain;
	size_t domainlen;
	size_t size;

	char line[TEXT_LINE_MAXLEN + 1];
	size_t len;

	int error;
	int ret;

	size = 0;
	error = 0;

	do {
		/* Read line. */
		if ((!input_stream_fgets (input_stream, line, sizeof (line), &len)) || (line[len - 1] != '\n')) {
			return -1;
		}

		size += len;

		/* End of pre-header? */
		if ((len == 1) || ((len == 2) && (line[0] == '\r'))) {
			/* If there is not reverse-path or no recipients... */
			if ((!mail_transaction->reverse_path[0]) || (mail_transaction->forward_paths.used == 0)) {
				return -1;
			}

			*offset = size;

			return 0;
		}

		/* Parse SMTP command. */
		if (((ret = parse_smtp_command ((unsigned char *) line, &argument, &error)) < 0) || (error != 0)) {
			return -1;
		}

		if ((eSmtpCommand) ret == MAIL) {
			/* If there was another "MAIL FROM: <reverse_path>" line... */
			if (mail_transaction->reverse_path[0]) {
				return -1;
			}

			/* Valid reverse path? */
			if (parse_reverse_path (argument, &local_part, &local_part_len, &domain, &domainlen, NULL, NULL) < 0) {
				return -1;
			}

			/* Null reverse path? */
			if (!local_part) {
				memcpy (mail_transaction->reverse_path, "<>", 3);
			} else {
				mail_transaction_set_reverse_path (mail_transaction, (const char *) local_part, local_part_len, (const char *) domain, domainlen);
			}
		} else if ((eSmtpCommand) ret == RCPT) {
			/* Valid forward path? */
			if (parse_forward_path (argument, &local_part, &local_part_len, &domain, &domainlen) < 0) {
				return -1;
			}

			local_part[local_part_len] = 0;
			domain[domainlen] = 0;

			if (mail_transaction_add_forward_path (mail_transaction, (const char *) local_part, local_part_len, (const char *) domain, domainlen) < 0) {
				return -1;
			}
		} else {
			return -1;
		}
	} while (1);
}

int connect_to_smtp_server (dnscache_entry_t *dnscache_entry)
{
	rr_t *rr_list;
	struct sockaddr_in addr;
	struct hostent *host;
	int sd;
	int flags;
	size_t i;

	sd = socket (PF_INET, SOCK_STREAM, 0);
	if (sd < 0) {
		return -1;
	}

	/* Make socket non-blocking. */
	flags = fcntl (sd, F_GETFL);
	flags |= O_NONBLOCK;
	if (fcntl (sd, F_SETFL, flags) < 0) {
		close (sd);
		return -1;
	}

	/* Disable the Nagle algorithm. */
	flags = 1;
	setsockopt (sd, IPPROTO_TCP, TCP_NODELAY, (const char *) &flags, sizeof (flags));

	addr.sin_port = htons (SMTP_DEFAULT_PORT);
	memset (&addr.sin_zero, 0, 8);

	/* Connect. */
	rr_list = dnscache_entry->rr_list;
	for (i = 0; i < dnscache_entry->nhosts; i++) {
		if (rr_list[i].type == T_A) {
			addr.sin_family = AF_INET;
			addr.sin_addr.s_addr = rr_list[i].u.addr;
		} else {
			host = gethostbyname (rr_list[i].u.name.data);
			if (!host) {
				continue;
			}

			addr.sin_family = host->h_addrtype;
			memcpy (&addr.sin_addr, host->h_addr_list[0], host->h_length);
		}

		if ((connect (sd, (struct sockaddr *) &addr, sizeof (struct sockaddr)) < 0) && (errno != EINPROGRESS)) {
			/* Try with next host of rr list. */
			continue;
		}

		/* Connected. */
		return sd;
	}

	/* We couldn't connect. */
	close (sd);

	return -1;
}

void remove_session (relay_t *relay, int client)
{
	struct epoll_event ev;
	session_t *session;
	int index;

	/* Remove session from epoll descriptor. */
	ev.events = 0;
	ev.data.u64 = 0;
	ev.data.fd = client;
	epoll_ctl (relay->epoll_fd, EPOLL_CTL_DEL, client, &ev);

	session = &(relay->sessions[client]);

	/* Save position of session in index array. */
	index = session->index;

	session_reset (session);

	relay->nfds--;

	/* If there are more sessions... */
	if (index < relay->nfds) {
		relay->index[index] = relay->index[relay->nfds];
		relay->sessions[relay->index[index]].index = index;
	}

#if DEBUG
	fprintf (stdout, "# sessions: %d.\n", relay->nfds);
#endif
}

int send_messages (relay_t *relay)
{
	int epoll_fd;
	struct epoll_event *events;
	struct epoll_event event;
	int maxevents;
	int nfds;
	time_t now;
	session_t **interrupted_sessions;
	session_t *session;
	int i;

	epoll_fd = relay->epoll_fd;
	events = relay->events;
	maxevents = relay->max_file_descriptors;
	interrupted_sessions = relay->interrupted_sessions;

	while ((server.running) && (relay->nfds > 0)) {
		if (server.handle_alarm) {
			now = time (NULL);
			if (server.current_time != now) {
				/* Save current time. */
				server.current_time = now;
				gmtime_r (&now, &server.stm);

				/* Check whether some session has been idle for a very long time. */
				i = 0;
				while (i < relay->nfds) {
					session = &(relay->sessions[relay->index[i]]);
					if (now - session->last_read_write > server.max_idle_time) {
#if DEBUG
						printf ("Removing session with socket %d for having been idle for a very long time (%lu seconds).\n", session->sd, now - session->last_read_write);
#endif

						remove_session (relay, session->sd);
					} else {
						i++;
					}
				}
			}

			server.handle_alarm = 0;
		}

		nfds = epoll_wait (epoll_fd, events, maxevents, -1);

		/* For each event... */
		for (i = 0; i < nfds; i++) {
			if (handle_session (&(relay->sessions[events[i].data.fd]), &(events[i])) < 0) {
				remove_session (relay, events[i].data.fd);
			}
		}

		/* Handle interrupted sessions. */
		i = 0;
		while (i < relay->number_interrupted_sessions) {
			event.events = EPOLLIN | EPOLLOUT;
			if (handle_session (interrupted_sessions[i], &event) < 0) {
				remove_session (relay, interrupted_sessions[i]->sd);
			}

			if (relay->number_interrupted_sessions > 1) {
				interrupted_sessions[0] = interrupted_sessions[relay->number_interrupted_sessions - 1];
			}

			relay->number_interrupted_sessions--;
		}
	}

	return 0;
}


text:
package org.selenide.examples.testng;

import com.codeborne.selenide.SelenideElement;
import com.codeborne.selenide.WebDriverRunner;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testcontainers.containers.BrowserWebDriverContainer;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.io.File;

import static com.codeborne.selenide.CollectionCondition.sizeGreaterThan;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.$$;
import static com.codeborne.selenide.Selenide.back;
import static com.codeborne.selenide.Selenide.open;
import static com.codeborne.selenide.Selenide.sleep;

public class SearchTestWithDockerTestNG {
  public BrowserWebDriverContainer chrome =
      new BrowserWebDriverContainer()
          .withRecordingMode(BrowserWebDriverContainer.VncRecordingMode.RECORD_ALL, new File("build"))
          .withCapabilities(DesiredCapabilities.chrome());

  @BeforeClass
  public void startContainer() {
    chrome.start();
    WebDriverRunner.setWebDriver(chrome.getWebDriver());
  }

  @AfterClass
  public void stopContainer() {
    WebDriverRunner.closeWebDriver();
    chrome.stop();
  }

  @Test
  public void search() {
    open("https://duckduckgo.com/");
    $(By.name("q")).val("Selenide").pressEnter();
    $$("#res .g").shouldHave(sizeGreaterThan(3));

    for (int i = 0; i < 3; i++) {
      SelenideElement link = $("#res .g", i).find("a");
      System.out.println(link.attr("href"));
      link.click();
      back();
    }
    sleep(1000);
  }
}


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

using UnityEngine;
using UnityEngine.Events;

namespace GVR.Samples.DragonFlight {
  /// <summary>
  /// Triggers a basic event every X seconds. Useful for periodic checks that are too expensive
  /// to evaluate every frame.
  /// </summary>
  public class IntervalTrigger : MonoBehaviour {
    [Tooltip("The amount of time, in seconds, between Event calls.")]
    public float Interval = 2.0f;

    [Tooltip("The UnityEvent triggered every X seconds.")]
    public UnityEvent OnTriggered;

    private float currentTime = 0f;

    void Start() {
      OnTriggered.Invoke();
    }

    void Update() {
      if (currentTime > Interval) {
        currentTime = 0f;
        OnTriggered.Invoke();
      } else {
        currentTime += Time.deltaTime;
      }
    }
  }
}