text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 14(1): 1 (1982)

#### Original name
Helotium callorioides Rehm, 1882

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
from django.db import models

class Foo(models.Model):
    name = models.CharField(max_length=5)

    class Meta:
        app_label = 'complex_app'


text:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class Button {
    private static JButton button;
    private static JPanel panel;
    private static JFrame frame;
    private static String[] txt = {"DO NOT PRESS", "* Ahem *\nDO NOT PRESS",
    "Sara, is that you?!", "Fine GoodBye!"};
    public static void main() {
        int x = 0;
        button = new JButton();
        panel = new JPanel();
        frame = new JFrame();

        panel.add(button);
        frame.add(panel);
        frame.setVisible(true);
        do {
            button.setText(txt[x]);
            x++;
        } while(x < txt.length);
    }
}


text:
package com.hazelcast.client.mapreduce.aggregation;

import com.hazelcast.core.IMap;
import com.hazelcast.mapreduce.aggregation.Aggregation;
import com.hazelcast.mapreduce.aggregation.Aggregations;
import com.hazelcast.mapreduce.aggregation.Supplier;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Random;

import static org.junit.Assert.assertEquals;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
@Ignore //https://github.com/hazelcast/hazelcast/issues/5916
public class MaxAggregationTest
        extends AbstractAggregationTest {

    @Test(timeout = 60000)
    public void testBigDecimalMax()
            throws Exception {

        BigDecimal[] values = buildPlainValues(new ValueProvider<BigDecimal>() {
            @Override
            public BigDecimal provideRandom(Random random) {
                return BigDecimal.valueOf(10000.0D + random(1000, 2000));
            }
        }, BigDecimal.class);

        BigDecimal expectation = BigDecimal.ZERO;
        for (int i = 0; i < values.length; i++) {
            BigDecimal value = values[i];
            expectation = i == 0 ? value : expectation.max(value);
        }

        Aggregation<String, BigDecimal, BigDecimal> aggregation = Aggregations.bigDecimalMax();
        BigDecimal result = testMax(values, aggregation);
        assertEquals(expectation, result);
    }

    @Test(timeout = 60000)
    public void testBigIntegerMax()
            throws Exception {

        BigInteger[] values = buildPlainValues(new ValueProvider<BigInteger>() {
            @Override
            public BigInteger provideRandom(Random random) {
                return BigInteger.valueOf(10000L + random(1000, 2000));
            }
        }, BigInteger.class);

        BigInteger expectation = BigInteger.ZERO;
        for (int i = 0; i < values.length; i++) {
            BigInteger value = values[i];
            expectation = i == 0 ? value : expectation.max(value);
        }

        Aggregation<String, BigInteger, BigInteger> aggregation = Aggregations.bigIntegerMax();
        BigInteger result = testMax(values, aggregation);
        assertEquals(expectation, result);
    }

    @Test(timeout = 60000)
    public void testDoubleMax()
            throws Exception {

        Double[] values = buildPlainValues(new ValueProvider<Double>() {
            @Override
            public Double provideRandom(Random random) {
                return 10000.0D + random(1000, 2000);
            }
        }, Double.class);

        double expectation = -Double.MAX_VALUE;
        for (int i = 0; i < values.length; i++) {
            double value = values[i];
            if (value > expectation) {
                expectation = value;
            }
        }

        Aggregation<String, Double, Double> aggregation = Aggregations.doubleMax();
        double result = testMax(values, aggregation);
        assertEquals(expectation, result, 0.0);
    }

    @Test(timeout = 60000)
    public void testIntegerMax()
            throws Exception {

        Integer[] values = buildPlainValues(new ValueProvider<Integer>() {
            @Override
            public Integer provideRandom(Random random) {
                return random(1000, 2000);
            }
        }, Integer.class);

        int expectation = Integer.MIN_VALUE;
        for (int i = 0; i < values.length; i++) {
            int value = values[i];
            if (value > expectation) {
                expectation = value;
            }
        }

        Aggregation<String, Integer, Integer> aggregation = Aggregations.integerMax();
        int result = testMax(values, aggregation);
        assertEquals(expectation, result);
    }

    @Test(timeout = 60000)
    public void testLongMax()
            throws Exception {

        Long[] values = buildPlainValues(new ValueProvider<Long>() {
            @Override
            public Long provideRandom(Random random) {
                return 10000L + random(1000, 2000);
            }
        }, Long.class);

        long expectation = Long.MIN_VALUE;
        for (int i = 0; i < values.length; i++) {
            long value = values[i];
            if (value > expectation) {
                expectation = value;
            }
        }

        Aggregation<String, Long, Long> aggregation = Aggregations.longMax();
        long result = testMax(values, aggregation);
        assertEquals(expectation, result);
    }

    @Test(timeout = 60000)
    public void testBigDecimalMaxWithExtractor()
            throws Exception {

        Value<BigDecimal>[] values = buildValues(new ValueProvider<BigDecimal>() {
            @Override
            public BigDecimal provideRandom(Random random) {
                return BigDecimal.valueOf(10000.0D + random(1000, 2000));
            }
        });

        BigDecimal expectation = BigDecimal.ZERO;
        for (int i = 0; i < values.length; i++) {
            Value<BigDecimal> value = values[i];
            expectation = i == 0 ? value.value : expectation.max(value.value);
        }

        Aggregation<String, BigDecimal, BigDecimal> aggregation = Aggregations.bigDecimalMax();
        BigDecimal result = testMaxWithExtractor(values, aggregation);
        assertEquals(expectation, result);
    }

    @Test(timeout = 60000)
    public void testBigIntegerMaxWithExtractor()
            throws Exception {

        Value<BigInteger>[] values = buildValues(new ValueProvider<BigInteger>() {
            @Override
            public BigInteger provideRandom(Random random) {
                return BigInteger.valueOf(10000L + random(1000, 2000));
            }
        });

        BigInteger expectation = BigInteger.ZERO;
        for (int i = 0; i < values.length; i++) {
            Value<BigInteger> value = values[i];
            expectation = i == 0 ? value.value : expectation.max(value.value);
        }

        Aggregation<String, BigInteger, BigInteger> aggregation = Aggregations.bigIntegerMax();
        BigInteger result = testMaxWithExtractor(values, aggregation);
        assertEquals(expectation, result);
    }

    @Test(timeout = 60000)
    public void testDoubleMaxWithExtractor()
            throws Exception {

        Value<Double>[] values = buildValues(new ValueProvider<Double>() {
            @Override
            public Double provideRandom(Random random) {
                return 10000.0D + random(1000, 2000);
            }
        });

        double expectation = -Double.MAX_VALUE;
        for (int i = 0; i < values.length; i++) {
            double value = values[i].value;
            if (value > expectation) {
                expectation = value;
            }
        }

        Aggregation<String, Double, Double> aggregation = Aggregations.doubleMax();
        double result = testMaxWithExtractor(values, aggregation);
        assertEquals(expectation, result, 0.0);
    }

    @Test(timeout = 60000)
    public void testIntegerMaxWithExtractor()
            throws Exception {

        Value<Integer>[] values = buildValues(new ValueProvider<Integer>() {
            @Override
            public Integer provideRandom(Random random) {
                return random(1000, 2000);
            }
        });

        int expectation = Integer.MIN_VALUE;
        for (int i = 0; i < values.length; i++) {
            int value = values[i].value;
            if (value > expectation) {
                expectation = value;
            }
        }

        Aggregation<String, Integer, Integer> aggregation = Aggregations.integerMax();
        int result = testMaxWithExtractor(values, aggregation);
        assertEquals(expectation, result);
    }

    @Test(timeout = 60000)
    public void testLongMaxWithExtractor()
            throws Exception {

        Value<Long>[] values = buildValues(new ValueProvider<Long>() {
            @Override
            public Long provideRandom(Random random) {
                return 10000L + random(1000, 2000);
            }
        });

        long expectation = Long.MIN_VALUE;
        for (int i = 0; i < values.length; i++) {
            long value = values[i].value;
            if (value > expectation) {
                expectation = value;
            }
        }

        Aggregation<String, Long, Long> aggregation = Aggregations.longMax();
        long result = testMaxWithExtractor(values, aggregation);
        assertEquals(expectation, result);
    }

    private <T, R> R testMax(T[] values, Aggregation<String, T, R> aggregation)
            throws Exception {

        String mapName = randomMapName();
        IMap<String, T> map = client.getMap(mapName);

        for (int i = 0; i < values.length; i++) {
            map.put("key-" + i, values[i]);
        }

        Supplier<String, T, T> supplier = Supplier.all();
        return map.aggregate(supplier, aggregation);
    }

    private <T, R> R testMaxWithExtractor(Value<T>[] values, Aggregation<String, T, R> aggregation)
            throws Exception {

        String mapName = randomMapName();
        IMap<String, Value<T>> map = client.getMap(mapName);

        for (int i = 0; i < values.length; i++) {
            map.put("key-" + i, values[i]);
        }

        Supplier<String, Value<T>, T> supplier = Supplier.all(new ValuePropertyExtractor<T>());
        return map.aggregate(supplier, aggregation);
    }
}


text:
package main

import (
	"bytes"
	"flag"
	"fmt"
	"go/build"
	"go/doc"
	"go/format"
	"go/parser"
	"go/token"
	"io/ioutil"
	"log"
	"os"
	"path"
	"path/filepath"
	"strings"
	"text/template"
	"time"
)

var (
	Force         = flag.Bool("f", false, "Run even if README.md exists, overwriting original")
	Recursive     = flag.Bool("r", false, "Run in all subdirectories containing Go code")
	PrintTemplate = flag.Bool("print-template", false, "write the built in template to stdout and exit")
	Template      = flag.String("template", "", "specify a file to use as template, overrides built in template and README.md.template")
)

type Doc struct {
	Name, Import, Synopsis, Doc, Today string
	RepoPath                           string //Import sans github.com
	Bugs                               []string
	Library, Command                   bool
	Travis                             bool //if a .travis.yml file is statable
	Example                            map[string]Example
}

type Example struct {
	Name   string
	Code   string
	Output string //the expected output, if not empty
}

func today() string {
	return time.Now().Format("2006.01.02")
}

var gopaths = build.Default.SrcDirs()

func importPath(dir string) (string, error) {
	abs, err := filepath.Abs(dir)
	if err != nil {
		return "", err
	}

	for _, p := range gopaths {
		p, err = filepath.Rel(p, abs)
		if err != nil {
			return "", err
		}
		//not a relative path, therefore the correct one
		if len(p) > 0 && p[0] != '.' {
			return filepath.ToSlash(p), nil
		}
	}
	return "", fmt.Errorf("Not in go root or element of $GOPATH: %s", dir)
}

func fmtDoc(doc string) string {
	var acc []string
	push := func(ss ...string) {
		acc = append(acc, ss...)
	}
	nl := func() {
		push("\n")
	}
	for _, b := range blocks(doc) {
		ls := b.lines
		switch b.op {
		case opPara:
			push(ls...)
			nl()
		case opHead:
			push("## ")
			push(ls...)
			nl()
		case opPre:
			push("```")
			nl()
			push(ls...)
			push("```")
			nl()
			nl()
		}
	}
	return strings.Join(acc, "")
}

