text:
/**
 *    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 net.floodlightcontroller.hasupport;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;

public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
	private final AsyncElection aelection;
	private final String controllerID;

	public ServerChannelInitializer(AsyncElection aelection, String controllerID) {
		this.aelection = aelection;
		this.controllerID = controllerID;
	}

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ch.pipeline().addLast(new ServerExceptionHandler());
		ch.pipeline().addLast(new ServerChannelInboundHandler(aelection, controllerID));
	}
}


text:
postgresql = node['postgresql']
gitlab = node['gitlab']

# 5.Database
include_recipe "postgresql::server"
include_recipe "database::postgresql"

postgresql_connexion = {
  :host => 'localhost',
  :username => 'postgres',
  :password => postgresql['password']['postgres']
}

## Create a user for GitLab.
postgresql_database_user gitlab['user'] do
  connection postgresql_connexion
  password gitlab['database_password']
  action :create
end

## Create the GitLab database & grant all privileges on database
postgresql_database "gitlabhq_#{gitlab['env']}" do
  connection postgresql_connexion
  action :create
end

postgresql_database_user gitlab['user'] do
  connection postgresql_connexion
  database_name "gitlabhq_#{gitlab['env']}"
  password gitlab['database_password']
  action :grant
end

redpajama_set_name: RedPajamaGithub


text:
package chipyard.example

import chisel3._
import chisel3.util._
import freechips.rocketchip.subsystem.{BaseSubsystem, CacheBlockBytes}
import freechips.rocketchip.config.{Parameters, Field, Config}
import freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp, IdRange}
import testchipip.TLHelper

case class InitZeroConfig(base: BigInt, size: BigInt)
case object InitZeroKey extends Field[Option[InitZeroConfig]](None)

class InitZero(implicit p: Parameters) extends LazyModule {
  val node = TLHelper.makeClientNode(
    name = "init-zero", sourceId = IdRange(0, 1))

  lazy val module = new InitZeroModuleImp(this)
}

class InitZeroModuleImp(outer: InitZero) extends LazyModuleImp(outer) {
  val config = p(InitZeroKey).get

  val (mem, edge) = outer.node.out(0)
  val addrBits = edge.bundle.addressBits
  val blockBytes = p(CacheBlockBytes)

  require(config.size % blockBytes == 0)

  val s_init :: s_write :: s_resp :: s_done :: Nil = Enum(4)
  val state = RegInit(s_init)

  val addr = Reg(UInt(addrBits.W))
  val bytesLeft = Reg(UInt(log2Ceil(config.size+1).W))

  mem.a.valid := state === s_write
  mem.a.bits := edge.Put(
    fromSource = 0.U,
    toAddress = addr,
    lgSize = log2Ceil(blockBytes).U,
    data = 0.U)._2
  mem.d.ready := state === s_resp

  when (state === s_init) {
    addr := config.base.U
    bytesLeft := config.size.U
    state := s_write
  }

  when (edge.done(mem.a)) {
    addr := addr + blockBytes.U
    bytesLeft := bytesLeft - blockBytes.U
    state := s_resp
  }

  when (mem.d.fire) {
    state := Mux(bytesLeft === 0.U, s_done, s_write)
  }
}

trait CanHavePeripheryInitZero { this: BaseSubsystem =>
  implicit val p: Parameters

  p(InitZeroKey) .map { k =>
    val initZero = LazyModule(new InitZero()(p))
    fbus.fromPort(Some("init-zero"))() := initZero.node
  }
}

// DOC include start: WithInitZero
class WithInitZero(base: BigInt, size: BigInt) extends Config((site, here, up) => {
  case InitZeroKey => Some(InitZeroConfig(base, size))
})
// DOC include end: WithInitZero


text:
$packageName = 'syncany'
$packageSearch = "syncany*"
$fileType = 'exe'
$silentArgs = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-'
$validExitCodes = @(0)
Get-ItemProperty -Path @( 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*',
                          'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*',
                          'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*' ) `
                 -ErrorAction:SilentlyContinue `
| Where-Object   { $_.DisplayName -like $packageSearch } `
| ForEach-Object { Uninstall-ChocolateyPackage -PackageName "$packageName" `
                                               -FileType "$fileType" `
                                               -SilentArgs "$($silentArgs)" `
                                               -File "$($_.UninstallString.Replace('"',''))" `
                                               -ValidExitCodes $validExitCodes }


text:
/*!
	folioGallery v1.4 - 2015-01-30
	(c) 2014 Harry Ghazanian - foliopages.com/php-jquery-ajax-photo-gallery-no-database
	This content is released under the http://www.opensource.org/licenses/mit-license.php MIT License.
*/
$(function() {

	var folioGalleryDir = './'; // foliogallery folder relative path - absolute path like http://my_website.com/foliogallery may not work

	// find divs with class folioGallery and load album in it based on its id
	$('.folioGallery').each(function() {

		var targetDiv = (this.id); // id of div to load albums
		var numPerPage = $('#'+targetDiv+' div.numPerPage').prop('title');

		if(targetDiv=='folioGallery') {
			var fullAlbum = 1;
			var showAlb = ''; // empty will show full gallery
		} else {
			var fullAlbum = 0;
			var showAlb = $('#'+targetDiv).prop('title'); // title attribute of div - same as album folder
		}

		loadGallery(folioGalleryDir,targetDiv,showAlb,numPerPage,1,fullAlbum); // inital load

		// in gallery view, load album when thumb is clicked
		$(this).on('click', 'a.showAlb', function() {
			var showAlb = $(this).prop('rel');
			loadGallery(folioGalleryDir,targetDiv,showAlb,numPerPage,1,fullAlbum);
			return false;
		});

		// paginate albums and pics
		$(this).on('click', 'a.pag', function() {
			var showAlb = $(this).prop('rel');
			var pageNum = $(this).prop('rev');
			loadGallery(folioGalleryDir,targetDiv,showAlb,numPerPage,pageNum,fullAlbum);
			return false;
		});

		// refresh div content
		$(this).on('click', 'a.refresh', function() {
		   loadGallery(folioGalleryDir,targetDiv,'',numPerPage,1,fullAlbum);
		   return false;
		});

	});

});

function loadGallery(folioGallerydir,targetdiv,album,numperpage,pagenum,fullalbum) {
	$.ajax
	({
		type: 'POST',
		url: folioGallerydir+'/foliogallery.php?'+album+'&p='+pagenum,
		data: {
			album: album,
			numperpage: numperpage,
			pagenum: pagenum,
			fullalbum: fullalbum
		},
		cache: false,
		success: function(msg)
		{
			$('#'+targetdiv).html(msg).hide().show();
		}
	});
	return false;
}


text:
""" Investable Server """

from flask import Flask, render_template, redirect, flash, request, jsonify, json
from flask_debugtoolbar import DebugToolbarExtension

import jinja2
import os
import geocoder

from zillow_utilities import *
from account_utilities import *
from mortgage_calculator import *
from db_queries import *
from model import *

app = Flask(__name__)

app.secret_key = os.environ['APP_KEY']
app.zwsid = os.environ['ZWSID']
app.gmaps = os.environ['GMAPS_JS']

