text:
package psidev.psi.mi.jami.utils.comparator.interactor;

import org.junit.Assert;
import org.junit.Test;
import psidev.psi.mi.jami.model.InteractorPool;
import psidev.psi.mi.jami.model.impl.DefaultInteractorPool;
import psidev.psi.mi.jami.model.impl.DefaultProtein;
import psidev.psi.mi.jami.utils.XrefUtils;

/**
 * Unit tester of UnambiguousExactInteractorPoolComparator
 *
 * @author Marine Dumousseau (marine@ebi.ac.uk)
 * @version $Id$
 * @since
29/05/13

 */

public class UnambiguousExactInteractorSetComparatorTest {

    private UnambiguousExactInteractorPoolComparator comparator = new UnambiguousExactInteractorPoolComparator();

    @Test
    public void test_interactor_set_null_after(){
        InteractorPool interactor1 = null;
        InteractorPool interactor2 = new DefaultInteractorPool("test");

        Assert.assertTrue(comparator.compare(interactor1, interactor2) > 0);
        Assert.assertTrue(comparator.compare(interactor2, interactor1) < 0);

        Assert.assertFalse(UnambiguousExactInteractorPoolComparator.areEquals(interactor1, interactor2));
    }

    @Test
    public void test_interactor_set_different_identifier(){
        InteractorPool interactor1 = new DefaultInteractorPool("test");
        interactor1.getIdentifiers().add(XrefUtils.createIdentityXref("intact", "EBI-xxx1"));
        InteractorPool interactor2 = new DefaultInteractorPool("test");
        interactor2.getIdentifiers().add(XrefUtils.createIdentityXref("intact", "EBI-xxx2"));

        Assert.assertTrue(comparator.compare(interactor1, interactor2) < 0);
        Assert.assertTrue(comparator.compare(interactor2, interactor1) > 0);

        Assert.assertFalse(UnambiguousExactInteractorPoolComparator.areEquals(interactor1, interactor2));
    }

    @Test
    public void test_interactor_different_content(){
        InteractorPool interactor1 = new DefaultInteractorPool("test");
        interactor1.getIdentifiers().add(XrefUtils.createIdentityXref("intact", "EBI-xxx1"));
        interactor1.add(new DefaultProtein("test2", "P12345"));
        interactor1.add(new DefaultProtein("test3", "P12346"));
        InteractorPool interactor2 = new DefaultInteractorPool("test");
        interactor2.getIdentifiers().add(XrefUtils.createIdentityXref("intact", "EBI-xxx1"));
        interactor2.add(new DefaultProtein("test4", "P12347"));
        interactor2.add(new DefaultProtein("test5", "P12348"));

        Assert.assertTrue(comparator.compare(interactor1, interactor2) < 0);
        Assert.assertTrue(comparator.compare(interactor2, interactor1) > 0);

        Assert.assertFalse(UnambiguousExactInteractorPoolComparator.areEquals(interactor1, interactor2));
    }

    @Test
    public void test_interactor_same_content(){
        InteractorPool interactor1 = new DefaultInteractorPool("test");
        interactor1.getIdentifiers().add(XrefUtils.createIdentityXref("intact", "EBI-xxx1"));
        interactor1.add(new DefaultProtein("test2", "P12345"));
        interactor1.add(new DefaultProtein("test3", "P12346"));
        InteractorPool interactor2 = new DefaultInteractorPool("test");
        interactor2.getIdentifiers().add(XrefUtils.createIdentityXref("intact", "EBI-xxx1"));
        interactor2.add(new DefaultProtein("test2", "P12345"));
        interactor2.add(new DefaultProtein("test3", "P12346"));

        Assert.assertTrue(comparator.compare(interactor1, interactor2) == 0);
        Assert.assertTrue(comparator.compare(interactor2, interactor1) == 0);

        Assert.assertTrue(UnambiguousExactInteractorPoolComparator.areEquals(interactor1, interactor2));
    }

    @Test
    public void test_interactor_same_content_ignore_order(){
        InteractorPool interactor1 = new DefaultInteractorPool("test");
        interactor1.getIdentifiers().add(XrefUtils.createIdentityXref("intact", "EBI-xxx1"));
        interactor1.add(new DefaultProtein("test3", "P12346"));
        interactor1.add(new DefaultProtein("test2", "P12345"));
        InteractorPool interactor2 = new DefaultInteractorPool("test");
        interactor2.getIdentifiers().add(XrefUtils.createIdentityXref("intact", "EBI-xxx1"));
        interactor2.add(new DefaultProtein("test2", "P12345"));
        interactor2.add(new DefaultProtein("test3", "P12346"));

        Assert.assertTrue(comparator.compare(interactor1, interactor2) == 0);
        Assert.assertTrue(comparator.compare(interactor2, interactor1) == 0);

        Assert.assertTrue(UnambiguousExactInteractorPoolComparator.areEquals(interactor1, interactor2));
    }
}


text:
package org.gradle.api.plugins.internal;

import groovy.lang.Closure;
import org.gradle.api.Action;
import org.gradle.api.JavaVersion;
import org.gradle.api.internal.file.FileLookup;
import org.gradle.api.internal.project.ProjectInternal;
import org.gradle.api.internal.tasks.DefaultSourceSetContainer;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.java.archives.internal.DefaultManifest;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.reflect.HasPublicType;
import org.gradle.api.reflect.TypeOf;
import org.gradle.api.reporting.ReportingExtension;
import org.gradle.api.tasks.SourceSetContainer;
import org.gradle.internal.Actions;
import org.gradle.testing.base.plugins.TestingBasePlugin;

import java.io.File;

import static org.gradle.api.reflect.TypeOf.typeOf;
import static org.gradle.util.ConfigureUtil.configure;

public class DefaultJavaPluginConvention extends JavaPluginConvention implements HasPublicType {
    private ProjectInternal project;

    private String docsDirName;

    private String testResultsDirName;

    private String testReportDirName;

    private final SourceSetContainer sourceSets;

    private JavaVersion srcCompat;
    private JavaVersion targetCompat;

    private boolean autoTargetJvm = true;

    public DefaultJavaPluginConvention(ProjectInternal project, ObjectFactory objectFactory) {
        this.project = project;
        sourceSets = objectFactory.newInstance(DefaultSourceSetContainer.class);
        docsDirName = "docs";
        testResultsDirName = TestingBasePlugin.TEST_RESULTS_DIR_NAME;
        testReportDirName = TestingBasePlugin.TESTS_DIR_NAME;
    }

    @Override
    public TypeOf<?> getPublicType() {
        return typeOf(JavaPluginConvention.class);
    }

    @Override
    public Object sourceSets(Closure closure) {
        return sourceSets.configure(closure);
    }

    @Override
    public File getDocsDir() {
        return project.getServices().get(FileLookup.class).getFileResolver(project.getBuildDir()).resolve(docsDirName);
    }

    @Override
    public File getTestResultsDir() {
        return project.getServices().get(FileLookup.class).getFileResolver(project.getBuildDir()).resolve(testResultsDirName);
    }

    @Override
    public File getTestReportDir() {
        return project.getServices().get(FileLookup.class).getFileResolver(getReportsDir()).resolve(testReportDirName);
    }

    private File getReportsDir() {
        return project.getExtensions().getByType(ReportingExtension.class).getBaseDir();
    }

    @Override
    public JavaVersion getSourceCompatibility() {
        return srcCompat != null ? srcCompat : JavaVersion.current();
    }

    @Override
    public void setSourceCompatibility(Object value) {
        setSourceCompatibility(JavaVersion.toVersion(value));
    }

    @Override
    public void setSourceCompatibility(JavaVersion value) {
        srcCompat = value;
    }

    @Override
    public JavaVersion getTargetCompatibility() {
        return targetCompat != null ? targetCompat : getSourceCompatibility();
    }

    @Override
    public void setTargetCompatibility(Object value) {
        setTargetCompatibility(JavaVersion.toVersion(value));
    }

    @Override
    public void setTargetCompatibility(JavaVersion value) {
        targetCompat = value;
    }

    @Override
    public Manifest manifest() {
        return manifest(Actions.<Manifest>doNothing());
    }

    @Override
    public Manifest manifest(Closure closure) {
        return configure(closure, createManifest());
    }

    @Override
    public Manifest manifest(Action<? super Manifest> action) {
        Manifest manifest = createManifest();
        action.execute(manifest);
        return manifest;
    }

    private Manifest createManifest() {
        return new DefaultManifest(project.getFileResolver());
    }

    @Override
    public String getDocsDirName() {
        return docsDirName;
    }

    @Override
    public void setDocsDirName(String docsDirName) {
        this.docsDirName = docsDirName;
    }

    @Override
    public String getTestResultsDirName() {
        return testResultsDirName;
    }

    @Override
    public void setTestResultsDirName(String testResultsDirName) {
        this.testResultsDirName = testResultsDirName;
    }

    @Override
    public String getTestReportDirName() {
        return testReportDirName;
    }

    @Override
    public void setTestReportDirName(String testReportDirName) {
        this.testReportDirName = testReportDirName;
    }

    @Override
    public SourceSetContainer getSourceSets() {
        return sourceSets;
    }

    @Override
    public ProjectInternal getProject() {
        return project;
    }

    @Override
    public void disableAutoTargetJvm() {
        this.autoTargetJvm = false;
    }

    @Override
    public boolean getAutoTargetJvmDisabled() {
        return !autoTargetJvm;
    }
}

redpajama_set_name: RedPajamaGithub


text:
ALTER TABLE ownerResetHexes RENAME TO resetHexes;

ALTER TABLE resetHexes RENAME ownerHex TO hex;

ALTER TABLE resetHexes
  ADD entity TEXT NOT NULL DEFAULT 'owner';


text:
from django.core.management.base import BaseCommand, CommandError
from course.models import Course, CourseVersion, QueryLog
from datetime import datetime
from datetime import time
from django.utils import timezone
import json
import pytz
import operator
import random