func getDoc(dir string) (Doc, error) {
	bi, err := build.ImportDir(dir, 0)
	if err != nil {
		return Doc{}, nil
	}

	ip, err := importPath(dir)
	if err != nil {
		return Doc{}, err
	}

	filter := func(fi os.FileInfo) bool {
		if fi.IsDir() {
			return false
		}
		nm := fi.Name()
		for _, f := range append(bi.GoFiles, bi.CgoFiles...) {
			if nm == f {
				return true
			}
		}
		return false
	}

	pkgs, err := parser.ParseDir(token.NewFileSet(), bi.Dir, filter, parser.ParseComments)
	if err != nil {
		return Doc{}, err
	}

	pkg := pkgs[bi.Name]
	docs := doc.New(pkg, bi.ImportPath, 0)

	examples, err := renderExamples(bi)
	if err != nil {
		return Doc{}, err
	}

	bugs := []string{}
	for _, bug := range docs.Notes["BUG"] {
		bugs = append(bugs, bug.Body)
	}

	name := bi.Name
	if name == "main" {
		name = filepath.Base(bi.Dir)
	}

	//get import path without the github.com/
	pathelms := strings.Split(ip, "/")[1:]
	repo := path.Join(pathelms...)

	return Doc{
		Name:     name,
		Import:   ip,
		Synopsis: bi.Doc,
		Doc:      fmtDoc(docs.Doc),
		Example:  examples,
		Today:    today(),
		RepoPath: repo,
		Bugs:     bugs,
		Library:  bi.Name != "main",
		Command:  bi.Name == "main",
	}, nil
}

func renderExamples(bi *build.Package) (map[string]Example, error) {
	examples := map[string]Example{}
	testFilenames := append(bi.TestGoFiles, bi.XTestGoFiles...)
	fset := token.NewFileSet()
	for _, filename := range testFilenames {
		path := filepath.Join(bi.Dir, filename)
		file, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
		if err != nil {
			return nil, err
		}
		for _, ex := range doc.Examples(file) {
			examples[ex.Name] = renderExample(ex)
		}
	}
	return examples, nil
}

func renderExample(ex *doc.Example) Example {
	e := Example{
		Name: strings.Replace(ex.Name, "_", " ", -1),
	}

	c := &bytes.Buffer{}
	format.Node(c, token.NewFileSet(), ex.Code)
	e.Code = fmt.Sprintf("Code:\n\n```\n%s\n```\n", c.String())

	if ex.Output != "" {
		e.Output = fmt.Sprintf("Output:\n\n```\n%s\n```\n", ex.Output)
	}

	return e
}

//only read and parse specified template once if -template and -r specified
var cached *template.Template

func getTemplate(dir string) (*template.Template, error) {
	if *Template != "" {
		if cached != nil {
			return cached, nil
		}
		bs, err := ioutil.ReadFile(*Template)
		if err != nil {
			return nil, err
		}
		cached, err = template.New("").Parse(string(bs))
		if err != nil {
			return nil, err
		}
		return cached, nil
	}

	bs, err := ioutil.ReadFile(filepath.Join(dir, "README.md.template"))
	//local template file found, prefer
	if err == nil {
		return template.New("").Parse(string(bs))
	}
	//the file was found but something else happened
	if !os.IsNotExist(err) {
		return nil, err
	}

	//the file was not found and no template specified, so use default
	return tmpl, nil
}

func getFile(dir string) (*os.File, error) {
	nm := filepath.Join(dir, "README.md")
	if !*Force {
		_, err := os.Stat(nm)
		if err == nil {
			return nil, fmt.Errorf("README.md already exists at %s. Use -f to overwrite", dir)
		} else if !os.IsNotExist(err) {
			return nil, err
		}
	}
	return os.Create(nm)
}

func hasTravisYml(dir string) (stated bool) {
	if _, err := os.Stat(filepath.Join(dir, ".travis.yml")); err == nil {
		stated = true
	}
	return
}

func dirs(start string) (ds []string, err error) {
	if !*Recursive {
		return []string{start}, nil
	}

	var follow func(string) error
	follow = func(dir string) error {
		fis, err := ioutil.ReadDir(dir)
		if err != nil {
			return err
		}

		hasgo := false
		for _, fi := range fis {
			nm := fi.Name()
			if fi.IsDir() {
				if nm[0] != '.' {
					if err := follow(nm); err != nil {
						return err
					}
				}
			} else if strings.HasSuffix(nm, ".go") {
				hasgo = true
			}
		}
		if hasgo {
			ds = append(ds, dir)
		}
		return nil
	}

	if err = follow(start); err != nil {
		return nil, err
	}

	return ds, nil
}

func init() {
	log.SetFlags(0)
}

func init() {
	flag.Usage = func() {
		log.Printf("Usage of %s: %s [directory]", os.Args[0], os.Args[0])
		flag.PrintDefaults()
	}
}

//Usage: %name %flags [directory]
func main() {
	flag.Parse()

	where := "."

	if args := flag.Args(); len(args) > 1 {
		log.Fatalln("Too many arguments: ", args[1:])
		flag.Usage()
	} else if len(args) == 1 {
		where = args[0]
	}

	where, err := filepath.Abs(where)
	if err != nil {
		log.Fatalln(err)
	}

	if *PrintTemplate {
		fmt.Print(tmplraw)
		return
	}

	ds, err := dirs(where)
	if err != nil {
		log.Fatalln(err)
	}

	warned := false
	warn := func(dir string, err error) {
		warned = true
		log.Println("Could not create README.md for", dir, "because:", err)
	}
	for _, dir := range ds {
		tmpl, err := getTemplate(dir)
		if err != nil {
			if *Template != "" && *Recursive {
				//don't want to show same error message for all dirs so just bail now
				log.Fatalln(err)
			}
			warn(dir, err)
			continue
		}

		doc, err := getDoc(dir)
		if err != nil {
			warn(dir, err)
			continue
		}

		doc.Travis = hasTravisYml(dir)

		f, err := getFile(dir)
		if err != nil {
			warn(dir, err)
			continue
		}

		if err = tmpl.Execute(f, doc); err != nil {
			warn(dir, err)
		}
	}
	if warned {
		os.Exit(1)
	}
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Controller extends CI_Controller {

      public $data = array(
        'display_name' => "default",
        'pathname' => "default",
        'view_foldername' => "vo_default",
        'id_column' => "id",
        'model_name' => "Default_model",
        'search_columns' => array(
              "title" => "Title"
            )
      );

      public function __construct() {
            parent::__construct();
            $this->load->model('User_model');
            $this->load->model($this->data['model_name']);
            $this->load->model('Function_model');
            $this->load->model('User_model');
            $this->load->model('User_login_token_model');

            $this->load->model('Products_model');
            $this->load->model('Capacitive_detail_model');
            $this->load->model('Industrial_detail_model');

            $this->data['init'] = $this->Function_model->page_init();
            //This section is all about user logged in information
            //we do it in constructor, so every method will call this once
            //and use in every pages
            $this->data['item_per_page'] = $this->Function_model->item_per_page();
            $this->data['webpage'] = $this->Function_model->get_web_setting();
            $this->data['islogin'] = $this->Function_model->isLogin();

            if ($this->data['islogin']) {
              $this->data['userdata'] = $this->User_model->getOne(array(
                  'user_id' => $this->data['islogin'],
                ));

              if(!in_array($this->data['userdata']['role_id'], array("-1"))){
                        redirect($init['langu'].'/profile','refresh');
                  }
            }else{
                redirect('/','refresh');
            }

            //What admin can search for?
            $this->data['search_columns'] = $this->data['search_columns'];

            $userlist = $this->User_model->getOptions(array(
                              'is_deleted' => 0,
            ));
            $this->data['userlist'] = $userlist;

      }

      //For listing
      public function index($search_column="ALL", $q="ALL", $page=1)
      {

            $this->data['search_column'] = $search_column;
            $this->data['q'] = $q;

            $this->data['page'] = $page;
            $limit_start = ($page-1)*$this->data['item_per_page'];

            $sql_where = array();
            $sql_where['is_deleted'] = 0;

            $sql_like = array();
            if($q!="ALL") {
              $sql_like[$search_column] = $q;
            }

            $this->data["total"] = $this->{$this->data['model_name']}->record_count($sql_where, $sql_like);

            $results = array();
            $results = $this->{$this->data['model_name']}->fetch($this->data['item_per_page'], $limit_start, $sql_where, $sql_like);
            $this->data["results"] = $results;

            $url = base_url().$this->data['init']['langu'].'/vo/'.$this->data['pathname'].'/list/'.$search_column."/".$q."/";
            $this->data['paging'] = $this->Function_model->get_paging($this->data['item_per_page'],10,$this->data['total'],$page,$url);

            $this->load->view('vo/header', $this->data);
            $this->load->view($this->data['view_foldername']."/list", $this->data);
            $this->load->view('vo/footer', $this->data);
      }

      public function add()
      {

          $this->data['mode'] = 'Add';
          $this->load->view('vo/header', $this->data);
          $this->load->view($this->data['view_foldername']."/add", $this->data);
          $this->load->view('vo/footer', $this->data);
      }

      public function edit($id)
      {

          $this->data['mode'] = 'Edit';

          $this->data['results'] = $this->{$this->data['model_name']}->getOne(array(
            $this->data['id_column'] => $id,
          ));

          $this->load->view('vo/header', $this->data);
          $this->load->view($this->data['view_foldername']."/add", $this->data);
          $this->load->view('vo/footer', $this->data);
      }

      public function Submit()
      {

          $mode = isset($_POST['mode'])?$_POST['mode']:'';
          $id = isset($_POST['id'])?$_POST['id']:'';

          $array = array(
             'title'  => $this->input->post("title", true),
              //your code
          );

          if($mode == 'Add'){
              $array['created_date'] = date("Y-m-d H:i:s");
              $this->{$this->data['model_name']}->insert($array);
          }else{
              $array['modified_date'] = date("Y-m-d H:i:s");
              $this->{$this->data['model_name']}->update(array(
                $this->data['id_column'] => $id,
              ),$array);
          }

          redirect(base_url($this->data['init']['langu'].'/vo/'.$this->data['pathname'].'/list'), 'refresh');
      }

      public function delete($id)
      {
          $this->{$this->data['model_name']}->delete(array(
            $this->data['id_column'] => $id,
          ));
          redirect(base_url($this->data['init']['langu'].'/vo/'.$this->data['pathname'].'/list'), 'refresh');
      }

}

?>


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('entries', '0004_auto_20161101_1250'),
    ]

    operations = [
        migrations.AlterField(
            model_name='entry',
            name='extra',
            field=models.TextField(blank=True),
        ),
    ]


text:
/)getXmlnsDefinitions;
@end

#endif // __WUXMIXamlMetadataProvider_DEFINED__

// Windows.UI.Xaml.Markup.IDataTemplateComponent
#ifndef __WUXMIDataTemplateComponent_DEFINED__
#define __WUXMIDataTemplateComponent_DEFINED__

@protocol WUXMIDataTemplateComponent
- (void)recycle;
- (void)processBindings:(RTObject*)item itemIndex:(int)itemIndex phase:(int)phase nextPhase:(int*)nextPhase;
@end

#endif // __WUXMIDataTemplateComponent_DEFINED__

// Windows.UI.Xaml.Markup.XamlBinaryWriter
#ifndef __WUXMXamlBinaryWriter_DEFINED__
#define __WUXMXamlBinaryWriter_DEFINED__