# jinja debugger
app.jinja_env.undefined = jinja2.StrictUndefined
app.jinja_env.auto_reload = True

##############################################################################
# Route definitions

@app.route('/')
def homepage():
    """ Brings user to the homepage. """

    return render_template('index.html', GMAPS_JS=app.gmaps)

@app.route('/search.json')
def search():
    """ Returns user search results from Zillow's API and PostgreSQL. """

    # Search address entered by the user
    full_address = {}
    full_address.update(request.args.items())

    # Gets API response data from zillow_utilities
    response_code, price, message, hoa = get_unit_price(full_address)

    # If the location is found in Zillow's API
    if response_code == 100:
        unit_details = get_zillow_unit_details(full_address)

        # Returns the response code and unit details from Zillow's API and PostgreSQL
        listing = { 'response': response_code,
                    'price': price,
                    'message': message,
                    'neighborhood': unit_details['neighborhood'],
                    'street': unit_details['street'],
                    'city': unit_details['city'],
                    'state': unit_details['state'],
                    'zipcode': unit_details['zipcode'],
                    'bedrooms': unit_details['bedrooms'],
                    'bathrooms': unit_details['bathrooms'],
                    'sqft': unit_details['sqft'],
                    'hoa': hoa,
                    'latitude': unit_details['latitude'],
                    'longitude': unit_details['longitude'],
                    'latlng_point': unit_details['latlng_point'],
                    'zpid': unit_details['zpid']
                    }

        # Adds a listing to the database
        add_listing_to_db(listing)

    else:
        listing = { 'response': response_code, 'price': price, 'message': message }

    return jsonify(listing)

@app.route('/avgrent.json')
def get_rent_avgs():
    """ Gets average rent data from db_queries. """

    listing = request.args.get('listing')
    listing_dict = json.loads(listing)

    # If source data contains a latlng_point
    if listing_dict.get('latlng_point'):
        latlng_point = listing_dict['latlng_point']
    # Otherwise, make a latlng point
    else:
        latlng_point = 'POINT({} {})'.format(listing_dict['latitude'],listing_dict['longitude'])

    rent_avgs = get_avg_rent(listing_dict['bedrooms'], listing_dict['bathrooms'], listing_dict['sqft'], latlng_point)

    return jsonify(rent_avgs)

@app.route('/listings.json')
def get_listings():
    """ Finds listings in the area filtered by bedrooms, bathrooms, and/or prices. """

    bounds = json.loads(request.args.get('geoBounds'))
    bedrooms = float(request.args.get('bedroomFilter'))
    bathrooms = float(request.args.get('bathroomFilter'))
    low_price = int(request.args.get('lowPrice'))
    high_price = int(request.args.get('highPrice'))

    # Retrieves listings from db_queries
    filtered_listings = find_all_listings(bounds, bedrooms, bathrooms, low_price, high_price)

    return jsonify(filtered_listings)

@app.route('/calculator')
def calculate_monthly_payment():
    """ Calculates the monthly mortgage payment based on user's details. """

    # User mortgage data pulled from AJAX
    mortgage_details = {}
    mortgage_details.update(request.args.items())
    mortgage, total_mortgage = calculate_mortgage(mortgage_details)

    return jsonify({ 'mortgage': mortgage, 'total_mortgage': total_mortgage })

##############################################################################
# Helper functions

if __name__ == "__main__":
    app.debug = False

    # Use the DebugToolbar
    DebugToolbarExtension(app)

    # Connect DB to Flask before running app
    connect_to_db_flask(app, os.environ.get("DATABASE_URL"))

    PORT = int(os.environ.get('PORT', 5000))
    app.run(host="0.0.0.0", port=PORT)