class Command(BaseCommand):
    help = 'Creates intial course versions'
    term_value = 201610

    date_min = datetime(year=2015, month=10, day=30)
    date_max = datetime(year=2015, month=11, day=15)
    pytz.timezone(timezone.get_default_timezone_name()).localize(date_min)
    pytz.timezone(timezone.get_default_timezone_name()).localize(date_max)

    def handle(self, *args, **options):
        courses = Course.objects.filter(term__value=self.term_value)
        versions = CourseVersion.objects.filter(
            term__value=self.term_value,
            time_created__gt=self.date_min,
            time_created__lt=self.date_max)
        self.find_seats(courses)
        self.find_types(courses)
        # self.find_subjects(courses)
        # self.compare_subjects(courses, Course.objects.filter(term__value=201600))
        # self.graph_seats_history(versions)
        # self.find_new_courses(courses, datetime.datetime(year=2015, month=8, day=24))
        # self.find_status(courses)
        # self.find_seats(courses.order_by('-seats')[:5])
        # self.graph_seats_time(courses, range(8, 21))
        # self.find_seats(courses.filter(instructor__rmp_score__isnull=False).order_by('-instructor__rmp_score')[:50])
        # self.find_new_courses(courses, datetime.datetime(year=2015, month=8, day=24, hour=5), datetime.datetime(year=2015, month=8, day=24, hour=15))
        #self.find_queries()

    def find_seats(self, courses):
        seats = 0
        max = 0
        max_course = None
        closed = 0
        self.stdout.write('Finding seats for ' + str(len(courses)) + ' courses')
        for course in courses:
            seats = seats + course.seats
            if course.seats == 0:
                closed += 1
            if course.seats > max:
                max = course.seats
                max_course = course
        self.stdout.write('Total: ' + str(seats))
        self.stdout.write('Average: ' + str(float(seats) / len(courses)))
        self.stdout.write('Max: ' + str(max) + ' (' + str(max_course) + ', ' + str(max_course.crn) + ')')
        self.stdout.write('Closed: ' + str(closed))

    def find_queries(self):
        queries = QueryLog.objects.filter(term__value=self.term_value)
        self.stdout.write('Searching ' + str(len(queries)) + ' queries')
        values = {}
        failed = []
        unique = []
        users = {}
        returned = 0
        fields = {}
        subjects = {}
        days = {}
        instructors = {}
        attributes = {}
        times = {}
        subj_total = 0
        instr_total = 0
        attr_total = 0
        for query in queries:
            if query.results == 0:
                failed.append(query.data)
                continue
            returned += query.results
            iden = query.user.email if query.user else 'none'
            users[iden] = users[iden] + 1 if iden in users else 1
            if query.data not in unique:
                unique.append(query.data)
            data = json.loads(query.data)
            if len(data) > 0:
                if len(data) == 1 and 'show_closed' in data:
                    continue
                for key, value in data.iteritems():
                    fields[key] = fields[key] + 1 if key in fields else 1
                    if key == 'course':
                        subj_total += 1
                        subject = value.split(" ")[0].upper()
                        subjects[subject] = subjects[subject] + 1 if subject in subjects else 1
                    if key == 'days':
                        days[value.upper()] = days[value.upper()] + 1 if value.upper() in days else 1
                    if key == 'instructor':
                        instr_total += 1
                        instructors[value.upper()] = instructors[value.upper()] + 1 if value.upper() in instructors else 1
                    if key == 'attribute':
                        attr_total += 1
                        attributes[value.upper()] = attributes[value.upper()] + 1 if value.upper() in attributes else 1
                    if key == 'start':
                        times[value] = times[value] + 1 if value in times else 1

        sorted_users = sorted(users.items(), key=operator.itemgetter(1))
        self.stdout.write('Total results: ' + str(returned))
        self.stdout.write('Unique searches ' + str(len(unique)) + ': ')
        self.stdout.write('Searches with results ' + str(len(queries) - len(failed)))
        #self.stdout.write('Users ' + str(len(users)) + ': ' + str(sorted_users))
        keys = []
        for key, value in fields.iteritems():
            obj = {'label': key, 'value': value}
            keys.append(obj)
        self.stdout.write('Keys: ' + json.dumps(keys))
        sorted_subjects = sorted(subjects.items(), key=operator.itemgetter(1))
        sorted_instructors = sorted(instructors.items(), key=operator.itemgetter(1))
        sorted_attributes = sorted(attributes.items(), key=operator.itemgetter(1))
        new_days = []
        for key, value in days.iteritems():
            obj = {'label': key, 'value': value}
            new_days.append(obj)
        new_times = []
        for key, value in times.iteritems():
            new_key = datetime.strptime(key, '%H:%M:%S').strftime('%I:%M %p')
            obj = {'label': new_key, 'value': value}
            new_times.append(obj)
        self.stdout.write('Subjects: ' + json.dumps(sorted_subjects) + '(' + str(subj_total) + ')')
        self.stdout.write('Days: ' + json.dumps(new_days))
        self.stdout.write('Times: ' + json.dumps(new_times))
        self.stdout.write('Instructors: ' + json.dumps(sorted_instructors) + '(' + str(instr_total) + ')')
        self.stdout.write('Attrs: ' + json.dumps(sorted_attributes) + '(' + str(attr_total) + ')')

    def find_types(self, courses):
        types = courses.order_by().values_list('ctype', flat=True).distinct()
        self.stdout.write('Finding courses for ' + str(len(types)) + ' types')
        values = []
        for t in types:
            courses = Course.objects.filter(term__value=self.term_value).filter(ctype=t)
            obj = {'label': t, 'value': len(courses)}
            values.append(obj)
        self.stdout.write(json.dumps(values))

    def find_subjects(self, courses):
        self.stdout.write('Finding subjects for ' + str(len(courses)) + ' courses')
        values = {}
        for course in courses:
            subject = course.course.split(' ')[0]
            values[subject] = values[subject] + 1 if subject in values else 1
        subjects = []
        for key, value in values.iteritems():
            obj = {'label': key, 'value': value}
            subjects.append(obj)
        self.stdout.write(json.dumps(subjects))
        return values

    def compare_subjects(self, courses1, courses2):
        values1 = self.find_subjects(courses1)
        values2 = self.find_subjects(courses2)
        missing1 = []
        missing2 = []
        diff = {}
        for key, value in values1.iteritems():
            if not key in values2:
                missing2.append(key)
            else:
                diff[key] = values1[key] - values2[key]
        for key, value in values2.iteritems():
            if not key in values1:
                missing1.append(key)
            else:
                diff[key] = values1[key] - values2[key]
        self.stdout.write('Missing in the first set: ' + json.dumps(missing1))
        self.stdout.write('Missing in the second set: ' + json.dumps(missing2))
        self.stdout.write('Diff: ' + json.dumps(diff))

    def graph_seats_time(self, courses, range):
        seats = []
        self.stdout.write('Creating graphs for ' + str(len(list(range))) + ' hours')
        for i in range:
            value = time(hour=i)
            values = courses.filter(meeting_times__start_time=value)
            if (len(values) > 0):
                avg = 0
                for course in values:
                    avg += course.seats
                avg = float(avg) / len(values)
                obj = {'label': value.strftime('%I %p'), 'value': '{0:.3g}'.format(avg)}
                seats.append(obj)
        self.stdout.write(json.dumps(seats))

    def graph_seats_history(self, courses):
        times = courses.datetimes('time_created', 'hour')
        seats = []
        self.stdout.write('Creating graphs for ' + str(len(times)) + ' versions')
        i = 0
        for time in times:
            i += 1
            self.stdout.write('-> Calculating seats for: ' + str(time))
            versions = CourseVersion.objects.filter(
                time_created__year=time.year,
                time_created__month=time.month,
                time_created__day=time.day,
                time_created__hour=time.hour)
            total = 0
            excluded_values = set([])
            for version in versions:
                value = version.field_list()['seats']
                total += value
                excluded_values.add(version.get_course().id)
            others = Course.objects.exclude(id__in=excluded_values)
            for other in others:
                latest = self.get_last_version(other, time)
                if latest:
                    value = latest.field_list()['seats']
                    total += value
            obj = {'x': str(int(time.strftime("%s")) * 1000), 'y': total}
            seats.append(obj)
            self.stdout.write('-> Seats: ' + str(total))
        self.stdout.write(json.dumps(seats))

    def find_status(self, courses):
        closed_list = []
        open_list = []
        self.stdout.write('Calculating statuses for ' + str(len(courses)) + ' courses')
        for course in courses:
            versions = CourseVersion.objects.find(course)
            closed = True
            open = True
            for version in versions:
                status = version.field_list()['status']
                if status == Course.CLOSED:
                    open = False
                if status == Course.OPEN:
                    closed = False
            if open:
                open_list.append(course)
            if closed:
                closed_list.append(course)
        self.stdout.write('-> Always closed: ' + str(len(closed_list)))
        self.find_subjects(closed_list)
        self.stdout.write('-> Always open: ' + str(len(open_list)))
        self.find_subjects(open_list)

    def find_new_courses(self, courses, after, before=None):
        after = pytz.utc.localize(after)
        if before:
            before = pytz.utc.localize(before)
        self.stdout.write('Finding courses added after ' + str(after) + ', before ' + str(before))
        new = []
        for course in courses:
            earliest = CourseVersion.objects.find(course).earliest('time_created')
            if earliest.time_created >= after:
                if before:
                    if earliest.time_created <= before:
                        new.append(course.id)
                else:
                    new.append(course.id)
        self.stdout.write('-> New courses: ' + str(len(new)))
        self.stdout.write(json.dumps(list(new)))
        self.find_types(Course.objects.filter(id__in=new))
        self.find_subjects(Course.objects.filter(id__in=new))

    def get_last_version(self, course, time):
        versions = CourseVersion.objects.filter(term=course.term, course_crn=course.crn, time_created__lt=time)
        if len(versions):
            return versions.latest('time_created')
        else:
            return None


text:
namespace Spritely.ReadModel.Sql.Test
{
    using System;
    using System.Collections.Generic;

    internal static class TestReadModelDatabaseExtensions
    {
        public static void AddOrUpdateModel(this TestReadModelDatabase testReadModelDatabase, TestModel model)
        {
            var command = new AddOrUpdateCommand<TestModel>
            {
                Model = model,
                ModelType = "TestModel"
            };

            var commandHandler = new AddOrUpdateCommandHandler<TestReadModelDatabase, TestModel>(testReadModelDatabase);

            commandHandler.Handle(command);
        }

        public static ICollection<TestModel> AddModelItems(
            this TestReadModelDatabase testReadModelDatabase,
            string namePrefix,
            int count = 3)
        {
            var testModels = new List<TestModel>();

            for (var i = 0; i < count; i++)
            {
                var model = new TestModel()
                {
                    Id = Guid.NewGuid(),
                    Name = namePrefix + i
                };

                testModels.Add(model);

                testReadModelDatabase.AddOrUpdateModel(model);
            }

            return testModels;
        }

        public static IReadOnlyCollection<TestModel> GetAllModelItems(this TestReadModelDatabase testReadModelDatabase)
        {
            var query = new GetAllQuery<TestModel>
            {
                ModelType = "TestModel"
            };

            var queryHandler = new GetAllQueryHandler<TestReadModelDatabase, TestModel>(testReadModelDatabase);

            var results = queryHandler.Handle(query);

            return results;
        }
    }
}


text:
use crate::max_cover::MaxCover;
use state_processing::per_block_processing::get_slashable_indices_modular;
use std::collections::{HashMap, HashSet};
use types::{AttesterSlashing, BeaconState, EthSpec};

#[derive(Debug, Clone)]
pub struct AttesterSlashingMaxCover<'a, T: EthSpec> {
    slashing: &'a AttesterSlashing<T>,
    effective_balances: HashMap<u64, u64>,
}