WINRT_EXPORT
@interface WUXMXamlBinaryWriter : RTObject
+ (WUXMXamlBinaryWriterErrorInformation*)write:(NSMutableArray* /* RTObject<WSSIRandomAccessStream>* */)inputStreams
                                 outputStreams:(NSMutableArray* /* RTObject<WSSIRandomAccessStream>* */)outputStreams
                          xamlMetadataProvider:(RTObject<WUXMIXamlMetadataProvider>*)xamlMetadataProvider;
@end

#endif // __WUXMXamlBinaryWriter_DEFINED__

// Windows.UI.Xaml.Markup.XamlReader
#ifndef __WUXMXamlReader_DEFINED__
#define __WUXMXamlReader_DEFINED__

WINRT_EXPORT
@interface WUXMXamlReader : RTObject
+ (RTObject*)Load:(NSString*)xaml;
+ (RTObject*)loadWithInitialTemplateValidation:(NSString*)xaml;
@end

#endif // __WUXMXamlReader_DEFINED__

// Windows.UI.Xaml.Markup.XamlBindingHelper
#ifndef __WUXMXamlBindingHelper_DEFINED__
#define __WUXMXamlBindingHelper_DEFINED__

WINRT_EXPORT
@interface WUXMXamlBindingHelper : RTObject
+ (RTObject<WUXMIDataTemplateComponent>*)getDataTemplateComponent:(WXDependencyObject*)element;
+ (void)setDataTemplateComponent:(WXDependencyObject*)element value:(RTObject<WUXMIDataTemplateComponent>*)value;
+ (void)suspendRendering:(WXUIElement*)target;
+ (void)resumeRendering:(WXUIElement*)target;
+ (RTObject*)convertValue:(WUXITypeName*)type value:(RTObject*)value;
+ (void)setPropertyFromString:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(NSString*)value;
+ (void)setPropertyFromBoolean:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(BOOL)value;
+ (void)setPropertyFromChar16:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(wchar_t)value;
+ (void)setPropertyFromDateTime:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(WFDateTime*)value;
+ (void)setPropertyFromDouble:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(double)value;
+ (void)setPropertyFromInt32:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(int)value;
+ (void)setPropertyFromUInt32:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(unsigned int)value;
+ (void)setPropertyFromInt64:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(int64_t)value;
+ (void)setPropertyFromUInt64:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(uint64_t)value;
+ (void)setPropertyFromSingle:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(float)value;
+ (void)setPropertyFromPoint:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(WFPoint*)value;
+ (void)setPropertyFromRect:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(WFRect*)value;
+ (void)setPropertyFromSize:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(WFSize*)value;
+ (void)setPropertyFromTimeSpan:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(WFTimeSpan*)value;
+ (void)setPropertyFromByte:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(uint8_t)value;
+ (void)setPropertyFromUri:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(WFUri*)value;
+ (void)setPropertyFromObject:(RTObject*)dependencyObject propertyToSet:(WXDependencyProperty*)propertyToSet value:(RTObject*)value;
+ (WXDependencyProperty*)dataTemplateComponentProperty;
@end

#endif // __WUXMXamlBindingHelper_DEFINED__


text:
require_dependency 'site_serializer'

class SiteController < ApplicationController
  layout false
  skip_before_filter :preload_json, :check_xhr
  skip_before_filter :redirect_to_login_if_required, only: ['basic_info']

  def site
    render json: Site.json_for(guardian)
  end

  def settings
    render json: SiteSetting.client_settings_json
  end

  def custom_html
    render json: custom_html_json
  end

  def banner
    render json: banner_json
  end

  def emoji
    render json: custom_emoji
  end

  def basic_info
    results = {
      logo_url: UrlHelper.absolute(SiteSetting.logo_url),
      logo_small_url: UrlHelper.absolute(SiteSetting.logo_small_url),
      apple_touch_icon_url: UrlHelper.absolute(SiteSetting.apple_touch_icon_url),
      favicon_url:  UrlHelper.absolute(SiteSetting.favicon_url),
      title: SiteSetting.title,
      description: SiteSetting.site_description
    }

    if SiteSetting.mobile_logo_url.present?
      results[:mobile_logo_url] = SiteSetting.mobile_logo_url
    end

    # this info is always available cause it can be scraped from a 404 page
    render json: results
  end
end


text:
module Rescue
  module Controller

    def self.included(base)
      base.extend Rescue::Controller::ClassMethods
      base.send(:private, :rescue_respond)
    end

    def rescue_respond call, params, options = {}
      begin
        send(call, params, (options[:validate] ? { context: options[:validate] } : {}))
        success_message = options[:success]||Flash.message(self, :success)
        flash[:success] = success_message unless success_message.blank?
        instance_exec(&options[:render])
      rescue => e
        Rails.logger.debug ([e.message] + e.backtrace).join("\n\t")
        error_message = options[:error]||Flash.message(self, :error)
        flash.now[:error] = error_message unless error_message.blank?
        instance_exec(&options[:rescue])
      end
    end

    module ClassMethods

      def rescue_associate *klasses, &block
        options = klasses.extract_options!

        unless block_given?
          if options.has_key?(:with)
            if options[:with].is_a?(Integer)
              block = lambda {|e| send(Rescue.config.respond_name, options[:with], e) }
            elsif options[:with].is_a?(Proc)
              block = options[:with]
            end
          else
            raise ArgumentError, "Need a handler. Supply an options hash that has a :with key as the last argument."
          end
        end

        klasses.each do |klass|
          key = if klass.is_a?(Class) && klass <= Exception
            klass.name
          elsif klass.is_a?(String) || klass.is_a?(Symbol)
            if options.has_key?(:superclass)
              Rescue::Bind.define_error_class klass, options[:superclass]
            else
              Rescue::Bind.define_error_class klass, StandardError
            end
            klass
          else
            raise ArgumentError, "#{klass} is neither an Exception nor a String"
          end
          self.rescue_handlers += [[key, block]]
        end
      end

      def rescue_controller clazz, *actions
        options      = actions.extract_options!
        method_names = actions + options.keys
        name         = clazz.name.underscore

        [:show, :edit, :new].each do |type|
          (options.delete(type)||[]).each do |name|
            method_names << name
            options[name] = { type: type }
          end
        end

        [:create, :update, :destroy].each do |type|
          options[type] ||= {}
          options[type][:params] ||= :"#{type}_params"
        end

        Action.define_call(self, clazz, :"@#{name}")
        Action.define(self, method_names, options)
      end

    end
  end
end


text:
<fieldset
  ng-if="!WizardConfigureConfirmStepCtrl.loadingPlugin"
  ng-disabled="WizardConfigureConfirmStepCtrl._isDisabled">

              {{::field.label}}

                {{::WizardConfigureConfirmStepCtrl.requiredPropertyError}}

</fieldset>

  Loading...

    Back

      Next

      Confirm

      Close


text:
import { LayoutState } from './layout.state';
import { Reducer } from '../util/reducer';

export class LayoutReducer extends Reducer<LayoutState> {
  public initialState: LayoutState = {
    isServerConnected: true
  };

}

let reducer = new LayoutReducer();
export function layoutReducerFunc(state, action) {
  return reducer.reduce(state, action);
}