text:
Write a script that backs itself up, that is, copies itself to a file named backup.sh.
Hint: Use the cat command and the appropriate positional parameter.


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-parent</artifactId>
        <version>2.10.6</version>
        <relativePath>../../parent</relativePath>
    </parent>

    <artifactId>camel-jmx</artifactId>
    <packaging>bundle</packaging>
    <name>Camel :: JMX</name>
    <description>Camel JMX support</description>

    <properties>
        <camel.osgi.export.pkg>org.apache.camel.component.jmx.*</camel.osgi.export.pkg>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>xmlunit</groupId>
            <artifactId>xmlunit</artifactId>
            <version>${xmlunit-version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.jvnet.jaxb2.maven2</groupId>
                <artifactId>maven-jaxb2-plugin</artifactId>
                <version>${jaxb2-plugin-version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <strict>false</strict>
                    <extension>true</extension>
                    <args>
                        <arg>-Xfluent-api</arg>
                    </args>
                    <plugins>
                        <plugin>
                            <groupId>net.java.dev.jaxb2-commons</groupId>
                            <artifactId>jaxb-fluent-api</artifactId>
                            <version>2.1.8</version>
                        </plugin>
                    </plugins>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
package com.comsysto.metagrapher.example;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@SpringBootApplication
@EnableEurekaClient
@Controller
public class Application {

    @Value("${example.name}")
    String applicationName;

    @RequestMapping("/")
    @ResponseBody
    public String listMetagrapherProperties() {
        return "Hello World " + applicationName;
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}


text:
namespace {

std::string RunScriptAndReturnResult(const extensions::ExtensionHost* host,
                                     const std::string& script) {
  std::string result;
  EXPECT_TRUE(content::ExecuteScriptAndExtractString(host->host_contents(),
                                                     script, &result))
      << script;
  return result;
}

}  // namespace

namespace extensions {

class HistoryApiTest : public ExtensionApiTest {
 public:
  void SetUpOnMainThread() override {
    ExtensionApiTest::SetUpOnMainThread();

    host_resolver()->AddRule("www.a.com", "127.0.0.1");
    host_resolver()->AddRule("www.b.com", "127.0.0.1");
  }
};

IN_PROC_BROWSER_TEST_F(HistoryApiTest, MiscSearch) {
  ASSERT_TRUE(StartEmbeddedTestServer());
  ASSERT_TRUE(
      RunExtensionTest("history/regular", {.page_url = "misc_search.html"}))
      << message_;
}

IN_PROC_BROWSER_TEST_F(HistoryApiTest, TimedSearch) {
  ASSERT_TRUE(StartEmbeddedTestServer());
  ASSERT_TRUE(
      RunExtensionTest("history/regular", {.page_url = "timed_search.html"}))
      << message_;
}

IN_PROC_BROWSER_TEST_F(HistoryApiTest, Delete) {
  ASSERT_TRUE(StartEmbeddedTestServer());
  ASSERT_TRUE(RunExtensionTest("history/regular", {.page_url = "delete.html"}))
      << message_;
}

IN_PROC_BROWSER_TEST_F(HistoryApiTest, DeleteProhibited) {
  browser()->profile()->GetPrefs()->
      SetBoolean(prefs::kAllowDeletingBrowserHistory, false);
  ASSERT_TRUE(StartEmbeddedTestServer());
  ASSERT_TRUE(RunExtensionTest("history/regular",
                               {.page_url = "delete_prohibited.html"}))
      << message_;
}

IN_PROC_BROWSER_TEST_F(HistoryApiTest, GetVisits) {
  ASSERT_TRUE(StartEmbeddedTestServer());
  ASSERT_TRUE(
      RunExtensionTest("history/regular", {.page_url = "get_visits.html"}))
      << message_;
}

IN_PROC_BROWSER_TEST_F(HistoryApiTest, SearchAfterAdd) {
  ASSERT_TRUE(StartEmbeddedTestServer());
  ASSERT_TRUE(RunExtensionTest("history/regular",
                               {.page_url = "search_after_add.html"}))
      << message_;
}

// Test when History API is used from incognito mode, it has access to the
// regular mode history and actual incognito navigation has no effect on it.
IN_PROC_BROWSER_TEST_F(HistoryApiTest, Incognito) {
  ASSERT_TRUE(StartEmbeddedTestServer());
  // Setup.
  Browser* incognito_browser = CreateIncognitoBrowser(browser()->profile());
  ExtensionTestMessageListener regular_listener("regular ready");
  ExtensionTestMessageListener incognito_listener("incognito ready");
  const Extension* extension =
      LoadExtension(test_data_dir_.AppendASCII("history/incognito"),
                    {.allow_in_incognito = true});
  ASSERT_TRUE(extension);
  ASSERT_TRUE(regular_listener.WaitUntilSatisfied());
  ASSERT_TRUE(incognito_listener.WaitUntilSatisfied());

  ExtensionHost* on_the_record_background_page =
      ProcessManager::Get(browser()->profile())
          ->GetBackgroundHostForExtension(extension->id());
  ASSERT_TRUE(on_the_record_background_page);

  ExtensionHost* incognito_background_page =
      ProcessManager::Get(incognito_browser->profile())
          ->GetBackgroundHostForExtension(extension->id());
  ASSERT_TRUE(incognito_background_page);
  EXPECT_NE(incognito_background_page, on_the_record_background_page);

  // Check if history is empty in regular mode.
  EXPECT_EQ("0", RunScriptAndReturnResult(on_the_record_background_page,
                                          "countItemsInHistory()"));

  // Insert an item in incognito mode.
  EXPECT_EQ(std::string("success"),
            RunScriptAndReturnResult(incognito_background_page, "addItem()"));

  // Check history in incognito mode.
  EXPECT_EQ("1", RunScriptAndReturnResult(on_the_record_background_page,
                                          "countItemsInHistory()"));

  // Check history in regular mode.
  EXPECT_EQ("1", RunScriptAndReturnResult(on_the_record_background_page,
                                          "countItemsInHistory()"));

  // Perform navigation in incognito mode.
  const GURL b_com =
      embedded_test_server()->GetURL("www.b.com", "/simple.html");
  content::TestNavigationObserver incognito_observer(
      incognito_browser->tab_strip_model()->GetActiveWebContents());
  ASSERT_TRUE(ui_test_utils::NavigateToURL(incognito_browser, b_com));
  EXPECT_TRUE(incognito_observer.last_navigation_succeeded());

  // Check history in regular mode is not modified by incognito navigation.
  EXPECT_EQ("1", RunScriptAndReturnResult(on_the_record_background_page,
                                          "countItemsInHistory()"));

  // Check that history in incognito mode is not modified by navigation as
  // incognito navigations are not recorded in history.
  EXPECT_EQ("1", RunScriptAndReturnResult(incognito_background_page,
                                          "countItemsInHistory()"));

  // Perform navigation in regular mode.
  content::TestNavigationObserver regular_observer(
      browser()->tab_strip_model()->GetActiveWebContents());
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), b_com));
  EXPECT_TRUE(regular_observer.last_navigation_succeeded());

  // Check history in regular mode is modified by navigation.
  EXPECT_EQ("2", RunScriptAndReturnResult(on_the_record_background_page,
                                          "countItemsInHistory()"));

  // Check history in incognito mode is modified by navigation.
  EXPECT_EQ("2", RunScriptAndReturnResult(incognito_background_page,
                                          "countItemsInHistory()"));
}

}  // namespace extensions


text:
<?php
/**
*@author:
*/

//Les importations nécessaires
import('phpens.framework.html.Page');
import('phpens.framework.html.Header');
import('phpens.framework.html.Text');
import('phpens.framework.View');
import('phpens.framework.Response');
import('phpens.framework.Data');
import('phpens.framework.html.*');

//Création de la page entière
$page=new Page();
$page->setTitle("Music Online");
$page->addCSSFile("css/nls_style.css");

//####################################################################################################################

//Création du header et de sa division
$divHeader = new Division();

//Asigne la classe header à cette division
$divHeader->setClass("header");

//Création du header
$header = new Header(1, 'Music Online');

//Ajout du header dans sa division
$divHeader->addElement($header);

//Ajout de la division du header dans la page principale
$page->addElement($divHeader);

//#####################################################################################################################

//Création du Menu sur le côté gauche
$divMenu = new Division();

//Assigne la classe left_panel à la division du menu
$divMenu->setClass("left_panel");

//Création du panneau de titre du menu
$divTitreMenu = new Division();
$divTitreMenu->setClass("menuBoxHeader");

//Ajout du panel de titre au panel complet du menu
$divMenu->addElement($divTitreMenu);

//Ajout du texte du titre
$divTitreMenu->addElement(new Text("Compte Client"));

//Création de la division du contenu du menu
$divContenuMenu = new Division();
$divContenuMenu->setClass("menuBoxContent");

//Ajout de la division du contenu dans la division du menu
$divMenu->addElement($divContenuMenu);