impl<'a, T: EthSpec> AttesterSlashingMaxCover<'a, T> {
    pub fn new(
        slashing: &'a AttesterSlashing<T>,
        proposer_slashing_indices: &HashSet<u64>,
        state: &BeaconState<T>,
    ) -> Option<Self> {
        let mut effective_balances: HashMap<u64, u64> = HashMap::new();
        let epoch = state.current_epoch();

        let slashable_validators =
            get_slashable_indices_modular(state, slashing, |index, validator| {
                validator.is_slashable_at(epoch) && !proposer_slashing_indices.contains(&index)
            })
            .ok()?;

        for vd in slashable_validators {
            let eff_balance = state.get_effective_balance(vd as usize).ok()?;
            effective_balances.insert(vd, eff_balance);
        }

        Some(Self {
            slashing,
            effective_balances,
        })
    }
}

impl<'a, T: EthSpec> MaxCover for AttesterSlashingMaxCover<'a, T> {
    /// The result type, of which we would eventually like a collection of maximal quality.
    type Object = AttesterSlashing<T>;
    type Intermediate = AttesterSlashing<T>;
    /// The type used to represent sets.
    type Set = HashMap<u64, u64>;

    fn intermediate(&self) -> &AttesterSlashing<T> {
        self.slashing
    }

    fn convert_to_object(slashing: &AttesterSlashing<T>) -> AttesterSlashing<T> {
        slashing.clone()
    }

    /// Get the set of elements covered.
    fn covering_set(&self) -> &HashMap<u64, u64> {
        &self.effective_balances
    }
    /// Update the set of items covered, for the inclusion of some object in the solution.
    fn update_covering_set(
        &mut self,
        _best_slashing: &AttesterSlashing<T>,
        covered_validator_indices: &HashMap<u64, u64>,
    ) {
        self.effective_balances
            .retain(|k, _| !covered_validator_indices.contains_key(k));
    }

    /// The quality of this item's covering set, usually its cardinality.
    fn score(&self) -> usize {
        self.effective_balances.values().sum::<u64>() as usize
    }
}


text:
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Toolkit.UI;
using System;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Esri.ArcGISRuntime.Toolkit.SampleApp.Samples.BasemapGallery
{
    public sealed partial class BasemapGalleryBehaviorSample : Page
    {
        public BasemapGalleryBehaviorSample()
        {
            InitializeComponent();
            MyMapView.Map = new Map(BasemapStyle.ArcGISImagery);
            MySceneView.Scene = new Scene(BasemapStyle.ArcGISImageryStandard);
            ViewStyleCombobox.Items.Add("List");
            ViewStyleCombobox.Items.Add("Grid");
            ViewStyleCombobox.SelectedIndex = 0;
        }

        private void ViewStyleCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (ViewStyleCombobox.SelectedIndex)
            {
                case 0:
                    Gallery.GalleryViewStyle = BasemapGalleryViewStyle.List;
                    break;
                case 1:
                    Gallery.GalleryViewStyle = BasemapGalleryViewStyle.Grid;
                    break;
            }
        }

        private async void Button_Load_Portal(object sender, RoutedEventArgs e)
        {
            try
            {
                Gallery.Portal = await Portal.ArcGISPortal.CreateAsync(new Uri("https://arcgisruntime.maps.arcgis.com/"));
            }
            catch (Exception)
            {

            }
        }

        private async void Button_Load_AGOL(object sender, RoutedEventArgs e)
        {
            try
            {
                Gallery.Portal = await Portal.ArcGISPortal.CreateAsync();
            }
            catch (Exception) { }
        }

        private void Button_Switch_To_Map(object sender, RoutedEventArgs e)
        {
            MySceneView.Visibility = Visibility.Collapsed;
            MyMapView.Visibility = Visibility.Visible;
            Gallery.GeoModel = MyMapView.Map;
        }

        private void Button_Switch_To_Scene(object sender, RoutedEventArgs e)
        {
            MyMapView.Visibility = Visibility.Collapsed;
            MySceneView.Visibility = Visibility.Visible;
            Gallery.GeoModel = MySceneView.Scene;
        }

        private void Button_Disconect_View(object sender, RoutedEventArgs e)
        {
            MySceneView.Visibility = Visibility.Collapsed;
            MyMapView.Visibility = Visibility.Collapsed;
            Gallery.GeoModel = null;
        }

        private async void Button_Add_Last(object sender, RoutedEventArgs e)
        {
            BasemapGalleryItem item = await BasemapGalleryItem.CreateAsync(new Basemap());
            item.Name = "With Thumbnail";
            item.Tooltip = Guid.NewGuid().ToString();
            item.Thumbnail = new ArcGISRuntime.UI.RuntimeImage(new Uri("https://www.esri.com/content/dam/esrisites/en-us/home/homepage-tile-arcgis-collaboration.jpg"));
            Gallery.AvailableBasemaps.Add(item);

            BasemapGalleryItem item2 = await BasemapGalleryItem.CreateAsync(new Basemap());
            item2.Name = "Without Thumbnail";
            Gallery.AvailableBasemaps.Add(item2);
        }

        private async void Button_Add_WGS84(object sender, RoutedEventArgs e)
        {
            BasemapGalleryItem item = await BasemapGalleryItem.CreateAsync(new Basemap(new Uri("https://www.arcgis.com/home/item.html?id=1396c369fa3b44a2a5437f18412f8032")));
            Gallery.AvailableBasemaps.Add(item);
        }

        private void Button_Remove_Last(object sender, RoutedEventArgs e)
        {
            if (Gallery.AvailableBasemaps.Any())
            {
                Gallery.AvailableBasemaps.Remove(Gallery.AvailableBasemaps.Last());
            }
        }

        private void Gallery_BasemapSelected(object sender, BasemapGalleryItem e)
        {
            LastSelectedDateLabel.Text = DateTime.Now.ToLongTimeString();
        }
    }
}


text:
#include "config.h"
#include "MockWebSpeechRecognizer.h"

#if ENABLE(SCRIPTED_SPEECH)

#include "Task.h"
#include "WebSpeechRecognitionResult.h"
#include "WebSpeechRecognizerClient.h"

using namespace WebKit;
using namespace WebTestRunner;

namespace {

// Task class for calling a client function that does not take any parameters.
typedef void (WebSpeechRecognizerClient::*ClientFunctionPointer)(const WebSpeechRecognitionHandle&);
class ClientCallTask : public MockWebSpeechRecognizer::Task {
public:
    ClientCallTask(MockWebSpeechRecognizer* mock, ClientFunctionPointer function)
        : MockWebSpeechRecognizer::Task(mock)
        , m_function(function)
    {
    }

    virtual void run() OVERRIDE { (m_recognizer->client()->*m_function)(m_recognizer->handle()); }

private:
    ClientFunctionPointer m_function;
};

// Task for delivering a result event.
class ResultTask : public MockWebSpeechRecognizer::Task {
public:
    ResultTask(MockWebSpeechRecognizer* mock, const WebString transcript, float confidence)
        : MockWebSpeechRecognizer::Task(mock)
        , m_transcript(transcript)
        , m_confidence(confidence)
    {
    }

    virtual void run() OVERRIDE
    {
        WebVector<WebString> transcripts(static_cast<size_t>(1));
        WebVector<float> confidences(static_cast<size_t>(1));
        transcripts[0] = m_transcript;
        confidences[0] = m_confidence;
        WebSpeechRecognitionResult res;
        res.assign(transcripts, confidences, true);

        m_recognizer->client()->didReceiveResult(m_recognizer->handle(), res, 0, WebVector<WebSpeechRecognitionResult>());
    }

private:
    WebString m_transcript;
    float m_confidence;
};

// Task for delivering a nomatch event.
class NoMatchTask : public MockWebSpeechRecognizer::Task {
public:
    NoMatchTask(MockWebSpeechRecognizer* mock) : MockWebSpeechRecognizer::Task(mock) { }
    virtual void run() OVERRIDE { m_recognizer->client()->didReceiveNoMatch(m_recognizer->handle(), WebSpeechRecognitionResult()); }
};

// Task for delivering an error event.
class ErrorTask : public MockWebSpeechRecognizer::Task {
public:
    ErrorTask(MockWebSpeechRecognizer* mock, int code, const WebString& message)
        : MockWebSpeechRecognizer::Task(mock)
        , m_code(code)
        , m_message(message)
    {
    }

    virtual void run() OVERRIDE { m_recognizer->client()->didReceiveError(m_recognizer->handle(), m_message, static_cast<WebSpeechRecognizerClient::ErrorCode>(m_code)); }

private:
    int m_code;
    WebString m_message;
};

} // namespace

PassOwnPtr<MockWebSpeechRecognizer> MockWebSpeechRecognizer::create()
{
    return adoptPtr(new MockWebSpeechRecognizer());
}

void MockWebSpeechRecognizer::start(const WebSpeechRecognitionHandle& handle, const WebSpeechRecognitionParams& params, WebSpeechRecognizerClient* client)
{
    m_wasAborted = false;
    m_handle = handle;
    m_client = client;

    m_taskQueue.append(adoptPtr(new ClientCallTask(this, &WebSpeechRecognizerClient::didStart)));
    m_taskQueue.append(adoptPtr(new ClientCallTask(this, &WebSpeechRecognizerClient::didStartAudio)));
    m_taskQueue.append(adoptPtr(new ClientCallTask(this, &WebSpeechRecognizerClient::didStartSound)));

    if (!m_mockTranscripts.isEmpty()) {
        ASSERT(m_mockTranscripts.size() == m_mockConfidences.size());

        for (size_t i = 0; i < m_mockTranscripts.size(); ++i)
            m_taskQueue.append(adoptPtr(new ResultTask(this, m_mockTranscripts[i], m_mockConfidences[i])));

        m_mockTranscripts.clear();
        m_mockConfidences.clear();
    } else
        m_taskQueue.append(adoptPtr(new NoMatchTask(this)));

    m_taskQueue.append(adoptPtr(new ClientCallTask(this, &WebSpeechRecognizerClient::didEndSound)));
    m_taskQueue.append(adoptPtr(new ClientCallTask(this, &WebSpeechRecognizerClient::didEndAudio)));
    m_taskQueue.append(adoptPtr(new ClientCallTask(this, &WebSpeechRecognizerClient::didEnd)));

    startTaskQueue();
}

void MockWebSpeechRecognizer::stop(const WebSpeechRecognitionHandle& handle, WebSpeechRecognizerClient* client)
{
    m_handle = handle;
    m_client = client;

    // FIXME: Implement.
    ASSERT_NOT_REACHED();
}

void MockWebSpeechRecognizer::abort(const WebSpeechRecognitionHandle& handle, WebSpeechRecognizerClient* client)
{
    m_handle = handle;
    m_client = client;

    clearTaskQueue();
    m_wasAborted = true;
    m_taskQueue.append(adoptPtr(new ClientCallTask(this, &WebSpeechRecognizerClient::didEnd)));
    startTaskQueue();
}

void MockWebSpeechRecognizer::addMockResult(const WebString& transcript, float confidence)
{
    m_mockTranscripts.append(transcript);
    m_mockConfidences.append(confidence);
}