text:
1. mkdir _ember; cd _ember
1. ember init --name=viewtastic
2. ember install ember-islands
3. ember g component doc-printer // name must have a hyphen
4. Config Brocfile as needed/desired
5. edit app/index.html to add a data component, e.g. `<div data-component="doc-printer"></div>`
6. ember build -e production
7  cp dist/assets/*.js ../js // or wherever
8. edit the page(s) you want the component on to load the js and include the data-component

```html
<script src="js/vendor.js"></script>
<script src="js/viewtastic.js"></script>
<div data-component="doc-printer"></div>
```

8. profit

Gotchas, things to make it work
- Brocfile.js
- meta

Boiler-plate follows

## Prerequisites

You will need the following things properly installed on your computer.

* [Git](http://git-scm.com/)
* [Node.js](http://nodejs.org/) (with NPM)
* [Bower](http://bower.io/)
* [Ember CLI](http://www.ember-cli.com/)
* [PhantomJS](http://phantomjs.org/)

## Installation

* `git clone <repository-url>` this repository
* change into the new directory
* `npm install`
* `bower install`

## Running / Development

* `ember server`
* Visit your app at [http://localhost:4200](http://localhost:4200).

### Code Generators

Make use of the many generators for code, try `ember help generate` for more details

### Running Tests

* `ember test`
* `ember test --server`

### Building

* `ember build` (development)
* `ember build --environment production` (production)

### Deploying

Specify what it takes to deploy your app.

## Further Reading / Useful Links

* [ember.js](http://emberjs.com/)
* [ember-cli](http://www.ember-cli.com/)
* Development Browser Extensions
  * [ember inspector for chrome](https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi)
  * [ember inspector for firefox](https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/)


text:
import test from 'ava';
import colors from 'colors';
import getPrototypeOf from './Object.getPrototypeOf.next.js';

test(`${colors.underline('getPrototypeOf')} exposure`, (t) => {
	t.is(toString.call(getPrototypeOf), '[object Function]', '"getPrototypeOf" should be an function');
});

test(`${colors.underline('getPrototypeOf')} String`, (t) => {
	t.deepEqual(getPrototypeOf(''), String.prototype, '"getPrototypeOf" should be an function');
});


text:
static int viewTag = 0x11;

@implementation AnimationViewController2

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    CGFloat X = scrollView.contentOffset.x;
    LxDBAnyVar(X);
    for (int i = 0; i < self.picturesArray.count; i++) {

        MoreInfoView *show = [scrollView viewWithTag:viewTag + i];
       // 这里其实应该是 y= 1*k+b
//        show.imageView.x   = (X - i * self.contentView.width)+ _onceLinearEquation.b;
        show.imageView.x   =  (X - i * self.view.width);
    }
}

@end


text:
#include <iostream>
#include <limits>
#include <assert.h>

#include "Logging.h"

#include "Model.h"
#include "Joint.h"

namespace RigidBodyDynamics {

using namespace Math;

void jcalc (
		const Model &model,
		const unsigned int &joint_id,
		SpatialTransform &XJ,
		SpatialVector &S,
		SpatialVector &v_J,
		SpatialVector &c_J,
		const double &q,
		const double &qdot
		) {
	// exception if we calculate it for the root body
	assert (joint_id > 0);

	// Set the joint axis
	S = model.mJoints[joint_id].mJointAxes[0];

	// the velocity dependent spatial acceleration is != 0 only for rhenomic
	// constraints (see RBDA, p. 55)
	c_J.setZero();

	if (model.mJoints[joint_id].mJointType == JointTypeRevolute) {
		XJ = Xrot (q, Vector3d (
					model.mJoints[joint_id].mJointAxes[0][0],
					model.mJoints[joint_id].mJointAxes[0][1],
					model.mJoints[joint_id].mJointAxes[0][2]
					));
	} else if (model.mJoints[joint_id].mJointType == JointTypePrismatic) {
		XJ = Xtrans ( Vector3d (
					model.mJoints[joint_id].mJointAxes[0][3] * q,
					model.mJoints[joint_id].mJointAxes[0][4] * q,
					model.mJoints[joint_id].mJointAxes[0][5] * q
					)
				);
	} else {
		// Only revolute joints supported so far
		assert (0);
	}

	v_J = S * qdot;
}

}


text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
#pragma once

#include <array>
#include <cstddef>

#include <thrift/lib/cpp/Thrift.h>

#include "thrift/compiler/test/fixtures/basic-cpp-async/gen-cpp/module_types.h"

struct _MyEnumEnumDataStorage {
  using type = MyEnum;
  static constexpr const std::size_t size = 2;
  static constexpr const std::array<MyEnum, 2> values = {{
    MyEnum::MyValue1,
    MyEnum::MyValue2,
  }};
  static constexpr const std::array<folly::StringPiece, 2> names = {{
    "MyValue1",
    "MyValue2",
  }};
};

namespace apache { namespace thrift {
template <> struct TEnumDataStorage< ::MyEnum> {
  using storage_type =  ::_MyEnumEnumDataStorage;
};
}} // apache::thrift


text:
require 'fileutils'

Given /^the (\w+) app is setup with the latest email steps$/ do |app_name|
  app_dir = File.join(root_dir, 'examples',"#{app_name}_root")
  email_specs_path = File.join(app_dir,'features','step_definitions','email_steps.rb')
  latest_specs_path = File.join(root_dir,'lib','generators','email_spec','steps','templates','email_steps.rb')
  FileUtils.rm(email_specs_path) if File.exists?(email_specs_path)
  FileUtils.cp_r(latest_specs_path, email_specs_path)
end

Then /^the (\w+) app should have the email steps in place$/ do |app_name|
  email_specs_path = "#{root_dir}/examples/#{app_name}_root/features/step_definitions/email_steps.rb"
  File.exists?(email_specs_path).should == true
end

Then /^I should see the following summary report:$/ do |expected_report|
  @output.should include(expected_report)
end

Given /^the (\w+) app is setup with the latest generators$/ do |app_name|
  app_dir= File.join(root_dir,'examples',"#{app_name}_root")
  email_specs_path = File.join(app_dir,'features','step_definitions','email_steps.rb')
  FileUtils.rm(email_specs_path) if File.exists?(email_specs_path)

  if app_name == 'rails3'
    #Testing using the gem
    #make sure we are listed in the bundle
    Dir.chdir(app_dir) do
      output =`bundle list`
      output.should include('email_spec')
    end
  else
    FileUtils.mkdir_p("#{app_dir}/vendor/plugins/email_spec")
    FileUtils.cp_r("#{root_dir}/rails_generators","#{app_dir}/vendor/plugins/email_spec/")
    Dir.chdir(app_dir) do
      system "ruby ./script/generate email_spec"
    end
  end
end

When /^I run "([^\"]*)" in the (\w+) app$/ do |cmd, app_name|
  cmd.gsub!('cucumber', "#{Cucumber::RUBY_BINARY} #{Cucumber::BINARY}")
  app_path = File.join(root_dir, 'examples', "#{app_name}_root")
  app_specific_gemfile = File.join(app_path,'Gemfile')
  Dir.chdir(app_path) do
    #hack to fight competing bundles (email specs vs rails3_root's
    if File.exists? app_specific_gemfile
      orig_gemfile = ENV['BUNDLE_GEMFILE']
      ENV['BUNDLE_GEMFILE'] = app_specific_gemfile
      @output = `#{cmd}`
      ENV['BUNDLE_GEMFILE'] = orig_gemfile
    else
      @output = `#{cmd}`
    end
  end
end


text:
UPDATE students SET avg_point = 5 WHERE student.id >= 1 AND student.id < 5;

UPDATE students SET first_name = 'Andrew', last_name = 'Kozlov' WHERE student.id = 3;


text:
@class NSMutableArray;

@interface NSThread (XCTestAdditions)
+ (unsigned long long)xct_currentThreadId;
@property(readonly) NSMutableArray *xct_contextStack;
@end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Lich. -Fl. Great Brit. 257 (1871)

#### Original name
Opegrapha saxigena var. trochodes Taylor ex Leight.

### Remarks
null


text:
package org.apache.wicket.coep;

import org.apache.wicket.coop.CrossOriginOpenerPolicyRequestCycleListener;
import org.apache.wicket.request.IRequestHandler;
import org.apache.wicket.request.cycle.IRequestCycleListener;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.http.WebResponse;
import org.apache.wicket.util.lang.Args;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.servlet.http.HttpServletRequest;

/**
 * Sets Cross-Origin Embedder
 * Policy (COEP) headers on the responses based on the mode specified by
 * {@link CrossOriginEmbedderPolicyConfiguration}. COEP can be enabled in REPORTING
 * mode which will set the headers as Cross-Origin-Embedder-Policy-Report-Only or
 * ENFORCING mode which will set the header as
 * Cross-Origin-Embedder-Policy. The header is not set for the paths that are exempted
 * from COEP. The only valid value of COEP is require-corp, so if the listener is
 * enabled the policy value will be specified as so.
 *
 * COEP prevents a document from loading any non-same-origin resources which don't explicitly grant
 * the document permission to be loaded. Using COEP and COOP together allows developers to safely
 * use powerful features such as SharedArrayBuffer,
 * performance.measureMemory(), and the JS Self-Profiling API.See
 * {@link CrossOriginOpenerPolicyRequestCycleListener} for instructions on how to enable COOP.
 * Read more about cross-origin isolation on
 * https://web.dev/why-coop-coep/
 *
 *
 * @author Santiago Diaz - saldiaz@google.com
 * @author Ecenaz Jen Ozmen - ecenazo@google.com
 *
 * @see CrossOriginEmbedderPolicyConfiguration
 * @see org.apache.wicket.settings.SecuritySettings
 */
public class CrossOriginEmbedderPolicyRequestCycleListener implements IRequestCycleListener
{
	private static final Logger log = LoggerFactory.getLogger(CrossOriginEmbedderPolicyRequestCycleListener.class);

	static final String REQUIRE_CORP = "require-corp";

	private CrossOriginEmbedderPolicyConfiguration coepConfig;

	public CrossOriginEmbedderPolicyRequestCycleListener(CrossOriginEmbedderPolicyConfiguration coepConfig)
	{
		this.coepConfig = Args.notNull(coepConfig, "coepConfig");
	}

	@Override
	public void onRequestHandlerResolved(RequestCycle cycle, IRequestHandler handler)
	{
		final Object containerRequest = cycle.getRequest().getContainerRequest();
		if (containerRequest instanceof HttpServletRequest)
		{
			HttpServletRequest request = (HttpServletRequest) containerRequest;
			String path = request.getContextPath();
			final String coepHeaderName = coepConfig.getCoepHeader();

			if (coepConfig.getExemptions().contains(path))
			{
				log.debug("Request path {} is exempted from COEP, no '{}' header added", path, coepHeaderName);
				return;
			}

			if (cycle.getResponse() instanceof WebResponse)
			{
				WebResponse webResponse = (WebResponse) cycle.getResponse();
				if (webResponse.isHeaderSupported())
				{
					webResponse.setHeader(coepHeaderName, REQUIRE_CORP);
				}
			}
		}
	}
}


text:
from .user import User
from .song import Song
from .queue import Queue


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <title>MJPG-streamer</title>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <link rel="stylesheet" href="style.css" type="text/css" />

MJPG-Streamer Demo Pages

a ressource friendly streaming application

        Home
        Static
        Stream
        Java
        Javascript
        VideoLAN
        Control

Version info:

v0.1 (Okt 22, 2007)

About

Details about the M-JPEG streamer

Congratulations

You sucessfully managed to install this streaming webserver. If you can see this page, you can also access the stream of JPGs, which can originate from your webcam for example. This installation consists of these example pages and you may customize the look and content.

The reason for developing this software was the need of a simple and ressource friendly streaming application for Linux-UVC compatible webcams. The predecessor uvc-streamer is working well, but i wanted to implement a few more ideas. For instance, plugins can be used to process the images. One input plugin copies images to a global variable, multiple output plugins can access those images. For example this webpage is served by the output_http.so plugin.

The image displayed here was grabbed by the input plugin. The HTTP request contains the GET parameters action=snapshot. This requests one single picture from the image-input. To display another example, just click on the picture.

About the examples

To view the stream with any browser you may try the javascript or java subpages. Firefox is able to display the M-JPEG-stream directly.

About this server

This server is running a software written for the MJPG-streamer project. The MJPG-streamer developers can not be made responsible for installations of this software.

© The MJPG-streamer team | Design by Andreas Viklund


text:
package org.mtransit.android.commons.provider;

import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

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

import org.mtransit.android.commons.Constants;
import org.mtransit.android.commons.MTLog;

/**
 * NO LOGIC HERE, just logs.
 */
public abstract class MTSQLiteOpenHelper extends SQLiteOpenHelper implements MTLog.Loggable {

	public MTSQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable CursorFactory factory, int version) {
		super(context, name, factory, version);
		if (Constants.LOG_PROVIDER_LIFECYCLE) {
			MTLog.v(this, "%s(%s, %s)", getLogTag(), name, version);
		}
	}

	public MTSQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable CursorFactory factory, int version, @Nullable DatabaseErrorHandler errorHandler) {
		super(context, name, factory, version, errorHandler);
		if (Constants.LOG_PROVIDER_LIFECYCLE) {
			MTLog.v(this, "%s(%s, %s)", getLogTag(), name, version);
		}
	}

	@Override
	public void onCreate(@NonNull SQLiteDatabase db) {
		if (Constants.LOG_PROVIDER_LIFECYCLE) {
			MTLog.v(this, "onCreate()");
		}
		onCreateMT(db);
	}

	/**
	 * @see SQLiteOpenHelper#onCreate(SQLiteDatabase)
	 */
	public abstract void onCreateMT(@NonNull SQLiteDatabase db);

	@Override
	public void onUpgrade(@NonNull SQLiteDatabase db, int oldVersion, int newVersion) {
		if (Constants.LOG_PROVIDER_LIFECYCLE) {
			MTLog.v(this, "onUpgrade(%s, %s)", oldVersion, newVersion);
		}
		onUpgradeMT(db, oldVersion, newVersion);
	}

	/**
	 * @see SQLiteOpenHelper#onUpgrade(SQLiteDatabase, int, int)
	 */
	public abstract void onUpgradeMT(@NonNull SQLiteDatabase db, int oldVersion, int newVersion);

	@Override
	public void onOpen(@NonNull SQLiteDatabase db) {
		if (Constants.LOG_PROVIDER_LIFECYCLE) {
			MTLog.v(this, "onOpen()");
		}
		super.onOpen(db);
	}
}


text:
class RemoveLeagueTableForeignKey < ActiveRecord::Migration[5.0]
  def change
    remove_foreign_key :seasons, :league_tables
  end
end


text:
import * as zrUtil from 'zrender/src/core/util';
import * as modelUtil from '../../util/model';
import { ECUnitOption, SeriesOption } from '../../util/types';
import { ParallelAxisOption } from './AxisModel';
import { ParallelSeriesOption } from '../../chart/parallel/ParallelSeries';

export default function parallelPreprocessor(option: ECUnitOption): void {
    createParallelIfNeeded(option);
    mergeAxisOptionFromParallel(option);
}

/**
 * Create a parallel coordinate if not exists.
 * @inner
 */
function createParallelIfNeeded(option: ECUnitOption): void {
    if (option.parallel) {
        return;
    }

    let hasParallelSeries = false;

    zrUtil.each(option.series, function (seriesOpt: SeriesOption) {
        if (seriesOpt && seriesOpt.type === 'parallel') {
            hasParallelSeries = true;
        }
    });

    if (hasParallelSeries) {
        option.parallel = [{}];
    }
}

/**
 * Merge aixs definition from parallel option (if exists) to axis option.
 * @inner
 */