//Création des éléments du contenu du menu
$divContenuMenu->addElement(new Text("
Se connecter
"));
$divContenuMenu->addElement(new Text("
Créer un Compte
"));

//Ajout du menu à la page
$page->addElement($divMenu);

//########################################################################################################################

//Création du contenu principal
$divContenuPrincipal = new Division();

//Création de la division du contenu du contenu principal
$divContenuContenuP = new Division();

// Ajout du texte dans le contenu, puis ajout du contenu
$divContenuContenuP->addElement(new text("Bonjour et bienvenue dans notre application musiconline"));
$divContenuPrincipal->addElement($divContenuContenuP);

// Assigne la classe main à la division du contenu principal
$divContenuPrincipal->setClass("main");

//Ajout du contenu principal dans la page
$page->addElement($divContenuPrincipal);

//########################################################################################################################

//Affichage de toute la page
echo $page;

?>


text:
package migration

import (
	v1 "github.com/sapcc/kubernikus/pkg/apis/kubernikus/v1"
	"github.com/sapcc/kubernikus/pkg/controller/config"
)

const (
	fixUpdateConf = `#!/bin/bash
cat <<EOF > /etc/coreos/update.conf
REBOOT_STRATEGY="off"
EOF

/usr/bin/pkill update_engine
/usr/bin/pkill locksmithd
`
)

func FixUpdateConf(rawKluster []byte, current *v1.Kluster, clients config.Clients, factories config.Factories) (err error) {
	client, err := clients.Satellites.ClientFor(current)
	if err != nil {
		return err
	}

	return ApplySuppository(fixUpdateConf, client)
}


text:
// <copyright file="ContentTypeModelValidator{TModel,TModelTypeAttribute}.cs" company="Logikfabrik">
//   Copyright (c) 2016 anton(at)logikfabrik.se. Licensed under the MIT license.
// </copyright>

namespace Logikfabrik.Umbraco.Jet
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// The <see cref="ContentTypeModelValidator{TModel,TModelTypeAttribute}" /> class.
    /// </summary>
    /// <typeparam name="TModel">The model type.</typeparam>
    /// <typeparam name="TModelTypeAttribute">The model type attribute type.</typeparam>
    // ReSharper disable once InheritdocConsiderUsage
    public class ContentTypeModelValidator<TModel, TModelTypeAttribute> : ModelValidator<TModel, TModelTypeAttribute>
        where TModel : ContentTypeModel<TModelTypeAttribute>
        where TModelTypeAttribute : ContentTypeModelTypeAttribute
    {
        /// <inheritdoc />
        public override void Validate(TModel[] models)
        {
            base.Validate(models);

            ValidateByAlias(models);
            ValidatePropertiesById(models);
            ValidatePropertiesByAlias(models);
        }

        private static void ValidateByAlias(TModel[] models)
        {
            var set = new HashSet<string>();

            foreach (var model in models)
            {
                // ReSharper disable once PossibleUnintendedLinearSearchInSet
                if (set.Contains(model.Alias, StringComparer.InvariantCultureIgnoreCase))
                {
                    var conflictingTypes = models.Where(m => m.Alias.Equals(model.Alias, StringComparison.InvariantCultureIgnoreCase)).Select(m => m.ModelType.Name);

                    throw new InvalidOperationException($"Alias conflict for types '{string.Join("', '", conflictingTypes)}'. Alias '{model.Alias}' is already in use.");
                }

                set.Add(model.Alias);
            }
        }

        private static void ValidatePropertiesById(IEnumerable<TModel> models)
        {
            foreach (var model in models)
            {
                ValidatePropertiesById(model);
            }
        }

        private static void ValidatePropertiesByAlias(IEnumerable<TModel> models)
        {
            foreach (var model in models)
            {
                ValidatePropertiesByAlias(model);
            }
        }

        private static void ValidatePropertiesById(TModel model)
        {
            var set = new HashSet<string>();

            foreach (var property in model.Properties)
            {
                // ReSharper disable once PossibleUnintendedLinearSearchInSet
                if (set.Contains(property.Alias, StringComparer.InvariantCultureIgnoreCase))
                {
                    var conflictingProperties = model.Properties.Where(m => m.Alias.Equals(property.Alias, StringComparison.InvariantCultureIgnoreCase)).Select(m => m.Name);

                    throw new InvalidOperationException($"Alias conflict for properties '{string.Join("', '", conflictingProperties)}'. Alias '{property.Alias}' is already in use.");
                }

                set.Add(property.Alias);
            }
        }

        private static void ValidatePropertiesByAlias(TModel model)
        {
            var set = new HashSet<Guid>();

            foreach (var property in model.Properties)
            {
                if (!property.Id.HasValue)
                {
                    continue;
                }

                if (set.Contains(property.Id.Value))
                {
                    var conflictingProperties = model.Properties.Where(m => m.Id.HasValue && m.Id.Value == property.Id.Value).Select(m => m.Name);

                    throw new InvalidOperationException($"ID conflict for properties '{string.Join("', '", conflictingProperties)}'. ID '{property.Id.Value}' is already in use.");
                }

                set.Add(property.Id.Value);
            }
        }
    }
}


text:
using grpc = global::Grpc.Core;

namespace Google.Cloud.TextToSpeech.V1 {
  ///
  /// Service that implements Google Cloud Text-to-Speech API.
  ///
  public static partial class TextToSpeech
  {
    static readonly string __ServiceName = "google.cloud.texttospeech.v1.TextToSpeech";

    static readonly grpc::Marshaller<global::Google.Cloud.TextToSpeech.V1.ListVoicesRequest> __Marshaller_ListVoicesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.TextToSpeech.V1.ListVoicesRequest.Parser.ParseFrom);
    static readonly grpc::Marshaller<global::Google.Cloud.TextToSpeech.V1.ListVoicesResponse> __Marshaller_ListVoicesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.TextToSpeech.V1.ListVoicesResponse.Parser.ParseFrom);
    static readonly grpc::Marshaller<global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechRequest> __Marshaller_SynthesizeSpeechRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechRequest.Parser.ParseFrom);
    static readonly grpc::Marshaller<global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechResponse> __Marshaller_SynthesizeSpeechResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechResponse.Parser.ParseFrom);

    static readonly grpc::Method<global::Google.Cloud.TextToSpeech.V1.ListVoicesRequest, global::Google.Cloud.TextToSpeech.V1.ListVoicesResponse> __Method_ListVoices = new grpc::Method<global::Google.Cloud.TextToSpeech.V1.ListVoicesRequest, global::Google.Cloud.TextToSpeech.V1.ListVoicesResponse>(
        grpc::MethodType.Unary,
        __ServiceName,
        "ListVoices",
        __Marshaller_ListVoicesRequest,
        __Marshaller_ListVoicesResponse);

    static readonly grpc::Method<global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechRequest, global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechResponse> __Method_SynthesizeSpeech = new grpc::Method<global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechRequest, global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechResponse>(
        grpc::MethodType.Unary,
        __ServiceName,
        "SynthesizeSpeech",
        __Marshaller_SynthesizeSpeechRequest,
        __Marshaller_SynthesizeSpeechResponse);

    /// Service descriptor
    public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
    {
      get { return global::Google.Cloud.TextToSpeech.V1.CloudTtsReflection.Descriptor.Services[0]; }
    }

    /// Base class for server-side implementations of TextToSpeech
    public abstract partial class TextToSpeechBase
    {
      ///
      /// Returns a list of [Voice][google.cloud.texttospeech.v1.Voice]
      /// supported for synthesis.
      ///
      /// <param name="request">The request received from the client.</param>
      /// <param name="context">The context of the server-side call handler being invoked.</param>
      /// <returns>The response to send back to the client (wrapped by a task).</returns>
      public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.TextToSpeech.V1.ListVoicesResponse> ListVoices(global::Google.Cloud.TextToSpeech.V1.ListVoicesRequest request, grpc::ServerCallContext context)
      {
        throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
      }

      ///
      /// Synthesizes speech synchronously: receive results after all text input
      /// has been processed.
      ///
      /// <param name="request">The request received from the client.</param>
      /// <param name="context">The context of the server-side call handler being invoked.</param>
      /// <returns>The response to send back to the client (wrapped by a task).</returns>
      public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechResponse> SynthesizeSpeech(global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechRequest request, grpc::ServerCallContext context)
      {
        throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
      }

    }

    /// Client for TextToSpeech
    public partial class TextToSpeechClient : grpc::ClientBase<TextToSpeechClient>
    {
      /// Creates a new client for TextToSpeech
      /// <param name="channel">The channel to use to make remote calls.</param>
      public TextToSpeechClient(grpc::Channel channel) : base(channel)
      {
      }
      /// Creates a new client for TextToSpeech that uses a custom <c>CallInvoker</c>.
      /// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
      public TextToSpeechClient(grpc::CallInvoker callInvoker) : base(callInvoker)
      {
      }
      /// Protected parameterless constructor to allow creation of test doubles.
      protected TextToSpeechClient() : base()
      {
      }
      /// Protected constructor to allow creation of configured clients.
      /// <param name="configuration">The client configuration.</param>
      protected TextToSpeechClient(ClientBaseConfiguration configuration) : base(configuration)
      {
      }

      ///
      /// Returns a list of [Voice][google.cloud.texttospeech.v1.Voice]
      /// supported for synthesis.
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
      /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
      /// <param name="cancellationToken">An optional token for canceling the call.</param>
      /// <returns>The response received from the server.</returns>
      public virtual global::Google.Cloud.TextToSpeech.V1.ListVoicesResponse ListVoices(global::Google.Cloud.TextToSpeech.V1.ListVoicesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
      {
        return ListVoices(request, new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      ///
      /// Returns a list of [Voice][google.cloud.texttospeech.v1.Voice]
      /// supported for synthesis.
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="options">The options for the call.</param>
      /// <returns>The response received from the server.</returns>
      public virtual global::Google.Cloud.TextToSpeech.V1.ListVoicesResponse ListVoices(global::Google.Cloud.TextToSpeech.V1.ListVoicesRequest request, grpc::CallOptions options)
      {
        return CallInvoker.BlockingUnaryCall(__Method_ListVoices, null, options, request);
      }
      ///
      /// Returns a list of [Voice][google.cloud.texttospeech.v1.Voice]
      /// supported for synthesis.
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
      /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
      /// <param name="cancellationToken">An optional token for canceling the call.</param>
      /// <returns>The call object.</returns>
      public virtual grpc::AsyncUnaryCall<global::Google.Cloud.TextToSpeech.V1.ListVoicesResponse> ListVoicesAsync(global::Google.Cloud.TextToSpeech.V1.ListVoicesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
      {
        return ListVoicesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      ///
      /// Returns a list of [Voice][google.cloud.texttospeech.v1.Voice]
      /// supported for synthesis.
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="options">The options for the call.</param>
      /// <returns>The call object.</returns>
      public virtual grpc::AsyncUnaryCall<global::Google.Cloud.TextToSpeech.V1.ListVoicesResponse> ListVoicesAsync(global::Google.Cloud.TextToSpeech.V1.ListVoicesRequest request, grpc::CallOptions options)
      {
        return CallInvoker.AsyncUnaryCall(__Method_ListVoices, null, options, request);
      }
      ///
      /// Synthesizes speech synchronously: receive results after all text input
      /// has been processed.
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
      /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
      /// <param name="cancellationToken">An optional token for canceling the call.</param>
      /// <returns>The response received from the server.</returns>
      public virtual global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechResponse SynthesizeSpeech(global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
      {
        return SynthesizeSpeech(request, new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      ///
      /// Synthesizes speech synchronously: receive results after all text input
      /// has been processed.
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="options">The options for the call.</param>
      /// <returns>The response received from the server.</returns>
      public virtual global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechResponse SynthesizeSpeech(global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechRequest request, grpc::CallOptions options)
      {
        return CallInvoker.BlockingUnaryCall(__Method_SynthesizeSpeech, null, options, request);
      }
      ///
      /// Synthesizes speech synchronously: receive results after all text input
      /// has been processed.
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
      /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
      /// <param name="cancellationToken">An optional token for canceling the call.</param>
      /// <returns>The call object.</returns>
      public virtual grpc::AsyncUnaryCall<global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechResponse> SynthesizeSpeechAsync(global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
      {
        return SynthesizeSpeechAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      ///
      /// Synthesizes speech synchronously: receive results after all text input
      /// has been processed.
      ///
      /// <param name="request">The request to send to the server.</param>
      /// <param name="options">The options for the call.</param>
      /// <returns>The call object.</returns>
      public virtual grpc::AsyncUnaryCall<global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechResponse> SynthesizeSpeechAsync(global::Google.Cloud.TextToSpeech.V1.SynthesizeSpeechRequest request, grpc::CallOptions options)
      {
        return CallInvoker.AsyncUnaryCall(__Method_SynthesizeSpeech, null, options, request);
      }
      /// Creates a new instance of client from given <c>ClientBaseConfiguration</c>.
      protected override TextToSpeechClient NewInstance(ClientBaseConfiguration configuration)
      {
        return new TextToSpeechClient(configuration);
      }
    }

    /// Creates service definition that can be registered with a server
    /// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
    public static grpc::ServerServiceDefinition BindService(TextToSpeechBase serviceImpl)
    {
      return grpc::ServerServiceDefinition.CreateBuilder()
          .AddMethod(__Method_ListVoices, serviceImpl.ListVoices)
          .AddMethod(__Method_SynthesizeSpeech, serviceImpl.SynthesizeSpeech).Build();
    }

  }
}
#endregion


text:
#include "board.h"

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}


text:
import { async, ComponentFixture, TestBed
} from '@angular/core/testing';

import { NO_ERRORS_SCHEMA } from '@angular/core';
import { By } from '@angular/platform-browser';

import { AppComponent }    from './app.component';
import { BannerComponent } from './banner.component';
import { SharedModule }    from './shared/shared.module';

import { Router, FakeRouter, FakeRouterLinkDirective, FakeRouterOutletComponent
} from '../testing';

let comp:    AppComponent;
let fixture: ComponentFixture<AppComponent>;

describe('AppComponent & TestModule', () => {
  beforeEach( async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent, BannerComponent,
        FakeRouterLinkDirective, FakeRouterOutletComponent
      ],
      providers: [{ provide: Router, useClass: FakeRouter }],
      schemas:   [NO_ERRORS_SCHEMA]
    })

    .compileComponents()

    .then(() => {
      fixture = TestBed.createComponent(AppComponent);
      comp    = fixture.componentInstance;
    });

  }));

  tests();
});

function tests() {

  it('can instantiate it', () => {
    expect(comp).not.toBeNull();
  });

  it('can get RouterLinks from template', () => {
    fixture.detectChanges();

    const links = fixture.debugElement
      // find all elements with an attached FakeRouterLink directive
      .queryAll(By.directive(FakeRouterLinkDirective))
      // use injector to get the RouterLink directive instance attached to each element
      .map(de => de.injector.get(FakeRouterLinkDirective) as FakeRouterLinkDirective);

    expect(links.length).toBe(3, 'should have 3 links');
    expect(links[0].linkParams).toBe('/dashboard', '1st link should go to Dashboard');
    expect(links[1].linkParams).toBe('/heroes', '1st link should go to Heroes');
  });

  it('can click Heroes link in template', () => {
    fixture.detectChanges();

    // Heroes RouterLink DebugElement
    const heroesLinkDe = fixture.debugElement
      .queryAll(By.directive(FakeRouterLinkDirective))[1];

    expect(heroesLinkDe).toBeDefined('should have a 2nd RouterLink');

    const link = heroesLinkDe.injector.get(FakeRouterLinkDirective) as FakeRouterLinkDirective;

    expect(link.navigatedTo).toBeNull('link should not have navigate yet');

    heroesLinkDe.triggerEventHandler('click', null);

    fixture.detectChanges();
    expect(link.navigatedTo).toBe('/heroes');
  });
}

//////// Testing w/ real root module //////
// Best to avoid
// Tricky because we are disabling the router and its configuration
import { AppModule }    from './app.module';

describe('AppComponent & AppModule', () => {

  beforeEach( async(() => {

    TestBed.configureTestingModule({
      imports:      [ AppModule ],
    })

    .overrideModule(AppModule, {
      // Must get rid of `RouterModule.forRoot` to prevent attempt to configure a router
      // Can't remove it because it doesn't have a known type (`forRoot` returns an object)
      // therefore, must reset the entire `imports` with just the necessary stuff
      set: { imports: [ SharedModule ]}
    })

    // Separate override because cannot both `set` and `add/remove` in same override
    .overrideModule(AppModule, {
      add: {
        declarations: [ FakeRouterLinkDirective, FakeRouterOutletComponent ],
        providers:    [{ provide: Router, useClass: FakeRouter }]
      }
    })

    .compileComponents()

    .then(() => {
      fixture = TestBed.createComponent(AppComponent);
      comp    = fixture.componentInstance;
    });
  }));

  tests();
});


text:
from scitwi.utils.attrs import list_float_attr, str_attr
from scitwi.utils.strs import list_obj_string, obj_string

class TweetCoordinates(object):
    """
    https://dev.twitter.com/overview/api/tweets#obj-coordinates
    """
    def __init__(self, coordinates: dict):

        self.coordinates = list_float_attr(coordinates, 'coordinates')
        self.type_ = str_attr(coordinates, 'type')

    def __str__(self):

        str_out = ''
        str_out += list_obj_string('Coordinates', self.coordinates)
        str_out += obj_string('Type', self.type_)
        return str_out


text:
  do { \
    OTS_FAILURE_MSG_(font->file, TABLE_NAME ": " __VA_ARGS__); \
    OTS_FAILURE_MSG("Table discarded"); \
    delete font->vorg; \
    font->vorg = 0; \
  } while (0)

namespace ots {

bool ots_vorg_parse(Font *font, const uint8_t *data, size_t length) {
  Buffer table(data, length);
  font->vorg = new OpenTypeVORG;
  OpenTypeVORG * const vorg = font->vorg;

  uint16_t num_recs;
  if (!table.ReadU16(&vorg->major_version) ||
      !table.ReadU16(&vorg->minor_version) ||
      !table.ReadS16(&vorg->default_vert_origin_y) ||
      !table.ReadU16(&num_recs)) {
    return OTS_FAILURE_MSG("Failed to read header");
  }
  if (vorg->major_version != 1) {
    DROP_THIS_TABLE("bad major version: %u", vorg->major_version);
    return true;
  }
  if (vorg->minor_version != 0) {
    DROP_THIS_TABLE("bad minor version: %u", vorg->minor_version);
    return true;
  }

  // num_recs might be zero (e.g., DFHSMinchoPro5-W3-Demo.otf).
  if (!num_recs) {
    return true;
  }

  uint16_t last_glyph_index = 0;
  vorg->metrics.reserve(num_recs);
  for (unsigned i = 0; i < num_recs; ++i) {
    OpenTypeVORGMetrics rec;

    if (!table.ReadU16(&rec.glyph_index) ||
        !table.ReadS16(&rec.vert_origin_y)) {
      return OTS_FAILURE_MSG("Failed to read record %d", i);
    }
    if ((i != 0) && (rec.glyph_index <= last_glyph_index)) {
      DROP_THIS_TABLE("the table is not sorted");
      return true;
    }
    last_glyph_index = rec.glyph_index;

    vorg->metrics.push_back(rec);
  }

  return true;
}

bool ots_vorg_should_serialise(Font *font) {
  if (!font->cff) return false;  // this table is not for fonts with TT glyphs.
  return font->vorg != NULL;
}

bool ots_vorg_serialise(OTSStream *out, Font *font) {
  OpenTypeVORG * const vorg = font->vorg;

  const uint16_t num_metrics = static_cast<uint16_t>(vorg->metrics.size());
  if (num_metrics != vorg->metrics.size() ||
      !out->WriteU16(vorg->major_version) ||
      !out->WriteU16(vorg->minor_version) ||
      !out->WriteS16(vorg->default_vert_origin_y) ||
      !out->WriteU16(num_metrics)) {
    return OTS_FAILURE_MSG("Failed to write table header");
  }

  for (uint16_t i = 0; i < num_metrics; ++i) {
    const OpenTypeVORGMetrics& rec = vorg->metrics[i];
    if (!out->WriteU16(rec.glyph_index) ||
        !out->WriteS16(rec.vert_origin_y)) {
      return OTS_FAILURE_MSG("Failed to write record %d", i);
    }
  }

  return true;
}

void ots_vorg_reuse(Font *font, Font *other) {
  font->vorg = other->vorg;
  font->vorg_reused = true;
}

void ots_vorg_free(Font *font) {
  delete font->vorg;
}

}  // namespace ots

#undef TABLE_NAME
#undef DROP_THIS_TABLE


text:
namespace wm {

class ShadowControllerTest : public aura::test::AuraTestBase {
 public:
  ShadowControllerTest() {}
  ~ShadowControllerTest() override {}

  void SetUp() override {
    AuraTestBase::SetUp();
    InstallShadowController(nullptr);
  }
  void TearDown() override {
    shadow_controller_.reset();
    AuraTestBase::TearDown();
  }

 protected:
  ShadowController* shadow_controller() { return shadow_controller_.get(); }

  void ActivateWindow(aura::Window* window) {
    DCHECK(window);
    DCHECK(window->GetRootWindow());
    GetActivationClient(window->GetRootWindow())->ActivateWindow(window);
  }

  void InstallShadowController(
      std::unique_ptr<ShadowControllerDelegate> delegate) {
    shadow_controller_ = std::make_unique<ShadowController>(
        GetActivationClient(root_window()), std::move(delegate));
  }

 private:
  std::unique_ptr<ShadowController> shadow_controller_;

  DISALLOW_COPY_AND_ASSIGN(ShadowControllerTest);
};

// Tests that various methods in Window update the Shadow object as expected.
TEST_F(ShadowControllerTest, Shadow) {
  std::unique_ptr<aura::Window> window(new aura::Window(NULL));
  window->SetType(aura::client::WINDOW_TYPE_NORMAL);
  window->Init(ui::LAYER_TEXTURED);
  ParentWindow(window.get());

  // The shadow is not created until the Window is shown (some Windows should
  // never get shadows, which is checked when the window first becomes visible).
  EXPECT_FALSE(ShadowController::GetShadowForWindow(window.get()));
  window->Show();

  const ui::Shadow* shadow = ShadowController::GetShadowForWindow(window.get());
  ASSERT_TRUE(shadow != NULL);
  EXPECT_TRUE(shadow->layer()->visible());

  // The shadow should remain visible after window visibility changes.
  window->Hide();
  EXPECT_TRUE(shadow->layer()->visible());

  // If the shadow is disabled, it should be hidden.
  SetShadowElevation(window.get(), kShadowElevationNone);
  window->Show();
  EXPECT_FALSE(shadow->layer()->visible());
  SetShadowElevation(window.get(), kShadowElevationInactiveWindow);
  EXPECT_TRUE(shadow->layer()->visible());

  // The shadow's layer should be a child of the window's layer.
  EXPECT_EQ(window->layer(), shadow->layer()->parent());
}

// Tests that the window's shadow's bounds are updated correctly.
TEST_F(ShadowControllerTest, ShadowBounds) {
  std::unique_ptr<aura::Window> window(new aura::Window(NULL));
  window->SetType(aura::client::WINDOW_TYPE_NORMAL);
  window->Init(ui::LAYER_TEXTURED);
  ParentWindow(window.get());
  window->Show();

  const gfx::Rect kOldBounds(20, 30, 400, 300);
  window->SetBounds(kOldBounds);

  // When the shadow is first created, it should use the window's size (but
  // remain at the origin, since it's a child of the window's layer).
  SetShadowElevation(window.get(), kShadowElevationInactiveWindow);
  const ui::Shadow* shadow = ShadowController::GetShadowForWindow(window.get());
  ASSERT_TRUE(shadow != NULL);
  EXPECT_EQ(gfx::Rect(kOldBounds.size()).ToString(),
            shadow->content_bounds().ToString());

  // When we change the window's bounds, the shadow's should be updated too.
  gfx::Rect kNewBounds(50, 60, 500, 400);
  window->SetBounds(kNewBounds);
  EXPECT_EQ(gfx::Rect(kNewBounds.size()).ToString(),
            shadow->content_bounds().ToString());
}

// Tests that activating a window changes the shadow style.
TEST_F(ShadowControllerTest, ShadowStyle) {
  std::unique_ptr<aura::Window> window1(new aura::Window(NULL));
  window1->SetType(aura::client::WINDOW_TYPE_NORMAL);
  window1->Init(ui::LAYER_TEXTURED);
  ParentWindow(window1.get());
  window1->SetBounds(gfx::Rect(10, 20, 300, 400));
  window1->Show();
  ActivateWindow(window1.get());

  // window1 is active, so style should have active appearance.
  ui::Shadow* shadow1 = ShadowController::GetShadowForWindow(window1.get());
  ASSERT_TRUE(shadow1 != NULL);
  EXPECT_EQ(kShadowElevationActiveWindow, shadow1->desired_elevation());

  // Create another window and activate it.
  std::unique_ptr<aura::Window> window2(new aura::Window(NULL));
  window2->SetType(aura::client::WINDOW_TYPE_NORMAL);
  window2->Init(ui::LAYER_TEXTURED);
  ParentWindow(window2.get());
  window2->SetBounds(gfx::Rect(11, 21, 301, 401));
  window2->Show();
  ActivateWindow(window2.get());

  // window1 is now inactive, so shadow should go inactive.
  ui::Shadow* shadow2 = ShadowController::GetShadowForWindow(window2.get());
  ASSERT_TRUE(shadow2 != NULL);
  EXPECT_EQ(kShadowElevationInactiveWindow, shadow1->desired_elevation());
  EXPECT_EQ(kShadowElevationActiveWindow, shadow2->desired_elevation());
}

// Tests that shadow gets updated when the window show state changes.
TEST_F(ShadowControllerTest, ShowState) {
  std::unique_ptr<aura::Window> window(new aura::Window(NULL));
  window->SetType(aura::client::WINDOW_TYPE_NORMAL);
  window->Init(ui::LAYER_TEXTURED);
  ParentWindow(window.get());
  window->Show();

  ui::Shadow* shadow = ShadowController::GetShadowForWindow(window.get());
  ASSERT_TRUE(shadow != NULL);
  EXPECT_EQ(kShadowElevationInactiveWindow, shadow->desired_elevation());

  window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED);
  EXPECT_FALSE(shadow->layer()->visible());

  window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL);
  EXPECT_TRUE(shadow->layer()->visible());

  window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN);
  EXPECT_FALSE(shadow->layer()->visible());
}

// Tests that we use smaller shadows for tooltips and menus.
TEST_F(ShadowControllerTest, SmallShadowsForTooltipsAndMenus) {
  std::unique_ptr<aura::Window> tooltip_window(new aura::Window(NULL));
  tooltip_window->SetType(aura::client::WINDOW_TYPE_TOOLTIP);
  tooltip_window->Init(ui::LAYER_TEXTURED);
  ParentWindow(tooltip_window.get());
  tooltip_window->SetBounds(gfx::Rect(10, 20, 300, 400));
  tooltip_window->Show();

  ui::Shadow* tooltip_shadow =
      ShadowController::GetShadowForWindow(tooltip_window.get());
  ASSERT_TRUE(tooltip_shadow != NULL);
  EXPECT_EQ(kShadowElevationMenuOrTooltip, tooltip_shadow->desired_elevation());

  std::unique_ptr<aura::Window> menu_window(new aura::Window(NULL));
  menu_window->SetType(aura::client::WINDOW_TYPE_MENU);
  menu_window->Init(ui::LAYER_TEXTURED);
  ParentWindow(menu_window.get());
  menu_window->SetBounds(gfx::Rect(10, 20, 300, 400));
  menu_window->Show();

  ui::Shadow* menu_shadow =
      ShadowController::GetShadowForWindow(tooltip_window.get());
  ASSERT_TRUE(menu_shadow != NULL);
  EXPECT_EQ(kShadowElevationMenuOrTooltip, menu_shadow->desired_elevation());
}

// http://crbug.com/120210 - transient parents of certain types of transients
// should not lose their shadow when they lose activation to the transient.
TEST_F(ShadowControllerTest, TransientParentKeepsActiveShadow) {
  std::unique_ptr<aura::Window> window1(new aura::Window(NULL));
  window1->SetType(aura::client::WINDOW_TYPE_NORMAL);
  window1->Init(ui::LAYER_TEXTURED);
  ParentWindow(window1.get());
  window1->SetBounds(gfx::Rect(10, 20, 300, 400));
  window1->Show();
  ActivateWindow(window1.get());

  // window1 is active, so style should have active appearance.
  ui::Shadow* shadow1 = ShadowController::GetShadowForWindow(window1.get());
  ASSERT_TRUE(shadow1 != NULL);
  EXPECT_EQ(kShadowElevationActiveWindow, shadow1->desired_elevation());

  // Create a window that is transient to window1, and that has the 'hide on
  // deactivate' property set. Upon activation, window1 should still have an
  // active shadow.
  std::unique_ptr<aura::Window> window2(new aura::Window(NULL));
  window2->SetType(aura::client::WINDOW_TYPE_NORMAL);
  window2->Init(ui::LAYER_TEXTURED);
  ParentWindow(window2.get());
  window2->SetBounds(gfx::Rect(11, 21, 301, 401));
  AddTransientChild(window1.get(), window2.get());
  SetHideOnDeactivate(window2.get(), true);
  window2->Show();
  ActivateWindow(window2.get());

  // window1 is now inactive, but its shadow should still appear active.
  EXPECT_EQ(kShadowElevationActiveWindow, shadow1->desired_elevation());
}

namespace {

class TestShadowControllerDelegate : public wm::ShadowControllerDelegate {
 public:
  TestShadowControllerDelegate() {}
  ~TestShadowControllerDelegate() override {}

  bool ShouldShowShadowForWindow(const aura::Window* window) override {
    return window->parent();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(TestShadowControllerDelegate);
};

}  // namespace

TEST_F(ShadowControllerTest, UpdateShadowWhenAddedToParent) {
  InstallShadowController(std::make_unique<TestShadowControllerDelegate>());
  std::unique_ptr<aura::Window> window1(new aura::Window(NULL));
  window1->SetType(aura::client::WINDOW_TYPE_NORMAL);
  window1->Init(ui::LAYER_TEXTURED);
  window1->SetBounds(gfx::Rect(10, 20, 300, 400));
  window1->Show();
  EXPECT_FALSE(ShadowController::GetShadowForWindow(window1.get()));

  ParentWindow(window1.get());

  ASSERT_TRUE(ShadowController::GetShadowForWindow(window1.get()));
  EXPECT_TRUE(
      ShadowController::GetShadowForWindow(window1.get())->layer()->visible());
}

}  // namespace wm


text:
The Google Cloud Deployment Manager v2 API provides services for configuring, deploying, and viewing Google Cloud services and APIs via templates which specify deployments of Cloud resources.

This page contains information about getting started with the Cloud Deployment Manager V2 API
using the Google API Client Library for Java. In addition, you may be interested
in the following documentation:

* Browse the [Javadoc reference for the Cloud Deployment Manager V2 API][javadoc]
* Read the [Developer's Guide for the Google API Client Library for Java][google-api-client].
* Interact with this API in your browser using the [APIs Explorer for the Cloud Deployment Manager V2 API][api-explorer]

## Installation

### Maven

Add the following lines to your `pom.xml` file:

```xml
<project>
  <dependencies>
    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-deploymentmanager</artifactId>
      <version>v2-rev20220908-2.0.0</version>
    </dependency>
  </dependencies>
</project>
```

### Gradle

```gradle
repositories {
  mavenCentral()
}
dependencies {
  implementation 'com.google.apis:google-api-services-deploymentmanager:v2-rev20220908-2.0.0'
}
```

[javadoc]: https://googleapis.dev/java/google-api-services-deploymentmanager/latest/index.html
[google-api-client]: https://github.com/googleapis/google-api-java-client/
[api-explorer]: https://developers.google.com/apis-explorer/#p/deploymentmanager/v1/


text:
import { Component, Input, OnInit }  from '@angular/core';
import { FormGroup }                 from '@angular/forms';
import { QuestionBase }              from './question-base';
import { QuestionControlService }    from './question-control.service';
/**
 * DynamicFormComponent is the entry point and the main container for the form.
 * Create components to represent the dynamic form.
 * presents a list of questions, each question bound to a <df-question> component element.
 * The <df-question> tag matches the DynamicFormQuestionComponent, the component responsible for
 * rendering the details of each individual question based on values in the data-bound question object.
 * modul.Id means Component-Relative Paths are used so we don't need to full path to the template.
 */
@Component({
  moduleId: module.id,
  selector: 'dynamic-form',
  templateUrl: 'dynamic-form.component.html',
  providers: [ QuestionControlService ]
})
export class DynamicFormComponent implements OnInit {
  @Input() questions: QuestionBase<any>[] = [];
  form: FormGroup;
  payLoad = '';
  constructor(private qcs: QuestionControlService) {  }

  /**
   * (property) DynamicFormComponent.qcs: QuestionControlService
   */
  ngOnInit() {
    this.form = this.qcs.toFormGroup(this.questions);
  }
  onSubmit() {
    this.payLoad = JSON.stringify(this.form.value);
  }
}


text:
from django.core.management import call_command
from django.test import TestCase
from entity_event.models import Medium, Source

from entity_emailer.utils import get_medium, get_admin_source

class AddEmailMediumCommandTest(TestCase):
    def test_idempotent(self):
        call_command('add_email_medium')
        call_command('add_email_medium')
        self.assertEqual(Medium.objects.count(), 1)

    def test_default(self):
        call_command('add_email_medium')
        medium = get_medium()
        self.assertEqual(medium.name, 'email')

    def test_custom(self):
        custom_medium_name = 'test-email'
        with self.settings(ENTITY_EMAILER_MEDIUM_NAME=custom_medium_name):
            call_command('add_email_medium')
            medium = get_medium()
        self.assertEqual(medium.name, custom_medium_name)

class EntityEmailerAdminSetupTest(TestCase):
    def test_idempotent(self):
        call_command('entity_emailer_admin_setup')
        call_command('entity_emailer_admin_setup')
        self.assertEqual(Source.objects.count(), 1)

    def test_defaults(self):
        call_command('entity_emailer_admin_setup')
        source = get_admin_source()
        self.assertEqual(source.name, 'admin')

    def test_custom_source(self):
        custom_source_name = 'test-email'
        with self.settings(ENTITY_EMAILER_ADMIN_SOURCE_NAME=custom_source_name):
            call_command('entity_emailer_admin_setup')
            source = get_admin_source()
        self.assertEqual(source.name, custom_source_name)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RavenDBBlogWeb.Controllers
{
    using Raven.Client;

    using RavenDBBlogWeb.Models;

    public class BlogsController : Controller
    {
        private readonly IDocumentSession _session;

        public BlogsController(IDocumentSession session)
        {
            _session = session;
        }

        //
        // GET: /Blogs/

        public ActionResult Index()
        {
            var blogs = _session.Query<Blog>().ToList();
            return View(blogs);
        }

        public ActionResult PostsByTag()
        {
            var results = _session.Query<PostsByTagResult, Posts_PostsByTag>();
            return View(results);
        }

        public ActionResult PostsByTagHttp()
        {
            return View();
        }
    }
}


text:
/*jslint sub: true */
var p = $A.ns.ComponentDef.prototype;
exp(p,
    "auraType", p.auraType,
    "getDescriptor", p.getDescriptor,
    "isAbstract", p.isAbstract,
    "isTemplate", p.isTemplate,
    "getSuperDef", p.getSuperDef,
    "getHelperDef", p.getHelperDef,
    "getHelper", p.getHelper,
    "getRendererDef", p.getRendererDef,
    "getProviderDef", p.getProviderDef,
    "getStyleDef", p.getStyleDef,
    "getAttributeDefs", p.getAttributeDefs,
    "getFacets", p.getFacets,
    "getControllerDef", p.getControllerDef,
    "getModelDef", p.getModelDef,
    "getEventDef", p.getEventDef,
    "toString", p.toString,
    "getLayouts", p.getLayouts,
    "getLocationChangeEvent", p.getLocationChangeEvent,
    "getAppHandlerDefs", p.getAppHandlerDefs,
    "getCmpHandlerDefs", p.getCmpHandlerDefs,
    "isInstanceOf", p.isInstanceOf,
    "getAllEvents", p.getAllEvents,
    "getStyleClassName", p.getStyleClassName
);


text:
import sys
import libvirt

target_vm = sys.argv[1]    # 第1引数に指定したターゲットVM名取得
uri = "qemu+ssh://ユーザ名@ホスト名orIPアドレス/system"

connection = libvirt.open(uri)

vm = connection.lookupByName(target_vm)
vm.create()


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