void MockWebSpeechRecognizer::setError(int code, const WebString& message)
{
    clearTaskQueue();
    m_taskQueue.append(adoptPtr(new ErrorTask(this, code, message)));
    m_taskQueue.append(adoptPtr(new ClientCallTask(this, &WebSpeechRecognizerClient::didEnd)));
    startTaskQueue();
}

MockWebSpeechRecognizer::MockWebSpeechRecognizer()
    : m_wasAborted(false)
    , m_taskQueueRunning(false)
{
}

MockWebSpeechRecognizer::~MockWebSpeechRecognizer()
{
}

void MockWebSpeechRecognizer::startTaskQueue()
{
    if (m_taskQueueRunning)
        return;
    postTask(new StepTask(this));
    m_taskQueueRunning = true;
}

void MockWebSpeechRecognizer::clearTaskQueue()
{
    m_taskQueue.clear();
    m_taskQueueRunning = false;
}

void MockWebSpeechRecognizer::StepTask::runIfValid()
{
    if (m_object->m_taskQueue.isEmpty()) {
        m_object->m_taskQueueRunning = false;
        return;
    }

    OwnPtr<Task> task = m_object->m_taskQueue[0].release();
    m_object->m_taskQueue.remove(0);
    task->run();

    if (m_object->m_taskQueue.isEmpty()) {
        m_object->m_taskQueueRunning = false;
        return;
    }

    postTask(new StepTask(m_object));
}

#endif // ENABLE(SCRIPTED_SPEECH)


text:
<?php $this->load->view('layout/header_head'); ?>
<?php $this->load->view('layout/header_body_default'); ?>

            <?php $this->load->view('components/panels/sensors_temperature_chart'); ?>

            <?php $this->load->view('components/panels/sensors_humidity_chart'); ?>

<?php $this->load->view('layout/footer_default'); ?>
<?php $this->load->view('layout/footer_footer'); ?>


text:
Sketch 支持对 `开始`、`完成`、`失败`、`取消` 以及 `下载进度` 进行监听

注意:
* listener 默认在主线程回调,但是当 Sketch.load() 和 Sketch.download() 开启了同步后其 listener 就在运行线程回调,可能是主线程,也可能是非主线程
* onStarted() 方法只有在需要进入非主线程加载或下载图片时才会被回调,因此有可能不回调 onStarted() 方法而直接回调其它方法

#### SketchImageView

```java
SketchImageView sketchImageView = ...;

// setDisplayListener() 一定要在 displayImage() 之前
sketchImageView.setDisplayListener(new DisplayListener() {
    @Override
    public void onStarted() {
        // 只有在需要进入非主线程加载图片时才会回调 onStarted() 方法
    }

    @Override
    public void onCompleted(Drawable drawable, ImageFrom imageFrom, ImageAttrs imageAttrs) {

    }

    @Override
    public void onError(ErrorCause errorCause) {

    }

    @Override
    public void onCanceled(CancelCause cancelCause) {

    }
});

// setDownloadProgressListener() 一定要在 displayImage() 之前
sketchImageView.setDownloadProgressListener(new DownloadProgressListener() {
    @Override
    public void onUpdateDownloadProgress(int totalLength, int completedLength) {

    }
});

sketchImageView.displayImage("http://b.zol-img.com.cn/desk/bizhi/image/4/1366x768/1387347695254.jpg");
```

``Sketch.display() 不支持设置 listener 和 downloadProgressListener``

#### Sketch.load()

```java
Sketch.with(context).load("http://t.cn/RShdS1f", new LoadListener() {
    @Override
    public void onStarted() {
        // 只有在需要进入非主线程加载图片时才会回调 onStarted() 方法
    }

    @Override
    public void onCompleted(LoadResult loadResult) {

    }

    @Override
    public void onError(ErrorCause errorCause) {

    }

    @Override
    public void onCanceled(CancelCause cancelCause) {

    }
}).downloadProgressListener(new DownloadProgressListener() {
    @Override
    public void onUpdateDownloadProgress(int totalLength, int completedLength) {

    }
}).maxSize(100, 100).commit();
```

#### Sketch.download()

```java
Sketch.with(context).download("http://t.cn/RShdS1f", new DownloadListener() {
    @Override
    public void onStarted() {
        // 只有在需要进入非主线程下载图片时才会回调 onStarted() 方法
    }

    @Override
    public void onCompleted(DownloadResult downloadResult) {

    }

    @Override
    public void onError(ErrorCause errorCause) {

    }

    @Override
    public void onCanceled(CancelCause cancelCause) {

    }
}).downloadProgressListener(new DownloadProgressListener() {
    @Override
    public void onUpdateDownloadProgress(int totalLength, int completedLength) {

    }
}).commit();
```


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
     xmlns:app="http://schemas.android.com/apk/res/com.roboo.like.google"

    android:layout_height="match_parent" >

    <com.roboo.like.google.staggeredgrid.StaggeredGridView
        android:id="@+id/sgv_gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fastScrollAlwaysVisible="true"
        android:fastScrollEnabled="true"
        app:column_count="2"
        app:item_margin="8dp" />

</RelativeLayout>


text:
<?php
namespace Blogger\BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\File\File;

use Doctrine\ORM\Event\LifecycleEventArgs;

//use Symfony\Component\Validator\Constraints as Assert;

/**
 * Description of Image
 * @ORM\Entity(repositoryClass="Blogger\BlogBundle\Entity\Repository\ImageRepository")
 * @ORM\Table(name="images")
 * @ORM\HasLifecycleCallbacks
 */
class Image {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     */
    protected $id;

    //
    /**
     * @ORM\Column(type="string", length=100)
     *
     */
    protected $filename;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $updated;

    /**
     *
    * Unmapped property to handle file uploads
     *
    */
    private $file;

    //@ORM\OneToOne(targetEntity="Blog", inversedBy="imageBlog")
    // * @ORM\JoinColumn(name="blog_id", referencedColumnName="id")
    /**
     *
     */
    //private $blog;

    const SERVER_PATH_TO_IMAGE_FOLDER = __DIR__ . '/../../../../web/uploads/images';

    /**
     * @ORM\PrePersist
     * @ORM\PreUpdate
     *
     * Lifecycle callback to upload the file to the server
     */
    public function lifecycleFileUpload(LifecycleEventArgs $event) {

        $this->upload();

    }

    public function __toString()
    {
        return strval($this->getFilename());
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set filename
     *
     * @param string $filename
     *
     * @return Image
     */
    public function setFilename($filename)
    {
        $this->filename = $filename;

        return $this;
    }

    /**
     * Get filename
     *
     * @return string
     */
    public function getFilename()
    {
        return $this->filename;
    }

    /**
     * Set updated
     *
     * @param \DateTime $updated
     *
     * @return Image
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;

        return $this;
    }

    /**
     * Get updated
     *
     * @return \DateTime
     */
    public function getUpdated()
    {
        return $this->updated;
    }

    /**
    * Sets file.
    *
    * @param UploadedFile $file
    */
    public function setFile(UploadedFile $file = null){

       $this->file = $file;

       return $this;

    }

    /**
    * Get file.
    *
    * @return UploadedFile
    */
    public function getFile()
    {
        return $this->file;
    }

    /**
    * Manages the copying of the file to the relevant place on the server
    */
   public function upload()
   {
       // the file property can be empty if the field is not required
       if (null === $this->getFile()) {
           return;
       }

       // we use the original file name here but you should
       // sanitize it at least to avoid any security issues

       // move takes the target directory and target filename as params
       $this->getFile()->move(
           self::SERVER_PATH_TO_IMAGE_FOLDER,
           $this->getFile()->getClientOriginalName()
       );

       // set the path property to the filename where you've saved the file
       $this->filename = $this->getFile()->getClientOriginalName();

       // clean up the file property as you won't need it anymore
       $this->setFile(null);
   }

   /**
    * Updates the hash value to force the preUpdate and postUpdate events to fire
    */
   public function refreshUpdated()
   {
       $this->setUpdated(new \DateTime());
   }

    /**
     * Set blog
     *
     * @param \Blogger\BlogBundle\Entity\Blog $blog
     *
     * @return Image
     */
    public function setBlog(\Blogger\BlogBundle\Entity\Blog $blog = null)
    {
        $this->blog = $blog;

        return $this;
    }

    /**
     * Get blog
     *
     * @return \Blogger\BlogBundle\Entity\Blog
     */
    public function getBlog()
    {
        return $this->blog;
    }

    public static function getWebPath(){

        return '/uploads/images';

    }
}


text:
/* eslint-disable no-restricted-syntax, guard-for-in */
/* global DiscussionModel */

import Vue from 'vue';

window.CommentsStore = {
  state: {},
  get(discussionId, noteId) {
    return this.state[discussionId].getNote(noteId);
  },
  createDiscussion(discussionId, canResolve) {
    let discussion = this.state[discussionId];
    if (!this.state[discussionId]) {
      discussion = new DiscussionModel(discussionId);
      Vue.set(this.state, discussionId, discussion);
    }

    if (canResolve !== undefined) {
      discussion.canResolve = canResolve;
    }

    return discussion;
  },
  create(noteObj) {
    const discussion = this.createDiscussion(noteObj.discussionId);

    discussion.createNote(noteObj);
  },
  update(discussionId, noteId, resolved, resolvedBy) {
    const discussion = this.state[discussionId];
    const note = discussion.getNote(noteId);
    note.resolved = resolved;
    note.resolved_by = resolvedBy;
  },
  delete(discussionId, noteId) {
    const discussion = this.state[discussionId];
    discussion.deleteNote(noteId);

    if (discussion.notesCount() === 0) {
      Vue.delete(this.state, discussionId);
    }
  },
  unresolvedDiscussionIds() {
    const ids = [];

    for (const discussionId in this.state) {
      const discussion = this.state[discussionId];

      if (!discussion.isResolved()) {
        ids.push(discussion.id);
      }
    }

    return ids;
  },
};


text:
<?php

namespace CCTracing\CMSBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use CCTracing\CMSBundle\Form\Type\FuenteType;
use CCTracing\CMSBundle\Entity\Fuente;

class FuenteController extends Controller
{

    public function createAction()
    {
        $request = $this->getRequest();

		$fuente = new Fuente();

		$form = $this->createForm(new FuenteType(), $fuente);

		if ($request->getMethod() == 'POST') {
			$form->bind($request);

			if ($form->isValid()) {
				// realiza alguna acción, como enviar un correo electrónico

				print_r($form->getData());

				$em = $this->getDoctrine()->getManager();
				$em->persist($fuente);
				$em->flush();

				// Redirige - Esto es importante para prevenir que el fuente
				// reenvíe el formulario si actualiza la página
				return $this->redirect($this->generateUrl('CCTracing_CMS_Fuente_create'));
			}
		}

		return $this->render('CCTracingCMSBundle:Fuente:create.html.twig', array(
												'form' => $form->createView()
							));
    }