function mergeAxisOptionFromParallel(option: ECUnitOption): void {
    const axes = modelUtil.normalizeToArray(option.parallelAxis) as ParallelAxisOption[];

    zrUtil.each(axes, function (axisOption) {
        if (!zrUtil.isObject(axisOption)) {
            return;
        }

        const parallelIndex = axisOption.parallelIndex || 0;
        const parallelOption = modelUtil.normalizeToArray(option.parallel)[parallelIndex] as ParallelSeriesOption;

        if (parallelOption && parallelOption.parallelAxisDefault) {
            zrUtil.merge(axisOption, parallelOption.parallelAxisDefault, false);
        }
    });
}


text:
package filodb.jmh

import java.util.concurrent.TimeUnit

import org.openjdk.jmh.annotations._
import spire.syntax.cfor._

import filodb.memory.NativeMemoryManager
import filodb.memory.format.MemoryReader._
import filodb.memory.format.vectors._

/**
 * Measures basic read benchmark with no NAs for a time series LongColumn.
 * Just raw read speed basically.
 * Roughly randomly increasing, constant increasing, probably using DDV to encode.
 *
 * For a description of the JMH measurement modes, see
 * https://github.com/ktoso/sbt-jmh/blob/master/src/sbt-test/sbt-jmh/
 *   jmh-run/src/main/scala/org/openjdk/jmh/samples/JMHSample_02_BenchmarkModes.scala
 */
@State(Scope.Thread)
class BasicFiloBenchmark {

  // Ok, create a LongColumn and benchmark it.
  val numValues = 1000
  val memFactory = new NativeMemoryManager(10 * 1024 * 1024)
  val acc = nativePtrReader

  val randomLongs = (0 until numValues).map(i => util.Random.nextInt.toLong)

  val ivbuilder = LongBinaryVector.appendingVectorNoNA(memFactory, numValues)
  randomLongs.foreach(ivbuilder.addData)
  val iv = ivbuilder.optimize(memFactory)
  val ivReader = LongBinaryVector(acc, iv)

  val dblBuilder = DoubleVector.appendingVectorNoNA(memFactory, numValues)
  randomLongs.map(_.toDouble).foreach(dblBuilder.addData)
  val dblReader= dblBuilder.reader.asDoubleReader

  val intBuilder = IntBinaryVector.appendingVectorNoNA(memFactory, numValues)
  randomLongs.map(n => (n / 256).toInt).foreach(intBuilder.addData)
  val intReader = intBuilder.reader.asIntReader

  val byteIVBuilder = LongBinaryVector.appendingVectorNoNA(memFactory, numValues)
  randomLongs.zipWithIndex.map { case (rl, i) => i * 10000 + (rl % 128) }.foreach(byteIVBuilder.addData)
  val byteVect = byteIVBuilder.optimize(memFactory)
  val byteReader = LongBinaryVector(acc, byteVect)

  @TearDown
  def shutdown(): Unit = {
    memFactory.shutdown()
  }

  // According to @ktosopl, be sure to return some value if possible so that JVM won't
  // optimize out the method body.  However JMH is apparently very good at avoiding this.
  // fastest loop possible using FiloVectorApply method
  @Benchmark
  @BenchmarkMode(Array(Mode.AverageTime))
  @OutputTimeUnit(TimeUnit.MICROSECONDS)
  def sumAllLongsApply(): Long = {
    var total = 0L
    val acc2 = acc // local variable to make the scala compiler not use virtual invoke
    cforRange { 0 until numValues } { i =>
      total += ivReader(acc2, iv, i)
    }
    total
  }

  @Benchmark
  @BenchmarkMode(Array(Mode.AverageTime))
  @OutputTimeUnit(TimeUnit.MICROSECONDS)
  def sumAllLongsIterate(): Long = {
    var total = 0L
    val it = ivReader.iterate(acc, iv)
    cforRange { 0 until numValues } { i =>
      total += it.next
    }
    total
  }

  @Benchmark
  @BenchmarkMode(Array(Mode.AverageTime))
  @OutputTimeUnit(TimeUnit.MICROSECONDS)
  def sumAllLongsSumMethod(): Double = {
    ivReader.sum(acc, iv, 0, numValues - 1)
  }

  @Benchmark
  @BenchmarkMode(Array(Mode.AverageTime))
  @OutputTimeUnit(TimeUnit.MICROSECONDS)
  def sumDoublesSumMethod(): Double = {
    dblReader.sum(acc, dblBuilder.addr, 0, numValues - 1)
  }

  @Benchmark
  @BenchmarkMode(Array(Mode.AverageTime))
  @OutputTimeUnit(TimeUnit.MICROSECONDS)
  def sumAllIntsSumMethod(): Long = {
    intReader.sum(acc, intBuilder.addr, 0, numValues - 1)
  }

  @Benchmark
  @BenchmarkMode(Array(Mode.AverageTime))
  @OutputTimeUnit(TimeUnit.MICROSECONDS)
  def sumTimeSeriesBytesApply(): Long = {
    var total = 0L
    val acc2 = acc // local variable to make the scala compiler not use virtual invoke
    cforRange { 0 until numValues } { i =>
      total += byteReader(acc2, byteVect, i)
    }
    total
  }

  @Benchmark
  @BenchmarkMode(Array(Mode.AverageTime))
  @OutputTimeUnit(TimeUnit.MICROSECONDS)
  def sumTimeSeriesBytesIterate(): Long = {
    var total = 0L
    val it = byteReader.iterate(acc, byteVect)
    cforRange { 0 until numValues } { i =>
      total += it.next
    }
    total
  }

