text:
import els from '../../elements/de';
import { navigateCategoryBySelector } from '../../helper/category';
import { goCategoriesPage, goFavoritesPage } from '../../helper/navigation';

describe('e2e functional test favoritePage', () => {
  before(goCategoriesPage);

  it('should add product with variants to favlist', () => {
    navigateCategoryBySelector(els.productVariantsCategory);
    navigateCategoryBySelector(els.productsWith2VariantsCategory);

    cy.spyAction('RECEIVE_PRODUCT_CACHED', () => {
      cy.get(els.visiblePage).within(() => {
        cy.get(els.productWithChild1MotherNameProductGrid)
          .should('be.visible')
          .last()
          .click();
      });
    });

    cy.spyAction('RECEIVE_FAVORITES', () => {
      cy.get(els.favoriteButtonProductPage)
        .should('be.visible')
        .last()
        .click();
    });

    goFavoritesPage();

    cy.get(els.visiblePage).within(() => {
      cy.get(els.addToCartButton)
        .should('be.visible')
        .click();
    });

    cy.get(els.basicDialogText)
      .should('be.visible')
      .contains('Um dieses Produkt zum Warenkorb hinzuzufügen, wählen Sie bitte die Varianten.');
    cy.get(els.basicDialogOkButton)
      .should('be.visible')
      .contains('Abbrechen')
      .click()
      .wait(500);

    cy.get(els.visiblePage).within(() => {
      cy.get(els.addToCartButton)
        .should('be.visible')
        .click();
    });

    cy.spyAction('RECEIVE_PRODUCT_CACHED', () => {
      cy.get(els.basicDialogOkButton)
        .should('be.visible')
        .contains('Varianten wählen')
        .click();
    });
    cy.get(els.variantPickerColor)
      .should('be.visible')
      .contains('Color auswählen');
    cy.get(els.variantPickerShoeSize)
      .should('be.visible')
      .contains('Shoe size auswählen');
  });

  it('should check for empty fav list', () => {
    cy.spyAction('RECEIVE_FAVORITES', () => {
      cy.get(els.favoriteButtonProductPage)
        .last()
        .should('be.visible')
        .click();
    });

    goFavoritesPage();

    cy.get(els.favoritesPageEmptyFavComponent).should('be.visible');
  });
});


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
    public class InKeywordRecommenderTests : KeywordRecommenderTests
    {
        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAtRoot_Interactive()
        {
            VerifyAbsence(SourceCodeKind.Script,
@"$$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAfterClass_Interactive()
        {
            VerifyAbsence(SourceCodeKind.Script,
@"class C { }
$$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAfterGlobalStatement_Interactive()
        {
            VerifyAbsence(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAfterGlobalVariableDeclaration_Interactive()
        {
            VerifyAbsence(SourceCodeKind.Script,
@"int i = 0;
$$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotInUsingAlias()
        {
            VerifyAbsence(
@"using Foo = $$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotInEmptyStatement()
        {
            VerifyAbsence(AddInsideMethod(
@"$$"));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAfterFrom()
        {
            VerifyAbsence(AddInsideMethod(
@"var q = from $$"));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void AfterFromIdentifier()
        {
            VerifyKeyword(AddInsideMethod(
@"var q = from x $$"));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void AfterFromAndTypeAndIdentifier()
        {
            VerifyKeyword(AddInsideMethod(
@"var q = from int x $$"));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAfterJoin()
        {
            VerifyAbsence(AddInsideMethod(
@"var q = from x in y
          join $$"));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void AfterJoinIdentifier()
        {
            VerifyKeyword(AddInsideMethod(
@"var q = from x in y
          join z $$"));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void AfterJoinAndTypeAndIdentifier()
        {
            VerifyKeyword(AddInsideMethod(
@"var q = from x in y
          join int z $$"));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void AfterJoinNotAfterIn()
        {
            VerifyAbsence(AddInsideMethod(
@"var q = from x in y
          join z in $$"));
        }

        [WorkItem(544158)]
        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAfterJoinPredefinedType()
        {
            VerifyAbsence(
@"using System;
using System.Linq;
class C {
    void M()
    {
        var q = from x in y
                join int $$");
        }

        [WorkItem(544158)]
        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAfterJoinType()
        {
            VerifyAbsence(
@"using System;
using System.Linq;
class C {
    void M()
    {
        var q = from x in y
                join Int32 $$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void InForEach()
        {
            VerifyKeyword(AddInsideMethod(
@"foreach (var v $$"));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void InForEach1()
        {
            VerifyKeyword(AddInsideMethod(
@"foreach (var v $$ c"));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void InForEach2()
        {
            VerifyKeyword(AddInsideMethod(
@"foreach (var v $$ c"));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotInForEach()
        {
            VerifyAbsence(AddInsideMethod(
@"foreach ($$"));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotInForEach1()
        {
            VerifyAbsence(AddInsideMethod(
@"foreach (var $$"));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotInForEach2()
        {
            VerifyAbsence(AddInsideMethod(
@"foreach (var v in $$"));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotInForEach3()
        {
            VerifyAbsence(AddInsideMethod(
@"foreach (var v in c $$"));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void InterfaceTypeVarianceAfterAngle()
        {
            VerifyKeyword(
@"interface IFoo<$$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void InterfaceTypeVarianceNotAfterIn()
        {
            VerifyAbsence(
@"interface IFoo<in $$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void InterfaceTypeVarianceAfterComma()
        {
            VerifyKeyword(
@"interface IFoo<Foo, $$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void InterfaceTypeVarianceAfterAttribute()
        {
            VerifyKeyword(
@"interface IFoo<[Foo]$$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void DelegateTypeVarianceAfterAngle()
        {
            VerifyKeyword(
@"delegate void D<$$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void DelegateTypeVarianceAfterComma()
        {
            VerifyKeyword(
@"delegate void D<Foo, $$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void DelegateTypeVarianceAfterAttribute()
        {
            VerifyKeyword(
@"delegate void D<[Foo]$$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotInClassTypeVarianceAfterAngle()
        {
            VerifyAbsence(
@"class IFoo<$$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotInStructTypeVarianceAfterAngle()
        {
            VerifyAbsence(
@"struct IFoo<$$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotInBaseListAfterAngle()
        {
            VerifyAbsence(
@"interface IFoo : Bar<$$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotInGenericMethod()
        {
            VerifyAbsence(
@"interface IFoo {
    void Foo<$$");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void From2()
        {
            VerifyKeyword(AddInsideMethod(
@"var q2 = from int x $$ ((IEnumerable)src))"));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void From3()
        {
            VerifyKeyword(AddInsideMethod(
@"var q2 = from x $$ ((IEnumerable)src))"));
        }

        [WorkItem(544158)]
        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAfterFromPredefinedType()
        {
            VerifyAbsence(
@"using System;
using System.Linq;
class C {
    void M()
    {
        var q = from int $$");
        }

        [WorkItem(544158)]
        [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public void NotAfterFromType()
        {
            VerifyAbsence(
@"using System;
using System.Linq;
class C {
    void M()
    {
        var q = from Int32 $$");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.itheima.zhuhuibeijing.global;

public class GlobalConstants {

	public static final String SERVER_URL = "http://zhihuibj.sinaapp.com/zhbj";//服务器主域名. 10.0.2.2表示模拟器访问本机电脑
//	public static final String SERVER_URL = "http://10.0.2.2:8080/zhbj";//服务器主域名. 10.0.2.2表示模拟器访问本机电脑
	public static final String CATEGORY_URL = SERVER_URL + "/categories.json";//分类信息接口
	public static final String PHOTOS_URL = SERVER_URL + "/photos/photos_1.json";//组图信息接口

}


text:
package com.googlecode.protobuf.format;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.MalformedInputException;
import java.util.zip.GZIPOutputStream;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.smile.Tool;
import org.junit.Test;

import protobuf_unittest.UnittestProto;
import protobuf_unittest.UnittestProto.OneString;
import protobuf_unittest.UnittestProto.TestAllTypes;

import com.google.protobuf.ByteString;
import com.google.protobuf.ExtensionRegistry;
import com.google.protobuf.Message;
import com.google.protobuf.TextFormat;
import com.google.protobuf.UnknownFieldSet;
import com.googlecode.protobuf.format.FormatFactory.Formatter;
import com.googlecode.protobuf.format.test.UnittestImport.ImportMessage;
import com.googlecode.protobuf.format.util.TextUtils;

/**
 * Unit test for {@link SmileFormat}
 *
 * @author jeffrey.damick@neustar.biz Jeffrey Damick
 *         Based on {@link TextFormat} originally written by:
 * @author eliran.bivas@gmail.com Eliran Bivas
 *         <p/>
 * @author wenboz@google.com (Wenbo Zhu)
 */
public class SmileFormatTest {
    private static final String bogusJson = "{\"data\": \"!@##&*)&*(&*&*&*\"}{))_+__+$$(((((((((((((((()!?:\">\"}";
    private static final String validJson = "{\"data\": \"!@##&*)&*(&*&*&*\\\"}{))_+__+$$(((((((((((((((()!?:\\\">\"}";
    private static final Charset CHARSET_UTF8 = Charset.forName("UTF-8");
    private final Tool smileTool = new Tool();
    private FormatFactory formatFactory = new FormatFactory();
    private ProtobufFormatter formatter = formatFactory.createFormatter(Formatter.SMILE);

    @Test
    public void testStackOverflow() throws Exception {
    	TestAllTypes bd = TestAllTypes.newBuilder().setDefaultBytes(ByteString.copyFrom(new byte[1024])).build();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        formatter.print(bd, output);
        TestAllTypes.Builder builder = TestAllTypes.newBuilder();
        formatter.merge(new ByteArrayInputStream(output.toByteArray()), builder);
        assertEquals(bd, builder.build());
    }

    @Test
    public void testNonUtf8Bytes() throws Exception {
    	TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    	byte[] ff = {(byte) 0xFF}; // RFC 3629 - The octet values C0, C1, F5 to FF never appear.
    	byte[] testStrBytes = "\n\r\t\b\u0012".getBytes(CHARSET_UTF8);
    	byte[] testBytes = new byte[testStrBytes.length + 1];
    	System.arraycopy(testStrBytes, 0, testBytes, 0, testStrBytes.length);
    	System.arraycopy(ff, 0, testBytes, testStrBytes.length, ff.length);

    	try {
    		ByteBuffer bb = ByteBuffer.wrap(testBytes);
    		CHARSET_UTF8.newDecoder().decode(bb);
    		fail("expected decode error, we want a non-utf8 ByteString");
    	} catch (MalformedInputException malformedException) {
    		// should catch
    	}
    	builder.setOptionalBytes(ByteString.copyFrom(testBytes));
    	TestAllTypes byteType = builder.build();

    	// put it out
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        formatter.print(byteType, output);
        TestAllTypes.Builder roundTripBuilder = TestAllTypes.newBuilder();
        formatter.merge(new ByteArrayInputStream(output.toByteArray()), roundTripBuilder);
        assertArrayEquals(byteType.getOptionalBytes().toByteArray(), roundTripBuilder.getOptionalBytes().toByteArray());
        // make we get back what we put in.
        assertArrayEquals(testBytes, roundTripBuilder.getOptionalBytes().toByteArray());
    }

    @Test
    public void testExtensions() throws Exception {
    	UnittestProto.TestAllExtensions.Builder builder = UnittestProto.TestAllExtensions.newBuilder();
    	ByteArrayOutputStream output = new ByteArrayOutputStream();
    	formatter.print(TestUtil.getAllExtensionsSet(), output);
    	formatter.merge(new ByteArrayInputStream(output.toByteArray()), TestUtil.getExtensionRegistry(), builder);
        assertEquals(TestUtil.getAllExtensionsSet(), builder.build());
    }

    @Test
    public void testUnregisteredExtensions() throws Exception {
    	UnittestProto.TestAllExtensions.Builder builder = UnittestProto.TestAllExtensions.newBuilder();
    	ByteArrayOutputStream output = new ByteArrayOutputStream();
    	formatter.print(TestUtil.getAllExtensionsSet(), output);
    	try {
    		formatter.merge(new ByteArrayInputStream(output.toByteArray()), builder);
    		fail("Should fail without the extension registered");
    	} catch (RuntimeException rte) {}
    }

    @Test
    public void testUnknown() throws Exception {
    	TestAllTypes allTypes = TestAllTypes.newBuilder().setDefaultInt32(123).setOptionalInt64(456l).setOptionalString("foo").setOptionalImportMessage(ImportMessage.newBuilder().setD(123)).build();

        // put it out
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        formatter.print(allTypes, output);

        // and back in..
        TestAllTypes.Builder oneFieldSmiled = TestAllTypes.newBuilder();
        formatter.merge(new ByteArrayInputStream(output.toByteArray()), oneFieldSmiled);

        // make sure both the reference object and the one we built match (without unknowns)
        // we leave off unknowns, because without also encoding the field number in the json
        // there is no way to add them to the UnknownFieldSet
        TestAllTypes.Builder oneFieldWithoutUnknowns = TestAllTypes.newBuilder(allTypes);
        oneFieldWithoutUnknowns.setUnknownFields(UnknownFieldSet.newBuilder().build()); // empty them
        assertEquals(oneFieldWithoutUnknowns.build(), oneFieldSmiled.build());

        TestAllTypes.Builder builder = TestAllTypes.newBuilder();
        formatter.merge(new ByteArrayInputStream(output.toByteArray()), builder);
        assertEquals(allTypes, builder.build());
    }

    // test a simple round trip
    @Test
    public void testAllFieldsSet() throws Exception {
    	ByteArrayOutputStream output = new ByteArrayOutputStream();
    	TestAllTypes allTypes = TestUtil.getAllSet();
    	formatter.print(allTypes, output);
    	// verify compatibility with JsonFormat
        TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    	formatter.merge(new ByteArrayInputStream(output.toByteArray()), builder);
    	//System.out.println(JsonFormat.printToString(allTypes));
    	//System.out.println("*************");
    	//System.out.println(JsonFormat.printToString(builder.build()));
    	assertEquals(allTypes, builder.build());
    }

    // test backward compatibility (except for byte arrays) with Json from Jackson and parsing with JsonFormat
    // @see testNonUtf8Bytes
    @Test
    public void testAllFieldsSetBackwardCompat() throws Exception {
    	StringWriter output = new StringWriter();

    	TestAllTypes.Builder allTypesBuilder = TestAllTypes.newBuilder();
        TestUtil.setAllFields(allTypesBuilder);
        // clear all byte fields since we are encoding bytes in Jackson's Base64 w/o linefeeds
        allTypesBuilder.clearOptionalBytes();
        allTypesBuilder.clearDefaultBytes();
        allTypesBuilder.clearRepeatedBytes();

    	TestAllTypes allTypes = allTypesBuilder.build();

    	printAsText(allTypes, output);

    	// verify compatibility with JsonFormat
        TestAllTypes.Builder builder = TestAllTypes.newBuilder();
        formatFactory.createFormatter(Formatter.JSON).merge(TextUtils.toInputStream(output.toString()), builder);
    	assertEquals(allTypes, builder.build());

    	TestAllTypes.Builder builder2 = TestAllTypes.newBuilder();
    	JsonFactory jsonFactory = new JsonFactory();
    	JsonParser parser = jsonFactory.createJsonParser(
    			new ByteArrayInputStream(output.toString().getBytes(CHARSET_UTF8)));
    	((SmileFormat) formatter).merge(parser, ExtensionRegistry.getEmptyRegistry(), builder2);
    	assertEquals(allTypes, builder2.build());
    }

    @Test
    public void testInvalidJson() throws Exception {
    	OneString msg = OneString.newBuilder().setData("!@##&*)&*(&*&*&*\"}{))_+__+$$(((((((((((((((()!?:\">").build();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ((SmileFormat) formatter).print(msg, smileTool.smileFactory.createJsonGenerator(output));

        ByteArrayOutputStream validSmile = new ByteArrayOutputStream();
        encode(validJson, validSmile);
        assertArrayEquals(validSmile.toByteArray(), output.toByteArray());

        try {
            ByteArrayOutputStream bogusSmile = new ByteArrayOutputStream();
            encode(bogusJson, bogusSmile);
            fail("Expect parsing error due to malformed JSON");
        } catch (Exception e) {
            // good
        }
    }

    @Test
    public void testReusingOutputStream() throws Exception {
    	GZIPOutputStream output = new GZIPOutputStream(new ByteArrayOutputStream());
    	OneString msg = OneString.newBuilder().setData("!@##&*)&*(&*&*&*\"}{))_+__+$$(((((((((((((((()!?:\">").build();
    	formatter.print(msg, output);
    	formatter.print(msg, output);
    }

    private void printAsText(Message msg, Writer writer) throws IOException {
    	JsonGenerator generator = (new JsonFactory()).createJsonGenerator(writer);
    	generator.useDefaultPrettyPrinter();
    	((SmileFormat) formatter).print(msg, generator);
    }

    // based on: org.codehaus.jackson.smile.Tool
    private void encode(String in, OutputStream out) throws IOException {
        JsonParser jp = smileTool.jsonFactory.createJsonParser(in);
        JsonGenerator jg = smileTool.smileFactory.createJsonGenerator(out, JsonEncoding.UTF8);
        while ((jp.nextToken()) != null) {
            jg.copyCurrentEvent(jp);
        }
        jp.close();
        jg.close();
    }
}


text:
function bsNavbar($window, $location) {

	var defaults = this.defaults = {
		activeClass: 'active',
		routeAttr: 'data-match-route',
		strict: true
	};

	return {
		restrict: 'A',
		link: function postLink(scope, element, attr, controller) {

			// Directive options
			var options = angular.copy(defaults);
			angular.forEach(Object.keys(defaults), function(key) {
				if(angular.isDefined(attr[key])) options[key] = attr[key];
			});

			// Watch for the $location
			scope.$watch(function() {

				return $location.path();

			}, function(newValue, oldValue) {

				var liElements = element[0].querySelectorAll('li[' + options.routeAttr + '],li > a[' + options.routeAttr + ']');

				angular.forEach(liElements, function(li) {

					var liElement = angular.element(li);
					var pattern = liElement.attr(options.routeAttr).replace('/', '\\/');
					if(options.strict) {
						pattern = '^' + pattern;
					}
					var regexp = new RegExp(pattern, ['i']);

					if(regexp.test(newValue)) {
						liElement.addClass(options.activeClass);
					} else {
						liElement.removeClass(options.activeClass);
					}

				});

				// Close all other opened elements
				var op = $('#sidebar-nav').find('.open:not(.active)');
				op.children('.submenu').slideUp('fast');
				op.removeClass('open');
			});

		}

	};
}

function gd(year, day, month) {
	return new Date(year, month - 1, day).getTime();
}

function showTooltip(x, y, label, data) {
	$('
' + '' + label + ': ' + data + '' + '
').css({
		top: y + 5,
		left: x + 20
	}).appendTo("body").fadeIn(200);
}

function showtab() {
    return {
        link: function (scope, element, attrs) {
            element.click(function(e) {
                e.preventDefault();
                $(element).tab('show');
            });
        }
    };
}

angular
	.module('cubeWebApp')
	.directive('bsNavbar', bsNavbar)
	.directive('showtab', showtab)


text:
module MapSource
  # Public: GDB header. Contains name of creator software, signature and
  # format version.
  class Header
    attr_accessor :created_by, :signed_by, :version
  end

  # Public: A Waypoint.
  class Waypoint
    attr_accessor :shortname, :latitude, :longitude, :altitude, :temperature, :depth, :notes, :creation_time, :proximity, :icon, :city, :state, :facility, :address, :description, :category
    attr_reader :urls

    def initialize(latitude, longitude)
      @latitude = latitude
      @longitude = longitude
      @urls = []
    end

    def add_url(url)
      @urls << url
    end

    def set_creation_time(value)
      puts value
    end
  end

  # Public: A Track.
  class Track
    attr_reader :name, :color

    def initialize(name, color)
      @name = name
      @color = color
      @waypoints = []
    end

    def waypoints
      @waypoints.dup
    end

    def add_waypoint(wpt)
      @waypoints << wpt
    end

    def size
      @waypoints.size
    end

    def each
      @waypoints.each { |wpt| yield wpt if block_given? }
    end
  end
end


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

import static com.google.firebase.messaging.Constants.TAG;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import com.google.android.datatransport.Encoding;
import com.google.android.datatransport.Event;
import com.google.android.datatransport.TransportFactory;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.FirebaseApp;
import com.google.firebase.analytics.connector.AnalyticsConnector;
import com.google.firebase.installations.FirebaseInstallations;
import com.google.firebase.messaging.Constants.AnalyticsKeys;
import com.google.firebase.messaging.Constants.FirelogAnalytics;
import com.google.firebase.messaging.Constants.FirelogAnalytics.MessagePriority;
import com.google.firebase.messaging.Constants.MessagePayloadKeys;
import com.google.firebase.messaging.Constants.ScionAnalytics;
import com.google.firebase.messaging.reporting.MessagingClientEvent;
import com.google.firebase.messaging.reporting.MessagingClientEventExtension;
import java.util.concurrent.ExecutionException;

/**
 * Provides integration between FCM and Scion.
 *
 *
All Scion dependencies should be kept in this class, and missing dependencies should be
 * handled gracefully. Instead of crashing the app if Scion has not been included in the APK we
 * instead log a message and don't send any events.
 *
 *
key/values expected by GcmAnalytics: (constants are defined in {@link Constants})
 *
 *

 *
google.c.a.e = 1 # Enable Analytics
 *
google.c.a.c_id = 123 # Composer Id
 *
google.c.a.c_l = Campaign1 # Composer Label
 *
google.c.a.ts = 1234 # Timestamp of message
 *
google.c.a.udt = 1 # Whether the ts should be used only for DateTime, without timezone
 *
google.c.a.m_l = dev-provided-label # message label provided by the developer
 *

 *
 * @hide
 */
public class MessagingAnalytics {
  private static final String REENGAGEMENT_SOURCE = "Firebase";
  private static final String REENGAGEMENT_MEDIUM = "notification";

  private static final String FCM_PREFERENCES = "com.google.firebase.messaging";
  private static final String DELIVERY_METRICS_EXPORT_TO_BIG_QUERY_PREF = "export_to_big_query";
  private static final String MANIFEST_DELIVERY_METRICS_EXPORT_TO_BIG_QUERY_ENABLED =
      "delivery_metrics_exported_to_big_query_enabled";

  /** Log that a notification was received by the client app. */
  public static void logNotificationReceived(Intent intent) {
    if (shouldUploadScionMetrics(intent)) {
      logToScion(ScionAnalytics.EVENT_NOTIFICATION_RECEIVE, intent.getExtras());
    }

    if (shouldUploadFirelogAnalytics(intent)) {
      logToFirelog(
          MessagingClientEvent.Event.MESSAGE_DELIVERED,
          intent,
          FirebaseMessaging.getTransportFactory());
    }
  }

  /** Log that a notification was opened. */
  public static void logNotificationOpen(Bundle extras) {
    setUserPropertyIfRequired(extras);
    logToScion(ScionAnalytics.EVENT_NOTIFICATION_OPEN, extras);
  }

  /** Log that a notification was dismissed. */
  public static void logNotificationDismiss(Intent intent) {
    logToScion(ScionAnalytics.EVENT_NOTIFICATION_DISMISS, intent.getExtras());
  }

  /**
   * Log that a notification was received while the app was in the foreground.
   *
   *
In this case, onMessageReceived() is invoked instead of showing a notification to the user.
   */
  public static void logNotificationForeground(Intent intent) {
    logToScion(ScionAnalytics.EVENT_NOTIFICATION_FOREGROUND, intent.getExtras());
  }

  /** check whether we should upload metrics data to scion. */
  public static boolean shouldUploadScionMetrics(Intent intent) {
    if (intent == null || isDirectBootMessage(intent)) {
      return false;
    }

    return shouldUploadScionMetrics(intent.getExtras());
  }

  /** check whether we should upload metrics data to scion. */
  public static boolean shouldUploadScionMetrics(Bundle extras) {
    if (extras == null) {
      return false;
    }

    return "1".equals(extras.getString(Constants.AnalyticsKeys.ENABLED));
  }

  /** check whether we should upload metrics data to firelog. */
  public static boolean shouldUploadFirelogAnalytics(Intent intent) {
    if (intent == null || isDirectBootMessage(intent)) {
      return false;
    }
    return deliveryMetricsExportToBigQueryEnabled();
  }

  private static boolean isDirectBootMessage(Intent intent) {
    // Analytics causes a crash in direct boot mode since FirebaseApp is not initialized
    // (and probably shouldn't be initialized since it may not be direct boot
    // compatible).
    return FirebaseMessagingService.ACTION_DIRECT_BOOT_REMOTE_INTENT.equals(intent.getAction());
  }

  /**
   * check whether we should upload metrics data to firelog by looking at the user setting in the
   * manifest and device storage.
   */
  static boolean deliveryMetricsExportToBigQueryEnabled() {
    try {
      FirebaseApp.getInstance();
    } catch (IllegalStateException e) {
      Log.i(
          TAG,
          "FirebaseApp has not being initialized. Device might be in direct boot mode."
              + " Skip exporting delivery metrics to Big Query");
      return false;
    }

    Context context = FirebaseApp.getInstance().getApplicationContext();
    SharedPreferences preferences =
        context.getSharedPreferences(FCM_PREFERENCES, Context.MODE_PRIVATE);

    // Flag value set at runtime overrides manifest setting
    if (preferences.contains(DELIVERY_METRICS_EXPORT_TO_BIG_QUERY_PREF)) {
      return preferences.getBoolean(DELIVERY_METRICS_EXPORT_TO_BIG_QUERY_PREF, false);
    }

    // After checking device db, check manifest
    try {
      PackageManager packageManager = context.getPackageManager();
      if (packageManager != null) {
        ApplicationInfo applicationInfo =
            packageManager.getApplicationInfo(
                context.getPackageName(), PackageManager.GET_META_DATA);
        if (applicationInfo != null
            && applicationInfo.metaData != null
            && applicationInfo.metaData.containsKey(
                MANIFEST_DELIVERY_METRICS_EXPORT_TO_BIG_QUERY_ENABLED)) {
          return applicationInfo.metaData.getBoolean(
              MANIFEST_DELIVERY_METRICS_EXPORT_TO_BIG_QUERY_ENABLED, false);
        }
      }
    } catch (PackageManager.NameNotFoundException e) {
      // Shouldn't happen. If happened, fall though to default.
    }

    // If there is no specification on disk nor in manifest, default to not logging
    return false;
  }

  /** Set the FIREBASE_LAST_NOTIFICATION user-property in Scion for conversion tracking. */
  private static void setUserPropertyIfRequired(Bundle extras) {
    if (extras == null) {
      return;
    }

    // If the user requested to track conversions, set the user property.
    String shouldTrackConversions = extras.getString(Constants.AnalyticsKeys.TRACK_CONVERSIONS);
    if ("1".equals(shouldTrackConversions)) {
      // TODO(b/78465387) Use components dependency framework to get analyticsConnector obj
      @SuppressWarnings("FirebaseUseExplicitDependencies")
      AnalyticsConnector analytics = FirebaseApp.getInstance().get(AnalyticsConnector.class);
      if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(
            TAG,
            "Received event with track-conversion=true."
                + " Setting user property and reengagement event");
      }
      if (analytics != null) {
        String composerId = extras.getString(Constants.AnalyticsKeys.COMPOSER_ID);
        analytics.setUserProperty(
            ScionAnalytics.ORIGIN_FCM,
            ScionAnalytics.USER_PROPERTY_FIREBASE_LAST_NOTIFICATION,
            composerId);

        // Also set the reengagement attribution
        Bundle params = new Bundle();
        params.putString(ScionAnalytics.PARAM_SOURCE, REENGAGEMENT_SOURCE);
        params.putString(ScionAnalytics.PARAM_MEDIUM, REENGAGEMENT_MEDIUM);
        params.putString(ScionAnalytics.PARAM_CAMPAIGN, composerId);
        analytics.logEvent(
            ScionAnalytics.ORIGIN_FCM, ScionAnalytics.EVENT_FIREBASE_CAMPAIGN, params);
      } else {
        // Client did not include the measurement library
        Log.w(
            TAG,
            "Unable to set user property for conversion tracking: "
                + " analytics library is missing");
      }
    } else {
      if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Received event with track-conversion=false. Do not set user property");
      }
    }
  }

  /**
   * Asynchronously log an event to Scion.
   *
   *
Scion schedules tasks to run on worker threads within the client app to send the event.
   */
  @VisibleForTesting
  static void logToScion(String event, Bundle extras) {
    try {
      FirebaseApp.getInstance();
    } catch (IllegalStateException e) {
      Log.e(TAG, "Default FirebaseApp has not been initialized. Skip logging event to GA.");
      return;
    }

    if (extras == null) {
      extras = new Bundle();
    }

    Bundle scionPayload = new Bundle();

    String composerId = getComposerId(extras);
    if (composerId != null) {
      scionPayload.putString(ScionAnalytics.PARAM_COMPOSER_ID, composerId);
    }

    String composerLabel = getComposerLabel(extras);
    if (composerLabel != null) {
      scionPayload.putString(ScionAnalytics.PARAM_MESSAGE_NAME, composerLabel);
    }

    String messageLabel = getMessageLabel(extras);
    if (!TextUtils.isEmpty(messageLabel)) {
      scionPayload.putString(ScionAnalytics.PARAM_LABEL, messageLabel);
    }

    String messageChannel = getMessageChannel(extras);
    if (!TextUtils.isEmpty(messageChannel)) {
      scionPayload.putString(ScionAnalytics.PARAM_MESSAGE_CHANNEL, messageChannel);
    }

    String topic = getTopic(extras);
    if (topic != null) {
      scionPayload.putString(ScionAnalytics.PARAM_TOPIC, topic);
    }

    String messageTime = getMessageTime(extras);
    if (messageTime != null) {
      try {
        scionPayload.putInt(ScionAnalytics.PARAM_MESSAGE_TIME, Integer.parseInt(messageTime));
      } catch (NumberFormatException e) {
        Log.w(TAG, "Error while parsing timestamp in GCM event", e);
      }
    }

    String useDeviceTime = getUseDeviceTime(extras);
    if (useDeviceTime != null) {
      try {
        scionPayload.putInt(
            ScionAnalytics.PARAM_MESSAGE_DEVICE_TIME, Integer.parseInt(useDeviceTime));
      } catch (NumberFormatException e) {
        Log.w(TAG, "Error while parsing use_device_time in GCM event", e);
      }
    }

    String messageType = getMessageTypeForScion(extras);
    if (ScionAnalytics.EVENT_NOTIFICATION_RECEIVE.equals(event)
        || ScionAnalytics.EVENT_NOTIFICATION_FOREGROUND.equals(event)) {
      scionPayload.putString(ScionAnalytics.PARAM_MESSAGE_TYPE, messageType);
    }

    if (Log.isLoggable(TAG, Log.DEBUG)) {
      Log.d(TAG, "Logging to scion event=" + event + " scionPayload=" + scionPayload);
    }

    // TODO(b/78465387) Use components dependency framework to get analyticsConnector obj
    @SuppressWarnings("FirebaseUseExplicitDependencies")
    AnalyticsConnector analytics = FirebaseApp.getInstance().get(AnalyticsConnector.class);
    if (analytics != null) {
      analytics.logEvent(ScionAnalytics.ORIGIN_FCM, event, scionPayload);
    } else {
      // Client did not include the measurement library
      Log.w(TAG, "Unable to log event: analytics library is missing");
    }
  }

  /**
   * Asynchronously log an event to Firelog.
   *
   *
Firelog batch-send usually delivery metrics within 1 hour (at most 24 hours) when the device
   * is idle and have network connection in a background thread.
   */
  private static void logToFirelog(
      MessagingClientEvent.Event event,
      Intent intent,
      @Nullable TransportFactory transportFactory) {
    if (transportFactory == null) {
      Log.e(TAG, "TransportFactory is null. Skip exporting message delivery metrics to Big Query");
      return;
    }
    MessagingClientEvent clientEvent = eventToProto(event, intent);
    if (clientEvent == null) {
      return;
    }

    try {
      // TODO(b/145299499): offload encoding to Firelog Thread
      transportFactory
          .getTransport(
              FirelogAnalytics.FCM_LOG_SOURCE,
              MessagingClientEventExtension.class,
              Encoding.of("proto"),
              MessagingClientEventExtension::toByteArray)
          .send(
              Event.ofData(
                  MessagingClientEventExtension.newBuilder()
                      .setMessagingClientEvent(clientEvent)
                      .build()));
    } catch (RuntimeException e) {
      Log.w(TAG, "Failed to send big query analytics payload.", e);
    }
  }

  static void setDeliveryMetricsExportToBigQuery(boolean enable) {
    SharedPreferences.Editor editor =
        FirebaseApp.getInstance()
            .getApplicationContext()
            .getSharedPreferences(FCM_PREFERENCES, Context.MODE_PRIVATE)
            .edit();
    editor.putBoolean(DELIVERY_METRICS_EXPORT_TO_BIG_QUERY_PREF, enable).apply();
  }

  @NonNull
  static int getTtl(Bundle extras) {
    Object ttl = extras.get(MessagePayloadKeys.TTL);
    if (ttl instanceof Integer) {
      return (int) ttl;
    } else if (ttl instanceof String) {
      try {
        return Integer.parseInt((String) ttl);
      } catch (NumberFormatException e) {
        Log.w(TAG, "Invalid TTL: " + ttl);
        // Fall through to default case
      }
    }
    return 0; // Default if unset or an error
  }

  @Nullable
  static String getCollapseKey(Bundle extras) {
    return extras.getString(MessagePayloadKeys.COLLAPSE_KEY);
  }

  @Nullable
  static String getComposerId(Bundle extras) {
    return extras.getString(AnalyticsKeys.COMPOSER_ID);
  }

  @Nullable
  static String getComposerLabel(Bundle extras) {
    return extras.getString(AnalyticsKeys.COMPOSER_LABEL);
  }

  @Nullable
  static String getMessageLabel(Bundle extras) {
    return extras.getString(AnalyticsKeys.MESSAGE_LABEL);
  }

  @Nullable
  static String getMessageChannel(Bundle extras) {
    return extras.getString(AnalyticsKeys.MESSAGE_CHANNEL);
  }

  @Nullable
  static String getMessageTime(Bundle extras) {
    return extras.getString(AnalyticsKeys.MESSAGE_TIMESTAMP);
  }

  @Nullable
  static String getMessageId(Bundle extras) {
    String messageId = extras.getString(MessagePayloadKeys.MSGID);
    if (messageId == null) {
      messageId = extras.getString(MessagePayloadKeys.MSGID_SERVER);
    }
    return messageId;
  }

  @NonNull
  static String getPackageName() {
    return FirebaseApp.getInstance().getApplicationContext().getPackageName();
  }

  @NonNull
  static String getInstanceId(Bundle extras) {
    String to = extras.getString(MessagePayloadKeys.TO);
    if (!TextUtils.isEmpty(to)) {
      return to;
    }
    try {
      return Tasks.await(FirebaseInstallations.getInstance(FirebaseApp.getInstance()).getId());
    } catch (ExecutionException | InterruptedException e) {
      throw new RuntimeException(e);
    }
  }

  @NonNull
  static String getMessageTypeForScion(Bundle extras) {
    return extras != null && NotificationParams.isNotification(extras)
        ? ScionAnalytics.MessageType.DISPLAY_NOTIFICATION
        : ScionAnalytics.MessageType.DATA_MESSAGE;
  }

  @NonNull
  static MessagingClientEvent.MessageType getMessageTypeForFirelog(Bundle extras) {
    return extras != null && NotificationParams.isNotification(extras)
        ? MessagingClientEvent.MessageType.DISPLAY_NOTIFICATION
        : MessagingClientEvent.MessageType.DATA_MESSAGE;
  }

  @Nullable
  static String getTopic(Bundle extras) {
    String from = extras.getString(MessagePayloadKeys.FROM);
    return ((from != null && from.startsWith("/topics/")) ? from : null);
  }

  @Nullable
  static String getUseDeviceTime(Bundle extras) {
    if (extras.containsKey(AnalyticsKeys.MESSAGE_USE_DEVICE_TIME)) {
      return extras.getString(AnalyticsKeys.MESSAGE_USE_DEVICE_TIME);
    }
    return null;
  }

  @NonNull
  static int getPriority(Bundle extras) {
    String priority = extras.getString(MessagePayloadKeys.DELIVERED_PRIORITY);
    if (priority == null) {
      if ("1".equals(extras.getString(MessagePayloadKeys.PRIORITY_REDUCED_V19))) {
        return RemoteMessage.PRIORITY_NORMAL;
      }
      priority = extras.getString(MessagePayloadKeys.PRIORITY_V19);
    }
    return getMessagePriority(priority);
  }

  @NonNull
  private static int getMessagePriority(String priority) {
    if ("high".equals(priority)) {
      return RemoteMessage.PRIORITY_HIGH;
    } else if ("normal".equals(priority)) {
      return RemoteMessage.PRIORITY_NORMAL;
    } else {
      return RemoteMessage.PRIORITY_UNKNOWN;
    }
  }

  @MessagePriority
  static int getMessagePriorityForFirelog(Bundle extras) {
    // translate from the RemoteMessage-flavored priority integers into the ones we use for backend
    // logging
    int priority = getPriority(extras);
    if (priority == RemoteMessage.PRIORITY_NORMAL) {
      return MessagePriority.NORMAL;
    } else if (priority == RemoteMessage.PRIORITY_HIGH) {
      return MessagePriority.HIGH;
    } else {
      return MessagePriority.UNKNOWN;
    }
  }

  @Nullable
  static long getProjectNumber(Bundle extras) {
    if (extras.containsKey(MessagePayloadKeys.SENDER_ID)) {
      // Sender ID was sent with the message, return that.
      try {
        return Long.parseLong(extras.getString(MessagePayloadKeys.SENDER_ID));
      } catch (NumberFormatException ex) {
        Log.w(TAG, "error parsing project number", ex);
      }
    }

    // Sender ID was not included with the message, get it from the FirebaseApp.
    FirebaseApp app = FirebaseApp.getInstance();
    // Check for an explicit sender id
    String senderId = app.getOptions().getGcmSenderId();
    if (senderId != null) {
      try {
        return Long.parseLong(senderId);
      } catch (NumberFormatException ex) {
        Log.w(TAG, "error parsing sender ID", ex);
      }
    }

    String appId = app.getOptions().getApplicationId();
    if (!appId.startsWith("1:")) {
      // Not v1, server should be updated to accept the full app ID now
      try {
        return Long.parseLong(appId);
      } catch (NumberFormatException ex) {
        Log.w(TAG, "error parsing app ID", ex);
      }
    } else {
      // For v1 app IDs, fall back to parsing the project ID out
      String[] parts = appId.split(":");
      if (parts.length < 2) {
        return 0L; // Invalid format
      }
      String projectId = parts[1];
      if (projectId.isEmpty()) {
        return 0L; // No project ID
      }

      try {
        return Long.parseLong(projectId);
      } catch (NumberFormatException ex) {
        Log.w(TAG, "error parsing app ID", ex);
      }
    }

    return 0L;
  }

  static MessagingClientEvent eventToProto(MessagingClientEvent.Event event, Intent intent) {
    if (intent == null) {
      return null;
    }
    Bundle extras = intent.getExtras();
    if (extras == null) {
      // even if no params were passed, we still grab some default values so don't bail just yet
      extras = Bundle.EMPTY;
    }

    MessagingClientEvent.Builder builder =
        MessagingClientEvent.newBuilder()
            .setTtl(getTtl(extras))
            .setEvent(event)
            .setInstanceId(getInstanceId(extras))
            .setPackageName(getPackageName())
            .setSdkPlatform(MessagingClientEvent.SDKPlatform.ANDROID)
            .setMessageType(getMessageTypeForFirelog(extras));

    // nullable parameters
    String messageId = getMessageId(extras);
    if (messageId != null) { // shouldn't happen in prod
      builder.setMessageId(messageId);
    }

    String topic = getTopic(extras);
    if (topic != null) {
      builder.setTopic(topic);
    }

    String collapseKey = getCollapseKey(extras);
    if (collapseKey != null) {
      builder.setCollapseKey(collapseKey);
    }

    String messageLabel = getMessageLabel(extras);
    if (messageLabel != null) {
      builder.setAnalyticsLabel(messageLabel);
    }

    String composerLabel = getComposerLabel(extras);
    if (composerLabel != null) {
      builder.setComposerLabel(composerLabel);
    }

    long projectNumber = getProjectNumber(extras);
    if (projectNumber > 0) {
      builder.setProjectNumber(projectNumber);
    }

    return builder.build();
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >

    <Button
        android:id="@+id/add_deck"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/add_deck"
        android:background="#0ABAB5"/>

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    </ListView>

</LinearLayout>


text:
using System.Collections.Generic;
using System.IO;
using Blog.Model;
using CommonMark;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace Blog.Controllers
{
    public class PostsController : Controller
    {
        private readonly IPosts _posts;
        private readonly IHostingEnvironment _env;

        private static readonly Dictionary<int, string> _htmlCache;

        static PostsController()
        {
            _htmlCache = new Dictionary<int, string>();
        }

        public PostsController(IPosts posts, IHostingEnvironment env)
        {
            _posts = posts;
            _env = env;
        }

        [Route("")]
        [Route("/latest/{page}")]
        public IActionResult List(int? page) => View(_posts.Paged(page ?? 1));

        [Route("/posts/404")]
        public IActionResult Detail()
        {
            string slug = HttpContext.Features
                .Get<IStatusCodeReExecuteFeature>()?.OriginalPath;

            if (slug != null)
            {
                Post post = _posts.SingleOrDefault(slug.TrimStart('/'));
                if (post != null)
                {
                    post.HtmlContent = GetHtmlContent(post.Id);

                    return View("~/Views/Posts/Detail.cshtml", post);
                }
            }

            return View("PageNotFound");
        }

        public string GetHtmlContent(int postId)
        {
            string html;

            if (_htmlCache.TryGetValue(postId, out html) && !string.IsNullOrWhiteSpace(html))
            {
                return html;
            }

            string filePath = Path.Combine(_env.ContentRootPath, "Posts", $"{postId.ToString().PadLeft(4, '0')}.md");
            string markdown = System.IO.File.ReadAllText(filePath);

            html = CommonMarkConverter.Convert(markdown);

            _htmlCache[postId] = html;

            return html;
        }
    }
}


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './shared_style.js';
import './toggle_row.js';

import {assert, assertNotReached} from '//resources/js/assert.m.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {App} from './app_management.mojom-webui.js';
import {Permission} from './app_management.mojom-webui.js';
import {BrowserProxy} from './browser_proxy.js';
import {AppManagementUserAction} from './constants.js';
import {PermissionType, PermissionTypeIndex, TriState} from './permission_constants.js';
import {createBoolPermission, createTriStatePermission, getBoolPermissionValue, getTriStatePermissionValue, isBoolValue, isTriStateValue} from './permission_util.js';
import {AppManagementToggleRowElement} from './toggle_row.js';
import {getPermission, getPermissionValueBool, recordAppManagementUserAction} from './util.js';

export class AppManagementPermissionItemElement extends PolymerElement {
  static get is() {
    return 'app-management-permission-item';
  }

  static get template() {
    return html`{__html_template__}`;
  }

  static get properties() {
    return {
      /**
       * The name of the permission, to be displayed to the user.
       */
      permissionLabel: String,

      /**
       * A string version of the permission type. Must be a value of the
       * permission type enum in appManagement.mojom.PermissionType.
       */
      permissionType: String,

      icon: String,

      /**
       * If set to true, toggling the permission item will not set the
       * permission in the backend. Call `syncPermission()` to set the
       * permission to reflect the current UI state.
       */
      syncPermissionManually: Boolean,

      app: Object,

      /**
       * True if the permission type is available for the app.
       */
      available_: {
        type: Boolean,
        computed: 'isAvailable_(app, permissionType)',
        reflectToAttribute: true,
      },

      disabled_: {
        type: Boolean,
        computed: 'isManaged_(app, permissionType)',
        reflectToAttribute: true,
      },
    };
  }

  app: App;
  permissionLabel: string;
  permissionType: PermissionTypeIndex;
  icon: string;
  private syncPermissionManually: boolean;
  private available_: boolean;
  private disabled_: boolean;

  override ready() {
    super.ready();
    this.addEventListener('click', this.onClick_);
    this.addEventListener('change', this.togglePermission_);
  }

  private isAvailable_(app: App, permissionType: PermissionTypeIndex): boolean {
    if (app === undefined || permissionType === undefined) {
      return false;
    }

    assert(app);

    return getPermission(app, permissionType) !== undefined;
  }

  private isManaged_(app: App, permissionType: PermissionTypeIndex): boolean {
    if (app === undefined || permissionType === undefined ||
        !this.isAvailable_(app, permissionType)) {
      return false;
    }

    assert(app);
    const permission = getPermission(app, permissionType);

    assert(permission);
    return permission.isManaged;
  }

  private getValue_(app: App, permissionType: PermissionTypeIndex): boolean {
    if (app === undefined || permissionType === undefined) {
      return false;
    }
    assert(app);

    return getPermissionValueBool(app, permissionType);
  }

  resetToggle() {
    const currentValue = this.getValue_(this.app, this.permissionType);
    this.shadowRoot!
        .querySelector<AppManagementToggleRowElement>('#toggle-row')!.setToggle(
            currentValue);
  }

  private onClick_() {
    this.shadowRoot!
        .querySelector<AppManagementToggleRowElement>('#toggle-row')!.click();
  }

  private togglePermission_() {
    if (!this.syncPermissionManually) {
      this.syncPermission();
    }
  }

  /**
   * Set the permission to match the current UI state. This only needs to be
   * called when `syncPermissionManually` is set.
   */
  syncPermission() {
    assert(this.app);

    let newPermission: Permission|undefined = undefined;

    let newBoolState = false;  // to keep the closure compiler happy.
    const permissionValue = getPermission(this.app, this.permissionType).value;
    if (isBoolValue(permissionValue)) {
      newPermission =
          this.getUIPermissionBoolean_(this.app, this.permissionType);
      newBoolState = getBoolPermissionValue(newPermission.value);
    } else if (isTriStateValue(permissionValue)) {
      newPermission =
          this.getUIPermissionTriState_(this.app, this.permissionType);

      newBoolState =
          getTriStatePermissionValue(newPermission.value) === TriState.kAllow;
    } else {
      assertNotReached();
    }

    BrowserProxy.getInstance().handler.setPermission(
        this.app.id, newPermission!);

    recordAppManagementUserAction(
        this.app.type,
        this.getUserMetricActionForPermission_(
            newBoolState, this.permissionType));
  }

  /**
   * Gets the permission boolean based on the toggle's UI state.
   */
  private getUIPermissionBoolean_(
      app: App, permissionType: PermissionTypeIndex): Permission {
    const currentPermission = getPermission(app, permissionType);

    assert(isBoolValue(currentPermission.value));

    const newPermissionValue = !getBoolPermissionValue(currentPermission.value);

    return createBoolPermission(
        PermissionType[permissionType], newPermissionValue,
        currentPermission.isManaged);
  }

  /**
   * Gets the permission tristate based on the toggle's UI state.
   */
  private getUIPermissionTriState_(
      app: App, permissionType: PermissionTypeIndex): Permission {
    let newPermissionValue;
    const currentPermission = getPermission(app, permissionType);

    assert(isTriStateValue(currentPermission.value));

    switch (getTriStatePermissionValue(currentPermission.value)) {
      case TriState.kBlock:
        newPermissionValue = TriState.kAllow;
        break;
      case TriState.kAsk:
        newPermissionValue = TriState.kAllow;
        break;
      case TriState.kAllow:
        // TODO(rekanorman): Eventually TriState.kAsk, but currently changing a
        // permission to kAsk then opening the site settings page for the app
        // produces the error:
        // "Only extensions or enterprise policy can change the setting to ASK."
        newPermissionValue = TriState.kBlock;
        break;
      default:
        assertNotReached();
        newPermissionValue = TriState.kBlock;
    }

    assert(newPermissionValue !== undefined);
    return createTriStatePermission(
        PermissionType[permissionType], newPermissionValue,
        currentPermission.isManaged);
  }

  private getUserMetricActionForPermission_(
      permissionValue: boolean,
      permissionType: PermissionTypeIndex): AppManagementUserAction {
    switch (permissionType) {
      case 'kNotifications':
        return permissionValue ?
            AppManagementUserAction.NOTIFICATIONS_TURNED_ON :
            AppManagementUserAction.NOTIFICATIONS_TURNED_OFF;

      case 'kLocation':
        return permissionValue ? AppManagementUserAction.LOCATION_TURNED_ON :
                                 AppManagementUserAction.LOCATION_TURNED_OFF;

      case 'kCamera':
        return permissionValue ? AppManagementUserAction.CAMERA_TURNED_ON :
                                 AppManagementUserAction.CAMERA_TURNED_OFF;

      case 'kMicrophone':
        return permissionValue ? AppManagementUserAction.MICROPHONE_TURNED_ON :
                                 AppManagementUserAction.MICROPHONE_TURNED_OFF;

      case 'kContacts':
        return permissionValue ? AppManagementUserAction.CONTACTS_TURNED_ON :
                                 AppManagementUserAction.CONTACTS_TURNED_OFF;

      case 'kStorage':
        return permissionValue ? AppManagementUserAction.STORAGE_TURNED_ON :
                                 AppManagementUserAction.STORAGE_TURNED_OFF;

      case 'kPrinting':
        return permissionValue ? AppManagementUserAction.PRINTING_TURNED_ON :
                                 AppManagementUserAction.PRINTING_TURNED_OFF;

      default:
        assertNotReached();
        return AppManagementUserAction.NOTIFICATIONS_TURNED_ON;
    }
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'app-management-permission-item': AppManagementPermissionItemElement;
  }
}

customElements.define(
    AppManagementPermissionItemElement.is, AppManagementPermissionItemElement);


text:
/* sanitize.css v3.0.0 | CC0 1.0 Public Domain | github.com/10up/sanitize.css */
audio:not([controls]) {
  display: none;
}
button {
  overflow: visible;
  -webkit-appearance: button;
}
details {
  display: block;
}
html {
  -ms-overflow-style: -ms-autohiding-scrollbar;
  overflow-y: scroll;
  -webkit-text-size-adjust: 100%;
}
input {
  -webkit-border-radius: 0;
}
input[type="button"],
input[type="reset"],
input[type="submit"] {
  -webkit-appearance: button;
}
input[type="number"] {
  width: auto;
}
input[type="search"] {
  -webkit-appearance: textfield;
}
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
  -webkit-appearance: none;
}
main {
  display: block;
}
pre {
  overflow: auto;
}
progress {
  display: inline-block;
}
small {
  font-size: 75%;
}
summary {
  display: block;
}
svg:not(:root) {
  overflow: hidden;
}
template {
  display: none;
}
textarea {
  overflow: auto;
}
[hidden] {
  display: none;
}
*,
::before,
::after {
  box-sizing: inherit;
}
* {
  font-size: inherit;
  line-height: inherit;
}
::before,
::after {
  text-decoration: inherit;
  vertical-align: inherit;
}
*,
::before,
::after {
  border-style: solid;
  border-width: 0;
}
* {
  background-repeat: no-repeat;
  margin: 0;
  padding: 0;
}
:root {
  background-color: #fff;
  box-sizing: border-box;
  color: #000;
  cursor: default;
  font: 100%/1.5 sans-serif;
  text-rendering: optimizeLegibility;
}
a {
  text-decoration: none;
}
audio,
canvas,
iframe,
img,
svg,
video {
  vertical-align: middle;
}
button,
input,
select,
textarea {
  background-color: transparent;
}
button,
input,
select,
textarea {
  color: inherit;
  font-family: inherit;
  font-style: inherit;
  font-weight: inherit;
}
button,
[type="button"],
[type="date"],
[type="datetime"],
[type="datetime-local"],
[type="email"],
[type="month"],
[type="number"],
[type="password"],
[type="reset"],
[type="search"],
[type="submit"],
[type="tel"],
[type="text"],
[type="time"],
[type="url"],
[type="week"],
select,
textarea {
  min-height: 1.5;
}
code,
kbd,
pre,
samp {
  font-family: monospace, monospace;
}
nav ol,
nav ul {
  list-style: none;
}
select {
  -moz-appearance: none;
  -webkit-appearance: none;
}
select::-ms-expand {
  display: none;
}
select::-ms-value {
  color: currentColor;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}
textarea {
  resize: vertical;
}
::-moz-selection {
  background-color: #b3d4fc;
  color: #fff;
  text-shadow: none;
}
::selection {
  background-color: #b3d4fc;
  color: #fff;
  text-shadow: none;
}
[aria-busy="true"] {
  cursor: progress;
}
[aria-controls] {
  cursor: pointer;
}
[aria-disabled] {
  cursor: default;
}
[hidden][aria-hidden="false"] {
  clip: rect(0 0 0 0);
  display: inherit;
  position: absolute;
}
[hidden][aria-hidden="false"]:focus {
  clip: auto;
}
html,
body {
  height: 100%;
}
body {
  display: flex;
  align-items: center;
  justify-content: center;
}
h1 {
  display: inline-block;
  font-size: 48px;
  text-align: center;
}


text:
namespace RussianChickenInspector
{
	namespace Creatures
	{
		class Interactable
		{
			virtual void Interact(Creature user);
			virtual bool IsAlive();
			virtual MINX::Rectangle GetCollisionBox();
			virtual std::string GetIdentifier();
		}
	}
}


text:
import { Observable } from 'rxjs';
import { Message } from "./message";
import { User } from "./user";
import { ParticipantResponse } from "./participant-response";
import { IChatParticipant } from './chat-participant';

export abstract class ChatAdapter
{
    // ### Abstract adapter methods ###

    public abstract listFriends(): Observable<ParticipantResponse[]>;

    public abstract getMessageHistory(destinataryId: any): Observable<Message[]>;

    public abstract sendMessage(message: Message): void;

    // ### Adapter/Chat income/ingress events ###

    public onFriendsListChanged(participantsResponse: ParticipantResponse[]): void
    {
        this.friendsListChangedHandler(participantsResponse);
    }

    public onMessageReceived(participant: IChatParticipant, message: Message): void
    {
        this.messageReceivedHandler(participant, message);
    }

    // Event handlers
    /** @internal */
    friendsListChangedHandler: (participantsResponse: ParticipantResponse[]) => void  = (participantsResponse: ParticipantResponse[]) => {};
    /** @internal */
    messageReceivedHandler: (participant: IChatParticipant, message: Message) => void = (participant: IChatParticipant, message: Message) => {};
}


text:
// The MIT License (MIT)
//
// Copyright (c) 2019-2022 Camptocamp SA
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import angular from 'angular';

import {unlistenByKeys as ngeoEventsUnlistenByKeys} from 'ngeo/events';
import ngeoQueryMode from 'ngeo/query/Mode';
import ngeoQueryModeSelector from 'ngeo/query/ModeSelector';
import ngeoQueryMapQuerent from 'ngeo/query/MapQuerent';

import {listen as olEventsListen} from 'ol/events';
import {always as olEventsConditionAlways} from 'ol/events/condition';
import olInteractionDraw, {createBox as olInteractionDrawCreateBox} from 'ol/interaction/Draw';
import olLayerVector from 'ol/layer/Vector';
import olSourceVector from 'ol/source/Vector';

import ImageLayer from 'ol/layer/Image';
import TileLayer from 'ol/layer/Tile';

/**
 * @type {angular.IModule}
 * @hidden
 */
const myModule = angular.module('ngeoQuery', [ngeoQueryModeSelector.name, ngeoQueryMapQuerent.name]);

/**
 * @hidden
 */
export class QueryController {
  /**
   * @param {import('ngeo/query/MapQuerent').MapQuerent} ngeoMapQuerent
   *    The ngeo map querent service.
   * @param {import('ngeo/query/ModeSelector').QueryModeSelector} ngeoQueryModeSelector
   *    The ngeo query modeSelector service.
   * @param {angular.IScope} $scope Scope.
   * @param {import('ngeo/options').ngeoQueryOptions} ngeoQueryOptions The options.
   * @ngInject
   * @ngdoc controller
   * @ngname NgeoQueryController
   */
  constructor(ngeoMapQuerent, ngeoQueryModeSelector, $scope, ngeoQueryOptions) {
    // === Binding properties ===

    /**
     * @type {boolean}
     */
    this.active;

    /**
     * @type {boolean}
     */
    this.autoclear;

    /**
     * @type {!import('ol/Map').default}
     */
    this.map;

    // === Injected properties ===

    /**
     * @type {import('ngeo/query/MapQuerent').MapQuerent}
     * @private
     */
    this.ngeoMapQuerent_ = ngeoMapQuerent;

    /**
     * @type {import('ngeo/query/ModeSelector').QueryModeSelector}
     * @private
     */
    this.ngeoQueryModeSelector_ = ngeoQueryModeSelector;

    /**
     * @type {import('ngeo/options').ngeoQueryOptions}
     * @private
     */
    this.ngeoQueryOptions_ = ngeoQueryOptions;

    /**
     * @type {angular.IScope}
     * @private
     */
    this.scope_ = $scope;

    // === Inner properties ===

    /**
     * @type {olSourceVector<import('ol/geom/Polygon').default>}
     * @private
     */
    this.vectorSource_ = new olSourceVector({
      wrapX: false,
    });

    /**
     * @type {olLayerVector<olSourceVector<import('ol/geom/Polygon').default>>}
     * @private
     */
    this.vectorLayer_ = new olLayerVector({
      source: this.vectorSource_,
    });

    /**
     * @type {olInteractionDraw}
     * @private
     */
    this.drawBoxInteraction_ = new olInteractionDraw({
      condition: olEventsConditionAlways,
      geometryFunction: olInteractionDrawCreateBox(),
      source: this.vectorSource_,
      stopClick: true,
      type: 'Circle',
    });

    /**
     * @type {olInteractionDraw}
     * @private
     */
    this.drawPolygonInteraction_ = new olInteractionDraw({
      condition: olEventsConditionAlways,
      source: this.vectorSource_,
      stopClick: true,
      type: 'Polygon',
    });

    /**
     * The event keys of the currently active "mode".
     *
     * @type {import('ol/events').EventsKey[]}
     * @private
     */
    this.listenerKeys_ = [];

    /**
     * @type {?string}
     * @private
     */
    this.mode_ = null;

    // === Event listeners that uses angular $scope

    $scope.$watch(() => this.active, this.handleActiveChange_.bind(this));

    $scope.$watch(() => {
      let value = null;
      if (this.active) {
        value = this.ngeoQueryModeSelector_.mode;
      }
      return value;
    }, this.enableMode_.bind(this));
  }

  /**
   * Called on initialization of the controller.
   */
  $onInit() {
    // Set default value of optional binding properties
    this.autoclear = !!this.autoclear;
  }

  /**
   * Called on destruction of the controller.
   */
  $onDestroy() {
    this.enableMode_(null);
  }

  // === Mode enabling/disabling ===

  /**
   * Disable the current mode, then enable a new mode, i.e. add any
   * interaction of that mode to the map.
   *
   * @param {?string} mode Mode to enable
   * @private
   */
  enableMode_(mode) {
    this.disableMode_();

    // No need to do anything if there's no mode to enable
    if (!mode) {
      return;
    }

    // For debug purpose
    // console.log(`mode enable: ${mode}`);

    switch (mode) {
      case ngeoQueryMode.CLICK:
        this.listenerKeys_.push(olEventsListen(this.map, 'singleclick', this.handleMapClick_, this));
        if (this.ngeoQueryOptions_.cursorHover) {
          this.listenerKeys_.push(olEventsListen(this.map, 'pointermove', this.handleMapPointerMove_, this));
        }
        break;

      case ngeoQueryMode.DRAW_BOX:
        this.map.addLayer(this.vectorLayer_);
        this.map.addInteraction(this.drawBoxInteraction_);
        this.listenerKeys_.push(
          olEventsListen(
            this.drawBoxInteraction_,
            'drawend',
            /** @type {import('ol/events').ListenerFunction} */ (this.handleDrawBoxInteractionDrawEnd_),
            this
          )
        );
        break;

      case ngeoQueryMode.DRAW_POLYGON:
        this.map.addLayer(this.vectorLayer_);
        this.map.addInteraction(this.drawPolygonInteraction_);
        this.listenerKeys_.push(
          olEventsListen(
            this.drawPolygonInteraction_,
            'drawend',
            /** @type {import('ol/events').ListenerFunction} */ (this.handleDrawPolygonInteractionDrawEnd_),
            this
          )
        );
        break;

      default:
        break;
    }

    this.mode_ = mode;
  }

  /**
   * Disable the current mode, i.e. remove any interaction of that
   * mode from the map.
   *
   * @private
   */
  disableMode_() {
    // No need to do anything if there's no mode currently active
    if (!this.mode_) {
      return;
    }

    // For debug purpose
    // console.log(`mode disable: ${this.mode_}`);

    switch (this.mode_) {
      case ngeoQueryMode.CLICK:
        // Reset cursor, if required
        if (this.ngeoQueryOptions_.cursorHover) {
          this.map.getTargetElement().style.cursor = '';
        }
        break;

      case ngeoQueryMode.DRAW_BOX:
        this.vectorSource_.clear();
        this.map.removeLayer(this.vectorLayer_);
        this.map.removeInteraction(this.drawBoxInteraction_);
        break;

      case ngeoQueryMode.DRAW_POLYGON:
        this.vectorSource_.clear();
        this.map.removeLayer(this.vectorLayer_);
        this.map.removeInteraction(this.drawPolygonInteraction_);
        break;

      default:
        break;
    }

    ngeoEventsUnlistenByKeys(this.listenerKeys_);

    this.mode_ = null;
  }

  // === Utilities ===

  /**
   * The maximum number of features a query should return. Obtained
   * from the options.
   *
   * @returns {number|undefined}
   * @private
   */
  getLimitOption_() {
    return this.ngeoQueryOptions_ && this.ngeoQueryOptions_.limit ? this.ngeoQueryOptions_.limit : undefined;
  }

  // === Handlers ===

  /**
   * Called when active property changes
   *
   * @param {boolean} active Whether this component is active or not.
   * @private
   */
  handleActiveChange_(active) {
    if (!active) {
      if (this.autoclear) {
        this.ngeoMapQuerent_.clear();
      }
    }
  }

  /**
   * Called when a box is drawn on the map. Use it to issue a query.
   *
   * @param {import('lib/ol.interaction.Draw').DrawEvent} evt The draw interaction drawend event being fired.
   * @private
   */
  handleDrawBoxInteractionDrawEnd_(evt) {
    const feature = evt.feature;

    const action = this.ngeoQueryModeSelector_.action;
    const extent = feature.getGeometry().getExtent();
    const limit = this.getLimitOption_();
    const map = this.map;

    this.ngeoQueryModeSelector_.pending = true;

    this.ngeoMapQuerent_
      .issue({
        action,
        extent,
        limit,
        map,
      })
      .then(() => {})
      .catch(() => {})
      .then(() => {
        // "finally"
        this.vectorSource_.clear();
        this.ngeoQueryModeSelector_.pending = false;
      });
  }

  /**
   * Called when a polygon is drawn on the map. Use it to issue a query.
   *
   * @param {import('lib/ol.interaction.Draw').DrawEvent} evt The draw interaction drawend event being fired.
   * @private
   */
  handleDrawPolygonInteractionDrawEnd_(evt) {
    const feature = evt.feature;

    const action = this.ngeoQueryModeSelector_.action;
    const geometry = feature.getGeometry();
    const limit = this.getLimitOption_();
    const map = this.map;

    this.ngeoQueryModeSelector_.pending = true;

    this.ngeoMapQuerent_
      .issue({
        action,
        geometry,
        limit,
        map,
      })
      .then(() => {})
      .catch(() => {})
      .then(() => {
        // "finally"
        this.vectorSource_.clear();
        this.ngeoQueryModeSelector_.pending = false;
      });
  }

  /**
   * Called when the map is clicked while this component is active and the mode is "click". Issue a request
   * to the query service using the coordinate that was clicked.
   *
   * @param {Event|import('ol/events/Event').default} evt The map browser event being fired.
   * @private
   */
  handleMapClick_(evt) {
    if (!evt.originalEvent) {
      // not a MapBrowserEvent
      return;
    }

    const action = this.ngeoQueryModeSelector_.action;
    const coordinate = evt.coordinate;
    const map = this.map;

    this.ngeoQueryModeSelector_.pending = true;

    this.ngeoMapQuerent_
      .issue({
        action,
        coordinate,
        map,
      })
      .then(() => {})
      .catch(() => {})
      .then(() => {
        // "finally"
        this.ngeoQueryModeSelector_.pending = false;
      });
  }

  /**
   * Called when the pointer is moved over the map while this component is active and the mode is "click".
   * Change the mouse pointer when hovering a non-transparent pixel on the map.
   *
   * @param {Event|import('ol/events/Event').default} evt The map browser event being fired.
   * @returns {boolean}
   */
  handleMapPointerMove_(evt) {
    // No need to do anything if user is dragging the map
    if (!evt.originalEvent || evt.dragging) {
      // not a MapBrowserEvent
      return false;
    }

    let hit = false;
    this.map.getAllLayers().forEach((layer) => {
      if (layer.get('visible') && !!layer.get('querySourceIds'))
        if (layer instanceof ImageLayer || layer instanceof TileLayer) {
          if (layer.getData(evt.pixel)) {
            hit = true;
          }
        }
    });
    this.map.getTargetElement().style.cursor = hit ? 'pointer' : '';
  }
}

myModule.component('ngeoQuery', {
  bindings: {
    'active': '=',
    'autoclear': '=?',
    'map': '<',
  },
  controller: QueryController,
});

export default myModule;


text:
from __future__ import absolute_import, division, print_function

from glue.core import Data, DataCollection
from qtpy import QtWidgets

from ..data_combo_helper import (ComponentIDComboHelper, ManualDataComboHelper,
                                 DataCollectionComboHelper)

def _items_as_string(combo):
    items = [combo.itemText(i) for i in range(combo.count())]
    return ":".join(items)

def test_component_id_combo_helper():

    combo = QtWidgets.QComboBox()

    dc = DataCollection([])

    helper = ComponentIDComboHelper(combo, dc)

    assert _items_as_string(combo) == ""

    data1 = Data(x=[1,2,3], y=[2,3,4], label='data1')

    dc.append(data1)
    helper.append_data(data1)

    assert _items_as_string(combo) == "x:y"

    data2 = Data(a=[1,2,3], b=['a','b','c'], label='data2')

    dc.append(data2)
    helper.append_data(data2)

    assert _items_as_string(combo) == "data1:x:y:data2:a:b"

    helper.categorical = False

    assert _items_as_string(combo) == "data1:x:y:data2:a"

    helper.numeric = False

    assert _items_as_string(combo) == "data1:data2"

    helper.categorical = True
    helper.numeric = True

    helper.visible = False
    assert _items_as_string(combo) == "data1:Pixel Axis 0 [x]:World 0:x:y:data2:Pixel Axis 0 [x]:World 0:a:b"
    helper.visible = True

    dc.remove(data2)

    assert _items_as_string(combo) == "x:y"

    # TODO: check that renaming a component updates the combo
    # data1.id['x'].label = 'z'
    # assert _items_as_string(combo) == "z:y"

    helper.remove_data(data1)

    assert _items_as_string(combo) == ""

def test_component_id_combo_helper_init():

    # Regression test to make sure that the numeric and categorical options
    # in the __init__ are taken into account properly

    combo = QtWidgets.QComboBox()

    dc = DataCollection([])

    data = Data(a=[1,2,3], b=['a','b','c'], label='data2')
    dc.append(data)

    helper = ComponentIDComboHelper(combo, dc)
    helper.append_data(data)
    assert _items_as_string(combo) == "a:b"

    helper = ComponentIDComboHelper(combo, dc, numeric=False)
    helper.append_data(data)
    assert _items_as_string(combo) == "b"

    helper = ComponentIDComboHelper(combo, dc, categorical=False)
    helper.append_data(data)
    assert _items_as_string(combo) == "a"

    helper = ComponentIDComboHelper(combo, dc, numeric=False, categorical=False)
    helper.append_data(data)
    assert _items_as_string(combo) == ""

def test_manual_data_combo_helper():

    combo = QtWidgets.QComboBox()

    dc = DataCollection([])

    helper = ManualDataComboHelper(combo, dc)

    data1 = Data(x=[1,2,3], y=[2,3,4], label='data1')

    dc.append(data1)

    assert _items_as_string(combo) == ""

    helper.append_data(data1)

    assert _items_as_string(combo) == "data1"

    data1.label = 'mydata1'
    assert _items_as_string(combo) == "mydata1"

    dc.remove(data1)

    assert _items_as_string(combo) == ""

def test_data_collection_combo_helper():

    combo = QtWidgets.QComboBox()

    dc = DataCollection([])

    helper = DataCollectionComboHelper(combo, dc)

    data1 = Data(x=[1,2,3], y=[2,3,4], label='data1')

    dc.append(data1)

    assert _items_as_string(combo) == "data1"

    data1.label = 'mydata1'
    assert _items_as_string(combo) == "mydata1"

    dc.remove(data1)

    assert _items_as_string(combo) == ""


text:
package squidpony.examples;

import squidpony.squidmath.Arrangement;

/**
 * Created by Tommy Ettinger on 10/28/2016.
 */
public class ArrangementTest {
    public static void main(String[] args){
        Arrangement<String> strings = new Arrangement<>(8);
        System.out.println("aaa: " + strings.add("aaa") + " " + strings.get("aaa"));
        System.out.println("bbb: " + strings.add("bbb") + " " + strings.get("bbb"));
        System.out.println("ccc: " + strings.add("ccc") + " " + strings.get("ccc"));
    }
}


text:
package org.apereo.portal.character.stream.events;

import java.io.Serializable;

/**
 * @author Eric Dalquist
 * @version $Revision$
 */
public interface CharacterEvent extends Serializable {
    public CharacterEventTypes getEventType();
}


text:
#include "video_engine/vie_performance_monitor.h"

#include "system_wrappers/interface/cpu_wrapper.h"
#include "system_wrappers/interface/critical_section_wrapper.h"
#include "system_wrappers/interface/event_wrapper.h"
#include "system_wrappers/interface/thread_wrapper.h"
#include "system_wrappers/interface/tick_util.h"
#include "system_wrappers/interface/trace.h"
#include "video_engine/include/vie_base.h"
#include "video_engine/vie_defines.h"

namespace webrtc {

enum { kVieMonitorPeriodMs = 975 };

ViEPerformanceMonitor::ViEPerformanceMonitor(int engine_id)
    : engine_id_(engine_id),
      pointer_cs_(CriticalSectionWrapper::CreateCriticalSection()),
      monitor_thread_(NULL),
      monitor_event_(*EventWrapper::Create()),
      cpu_(NULL),
      vie_base_observer_(NULL) {
}

ViEPerformanceMonitor::~ViEPerformanceMonitor() {
  Terminate();
  delete pointer_cs_;
  delete &monitor_event_;
}

int ViEPerformanceMonitor::Init(ViEBaseObserver* vie_base_observer) {
  WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(engine_id_),
               "%s", __FUNCTION__);

  CriticalSectionScoped cs(pointer_cs_);
  if (!vie_base_observer || vie_base_observer_) {
    WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(engine_id_),
                 "%s: Bad input argument or observer already set",
                 __FUNCTION__);
    return -1;
  }

  cpu_ = CpuWrapper::CreateCpu();
  if (cpu_ == NULL) {
    // Performance monitoring not supported
    WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideo,
                 ViEId(engine_id_), "%s: Not supported", __FUNCTION__);
    return 0;
  }

  if (monitor_thread_ == NULL) {
    monitor_event_.StartTimer(true, kVieMonitorPeriodMs);
    monitor_thread_ = ThreadWrapper::CreateThread(ViEMonitorThreadFunction,
                                                  this, kNormalPriority,
                                                  "ViEPerformanceMonitor");
    unsigned int t_id = 0;
    if (monitor_thread_->Start(t_id)) {
      WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(engine_id_),
                   "%s: Performance monitor thread started %u",
                   __FUNCTION__, t_id);
    } else {
      WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(engine_id_),
                   "%s: Could not start performance monitor", __FUNCTION__);
      monitor_event_.StopTimer();
      return -1;
    }
  }
  vie_base_observer_ = vie_base_observer;
  return 0;
}

void ViEPerformanceMonitor::Terminate() {
  WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideo, ViEId(engine_id_),
               "%s", __FUNCTION__);

  pointer_cs_->Enter();
  if (!vie_base_observer_) {
    pointer_cs_->Leave();
    return;
  }

  vie_base_observer_ = NULL;
  monitor_event_.StopTimer();
  if (monitor_thread_) {
    ThreadWrapper* tmp_thread = monitor_thread_;
    monitor_thread_ = NULL;
    monitor_event_.Set();
    pointer_cs_->Leave();
    if (tmp_thread->Stop()) {
      pointer_cs_->Enter();
      delete tmp_thread;
      tmp_thread = NULL;
      delete cpu_;
    }
    cpu_ = NULL;
  }
  pointer_cs_->Leave();
}

bool ViEPerformanceMonitor::ViEBaseObserverRegistered() {
  CriticalSectionScoped cs(pointer_cs_);
  return vie_base_observer_ != NULL;
}

bool ViEPerformanceMonitor::ViEMonitorThreadFunction(void* obj) {
  return static_cast<ViEPerformanceMonitor*>(obj)->ViEMonitorProcess();
}

bool ViEPerformanceMonitor::ViEMonitorProcess() {
  // Periodically triggered with time KViEMonitorPeriodMs
  monitor_event_.Wait(kVieMonitorPeriodMs);
  if (monitor_thread_ == NULL) {
    // Thread removed, exit
    return false;
  }

  CriticalSectionScoped cs(pointer_cs_);
  if (cpu_) {
    int cpu_load = cpu_->CpuUsage();
    if (cpu_load > 75) {
      if (vie_base_observer_) {
        vie_base_observer_->PerformanceAlarm(cpu_load);
      }
    }
  }
  return true;
}

}  // namespace webrtc


text:
extern const std::string CLIENT_NAME;
extern const std::string CLIENT_BUILD;
extern const std::string CLIENT_DATE;

//returns build number or 0 if cannot be parsed
extern int build_version_number(int v1,int v2,int v3,int v4);

static const int CLIENT_VERSION =
  build_version_number(CLIENT_VERSION_MAJOR,CLIENT_VERSION_MINOR,CLIENT_VERSION_REVISION,CLIENT_VERSION_BUILD);

static const int COIN_VERSION =
  build_version_number(COIN_VERSION_MAJOR,COIN_VERSION_MINOR,COIN_VERSION_REVISION,COIN_VERSION_BUILD);

//
// network protocol versioning
//

static const int PROTOCOL_VERSION = 60004;

// earlier versions not supported as of Feb 2012, and are disconnected
// NOTE: as of bitcoin v0.6 message serialization (vSend, vRecv) still
// uses MIN_PROTO_VERSION(209), where message format uses PROTOCOL_VERSION
static const int MIN_PROTO_VERSION = 209;

// nTime field added to CAddress, starting with this version;
// if possible, avoid requesting addresses nodes older than this
static const int CADDR_TIME_VERSION = 31402;

// only request blocks from nodes outside this range of versions
static const int NOBLKS_VERSION_START = 32000;
static const int NOBLKS_VERSION_END = 32400;

// BIP 0031, pong message, is enabled for all versions AFTER this one
static const int BIP0031_VERSION = 60000;

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:paddingLeft="16dp"
    android:paddingTop="4dp"
    android:layout_height="match_parent">
    <EditText
        android:layout_width="match_parent"
        android:hint="Banner URL (Optional)"
        android:id="@+id/edit_banner"
        android:visibility="gone"
        android:layout_height="wrap_content" />
    <Button
        android:layout_width="match_parent"
        android:text="Custom Banner or Icon"
        android:id="@+id/change_banner"
        android:layout_height="wrap_content" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Switch
            android:layout_width="wrap_content"
            android:id="@+id/switch_isgame"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="wrap_content"
            android:text="This is a game."
            android:paddingLeft="36dp"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>


text:
You can use common debugging tools like tcpdump or strace with Toolbox. Using the filesystem of a specified Docker container Toolbox will launch a container with full system privileges including access to system PIDs, network interfaces and other global information. Inside of the toolbox, the machine's filesystem is mounted to `/media/root`.

## Quick Debugging

By default, Toolbox uses the stock Fedora Docker container. To start using it, simply run:

```sh
/usr/bin/toolbox
```

You're now in the namespace of Fedora and can install any software you'd like via `yum`. For example, if you'd like to use `tcpdump`:

```sh
[root@srv-3qy0p ~]# yum install tcpdump
[root@srv-3qy0p ~]# tcpdump -i ens3
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on ens3, link-type EN10MB (Ethernet), capture size 65535 bytes
```

### Specify a Custom Docker Image

Create a `.toolboxrc` in the user's home folder to use a specific Docker image:

```sh
$ cat .toolboxrc
TOOLBOX_DOCKER_IMAGE=index.example.com/debug
TOOLBOX_USER=root
$ /usr/bin/toolbox
Pulling repository index.example.com/debug
...
```

You can also specify this in cloud-config:

```
#cloud-config
write_files:
  - path: /home/core/.toolboxrc
    owner: core
    content: |
      TOOLBOX_DOCKER_IMAGE=index.example.com/debug
      TOOLBOX_DOCKER_TAG=v1
      TOOLBOX_USER=root
```

## SSH Directly Into A Toolbox

Advanced users can SSH directly into a toolbox by setting up an `/etc/passwd` entry:

```sh
useradd bob -m -p '*' -s /usr/bin/toolbox -U -G sudo,docker
```

To test, SSH as bob:

```sh
ssh bob@hostname.example.com

   ______                ____  _____
  / ____/___  ________  / __ \/ ___/
 / /   / __ \/ ___/ _ \/ / / /\__ \
/ /___/ /_/ / /  /  __/ /_/ /___/ /
\____/\____/_/   \___/\____//____/
[root@srv-3qy0p ~]# yum install emacs
[root@srv-3qy0p ~]# emacs /media/root/etc/systemd/system/docker.service
```


text:
class CreateRepositories < ActiveRecord::Migration
  def self.up
    create_table :repositories do |t|
      t.integer :project_id
      t.boolean :is_active
      t.boolean :use_internal
      t.string :external_url

      t.timestamps
    end
  end

  def self.down
    drop_table :repositories
  end
end


text:
"""
A task for MapRoulette.
"""

class MapRouletteTask(object):
    """
    Typical usage::

        task = MapRouletteTask(
            identifier,
            challenge=challenge,
            geometries=geometries,
            instruction=instruction)
        task.create(server_instance)

    :param identifier: A valid Task identifier
    :param challenge: An instance of MapRouletteChallenge
    :param geometries: One or more geometries serialized as a GeoJSON FeatureCollection
    :type geometries: FeatureCollection
    :param instruction: A task-level instruction
    :param status: The task's initial status (defaults to 'created' in MapRoulette)
    """
    instruction = None
    geometries = None
    status = None
    __challenge__ = None
    identifier = None

    def __init__(
            self,
            identifier,
            challenge=None,
            geometries=None,
            instruction=None,
            status=None):
        self.__challenge__ = challenge
        self.identifier = identifier
        self.geometries = geometries
        self.instruction = instruction or ''
        self.status = status or None

    def create(self, server):
        """Create the task on the server"""
        if len(self.geometries) == 0:
            raise Exception('no geometries')
        return server.post(
            'task_admin',
            self.as_payload(),
            replacements={
                'slug': self.__challenge__.slug,
                'identifier': self.identifier})

    def update(self, server):
        """Update existing task on the server"""
        return server.put(
            'task_admin',
            self.as_payload(),
            replacements={
                'slug': self.__challenge__.slug,
                'identifier': self.identifier})

    def exists(self, server):
        """Check if a task exists on the server"""
        try:
            server.get(
                'task',
                replacements={
                    'slug': self.__challenge__.slug,
                    'identifier': self.identifier})
        except Exception:
            return False
        return True

    def as_payload(self, with_identifier=False):
        payload = {
            key: value for key, value in self.__dict__.items()
            if not key.startswith('__')
            and not value is None
            and not callable(key)}
        if with_identifier:
            payload['identifier'] = self.identifier
        return payload

    def __eq__(self, other):
        return (isinstance(other, self.__class__)
                and self.__dict__ == other.__dict__)

    @classmethod
    def from_server(cls, server, slug, identifier):
        """Retrieve a task from the server"""
        task = server.get(
            'task',
            replacements={
                'slug': slug,
                'identifier': identifier})
        return cls(**task)

    @classmethod
    def from_payload(cls, payload):
        """Create a task from JSON"""
        return cls(**payload)


text:
Apply MinDiff in instances where your model performs well
generally, but produces harmful errors more frequently on examples belonging to
a sensitive group, and you wish to close the performance gap. The sensitive
groups of interest may vary depending on your use case, but often include
protected classes, such as race, religion, gender, sexual orientation, and more.
Throughout this document, we will use "sensitive group" to refer to any set of
examples belonging to a protected class.

There are two primary conditions for using MinDiff to address underperforming
slices of data:

-   You have already tuned and evaluated your model, identifying metrics that
show underperforming slices of data. This must be done *before* applying model
remediation.
-   You have, or can obtain, a sufficient number of relevant labeled examples
belonging to the underperforming group (more details below).

Note: If you're new to evaluating for fairness, we recommend reviewing this
module in Google's Machine Learning Crash Course, which provides an introduction
to this topic, and this guide for a broader discussion on the topic.

MinDiff is one of many techniques for remediating unequal behavior. In
particular, it may be a good choice when you're trying to directly equalize
performance between groups. MinDiff can be used in conjunction with other
approaches, such as data augmentation and others, which may lead to better
results. However, if you need to prioritize which technique to invest in, you
should do so according to your product needs.

When applying MinDiff, you may see performance degrade or shift slightly for
your best performing groups, as your underperforming groups improve. This
tradeoff is expected, and should be evaluated in the context of your product
requirements. In practice, we have often seen that MinDiff does not cause top
performing slices to drop below acceptable levels, but this is application-
specific and a decision that needs to be made by the product owner.

### On what model types can I apply MinDiff?
MinDiff has been shown to be consistently effective when applied to *binary
classifiers.* Adapting the method for other applications is possible, but has
not been fully tested. Some work has been done to show success in multi-
classification and ranking tasks1 but any use of MinDiff on these or
other types of models should be considered experimental.

### On what metrics can I apply MinDiff?
MinDiff may be a good solution when the metric you're trying to equalize across
groups is *false positive rate (FPR)*, or *false negative rate (FNR)*, but it may
work for other metrics. As a general rule, MinDiff may work when the metric
you're targeting is a result of differences in the score distributions between
examples belonging to a sensitive group and examples not belonging to a
sensitive group.

## Building your MinDiff dataset
When preparing to train with MinDiff, you'll need to prepare three separate
datasets. As with regular training, your MinDiff datasets should be
representative of the users your model serves. MinDiff may work without this but
you should use extra caution in such cases.

Assuming you're trying to improve your model's FPR for examples belonging to a
sensitive class, you'll need:
1. The original training set - The original dataset that was used for training
your baseline model
2. The MinDiff sensitive set - A dataset of examples belonging to the sensitive
class with *only* negative ground truth labels. These examples will be used only
for calculating the MinDiff loss.
3. The MinDiff non-sensitive set - A dataset of examples *not* belonging to the
sensitive class with *only* negative ground truth labels. These examples will be
used only for calculating the MinDiff loss.

Note: The examples in your MinDiff datasets may overlap partially, or completely
with your original training dataset.

When using the library, you will combine all three of these datasets into a
single dataset, which will serve as your new training set.

### Picking examples for MinDiff
It may have seemed counterintuitive in the example above to carve out sets of
*negatively* labeled examples if you are primarily concerned with disparities in
*false positive rate*. However, remember that a false positive prediction comes
from a negatively labeled example incorrectly classified as positive.

When collecting your data for MinDiff, you should pick examples where the
disparity in performance is evident. In our example above, this meant choosing
negatively labeled examples to address FPR. Had we been interested in targeting
FNR, we would have needed to choose positively labeled examples.

### How much data do I need?
Good question--it depends on your use case! Based on your model architecture,
data distribution, and MinDiff configuration, the amount of data needed can vary
significantly. In past applications, we have seen MinDiff work well with 5,000
examples in each MinDiff training set (sets 2 and 3 in the previous section).
With less data, there is increased risk of lowered performance, but this may be
minimal or acceptable within the bounds of your production constraints. After
applying MinDiff, you will need to evaluate your results thoroughly to ensure
acceptable performance. If they are unreliable, or do not meet performance
expectations, you may still want to consider gathering more data.

## When is MinDiff *not* right for me?
MinDiff is a powerful technique that can provide impressive results, but this
does not mean that it is the right method for all situations. Applying it
haphazardly does not guarantee that you will achieve an adequate solution.

Beyond the requirements discussed above, there are cases where MinDiff may be
technically feasible, but not suitable. You should always design your ML
workflow according to known recommended practices. For instance, if your model
task is ill-defined, the product needs unclear, or your example labels overly
skewed, you should prioritize addressing these issues. Similarly, if you do not
have a clear definition of the sensitive group, or are unable to reliably
determine whether examples belong to the sensitive group, you will not be able
to apply MinDiff effectively.

At a higher level, you should always consider whether your product is an
appropriate use for ML at all. If it is, consider the potential vectors for user
harm it creates. The pursuit of responsible ML is a multi-faceted effort which
aims to anticipate a broad range of potential harms; MinDiff can help mitigate
some of these, but all outcomes deserve careful consideration.

1Beutel A., Chen, J., Doshi, T., Qian, H., Wei, L., Wu, Y., Heldt,
L., Zhao, Z., Hong, L., Chi, E., Goodrow, C. (2019). [Fairness in Recommendation
Ranking through Pairwise
Comparisons.](https://dl.acm.org/doi/abs/10.1145/3292500.3330745)


text:
To create a custom button on your form, you need to edit the javascript file associated to your doctype. For example, If you want to add a custom button to User form then you must edit `user.js`.

In this file, you need to write a new method `add_custom_button` which should add a button to your form.

#### Function Signature for `add_custom_button(...)`
    frm.add_custom_button(__(buttonName), function(){
      //perform desired action such as routing to new form or fetching etc.
    }, __(groupName));

#### Example-1: Adding a button to User form
We should edit `frappe\core\doctype\user\user.js`

    frappe.ui.form.on('User', {
    	refresh: function(frm) {
        ...
          frm.add_custom_button(__('Get User Email ID'), function(){
            frappe.msgprint(frm.doc.email);
        }, __("Utilities"));
        ...
      }
    });

You should be seeing a button on user form as shown below,

![add_custom_button_screenshot](/assets/img/app-development/add_custom_button.png)

<!-- markdown -->


text:
<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class LuckyController extends Controller
{
    public function numberAction()
    {
        return $this->render('AppBundle:Lucky:number.html.twig', array(
            // ...
        ));
    }

}