	public function listAction(){
		$repository = $this->getDoctrine()->getRepository('CCTracingCMSBundle:Fuente');
		$fuentes = $repository->findAll();

		return $this->render('CCTracingCMSBundle:Fuente:list.html.twig', array(
			'fuentes' => $fuentes
		));
	}

	/**
	 * @Template()
	 */

	public function campanasAction()
    {
        $marca_id = $this->getRequest()->request->get('marca_id');

		$em = $this->getDoctrine()->getManager();

        $campanas = $em->getRepository('CCTracingCMSBundle:Campana')->findByMarca($marca_id);

		return array(
            'campanas' => $campanas
        );
    }

	public function editAction($idfuente){

		$request = $this->getRequest();

		$em = $this->getDoctrine()->getManager();
		$fuente = $em->getRepository('CCTracingCMSBundle:Fuente')->find($idfuente);

		if (!$fuente) {
			throw $this->createNotFoundException(
				'No existe Marca para el id: '.$idfuente
			);
		}

		$form = $this->createForm(new FuenteType(), $fuente);

		//print_r($form["tipo"]->getData());die();

		if ($request->getMethod() == 'POST') {
			$form->bind($request);

			if ($form->isValid()) {
				// realiza alguna acción, como enviar un correo electrónico

				//$fuente->setFuente($form["fuente"]->getData());

				$em = $this->getDoctrine()->getManager();
				$em->persist($fuente);
				$em->flush();

				// Redirige - Esto es importante para prevenir que el usuario
				// reenvíe el formulario si actualiza la página
				return $this->redirect($this->generateUrl('CCTracing_CMS_Fuente_list'));
			}
		}

		return $this->render('CCTracingCMSBundle:Fuente:edit.html.twig', array(
																	'form' => $form->createView(),
																	'idfuente' => $idfuente
																));

	}

	public function deleteAction($idfuente){
		$em = $this->getDoctrine()->getEntityManager();
		$fuente = $em->getRepository('CCTracingCMSBundle:Fuente')->find($idfuente);

		if (!$fuente) {
			throw $this->createNotFoundException(
				'No existe Campaña para el id: '.$idfuente
			);
		}

		$em->remove($fuente);
		$em->flush();

		return $this->redirect($this->generateUrl('CCTracing_CMS_Fuente_list'));
	}
}


text:
'use strict';

const config = require('config').get('openSenseMap-API-models.db'),
  log = require('./log');

// Bring Mongoose into the app
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;

mongoose.set('debug', process.env.NODE_ENV !== 'production');

const getDBUri = function getDBUri (uri) {
  // if available, use user specified db connection uri
  if (uri) {
    return uri;
  }

  // get uri from config
  uri = config.get('mongo_uri');
  if (uri) {
    return uri;
  }

  // otherwise build uri from config supplied values
  const { user, userpass, host, port, db, authsource } = config;

  return `mongodb://${user}:${userpass}@${host}:${port}/${db}?authSource=${authsource}`;
};

const connect = function connect (uri) {
  uri = getDBUri(uri);

  mongoose.connection.on('connecting', function () {
    log.info('trying to connect to MongoDB...');
  });

  // Create the database connection
  return new Promise(function (resolve, reject) {
    mongoose
      .connect(uri, {
        useMongoClient: true,
        reconnectTries: Number.MAX_VALUE,
        promiseLibrary: global.Promise
      })
      .then(function () {
        // CONNECTION EVENTS

        // If the connection throws an error
        mongoose.connection.on('error', function (err) {
          log.error(err, 'Mongoose connection error');
          throw err;
        });

        // When the connection is disconnected
        mongoose.connection.on('disconnected', function () {
          log.warn('Mongoose connection disconnected. Retrying with mongo AutoReconnect.');
        });

        // When the connection is resconnected
        mongoose.connection.on('reconnected', function () {
          log.info('Mongoose connection reconnected.');
        });

        log.info('Successfully connected to MongoDB.');

        return resolve();
      })
      .catch(function (err) {
        // only called if the initial mongoose.connect fails on first connect
        if (err.message.startsWith('failed to connect to server')) {
          log.info(`Error ${err.message} - retrying manually in 1 second.`);
          mongoose.connection.removeAllListeners();

          return new Promise(function () {
            setTimeout(function () {
              resolve(connect());
            }, 1000);
          });
        }

        return reject(err);
      });
  });
};

module.exports = {
  connect,
  mongoose
};


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
using ECharts.Entities;
using ECharts.Entities.style;

namespace ECharts.Entities {
	public class Brush : Basic<Brush> {

		public IList<BrushToolBoxType> toolbox{
			get;
			set;
		}

		public object brushLink{
			get;
			set;
		}

		public object seriesIndex{
			get;
			set;
		}

		public object geoIndex{
			get;
			set;
		}

		public BrushType? brushType{
			get;
			set;
		}

		public BrushMode? brushMode{
			get;
			set;
		}

		public bool? transformable{
			get;
			set;
		}

		public BrushStyle brushStyle{
			get;
			set;
		}

		public BrushThrottleType? throttleType{
			get;
			set;
		}

		public int? throttleDelay{
			get;
			set;
		}

        public bool? removeOnClick { get; set; }

		public VisualItem inBrush{
			get;
			set;
		}

		public VisualItem outBrush{
			get;
			set;
		}

	    public BrushStyle BrushStyle()
	    {
	        if(this.brushStyle==null)
                this.brushStyle = new BrushStyle();
	        return this.brushStyle;
	    }

		///
		/// <param name="toolbox"></param>
		public Brush Toolbox(IList<BrushToolBoxType> toolbox){
		     this.toolbox=toolbox;
		return this;
		}

		///
		/// <param name="brushLink"></param>
		public Brush BrushLink(object brushLink){
		     this.brushLink=brushLink;
		return this;
		}

	    ///
		/// <param name="geoIndex"></param>
		public Brush GeoIndex(object geoIndex){
		     this.geoIndex=geoIndex;
		return this;
		}

		///
		/// <param name="brushType"></param>
		public Brush BrushType(BrushType brushType){
		     this.brushType=brushType;
		return this;
		}

	    ///
	    /// <param name="burshMode"></param>
        public Brush BrushMode(BrushMode brushMode)
	    {
	        this.brushMode = brushMode;
	        return this;
	    }

	    ///
        /// <param name="transformable"></param>
	    public Brush Transformable(bool transformable)
	    {
            this.transformable = transformable;
	        return this;
	    }

	    ///
		/// <param name="brushStyle"></param>
		public Brush BurshStyle(BrushStyle brushStyle){
		     this.brushStyle=brushStyle;
		return this;
		}

		///
		/// <param name="throttleType"></param>
		public Brush ThrottleType(BrushThrottleType throttleType){
		     this.throttleType=throttleType;
		return this;
		}

		///
		/// <param name="throttleDelay"></param>
		public Brush ThrottleDelay(int throttleDelay){
		     this.throttleDelay=throttleDelay;
		return this;
		}

		///
		/// <param name="removeOnClick"></param>
		public Brush RemoveOnClick(bool removeOnClick){
            this.removeOnClick = removeOnClick;
		return this;
		}

        public VisualItem InBrush()
        {
            if(this.inBrush==null)
                this.inBrush = new VisualItem();
		  return this.inBrush;
		}

        public VisualItem OutOfBrush()
        {
            if (this.outBrush == null)
                this.outBrush = new VisualItem();
            return this.outBrush;
		}

		///
		/// <param name="seriesIndex"></param>
		public Brush SeriesIndex(string seriesIndex){
		     this.seriesIndex=seriesIndex;
		return this;
		}

	    public Brush SeriesIndex(params int[] value)
	    {
	        this.seriesIndex = value.ToList();
	        return this;
	    }

		///
		/// <param name="seriesIndex"></param>
		public Brush SeriesIndex(int seriesIndex){
		     this.seriesIndex=seriesIndex;
		return this;
		}

	}//end Brush

}//end namespace Entities


text:
using System.ComponentModel.DataAnnotations;

namespace Grafika.Web.Models
{
    public class CheckUsernameModel
    {
        [Required]
        public string Username { get; set; }

        public string Email { get; set; }
    }
}


text:
package com.amazonaws.services.guardduty.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.guardduty.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * OrganizationKubernetesConfigurationResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class OrganizationKubernetesConfigurationResultJsonUnmarshaller implements
        Unmarshaller<OrganizationKubernetesConfigurationResult, JsonUnmarshallerContext> {

    public OrganizationKubernetesConfigurationResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        OrganizationKubernetesConfigurationResult organizationKubernetesConfigurationResult = new OrganizationKubernetesConfigurationResult();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("auditLogs", targetDepth)) {
                    context.nextToken();
                    organizationKubernetesConfigurationResult.setAuditLogs(OrganizationKubernetesAuditLogsConfigurationResultJsonUnmarshaller.getInstance()
                            .unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return organizationKubernetesConfigurationResult;
    }

    private static OrganizationKubernetesConfigurationResultJsonUnmarshaller instance;

    public static OrganizationKubernetesConfigurationResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new OrganizationKubernetesConfigurationResultJsonUnmarshaller();
        return instance;
    }
}


text:
void bam_likes_init();
void call_bam(chunkyT *chk,double **likes,int trim);
void bam_likes_destroy();


text:
package org.apache.crunch.io.avro;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.IOException;

import org.apache.avro.generic.GenericData.Record;
import org.apache.avro.mapred.AvroJob;
import org.apache.crunch.test.Person;
import org.apache.crunch.test.StringWrapper;
import org.apache.crunch.types.avro.AvroType;
import org.apache.crunch.types.avro.Avros;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Job;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class AvroFileSourceTest {

  private Job job;
  File tempFile;

  @Before
  public void setUp() throws IOException {
    job = new Job();
    tempFile = File.createTempFile("test", ".avr");
  }

  @After
  public void tearDown() {
    tempFile.delete();
  }

  @Test
  public void testConfigureJob_SpecificData() throws IOException {
    AvroType<Person> avroSpecificType = Avros.records(Person.class);
    AvroFileSource<Person> personFileSource = new AvroFileSource<Person>(new Path(tempFile.getAbsolutePath()),
        avroSpecificType);

    personFileSource.configureSource(job, -1);

    assertFalse(job.getConfiguration().getBoolean(AvroJob.INPUT_IS_REFLECT, true));
    assertEquals(Person.SCHEMA$.toString(), job.getConfiguration().get(AvroJob.INPUT_SCHEMA));
  }

  @Test
  public void testConfigureJob_GenericData() throws IOException {
    AvroType<Record> avroGenericType = Avros.generics(Person.SCHEMA$);
    AvroFileSource<Record> personFileSource = new AvroFileSource<Record>(new Path(tempFile.getAbsolutePath()),
        avroGenericType);

    personFileSource.configureSource(job, -1);

    assertFalse(job.getConfiguration().getBoolean(AvroJob.INPUT_IS_REFLECT, true));

  }

  @Test
  public void testConfigureJob_ReflectData() throws IOException {
    AvroType<StringWrapper> avroReflectType = Avros.reflects(StringWrapper.class);
    AvroFileSource<StringWrapper> personFileSource = new AvroFileSource<StringWrapper>(new Path(
        tempFile.getAbsolutePath()), avroReflectType);

    personFileSource.configureSource(job, -1);

    assertTrue(job.getConfiguration().getBoolean(AvroJob.INPUT_IS_REFLECT, false));

  }

}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" href="css/leaflet.css">
    <link rel="stylesheet" href="css/stylesheet.css">