  @Benchmark
  @BenchmarkMode(Array(Mode.AverageTime))
  @OutputTimeUnit(TimeUnit.MICROSECONDS)
  def sumTimeSeriesBytesSum(): Double = {
    byteReader.sum(acc, byteVect, 0, numValues - 1)
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Irenopsis crataegi S.K. Bose

### Remarks
null


text:
module RuboCop
  module Cop
    module Style
      # This cop checks for the use of strings as keys in hashes. The use of
      # symbols is preferred instead.
      #
      # @example
      #   # bad
      #   { 'one' => 1, 'two' => 2, 'three' => 3 }
      #
      #   # good
      #   { one: 1, two: 2, three: 3 }
      class StringHashKeys < Cop
        MSG = 'Prefer symbols instead of strings as hash keys.'

        def_node_matcher :string_hash_key?, <<~PATTERN
          (pair (str _) _)
        PATTERN

        def_node_matcher :receive_environments_method?, <<~PATTERN
          {
            ^^(send (const {nil? cbase} :IO) :popen ...)
            ^^(send (const {nil? cbase} :Open3)
                {:capture2 :capture2e :capture3 :popen2 :popen2e :popen3} ...)
            ^^^(send (const {nil? cbase} :Open3)
                {:pipeline :pipeline_r :pipeline_rw :pipeline_start :pipeline_w} ...)
            ^^(send {nil? (const {nil? cbase} :Kernel)} {:spawn :system} ...)
            ^^(send _ {:gsub :gsub!} ...)
          }
        PATTERN

        def on_pair(node)
          return unless string_hash_key?(node)
          return if receive_environments_method?(node)

          add_offense(node.key)
        end

        def autocorrect(node)
          lambda do |corrector|
            symbol_content = node.str_content.to_sym.inspect
            corrector.replace(node, symbol_content)
          end
        end
      end
    end
  end
end


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

<!--Automatically reloading configuration file upon modification; default scan = once per minute -->
<configuration scan="true">

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder
        by default -->
        <encoder>
            <pattern>%d{dd MMM yyyy;HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n
            </pattern>
        </encoder>
    </appender>
    <logger name="org.apache.commons.digester.Digester" level="FATAL"/>
    <logger name="io.sovaj" level="INFO"/>
    <logger name="org.springframework" level="INFO"/>
    <logger name="org.eclipse.jetty.util.log" level="INFO"/>
    <!-- Strictly speaking, the level attribute is not necessary since -->
    <!-- the level of the root level is set to DEBUG by default. -->
    <root level="INFO">
        <appender-ref ref="STDOUT"/>

    </root>

</configuration>


text:
/* global exports */
"use strict";

// module DOM.Event.EventTarget

exports.eventListener = function (fn) {
  return function (event) {
    return fn(event)();
  };
};

exports.addEventListener = function (type) {
  return function (listener) {
    return function (useCapture) {
      return function (target) {
        return function () {
          target.addEventListener(type, listener, useCapture);
          return {};
        };
      };
    };
  };
};

exports.removeEventListener = function (type) {
  return function (listener) {
    return function (useCapture) {
      return function (target) {
        return function () {
          target.removeEventListener(type, listener, useCapture);
          return {};
        };
      };
    };
  };
};

exports.dispatchEvent = function (event) {
  return function (target) {
    return function () {
      return target.dispatchEvent(event);
    };
  };
};


text:
using uWebshop.Domain.Interfaces;

namespace uWebshop.Domain.Services
{
	internal class UrlFormatService : IUrlFormatService
	{
		private readonly ISettingsService _settings;
		private readonly ICMSApplication _cmsApplication;

		public UrlFormatService(ISettingsService settings, ICMSApplication cmsApplication)
		{
			_settings = settings; // todo: this is wrong in the current setup if resolved before settings is replaced by actual
			_cmsApplication = cmsApplication;
		}

		public string FormatUrl(string resultUrl)
		{
			if (_cmsApplication.AddTrailingSlash && !resultUrl.EndsWith("/"))
			{
				resultUrl += "/";
			}
			if (resultUrl.StartsWith("//"))
			{
				resultUrl = resultUrl.Substring(1);
			}
			if (!resultUrl.StartsWith("/") && !resultUrl.StartsWith("http"))
			{
				resultUrl = resultUrl.Insert(0, "/");
			}
			return _settings.UseLowercaseUrls ? resultUrl.ToLower() : resultUrl;
		}
	}
}


text:
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
require "authlogic/test_case"
require File.expand_path(File.dirname(__FILE__) + "/../vendor/extensions/payment_gateway/test/mocks/authorize_net_cim_mock")

class ActiveSupport::TestCase
  self.use_transactional_fixtures = true
  self.use_instantiated_fixtures  = false
  fixtures :all
end

I18n.locale = "en-US"
Spree::Config.set(:default_country_id => Country.first.id) if Country.first

class ActionController::TestCase
  setup :activate_authlogic
end

ActionController::TestCase.class_eval do
  # special overload methods for "global"/nested params
  [ :get, :post, :put, :delete ].each do |overloaded_method|
    define_method overloaded_method do |*args|
      action,params,extras = *args
      super action, params || {}, *extras unless @params
      super action, @params.merge( params || {} ), *extras if @params
    end
  end
end

def setup
  super
  @params = {}
end

class TestCouponCalc
  def self.calculate_discount(checkout)
    0.99
  end
end

Zone.class_eval do
  def self.global
    find_by_name("GlobalZone") || Factory(:global_zone)
  end
end

def create_complete_order
  @zone = Zone.global
  @order = Factory(:order)
  3.times do
    #variant = Factory(:product).variants.first
    variant = Factory(:variant)
    Factory(:line_item, :variant => variant, :order => @order)
  end

  @shipping_method = Factory(:shipping_method)
  @checkout = @order.checkout

  @checkout.ship_address = Factory(:address)
  @checkout.shipping_method = @shipping_method

  @checkout.payments = [Factory(:payment, :amount => @order.total)]
  @checkout.save

  @shipment = @order.shipment

  @checkout.bill_address = Factory(:address)

  unless @zone.include?(@order.shipment.address)
    ZoneMember.create(:zone => Zone.global, :zoneable => @checkout.ship_address.country)
    @zone.reload
  end

  @checkout.save
  @shipment.save
  @order.save
  @order.reload
  @order.save
  @order
end

# Sets up an order with state 'new' with completed checkout and authorized payment
def create_new_order
  create_complete_order
  @checkout.next!
  @checkout.next!
  @checkout.creditcard_attributes = Factory.attributes_for(:creditcard)
  @checkout.next!
end

def create_new_order_v2
  create_complete_order
  @checkout.payments = [Factory(:payment)]
  @checkout.state = "complete"
  @checkout.save
  @order.complete!
end

# useful method for functional tests that require an authenticated user
def set_current_user
  @user = Factory(:user)
  @controller.stub!(:current_user, :return => @user)
end

def sort_list_hash(thing)
  thing.map(&:sort).sort
end
def assert_equal_list_hash(alpha,beta)
  assert_equal(sort_list_hash(alpha), sort_list_hash(beta))
end


text:
extern crate rand;
pub mod dice;

#[test]
fn it_works() {
    println!("It works!");
}


text:
WV.Chat = {}

WV.Chat.initialized = false;
WV.Chat.watching = false;
WV.Chat.showTimeStamps = true;

WV.Chat.handleData = function(data, name)
{
    report("handleChatData "+name);
    //report("data: "+WV.toJSON(data));
    var layer = WV.layers["chat"];
    //if (!layer.visible) {
    //	return;
    //}
    var t = WV.getClockTime();
    var recs = WV.getRecords(data);
    recs.sort(function(a,b) { return a.t-b.t; })
    for (var i=0; i<recs.length; i++) {
        var rec = recs[i];
	if (rec.t == null) {
	    report("Bad rec with no time "+JSON.stringify(rec));
	    continue;
	}
	//report("chat rec: "+JSON.stringify(rec));
	var dt = t - rec.t;
	var str = rec.name+": "+rec.text;
	if (WV.Chat.showTimeStamps)
	    str = WV.toTimeStr(rec.t) + " " + str
	WV.Chat.widget.prepend(str+"
");
    }
}

WV.Chat.hide = function()
{
    WV.Chat.setVisibility(false);
}

WV.Chat.setVisibility = function(v)
{
    var layer = WV.layers["chat"];
    if (v) {
	report("Show #chatWindow ");
	$("#cb_chat").prop("checked", true);
	//$("#chatWindow").show(200);
	WV.Chat.widget.show();
	if (!WV.Chat.watching)
	    WV.Chat.postMessage("[joining chat]");
	WV.Chat.watching = true;
	if (!layer.visible)
	layer.visible = true;
	//$("#chatText").append("
");
	/*
	setTimeout(function() {
		report("ughhh......");
		$("#chatText").append("
");
	    }, 1000);
	*/
    }
    else {
	report("hide #chatWindow ");
	$("#cb_chat").prop("checked", false);
	layer.visible = false;
	//$("#chatWindow").hide(200);
	WV.Chat.widget.hide();
	if (WV.Chat.watching)
	    WV.Chat.postMessage("[leaving chat]");
	WV.Chat.watching = false;
    }
    //
}

//WV.WVCom.prototype.postMessage = function(text)
WV.Chat.postMessage = function(text)
{
    var msg = WV.getStatusObj();
    msg.text = text;
    msg.type = "chat";
    msg.id = WV.getUniqueId('chat');
    wvCom.sendMsg('chat', msg);
}

WV.xxxx = 0;
WV.chatter = function()
{
    WV.xxxx++;
    WV.Chat.postMessage("hello.  I am sam "+WV.xxxx);
    setTimeout(WV.chatter, 5000);
}

$(document).ready(function()
{
    WV.Chat.widget = new WV.WindowWidget("chat");
    WV.Chat.widget.dismiss = WV.Chat.hide;
    WV.Chat.widget.handleInput = WV.Chat.postMessage;

    WV.registerLayerType("chat", {
         dataHandler: WV.Chat.handleData,
         setVisibility: WV.Chat.setVisibility,
	     });

});


text:
import app from '../../app';
import BaseVw from '../baseVw';
import ListingCard from '../components/ListingCard';

export default class extends BaseVw {
  constructor(options = {}) {
    // If this grid is for a Store, pass in a storeOwnerProfile option
    // with the Profile model of the store owner.
    const opts = {
      viewType: app.localSettings.get('listingsGridViewType'),
      ...options,
    };

    super(opts);
    this.options = opts;

    if (!this.collection) {
      throw new Error('Please provide a collection.');
    }

    if (!this.options.listingBaseUrl && !this.options.storeOwnerProfile) {
      let allHaveVendor = true;

      try {
        this.collection.forEach(md => {
          if (!md.get('vendor')) throw new Error();
        });
      } catch (e) {
        allHaveVendor = false;
      }

      if (!allHaveVendor) {
        throw new Error('I am unable to determine a listingBaseUrl for one or more of the ' +
          'provided listings. Please either pass in a listingBaseUrl option or it can be ' +
          'derived if you provid a storeOwnerProfile option or every model has an embedded ' +
          ' Vendor object.');
      }
    }

    this.viewType = opts.viewType;
    this.listingCardViews = [];

    this.listenTo(this.collection, 'update', (updatedCl, updateOpts) => {
      // The only updates we're expecting are a new "page" of
      // listings being added to the end of the collection.
      if (updateOpts.add) {
        this.renderListingCards(updateOpts.changes.added);
      }
    });
  }

  className() {
    return 'listingsGrid flex';
  }

  get viewType() {
    return this._viewType;
  }

  set viewType(type) {
    if (['list', 'grid'].indexOf(type) === '-1') {
      throw new Error('The type provided is not one of the available types.');
    }

    // This just sets the flag. It's up to you to re-render to update the UI.
    this._viewType = type;
    app.localSettings.save('listingsGridViewType', type);
  }

  get listingCount() {
    return this.listingCardViews ?
      this.listingCardViews.length : 0;
  }

  createListingCardView(model) {
    let listingBaseUrl;

    // The listingBaseUrl can be directly provided as an option or we
    // will attempt to derive it from a passed in Profile model or
    // Vendor information in the listing short models.
    if (this.options.listingBaseUrl) {
      listingBaseUrl = this.options.listingBaseUrl;
    } else if (model.get('vendor')) {
      const base = model.get('vendor').handle ?
        `@${model.get('vendor').handle}` : model.get('vendor').peerID;
      listingBaseUrl = `${base}/store/`;
    } else if (this.options.storeOwnerProfile) {
      const base = this.options.storeOwnerProfile.get('handle') ?
        `@${this.options.storeOwnerProfile.get('handle')}` :
          this.options.storeOwnerProfile.id;
      listingBaseUrl = `${base}/store/`;
    }

    const options = {
      listingBaseUrl,
      viewType: this.viewType,
      model,
    };

    if (this.options.storeOwnerProfile) {
      options.profile = this.options.storeOwnerProfile;
      // Flag so the listing card knows it's on a store. This is useful to
      // the listing detail modal and will be passed into there.
      options.onStore = true;
    }

    return this.createChild(ListingCard, options);
  }

  renderListingCards(models = []) {
    const listingsFrag = document.createDocumentFragment();

    models.forEach(model => {
      // In the proposed search API, vendor info will be provided in the
      // search results. If that's the case we'll pass it to the listing
      // card view.
      const listingCardVw = this.createListingCardView(model);

      this.listingCardViews.push(listingCardVw);
      listingCardVw.render().$el.appendTo(listingsFrag);
    });

    this.$el.append(listingsFrag);
  }

  render() {
    this.$el[this.viewType === 'list' ? 'addClass' : 'removeClass']('listingsGridListView');
    this.listingCardViews.forEach(vw => vw.remove());
    this.listingCardViews = [];
    this.$el.empty();
    this.renderListingCards(this.collection);

    return this;
  }
}

// Standard width grid has 3 columns, so best to leave this
// as a multiple of 3.
export const LISTINGS_PER_PAGE = 24;


text:
/* $OpenBSD$ */

/*
 * Copyright (c) 2009 Nicholas Marriott <nicholas.marriott@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>

#include <string.h>

#include "tmux.h"

/*
 * Set window layouts - predefined methods to arrange windows. These are
 * one-off and generate a layout tree.
 */

static void	layout_set_even_h(struct window *);
static void	layout_set_even_v(struct window *);
static void	layout_set_main_h(struct window *);
static void	layout_set_main_v(struct window *);
static void	layout_set_tiled(struct window *);

static const struct {
	const char	*name;
	void	      	(*arrange)(struct window *);
} layout_sets[] = {
	{ "even-horizontal", layout_set_even_h },
	{ "even-vertical", layout_set_even_v },
	{ "main-horizontal", layout_set_main_h },
	{ "main-vertical", layout_set_main_v },
	{ "tiled", layout_set_tiled },
};

int
layout_set_lookup(const char *name)
{
	u_int	i;
	int	matched = -1;

	for (i = 0; i < nitems(layout_sets); i++) {
		if (strncmp(layout_sets[i].name, name, strlen(name)) == 0) {
			if (matched != -1)	/* ambiguous */
				return (-1);
			matched = i;
		}
	}

	return (matched);
}

u_int
layout_set_select(struct window *w, u_int layout)
{
	if (layout > nitems(layout_sets) - 1)
		layout = nitems(layout_sets) - 1;

	if (layout_sets[layout].arrange != NULL)
		layout_sets[layout].arrange(w);

	w->lastlayout = layout;
	return (layout);
}

u_int
layout_set_next(struct window *w)
{
	u_int	layout;

	if (w->lastlayout == -1)
		layout = 0;
	else {
		layout = w->lastlayout + 1;
		if (layout > nitems(layout_sets) - 1)
			layout = 0;
	}

	if (layout_sets[layout].arrange != NULL)
		layout_sets[layout].arrange(w);
	w->lastlayout = layout;
	return (layout);
}

u_int
layout_set_previous(struct window *w)
{
	u_int	layout;

	if (w->lastlayout == -1)
		layout = nitems(layout_sets) - 1;
	else {
		layout = w->lastlayout;
		if (layout == 0)
			layout = nitems(layout_sets) - 1;
		else
			layout--;
	}

	if (layout_sets[layout].arrange != NULL)
		layout_sets[layout].arrange(w);
	w->lastlayout = layout;
	return (layout);
}

static void
layout_set_even(struct window *w, enum layout_type type)
{
	struct window_pane	*wp;
	struct layout_cell	*lc, *lcnew;
	u_int			 n;

	layout_print_cell(w->layout_root, __func__, 1);

	/* Get number of panes. */
	n = window_count_panes(w);
	if (n <= 1)
		return;

	/* Free the old root and construct a new. */
	layout_free(w);
	lc = w->layout_root = layout_create_cell(NULL);
	layout_set_size(lc, w->sx, w->sy, 0, 0);
	layout_make_node(lc, type);

	/* Build new leaf cells. */
	TAILQ_FOREACH(wp, &w->panes, entry) {
		lcnew = layout_create_cell(lc);
		layout_make_leaf(lcnew, wp);
		lcnew->sx = w->sx;
		lcnew->sy = w->sy;
		TAILQ_INSERT_TAIL(&lc->cells, lcnew, entry);
	}

	/* Spread out cells. */
	layout_spread_cell(w, lc);

	/* Fix cell offsets. */
	layout_fix_offsets(lc);
	layout_fix_panes(w, w->sx, w->sy);

	layout_print_cell(w->layout_root, __func__, 1);

	notify_window("window-layout-changed", w);
	server_redraw_window(w);
}

static void
layout_set_even_h(struct window *w)
{
	layout_set_even(w, LAYOUT_LEFTRIGHT);
}

static void
layout_set_even_v(struct window *w)
{
	layout_set_even(w, LAYOUT_TOPBOTTOM);
}

static void
layout_set_main_h(struct window *w)
{
	struct window_pane	*wp;
	struct layout_cell	*lc, *lcmain, *lcrow, *lcchild;
	u_int			 n, mainheight, otherheight, width, height;
	u_int			 used, i, j, columns, rows, totalrows;

	layout_print_cell(w->layout_root, __func__, 1);

	/* Get number of panes. */
	n = window_count_panes(w);
	if (n <= 1)
		return;
	n--;	/* take off main pane */

	/* How many rows and columns will be needed, not counting main? */
	columns = (w->sx + 1) / (PANE_MINIMUM + 1);	/* maximum columns */
	if (columns == 0)
		columns = 1;
	rows = 1 + (n - 1) / columns;
	columns = 1 + (n - 1) / rows;
	width = (w->sx - (n - 1)) / columns;

	/* Get the main pane height and add one for separator line. */
	mainheight = options_get_number(w->options, "main-pane-height") + 1;

	/* Get the optional other pane height and add one for separator line. */
	otherheight = options_get_number(w->options, "other-pane-height") + 1;

	/*
	 * If an other pane height was specified, honour it so long as it
	 * doesn't shrink the main height to less than the main-pane-height
	 */
	if (otherheight > 1 && w->sy - otherheight > mainheight)
		mainheight = w->sy - otherheight;
	if (mainheight < PANE_MINIMUM + 1)
		mainheight = PANE_MINIMUM + 1;

	/* Try and make everything fit. */
	totalrows = rows * (PANE_MINIMUM + 1) - 1;
	if (mainheight + totalrows > w->sy) {
		if (totalrows + PANE_MINIMUM + 1 > w->sy)
			mainheight = PANE_MINIMUM + 2;
		else
			mainheight = w->sy - totalrows;
		height = PANE_MINIMUM;
	} else
		height = (w->sy - mainheight - (rows - 1)) / rows;

	/* Free old tree and create a new root. */
	layout_free(w);
	lc = w->layout_root = layout_create_cell(NULL);
	layout_set_size(lc, w->sx, mainheight + rows * (height + 1) - 1, 0, 0);
	layout_make_node(lc, LAYOUT_TOPBOTTOM);

	/* Create the main pane. */
	lcmain = layout_create_cell(lc);
	layout_set_size(lcmain, w->sx, mainheight - 1, 0, 0);
	layout_make_leaf(lcmain, TAILQ_FIRST(&w->panes));
	TAILQ_INSERT_TAIL(&lc->cells, lcmain, entry);

	/* Create a grid of the remaining cells. */
	wp = TAILQ_NEXT(TAILQ_FIRST(&w->panes), entry);
	for (j = 0; j < rows; j++) {
		/* If this is the last cell, all done. */
		if (wp == NULL)
			break;

		/* Create the new row. */
		lcrow = layout_create_cell(lc);
		layout_set_size(lcrow, w->sx, height, 0, 0);
		TAILQ_INSERT_TAIL(&lc->cells, lcrow, entry);

		/* If only one column, just use the row directly. */
		if (columns == 1) {
			layout_make_leaf(lcrow, wp);
			wp = TAILQ_NEXT(wp, entry);
			continue;
		}

		/* Add in the columns. */
		layout_make_node(lcrow, LAYOUT_LEFTRIGHT);
		for (i = 0; i < columns; i++) {
			/* Create and add a pane cell. */
			lcchild = layout_create_cell(lcrow);
			layout_set_size(lcchild, width, height, 0, 0);
			layout_make_leaf(lcchild, wp);
			TAILQ_INSERT_TAIL(&lcrow->cells, lcchild, entry);

			/* Move to the next cell. */
			if ((wp = TAILQ_NEXT(wp, entry)) == NULL)
				break;
		}

		/* Adjust the row to fit the full width if necessary. */
		if (i == columns)
			i--;
		used = ((i + 1) * (width + 1)) - 1;
		if (w->sx <= used)
			continue;
		lcchild = TAILQ_LAST(&lcrow->cells, layout_cells);
		layout_resize_adjust(w, lcchild, LAYOUT_LEFTRIGHT,
		    w->sx - used);
	}

	/* Adjust the last row height to fit if necessary. */
	used = mainheight + (rows * height) + rows - 1;
	if (w->sy > used) {
		lcrow = TAILQ_LAST(&lc->cells, layout_cells);
		layout_resize_adjust(w, lcrow, LAYOUT_TOPBOTTOM,
		    w->sy - used);
	}

	/* Fix cell offsets. */
	layout_fix_offsets(lc);
	layout_fix_panes(w, w->sx, w->sy);

	layout_print_cell(w->layout_root, __func__, 1);

	notify_window("window-layout-changed", w);
	server_redraw_window(w);
}

static void
layout_set_main_v(struct window *w)
{
	struct window_pane	*wp;
	struct layout_cell	*lc, *lcmain, *lccolumn, *lcchild;
	u_int			 n, mainwidth, otherwidth, width, height;
	u_int			 used, i, j, columns, rows, totalcolumns;

	layout_print_cell(w->layout_root, __func__, 1);

	/* Get number of panes. */
	n = window_count_panes(w);
	if (n <= 1)
		return;
	n--;	/* take off main pane */

	/* How many rows and columns will be needed, not counting main? */
	rows = (w->sy + 1) / (PANE_MINIMUM + 1);	/* maximum rows */
	if (rows == 0)
		rows = 1;
	columns = 1 + (n - 1) / rows;
	rows = 1 + (n - 1) / columns;
	height = (w->sy - (n - 1)) / rows;

	/* Get the main pane width and add one for separator line. */
	mainwidth = options_get_number(w->options, "main-pane-width") + 1;

	/* Get the optional other pane width and add one for separator line. */
	otherwidth = options_get_number(w->options, "other-pane-width") + 1;

	/*
	 * If an other pane width was specified, honour it so long as it
	 * doesn't shrink the main width to less than the main-pane-width
	 */
	if (otherwidth > 1 && w->sx - otherwidth > mainwidth)
		mainwidth = w->sx - otherwidth;
	if (mainwidth < PANE_MINIMUM + 1)
		mainwidth = PANE_MINIMUM + 1;

	/* Try and make everything fit. */
	totalcolumns = columns * (PANE_MINIMUM + 1) - 1;
	if (mainwidth + totalcolumns > w->sx) {
		if (totalcolumns + PANE_MINIMUM + 1 > w->sx)
			mainwidth = PANE_MINIMUM + 2;
		else
			mainwidth = w->sx - totalcolumns;
		width = PANE_MINIMUM;
	} else
		width = (w->sx - mainwidth - (columns - 1)) / columns;

	/* Free old tree and create a new root. */
	layout_free(w);
	lc = w->layout_root = layout_create_cell(NULL);
	layout_set_size(lc, mainwidth + columns * (width + 1) - 1, w->sy, 0, 0);
	layout_make_node(lc, LAYOUT_LEFTRIGHT);

	/* Create the main pane. */
	lcmain = layout_create_cell(lc);
	layout_set_size(lcmain, mainwidth - 1, w->sy, 0, 0);
	layout_make_leaf(lcmain, TAILQ_FIRST(&w->panes));
	TAILQ_INSERT_TAIL(&lc->cells, lcmain, entry);

	/* Create a grid of the remaining cells. */
	wp = TAILQ_NEXT(TAILQ_FIRST(&w->panes), entry);
	for (j = 0; j < columns; j++) {
		/* If this is the last cell, all done. */
		if (wp == NULL)
			break;

		/* Create the new column. */
		lccolumn = layout_create_cell(lc);
		layout_set_size(lccolumn, width, w->sy, 0, 0);
		TAILQ_INSERT_TAIL(&lc->cells, lccolumn, entry);

		/* If only one row, just use the row directly. */
		if (rows == 1) {
			layout_make_leaf(lccolumn, wp);
			wp = TAILQ_NEXT(wp, entry);
			continue;
		}

		/* Add in the rows. */
		layout_make_node(lccolumn, LAYOUT_TOPBOTTOM);
		for (i = 0; i < rows; i++) {
			/* Create and add a pane cell. */
			lcchild = layout_create_cell(lccolumn);
			layout_set_size(lcchild, width, height, 0, 0);
			layout_make_leaf(lcchild, wp);
			TAILQ_INSERT_TAIL(&lccolumn->cells, lcchild, entry);

			/* Move to the next cell. */
			if ((wp = TAILQ_NEXT(wp, entry)) == NULL)
				break;
		}

		/* Adjust the column to fit the full height if necessary. */
		if (i == rows)
			i--;
		used = ((i + 1) * (height + 1)) - 1;
		if (w->sy <= used)
			continue;
		lcchild = TAILQ_LAST(&lccolumn->cells, layout_cells);
		layout_resize_adjust(w, lcchild, LAYOUT_TOPBOTTOM,
		    w->sy - used);
	}

	/* Adjust the last column width to fit if necessary. */
	used = mainwidth + (columns * width) + columns - 1;
	if (w->sx > used) {
		lccolumn = TAILQ_LAST(&lc->cells, layout_cells);
		layout_resize_adjust(w, lccolumn, LAYOUT_LEFTRIGHT,
		    w->sx - used);
	}

	/* Fix cell offsets. */
	layout_fix_offsets(lc);
	layout_fix_panes(w, w->sx, w->sy);

	layout_print_cell(w->layout_root, __func__, 1);

	notify_window("window-layout-changed", w);
	server_redraw_window(w);
}

void
layout_set_tiled(struct window *w)
{
	struct window_pane	*wp;
	struct layout_cell	*lc, *lcrow, *lcchild;
	u_int			 n, width, height, used;
	u_int			 i, j, columns, rows;

	layout_print_cell(w->layout_root, __func__, 1);

	/* Get number of panes. */
	n = window_count_panes(w);
	if (n <= 1)
		return;

	/* How many rows and columns are wanted? */
	rows = columns = 1;
	while (rows * columns < n) {
		rows++;
		if (rows * columns < n)
			columns++;
	}

	/* What width and height should they be? */
	width = (w->sx - (columns - 1)) / columns;
	if (width < PANE_MINIMUM)
		width = PANE_MINIMUM;
	height = (w->sy - (rows - 1)) / rows;
	if (height < PANE_MINIMUM)
		height = PANE_MINIMUM;

	/* Free old tree and create a new root. */
	layout_free(w);
	lc = w->layout_root = layout_create_cell(NULL);
	layout_set_size(lc, (width + 1) * columns - 1,
	    (height + 1) * rows - 1, 0, 0);
	layout_make_node(lc, LAYOUT_TOPBOTTOM);

	/* Create a grid of the cells. */
	wp = TAILQ_FIRST(&w->panes);
	for (j = 0; j < rows; j++) {
		/* If this is the last cell, all done. */
		if (wp == NULL)
			break;

		/* Create the new row. */
		lcrow = layout_create_cell(lc);
		layout_set_size(lcrow, w->sx, height, 0, 0);
		TAILQ_INSERT_TAIL(&lc->cells, lcrow, entry);

		/* If only one column, just use the row directly. */
		if (n - (j * columns) == 1 || columns == 1) {
			layout_make_leaf(lcrow, wp);
			wp = TAILQ_NEXT(wp, entry);
			continue;
		}

		/* Add in the columns. */
		layout_make_node(lcrow, LAYOUT_LEFTRIGHT);
		for (i = 0; i < columns; i++) {
			/* Create and add a pane cell. */
			lcchild = layout_create_cell(lcrow);
			layout_set_size(lcchild, width, height, 0, 0);
			layout_make_leaf(lcchild, wp);
			TAILQ_INSERT_TAIL(&lcrow->cells, lcchild, entry);

			/* Move to the next cell. */
			if ((wp = TAILQ_NEXT(wp, entry)) == NULL)
				break;
		}

		/*
		 * Adjust the row and columns to fit the full width if
		 * necessary.
		 */
		if (i == columns)
			i--;
		used = ((i + 1) * (width + 1)) - 1;
		if (w->sx <= used)
			continue;
		lcchild = TAILQ_LAST(&lcrow->cells, layout_cells);
		layout_resize_adjust(w, lcchild, LAYOUT_LEFTRIGHT,
		    w->sx - used);
	}

	/* Adjust the last row height to fit if necessary. */
	used = (rows * height) + rows - 1;
	if (w->sy > used) {
		lcrow = TAILQ_LAST(&lc->cells, layout_cells);
		layout_resize_adjust(w, lcrow, LAYOUT_TOPBOTTOM,
		    w->sy - used);
	}

	/* Fix cell offsets. */
	layout_fix_offsets(lc);
	layout_fix_panes(w, w->sx, w->sy);

	layout_print_cell(w->layout_root, __func__, 1);

	notify_window("window-layout-changed", w);
	server_redraw_window(w);
}


text:
In alphabetical order:

  1. Jorge Arias <mail@jorgearias.cl>
  2. Jose Zamudio <jose.zamudiobarrera@postgrad.manchester.ac.uk>
  3. Kartik Arora <chipset95@yahoo.co.in>
  4. Marcus Eisele <marcus.eisele@gmail.com>
  5. Nathan Jaremkio <njaremko@gmail.com>
  6. Panos Sakkos <panos.sakkos@protonmail.com>
  7. Prashant Solanki <prs.solanki@live.com>
  8. Fatima Villanueva (Kaira) <fzf.villanueva@gmail.com>


text:
package becta.viewer.filemanagement;

import java.awt.Color;
import java.util.ArrayList;
import java.util.List;

import javax.media.ControllerListener;
import javax.media.Manager;

import becta.viewer.drawing.Annotation;
import becta.viewer.drawing.BaseElement;
import becta.viewer.drawing.FlashElement;
import becta.viewer.drawing.Group;
import becta.viewer.drawing.ImageElement;
import becta.viewer.drawing.Link;
import becta.viewer.drawing.Linkable;
import becta.viewer.drawing.MovieElement;
import becta.viewer.drawing.RectangleElement;

/**
 * This class implements each page of the document
 */
public class Page {

	/**
	 * Content type not defined
	 */
	private static final int CONTENT_UNDEFINED = 1;
	/**
	 * Normal content
	 */
	private static final int CONTENT_NORMAL = 2;
	/**
	 * content contains audio
	 */
	private static final int CONTENT_AUDIO = 4;
	/**
	 * content contains video
	 */
	private static final int CONTENT_MOVIE = 8;
	/**
	 * content contains flash
	 */
	private static final int CONTENT_FLASH = 16;

	/**
	 * Reference to revealr
	 */
	private RectangleElement revealer;

	/**
	 * Holds the list of elements
	 */
	private ArrayList<BaseElement> elements;

	/**
	 * Holds annotations
	 */
	private ArrayList<Annotation> annotations;

	/**
	 * Background colour
	 */
	private Color bgColour;
	/**
	 * background image
	 */
	private ImageElement bgImage;

	/**
	 * background image posture
	 */
	private int bgImagePosture;

	/**
	 * Page id
	 */
	private String id;

	/**
	 * content type
	 */
	private int contentType =CONTENT_UNDEFINED;

	/**
	 * Constructor for this class
	 */
	public Page() {

		elements = new ArrayList<BaseElement>();
		annotations = new ArrayList<Annotation>();
	}

	/**
	 * Initialize controls added to elements in this page
	 */
	public void beginInitialize(ControllerListener listener){

		for (BaseElement element : elements) {
			element.beginInitialize(listener);
			element.play();
		}
	}

	/**
	 *  Called on completing the initialization
	 */
	public void endInitialize(){

		for (BaseElement element : elements) {
			element.endInitialize();
		}
	}
	/**
	 * Dispose controls added to elements in this page
	 */
	public void dispose(boolean close){

		for (BaseElement element : elements) {
			element.dispose(close);
		}
	}

	/**
	 * Gets page identifier
	 * @return id
	 */
	public String getIdentifier(){
		return id;
	}

	/**
	 * Sets page identifier
	 * @param id
	 */
	public void setIdentifier(String id){
		this.id = id;
	}

	/**
	 * Gets page revealer
	 * @return id
	 */
	public RectangleElement getRevealer(){
		return revealer;
	}

	/**
	 * Sets page revealer
	 * @param element
	 */
	public void setRevealer(RectangleElement element){
		this.revealer = element;
	}

	/**
	 * Add an element to the elements list
	 * @param element
	 */
	public void addElement(BaseElement element) {

		elements.add(element);
	}

	/**
	 * Removes an element
	 * @param element
	 */
	public void removeElement(BaseElement element){

		elements.remove(element);

		//if the element has gotr audio , then we have to
		// to update the content type by going through all the elements
		//We don't have to consider MOVIE and Flash as it is not possible to
		//delete elements from a page having movie/flash

		if(elements.size()<=0 || element.hasMedia())
			contentType = CONTENT_UNDEFINED;

	}

	/**
	 * Adds an annotation to the page
	 * @param element
	 */
	public void addAnnotation(Annotation element) {

		annotations.add(element);
	}

	/**
	 * Removes an annotation from the page
	 * @param element
	 */
	public void removeAnnotation(Annotation element) {

		annotations.remove(element);
	}

	/**
	 * Gets the list elements in this page
	 * @return
	 */
	public List<BaseElement> getElements(){

		return elements;
	}

	/**
	 * Gets the list elements in this page
	 * @return
	 */
	public List<Annotation> getAnnotations(){

		return annotations;
	}

	/**
	 * Gets the list of links in the page
	 * @return
	 */
	public List<Link>  getLinks(){

		ArrayList<Link> links = new ArrayList<Link>();

		for (BaseElement element : elements) {

			if(element instanceof Linkable  ){

				List<Link> elementLinks = ((Linkable)element).getLinks();
				if(elementLinks!=null)
					links.addAll(elementLinks);
			}
		}

		return links;
	}

	/**
	 * Sets background colour
	 * @param colour
	 */
	public void setBackgroundColour(Color colour){

		this.bgColour = colour;
	}
	/**
	 * Sets the background image
	 * @param colour
	 */
	public void setBackgroundImage(ImageElement image, int posture){

		this.bgImage = image;
		bgImage.setLocked(true);
		bgImagePosture = posture;
	}

	/**
	 * Gets background colour
	 * @param colour
	 */
	public Color getBackgroundColour(){

		return this.bgColour;
	}
	/**
	 * Gets the background image
	 * @param colour
	 */
	public ImageElement getBackgroundImage(){

		return this.bgImage;
	}

	/**
	 * Sets the background image posture
	 * @param colour
	 */
	public int getBackgroundImagePosture(){

		return this.bgImagePosture;
	}

	/**
	 * Clears all annotation in this page
	 */
	public void clearAnnotations() {

		annotations.clear();
	}

	private void findContentType(){

		//if the content type is not yet defined. go through the elements to find the type
		if(contentType==CONTENT_UNDEFINED)
		{
			for (BaseElement element : elements) {

				if(element.hasMedia())
					contentType = contentType | CONTENT_AUDIO;

			 	if(element instanceof MovieElement)
			 		contentType = contentType | CONTENT_MOVIE;

	    		else if(element instanceof FlashElement)
	    			contentType = contentType | CONTENT_FLASH;
	    		else
	    			contentType = contentType | CONTENT_NORMAL;
	    	}
		}
	}

	/**
	 * Gets whether current page has movie/audio element
	 * @return
	 */
	public boolean hasMedia(){

		findContentType();
		return (contentType & CONTENT_MOVIE) ==CONTENT_MOVIE || (contentType & CONTENT_AUDIO) ==CONTENT_AUDIO;
	}

	/**
	 * Gets whether current page has movie or flash element
	 * @return
	 */
	public boolean hasMediaElement(){

		findContentType();
    	return (contentType & CONTENT_MOVIE) ==CONTENT_MOVIE  || (contentType & CONTENT_FLASH) ==CONTENT_FLASH;
	}

	/**
	 * Gets whether current page has flash element
	 * @return
	 */
	public boolean hasFlash(){

		findContentType();
    	return (contentType & CONTENT_FLASH) ==CONTENT_FLASH;
	}

	/**
	 * Gets whether the page has got selectable items
	 * @return
	 */
	public boolean hasSelectableItem(){

		findContentType();
		//Selection is enabled in folloing cases
		//1-Annotation exists
		//2- The page has got ordinary elements at the same time doesn't have any flash/video
		return  annotations.size()>0 || (contentType!=CONTENT_UNDEFINED && !hasMediaElement());
	}

	/**
	 * Play each media element in this page
	 */
	public void resumeMedia() {

    	for (BaseElement element : elements) {

    		element.resume();
    	}
	}

	/**
	 * Stop each media element in this page
	 */
	/*public void stopMedia(boolean close) {

    	for (BaseElement element : elements) {
    		element.stop(close);
    	}
	}*/

	/**
	 * Pause each media element in this page
	 */
	public void pauseMedia() {

    	for (BaseElement element : elements) {
    		element.pause();
    	}
	}

	/**
	 * Set mute for each media element in this page
	 * @param enable
	 */
    public void setMute(boolean enable){

    	for (BaseElement element : elements) {
    		element.setMute(enable);
    	}
    }

    /**
     * Set volume for each media element in this page
     * @param volume
     */
    public void setVolume( int volume){

    	for (BaseElement element : elements) {

    		element.setVolume(volume);
    	}
    }

	/**
	 * Clones current page
	 */
	@Override
	protected Page clone(){

		Page clone = new Page();

		ArrayList<BaseElement> clonedElements = new ArrayList<BaseElement>(elements.size());

		//create clone of elements
		for (BaseElement element : elements) {

			BaseElement ce =  element.clone();
			ce.setGroup(null);
			clonedElements.add(ce);
		}

		for (int i = 0; i < elements.size(); i++) {

			Group group = elements.get(i).getGroup();
			if( group!=null && clonedElements.get(i).getGroup()==null){
				Group cgroup = new Group(group.size());
				for (BaseElement baseElement : group) {
					for (BaseElement cElement : clonedElements) {
						if(baseElement.getIdentifier()==cElement.getIdentifier()){
							cgroup.add(cElement);
							cElement.setGroup(cgroup);
							break;
						}
					}
				}
			}
		}

		clone.elements = clonedElements;
		clone.bgImage = this.bgImage;
		clone.bgColour = this.bgColour;
		clone.bgImagePosture = this.bgImagePosture;
		clone.id = this.id;
		clone.revealer = this.revealer;
		return clone;
	}
}