text:
function y = midi2audioTrackByTrack(input,Fs,synthtype,instrTrack,limitSamples)
% y = midi2audio(input, Fs, synthtype,instrTrack,limitSamples)
% y = midi2audio(input, Fs, synthtype,instrTrack)
% y = midi2audio(input, Fs, synthtype)
% y = midi2audio(input, Fs)
% y = midi2audio(input)
%
% Convert midi structure to a digital waveform
%
% Inputs:
%  input - can be one of:
%    a structure: matlab midi structure (created by readmidi.m)
%    a string: a midi filename
%    other: a 'Notes' matrix (as ouput by midiInfo.m)
%
%  synthtype - string to choose synthesis method
%      passed to synth function in synth.m
%      current choices are: 'fm', 'sine' or 'saw'
%      default='fm'
%
%  Fs - sampling frequency in Hz (beware of aliasing!)
%       default =  44.1e3
%
%  instrTrack - cell array of string. These string are the name of the
%       instrument to synthesize for each track. (see instrumentNames.mat a list of the supported instruments)
%
%  limitSamples - an array where the first element is the index of the
%       first sample to synthesize, and the second the one of the last sample.

% Copyright (c) 2009 Ken Schutte
% more info at: http://www.kenschutte.com/midi

if (nargin<2)
  Fs=44.1e3;
end
if (nargin<3)
  synthtype='fm';
end
if (nargin<4 &&  synthtype == 'multi')
    error('need fourth argument for multi synthtype')
end
if (nargin<5)
    limitSamples = [1,inf];
end

endtime = -1;
if (isstruct(input))
  [Notes,endtime] = midiInfo(input,0);
elseif (ischar(input))
  [Notes,endtime] = midiInfo(readmidi(input), 0);
else
  Notes = input;
end

% t2 = 6th col
if (endtime == -1)
  endtime = max(Notes(:,6));
end
if (length(endtime)>1)
  endtime = max(endtime);
end

maxTracks = max(Notes(:,1));

y = cell(maxTracks,1);

for k = 1:maxTracks
    y{k} = zeros(ceil(endtime*Fs),1);
end

failureCount = 0;
failedInstruments = {};

for i=1:size(Notes,1)

    if Notes(i,5)*Fs+1>=limitSamples(1)&&Notes(i,5)*Fs+1<=limitSamples(2)
        f = midi2freq(Notes(i,3));
        dur = Notes(i,6) - Notes(i,5);
        velocity = Notes(i,4);
        amp = velocity/127;

        if strcmp(synthtype,'multi')
            [yt synthOK] = synth(f, dur, amp, Fs, instrTrack{Notes(i,1)});
            if ~synthOK
               failureCount = failureCount + 1;
               failedInstruments{end+1} = instrTrack{Notes(i,1)};
            end
        else
            yt = synth(f, dur, amp, Fs, synthtype);
        end

        n1 = floor(Notes(i,5)*Fs)+1;
        N = length(yt);

        % ensure yt is [N,1]:
        y{Notes(i,1)}(n1:n1+N-1) = y{Notes(i,1)}(n1:n1+N-1) + reshape(yt,[],1);
    end
end

for k = 1:maxTracks
    if sum(abs(y{k}))==0
        y{k} = [];
    end
end

disp(' ')
disp([int2str(failureCount) ' notes were not synthesized.']);
if failureCount
    disp('Following instruments failed for at least one note: ');
    failedInstruments = unique(failedInstruments);
    for k = 1:length(failedInstruments)
        disp([ ' - ' failedInstruments{k}])
    end
    disp(' ')
end


text:
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.Logging.Type {

  /// Holder for reflection information generated from google/logging/type/log_severity.proto
  public static partial class LogSeverityReflection {

    #region Descriptor
    /// File descriptor for google/logging/type/log_severity.proto
    public static pbr::FileDescriptor Descriptor {
      get { return descriptor; }
    }
    private static pbr::FileDescriptor descriptor;

    static LogSeverityReflection() {
      byte[] descriptorData = global::System.Convert.FromBase64String(
          string.Concat(
            "CiZnb29nbGUvbG9nZ2luZy90eXBlL2xvZ19zZXZlcml0eS5wcm90bxITZ29v",
            "Z2xlLmxvZ2dpbmcudHlwZRocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90",
            "byqCAQoLTG9nU2V2ZXJpdHkSCwoHREVGQVVMVBAAEgkKBURFQlVHEGQSCQoE",
            "SU5GTxDIARILCgZOT1RJQ0UQrAISDAoHV0FSTklORxCQAxIKCgVFUlJPUhD0",
            "AxINCghDUklUSUNBTBDYBBIKCgVBTEVSVBC8BRIOCglFTUVSR0VOQ1kQoAZC",
            "gwEKF2NvbS5nb29nbGUubG9nZ2luZy50eXBlQhBMb2dTZXZlcml0eVByb3Rv",
            "UAFaOGdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvbG9n",
            "Z2luZy90eXBlO2x0eXBlqgIZR29vZ2xlLkNsb3VkLkxvZ2dpbmcuVHlwZWIG",
            "cHJvdG8z"));
      descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
          new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
          new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Cloud.Logging.Type.LogSeverity), }, null));
    }
    #endregion

  }
  #region Enums
  ///
  ///  The severity of the event described in a log entry, expressed as one of the
  ///  standard severity levels listed below.  For your reference, the levels are
  ///  assigned the listed numeric values. The effect of using numeric values other
  ///  than those listed is undefined.
  ///
  ///  You can filter for log entries by severity.  For example, the following
  ///  filter expression will match log entries with severities `INFO`, `NOTICE`,
  ///  and `WARNING`:
  ///
  ///      severity > DEBUG AND severity <= WARNING
  ///
  ///  If you are writing log entries, you should map other severity encodings to
  ///  one of these standard levels. For example, you might map all of Java's FINE,
  ///  FINER, and FINEST levels to `LogSeverity.DEBUG`. You can preserve the
  ///  original severity level in the log entry payload if you wish.
  ///
  public enum LogSeverity {
    ///
    ///  (0) The log entry has no assigned severity level.
    ///
    [pbr::OriginalName("DEFAULT")] Default = 0,
    ///
    ///  (100) Debug or trace information.
    ///
    [pbr::OriginalName("DEBUG")] Debug = 100,
    ///
    ///  (200) Routine information, such as ongoing status or performance.
    ///
    [pbr::OriginalName("INFO")] Info = 200,
    ///
    ///  (300) Normal but significant events, such as start up, shut down, or
    ///  a configuration change.
    ///
    [pbr::OriginalName("NOTICE")] Notice = 300,
    ///
    ///  (400) Warning events might cause problems.
    ///
    [pbr::OriginalName("WARNING")] Warning = 400,
    ///
    ///  (500) Error events are likely to cause problems.
    ///
    [pbr::OriginalName("ERROR")] Error = 500,
    ///
    ///  (600) Critical events cause more severe problems or outages.
    ///
    [pbr::OriginalName("CRITICAL")] Critical = 600,
    ///
    ///  (700) A person must take an action immediately.
    ///
    [pbr::OriginalName("ALERT")] Alert = 700,
    ///
    ///  (800) One or more systems are unusable.
    ///
    [pbr::OriginalName("EMERGENCY")] Emergency = 800,
  }

  #endregion

}

#endregion Designer generated code


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using Acrolinx.Sdk.Sidebar.Util.Changetracking;
using Acrolinx.Sdk.Sidebar.Documents;
using Acrolinx.Sdk.Sidebar.Storage;
using System.IO;

namespace Acrolinx.Sdk.Sidebar.Tests
{
    [TestClass]
    public class AcrolinxStorageTest
    {
        [TestMethod]
        public void SetItemGetItemInitStorage()
        {
            RegistryAcrolinxStorage storage = RegistryAcrolinxStorage.Instance;

            storage.SetItem("acro.test.token1", "tokendata1");
            storage.SetItem("acro.test.token2", "tokendata2");

            var value = storage.GetItem("acro.test.token1");

            Assert.AreEqual(value, "tokendata1");

            value = storage.GetItem("acro.test.token2");

            Assert.AreEqual(value, "tokendata2");
        }

        [TestMethod]
        public void GetAllItems()
        {
            RegistryAcrolinxStorage storage = RegistryAcrolinxStorage.Instance;

            storage.SetItem("acro.test.token1", "tokendata1");
            storage.SetItem("acro.test.token2", "tokendata2");
            storage.SetItem("acro.test.token3", "tokendata3");
            storage.SetItem("acro.test.token4", "tokendata4");
            storage.SetItem("acro.test.token5", "tokendata5");

            var items = storage.GetAllItems();

            Assert.AreEqual(items.GetValue("acro.test.token1"), "tokendata1");
            Assert.AreEqual(items.GetValue("acro.test.token2"), "tokendata2");
            Assert.AreEqual(items.GetValue("acro.test.token3"), "tokendata3");
            Assert.AreEqual(items.GetValue("acro.test.token4"), "tokendata4");
            Assert.AreEqual(items.GetValue("acro.test.token5"), "tokendata5");
        }

        [TestMethod]
        public void GetItemFromHKLM()
        {
            RegistryAcrolinxStorage storage = RegistryAcrolinxStorage.Instance;

            var value = storage.GetItem("unknown");

            Assert.AreEqual(value, null);
        }

        [TestMethod]
        public void RemoveItem()
        {
            RegistryAcrolinxStorage storage = RegistryAcrolinxStorage.Instance;

            storage.SetItem("acro.test.token1", "tokendata1");
            storage.SetItem("acro.test.token2", "tokendata2");
            storage.RemoveItem("acro.test.token2");

            var value = storage.GetItem("acro.test.token2");

            Assert.AreEqual(value, null);

            value = storage.GetItem("acro.test.token1");

            Assert.AreEqual(value, "tokendata1");

        }

        [TestMethod]
        public void OverwriteAcrolinxStorage()
        {
            RegistryAcrolinxStorage storage = RegistryAcrolinxStorage.Instance;

            storage.SetItem("acro.test.token1", "tokendata1");
            storage.SetItem("acro.test.token1", "tokendata2");

            var value = storage.GetItem("acro.test.token1");

            Assert.AreEqual(value, "tokendata2");
        }

    }
}


text:
//This module is in charge of creating the application interface (menus, sidepanels, tabs, statusbar, etc)
var InterfaceModule = {

	init: function()
	{
		//create menubar
		LiteGUI.createMenubar();

		//fill menubar with sections
		LiteGUI.menubar.add("Project");
		LiteGUI.menubar.add("Edit");
		LiteGUI.menubar.add("View");
		LiteGUI.menubar.add("Node");
		LiteGUI.menubar.add("Scene");
		LiteGUI.menubar.add("Actions");

		//create a main container and split it in two (workarea: leftwork, sidebar)
		var mainarea = new LiteGUI.Area("mainarea",{content_id:"workarea", height: "calc(100% - 30px)", autoresize: true, inmediateResize: true});
		mainarea.split("horizontal",[null,300], true);
		this.mainarea = mainarea;
		//globalarea.getSection(1).add( mainarea );
		LiteGUI.add( mainarea );

		//var workarea_split = mainarea.getSection(0);
		//workarea_split.content.innerHTML = "

";

		this.createTabs();
		this.createSidePanel();

		//window.onbeforeunload = function() { return "You work will be lost."; };
	},

	createTabs: function()
	{
		var main_tabs = new LiteGUI.Tabs("worktabs", { width: "full", mode: "vertical" });
		this.mainarea.getSection(0).add( main_tabs );
		//document.getElementById("leftwork").appendChild( main_tabs.root );
		LiteGUI.main_tabs = main_tabs;
	},

	selectTab: function(name)
	{
		return LiteGUI.main_tabs.selectTab(name);
	},

	createLowerArea: function()
	{
		var visorarea = this.visorarea = new LiteGUI.Area("visorarea",{ autoresize: true, inmediateResize: true});
		//document.getElementById("leftwork").appendChild( visorarea.root );
		this.mainarea.getSection(0).add( visorarea );

		visorarea.split("vertical",[null,200], true);
		visorarea.getSection(0).content.innerHTML = "

";
		visorarea.getSection(1).content.innerHTML = "FOO";
	},

	createSidePanel: function()
	{
		this.side_panel_visibility = true;

		//test dock panel
		var docked = new LiteGUI.Panel("side_panel", {title:'side panel'});
		this.mainarea.getSection(1).add( docked );
		LiteGUI.sidepanel = docked;

		//close button
		var close_button = new LiteGUI.Button("X", function() { InterfaceModule.setSidePanelVisibility(); });
		close_button.root.style.float = "right";
		close_button.content.style.width = "20px";
		docked.header.appendChild( close_button.root );

		//split button
		var split_button = new LiteGUI.Button("-", function() { InterfaceModule.splitSidePanel(); });
		split_button.root.style.float = "right";
		split_button.content.style.width = "20px";
		docked.header.appendChild( split_button.root );

		//tabs
		var tabs_widget = new LiteGUI.Tabs("paneltabs", { size: "full" });
		tabs_widget.addTab("Scene Tree", {selected:true, id:"nodelist", size: "full", width: "100%"});
		tabs_widget.addTab("Inspector", { size: "full" });
		docked.add( tabs_widget );
		this.sidepaneltabs = tabs_widget;

		LiteGUI.menubar.add("Window/Sidepanel", { callback: function() { InterfaceModule.setSidePanelVisibility(); } });
		LiteGUI.menubar.add("Window/Animation panel", { callback: function() { InterfaceModule.setLowerPanelVisibility(); } });

		//LiteGUI.menubar.add("Window/show view app", { callback: function() { window.open("simple.html"); } });

		/*
		LiteGUI.menubar.add("Window/maximized", { checkbox: false, callback: function(v) {
			if(v.checkbox)
				LiteGUI.setWindowSize();
			else
				LiteGUI.setWindowSize(1000,600);
		}});
		*/
		LiteGUI.menubar.add("About", { callback: function() {
			LiteGUI.showMessage("
Application created by Javi Agenjo

GTI department of Universitat Pompeu Fabra

Github", {title:"About info"});
		}});

		//split in top-bottom for header and workarea
		var sidepanelarea = new LiteGUI.Area("sidepanelarea",{ autoresize: true, inmediateResize: true });
		sidepanelarea.split("vertical",["30%",null], true);
		sidepanelarea.hide();
		LiteGUI.sidepanel.splitarea = sidepanelarea;
		LiteGUI.sidepanel.add( sidepanelarea );

		//create scene tree
		this.scene_tree = new SceneTreeWidget("sidepanel-inspector");
		tabs_widget.getTab("Scene Tree").add( this.scene_tree );

		//create inspector
		this.inspector = new LiteGUI.Inspector("sidepanel-inspector", {name_width: "40%" });
		this.inspector.onchange = function()
		{
			RenderModule.requestFrame();
		}
		tabs_widget.getTab("Inspector").add( this.inspector );
		this.inspector.addInfo(null,"select something to see its attributes");
		EditorModule.inspector = this.inspector; //LEGACY

		//default
		tabs_widget.selectTab("Inspector");
		this.splitSidePanel();
	},

	splitSidePanel: function()
	{
		var tabs = this.sidepaneltabs;
		var sidepanelarea = LiteGUI.sidepanel.splitarea;

		var tree = this.scene_tree.root;
		var attr = this.inspector.root;

		if(!this.is_sidepanel_splitted)
		{
			tree.style.display = attr.style.display = "block";
			tree.style.height = attr.style.height = "100%";
			tabs.hide();
			sidepanelarea.show();

			sidepanelarea.getSection(0).add( tree );
			sidepanelarea.getSection(0).root.style.overflow = "auto";
			sidepanelarea.getSection(1).add( attr );
			sidepanelarea.getSection(1).root.style.overflow = "auto";
			this.is_sidepanel_splitted = true;
		}
		else
		{
			tabs.getTab("Scene Tree").content.appendChild( tree );
			tabs.getTab("Inspector").content.appendChild( attr );

			tabs.show();
			sidepanelarea.hide();

			this.is_sidepanel_splitted = false;
		}
	},

	/*
	inspectNode: function(node)
	{
	},
	*/

	//show side panel
	toggleInspectorTab: function()
	{
		var tabs = this.sidepaneltabs;
		var current = tabs.getCurrentTab();
		if(current[0] != "Inspector")
			tabs.selectTab("Inspector");
		else
			tabs.selectTab("Scene Tree");
	},

	getSidePanelVisibility: function(v)
	{
		return this.side_panel_visibility;
	},

	createSidebarOpener: function()
	{
		if(this.opensidepanel_button)
			return;

		var visor = document.getElementById("visor");
		if(!visor)
			return;

		var open_button = this.opensidepanel_button = document.createElement("button");
		open_button.className = "opensidepanel-button";
		open_button.innerHTML = "<";
		visor.appendChild( open_button );
		open_button.style.display = "none";
		open_button.addEventListener("click", function() { InterfaceModule.setSidePanelVisibility(true); });
	},

	setSidePanelVisibility: function(v)
	{
		if (v === undefined)
			v = !this.side_panel_visibility;

		if(!this.opensidepanel_button)
			this.createSidebarOpener();

		this.side_panel_visibility = v;
		if(v)
		{
			this.mainarea.showSection(1);
			if(this.opensidepanel_button)
				this.opensidepanel_button.style.display = "none";
		}
		else
		{
			this.mainarea.hideSection(1);
			if(this.opensidepanel_button)
				this.opensidepanel_button.style.display = "block";
		}
	},

	//created inside RenderModule
	setVisorArea: function( area )
	{
		this.visorarea = area;

		//add lower panel tabs
		var lower_tabs_widget = new LiteGUI.Tabs("lowerpaneltabs", { size: "full" });
		this.visorarea.getSection(1).add( lower_tabs_widget );
		this.lower_tabs_widget = lower_tabs_widget;

		//add close button
		var button = LiteGUI.createButton("close_lowerpanel","X", function(){
			InterfaceModule.setLowerPanelVisibility(false);
		});
		button.style.float = "right";
		button.style.minWidth = "20px";
		this.lower_tabs_widget.tabs_root.appendChild(button);
	},

	setLowerPanelVisibility: function(v)
	{
		if (v === undefined)
			v = !this.lower_panel_visibility;

		this.lower_panel_visibility = v;
		if(v)
			this.visorarea.showSection(1);
		else
			this.visorarea.hideSection(1);

		LiteGUI.trigger( this.visorarea.root, "visibility_change" );
	},
};

LiteGUI.registerModule( InterfaceModule );


text:
Term.where(expectation_type: 'CustomExpectation').pluck(:id).each do |id|
  term = Term.find(id)
  expectation = term.expectation
  next if expectation.blank?
  assignment = expectation.create_assignment!({
    parameters: {
      comparison: expectation.comparison,
      endpoint: expectation.endpoint,
      fields: expectation.fields,
      final_value: expectation.final_value,
      schedule_arguments: {
        hour: '*',
        minute: '0',
      }
    },
    end_at: [term.end_at, (term.created_at + 1)].max,
    start_at: term.created_at,
    status: term.status,
    term: term,
  })

  term.update_attributes!(expectation: assignment)
end

Term.where(expectation_type: 'EthereumOracle').pluck(:id).each do |id|
  term = Term.find(id)
  expectation = term.expectation
  assignment = expectation.create_assignment!({
    parameters: {
      endpoint: expectation.endpoint,
      fields: expectation.fields,
      schedule_arguments: {
        hour: '0',
        minute: '0',
      }
    },
    end_at: [term.end_at, (term.created_at + 1)].max,
    start_at: term.created_at,
    status: term.status,
    term: term,
  })

  term.update_attributes!(expectation: assignment)
end


text:
<?php
$language = array (
  'pages' => 'Documents col·laboratius',
  'pages:owner' => 'Documents col·laboratius: %s',
  'pages:friends' => 'Documents col·laboratius: Contactes',
  'pages:all' => 'Documents col·laboratius: Tots',
  'pages:add' => 'Crea un document',
  'pages:group' => 'Documents col·laboratius',
  'groups:enablepages' => 'Habilita la creació de documents col·laboratius',
  'pages:edit' => 'Edita aquest document',
  'pages:delete' => 'Esborra aquest document',
  'pages:history' => 'Històric',
  'pages:view' => 'Veure el document',
  'pages:revision' => 'Versió',
  'pages:current_revision' => 'Versió actual',
  'pages:revert' => 'Tornar a la darrera versió desada',
  'pages:navigation' => 'Navegació',
  'pages:new' => 'Un nou document col·laboratiu',
  'pages:notification' => 'En/Na %s ha creat el següent document col·laboratiu:

%s
%s

Si vols veure i fer comentaris al nou document, clica l\'enllaç següent:
%s',
  'item:object:page_top' => 'Documents principals',
  'item:object:page' => 'Documents col·laboratius',
  'pages:nogroup' => 'Aquesta comissió encara no ha creat cap document',
  'pages:more' => 'Més documents',
  'pages:none' => 'Encara no hi ha cap document',
  'pages:title' => 'Nom del document',
  'pages:description' => 'Contingut del document',
  'pages:tags' => 'Etiquetes',
  'pages:parent_guid' => 'Document principal',
  'pages:access_id' => 'Accés de lectura',
  'pages:write_access_id' => 'Accés d\'escriptura',
  'pages:noaccess' => 'Sense accés',
  'pages:cantedit' => 'No pots editar aquest document',
  'pages:saved' => 'Document desat',
  'pages:notsaved' => 'El document no s\'ha pogut desar',
  'pages:error:no_title' => 'Has d\'especificar un nom pel document',
  'pages:delete:success' => 'El document s\'ha esborrat correctament',
);
add_translation("ca", $language);


text:
require 'sinatra'
require 'net/http'
require 'json'

set :public_folder, "../dist"

KEY = ENV['KEY']
get "/baqi/" do
  uri = URI('https://api.breezometer.com/baqi/?' + request.query_string + "&key=#{KEY}")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  response = http.request(Net::HTTP::Get.new(uri.request_uri))

  data = JSON.parse(response.body)

  if data["data_valid"]
    return response.body
  else
    default = {
      "country_name"=> "",
      "breezometer_aqi"=> 0,
      "breezometer_color"=> "#FFFFFF",
      "breezometer_description"=> "Air Quality Report Not Found. Please try searching again.",
      "country_aqi"=> 0,
      "country_aqi_prefix"=> "",
      "country_color"=> "#FFFFFF",
      "country_description"=> "Air Quality Report Not Found",
      "data_valid"=> true,
      "key_valid"=> true,
      "random_recommendations"=> {
        "children"=> "",
        "sport"=> "",
        "health"=> "",
        "inside"=> "",
        "outside"=> ""
      },
      "dominant_pollutant_canonical_name"=> "No Air Quality Reports Found",
      "dominant_pollutant_description"=> "No details found. Please try searching again.",
      "dominant_pollutant_text"=> {
        "main"=> "",
        "effects"=> "",
        "causes"=> ""
      }
    }
    return JSON.generate(default)
  end

end

get "/" do
  send_file "#{__dir__}/../dist/index.html"
end

# get "/index_bundle.js" do
#   send_file "#{__dir__}/../dist/index_bundle.js"
# end


text:
/* TEMPLATES */
.sheet-rolltemplate-mold hr{
    padding: 0px;
    margin: 2px;
    border-style: dashed;
    border-width: 1px;
    border-color: black;
}
.sheet-rolltemplate-mold table {
    width: 189px;
    padding: 2px;
    border: 1px solid;
    background-color: #ffffff;
    background-image:url(https://lh3.googleusercontent.com/NC97QOTir3vtbsRfT_LJxW8sizpWqOCXOnkeZWB5P4oj=w640-h848-no);
    background-repeat:no-repeat;
    background-origin: border-box;
    background-size: cover;
}
.sheet-rolltemplate-mold th {
    color: rgb(126, 45, 64);
    padding-left: 5px;
    font-size: 1.5em;
    text-align: left;
    font-family: 'Courier New';
    font-variant: small-caps;
    font-weight: bold;
}
.sheet-rolltemplate-mold .sheet-subheader {
    color: #000;
    font-size: 1em;
    font-style: italic;
    text-align: right;
}
.sheet-rolltemplate-mold .sheet-arrow-right {
    border-top: 3px solid transparent;
    border-bottom: 3px solid transparent;
    border-left: 180px solid rgb(126, 45, 64);
}
.sheet-rolltemplate-mold .sheet-tcat {
    font-family: 'Courier New';
    font-size: 15px;
    font-weight: bold;
}
.sheet-rolltemplate-mold td {
    padding-left: 5px;
    font-size: 14px;
 }
.sheet-rolltemplate-mold .inlinerollresult  {
    background-color: rgba(255,255,255,0.9);
    border-width: 0px 0px 0px 1px;
    border-color: black;
    border-top-style: none;
    border-right-style: none;
    border-left-style: none;
    border-bottom-style: solid;
}
.sheet-rolltemplate-mold .inlinerollresult.fullcrit {
    color: #3FB315;
    border-width: 0px 0px 0px 1px;
    border-color: #3FB315;
    border-top-style: none;
    border-right-style: none;
    border-left-style: none;
    border-bottom-style: solid;
}
.sheet-rolltemplate-mold .inlinerollresult.fullfail {
    color: #B31515;
    border-width: 0px 0px 0px 1px;
    border-color: #B31515;
    border-top-style: none;
    border-right-style: none;
    border-left-style: none;
    border-bottom-style: solid;
}
.sheet-rolltemplate-mold .inlinerollresult.importantroll {
    color: #4A57ED;
    border-width: 0px 0px 0px 1px;
    border-color: #4A57ED;
    border-top-style: none;
    border-right-style: none;
    border-left-style: none;
    border-bottom-style: solid;
}
/* SHEET */
div,
textarea,
span{
    box-sizing: border-box;
    color: black;
    font-family: 'Courier New';
    font-size: 14px;
    font-weight: normal;
    border-radius: 0px;
    text-align:left;
}
div.sheet-bbox{
    width: 100%;
    padding: 4px;
    border-color: black;
    border-style: solid;
    border-width: 1px 1px 0px 1px;
}
input{
    box-sizing: border-box;
    color: #404040;
    background-color: transparent;
    padding-left: 0.3em;
    padding-right: 0.2em;
    padding-top: 0.2em;
    padding-bottom: 0.1em;
    margin: 0px;
    font-family: 'Patrick Hand';
    font-size: 16px;
    font-weight: normal;
    border-radius: 0px;
    text-align:left;
}
.charsheet button[type="roll"] {
    box-sizing: border-box;
    padding: 0px;
    margin: 0px;
    height: 26px;
    text-align: left;
    color:black;
    border: 2px solid rgba(255,255,255,0.5);
    border-radius: 12px;
    transition: border 2s;
}
.charsheet button[type="roll"]:hover{
    border: 2px black inset;
}
select{
    box-sizing: border-box;
    color: #404040;
    font-family: 'Patrick Hand';
    font-size: 16px;
    font-weight: normal;
    border-radius: 0px;
    text-align:left;
    background-color: transparent;
    padding: 0px;
    margin: 0px;
    height: 1.6em;
    line-height: 1.6em;
    max-height 1.6em;
    font-weight:normal;
    border-width: 0px 0px 1px 3px;
    border-color: black;
    border-top-style: none;
    border-right-style: none;
    border-left-style: none;
    border-bottom-style: dotted;
}
hr{
    padding: 0px;
    margin: 4px;
    border-style: solid;
    border-width: 1px;
    border-color: gray;
}
span{
    text-align: left;
    padding-left: 0.3em;
    padding-right: 0.2em;
    padding-top: 0.2em;
    padding-bottom: 0.1em;
}
textarea {
    resize: vertical;
    display: inline-block;
    text-align: left;
    background-color:rgba(255,255,255,0.9);
    padding-left: 0.3em;
    padding-right: 0.2em;
    padding-top: 0.2em;
    padding-bottom: 0.1em;
    margin: 0px;
    border-bottom-left-radius: 4px;
}
.sheet-mainBg{
    background-image:url(https://lh3.googleusercontent.com/NC97QOTir3vtbsRfT_LJxW8sizpWqOCXOnkeZWB5P4oj=w640-h848-no);
    background-repeat:no-repeat;
    background-origin: border-box;
    background-size: cover;
    border: none;
    padding-top : 10px;
    padding-left: 30px;
    padding-right: 30px;
    padding-bottom: 10px;
}
.sheet-portrait{
    width: 100px;
    max-width: 100px;
}
.sheet-libel1{
    padding-bottom: 6px;
    padding-top: 0px;
    font-weight: bold;
}
input.sheet-inMainNum{
    text-align: right;
    border-width: 1px;
    border-color: black;
    border-top-style: none;
    border-right-style: none;
    border-left-style: none;
    border-bottom-style: dotted;
}
input.sheet-inPetitNum{
    max-width: 44px;
    text-align: right;
    border-width: 1px;
    border-color: black;
    border-style: dotted;
}
input.sheet-inMainTxt{
    border-width: 1px;
    border-color: black;
    border-top-style: none;
    border-right-style: none;
    border-left-style: none;
    border-bottom-style: dotted;
}
input.sheet-inCA{
    height: 35px;
    max-width: 35px;
    text-align: center;
    border : solid black 2px;
    font-size: 20px;
    font-weight: bold;
    box-shadow: 4px 4px 8px rgba(0,0,0,.3);
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;
    border-bottom-right-radius: 17px;
    border-bottom-left-radius: 17px;
}
input.sheet-inPV{
    height: 35px;
    max-width: 40px;
    text-align: center;
    border : solid black 2px;
    font-size: 20px;
    font-weight: bold;
    box-shadow: 4px 4px 8px rgba(0,0,0,.3);
    border-top-left-radius: 100px;
    border-top-right-radius: 0px;
    border-bottom-right-radius: 0px;
    border-bottom-left-radius: 100px;
}
input.sheet-inPVMax{
    height: 35px;
    max-width: 40px;
    text-align: center;
    border : solid black 2px;
    font-size: 20px;
    font-weight: bold;
    box-shadow: 4px 4px 8px rgba(0,0,0,.3);
    border-top-left-radius: 0px;
    border-top-right-radius: 100px;
    border-bottom-right-radius: 100px;
    border-bottom-left-radius: 0px;
}
div.sheet-titre1{
    display: table-cell;
    font-weight: bold;
    font-size: 16px;
    text-align: left;
    padding: 2px;
}
div.sheet-carac-num{
    display: table-cell;
    padding: 5px;
    background-color: black;
    text-align: center;
}
input.sheet-attr-num{
    width: 26px;
    height: 26px;
    background-color: rgba(255,255,255,0.95);
    text-align: center;
    vertical-align: middle;
    border: none;
    font-weight: bold;
}
input.sheet-save-num{
    width: 26px;
    height: 26px;
    background-color: rgba(255,255,255,0.95);
    text-align: center;
    vertical-align: middle;
    border: none;
    border-radius:15px;
    font-weight: bold;
}
div.sheet-carac-lib{
    display: table-cell;
    padding-left: 4px;
    padding-right: 6px;
    text-align: left;
    font-family: "Times New Roman", serif;
    font-size: 12px;
    font-weight: bold;
}
div.sheet-carac-roll{
    display: table-cell;
}
div.sheet-carac-mod{
    display: table-cell;
    text-align: left;
    width: 25px;
    padding-right: 6px;
}
input.sheet-carac-mod{
    font-size:12px;
    text-align: right;
    border-width: 0px 0px 1px 2px;
    border-color: black;
    border-top-style: none;
    border-right-style: none;
    border-left-style: none;
    border-bottom-style: dotted;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.gildedrose</groupId>
    <artifactId>gilded-rose-kata</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
        <junit.jupiter.version>5.6.2</junit.jupiter.version>
        <maven.maven-compiler-plugin.version>3.1</maven.maven-compiler-plugin.version>
        <maven.maven-surefire-plugin.version>3.0.0-M4</maven.maven-surefire-plugin.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.approvaltests</groupId>
            <artifactId>approvaltests</artifactId>
            <version>12.1.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.maven-compiler-plugin.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven.maven-surefire-plugin.version}</version>
            </plugin>
        </plugins>
    </build>

</project>