text:
import { JsonObject } from '@angular-devkit/core';
import { EmptyTree } from '@angular-devkit/schematics';
import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing';
import {
  BuilderTarget,
  Builders,
  ProjectType,
  WorkspaceSchema,
} from '../../utility/workspace-models';

function getBuildTarget(tree: UnitTestTree): BuilderTarget<Builders.Browser, JsonObject> {
  return JSON.parse(tree.readContent('/angular.json')).projects.app.architect.build;
}

function createWorkSpaceConfig(tree: UnitTestTree) {
  const angularConfig: WorkspaceSchema = {
    version: 1,
    projects: {
      app: {
        root: '',
        sourceRoot: 'src',
        projectType: ProjectType.Application,
        prefix: 'app',
        architect: {
          build: {
            builder: Builders.Browser,
            options: {
              aot: true,
              optimization: true,
              experimentalRollupPass: false,
              buildOptimizer: false,
              namedChunks: true,
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
            } as any,
            configurations: {
              one: {
                aot: true,
              },
              two: {
                experimentalRollupPass: true,
                aot: false,
                optimization: false,
              },
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
            } as any,
          },
        },
      },
    },
  };

  tree.create('/angular.json', JSON.stringify(angularConfig, undefined, 2));
}

const schematicName = 'update-angular-config-v12';

describe(`Migration to update 'angular.json'. ${schematicName}`, () => {
  const schematicRunner = new SchematicTestRunner(
    'migrations',
    require.resolve('../migration-collection.json'),
  );

  let tree: UnitTestTree;
  beforeEach(() => {
    tree = new UnitTestTree(new EmptyTree());
    createWorkSpaceConfig(tree);
  });

  it(`should remove 'experimentalRollupPass'`, async () => {
    const newTree = await schematicRunner.runSchematicAsync(schematicName, {}, tree).toPromise();
    const { options, configurations } = getBuildTarget(newTree);

    expect(options.experimentalRollupPass).toBeUndefined();
    expect(options.buildOptimizer).toBeFalse();
    expect(configurations).toBeDefined();
    expect(configurations?.one.experimentalRollupPass).toBeUndefined();
    expect(configurations?.two.experimentalRollupPass).toBeUndefined();
  });

  it(`should remove value from "options" section which value is now the new default`, async () => {
    const newTree = await schematicRunner.runSchematicAsync(schematicName, {}, tree).toPromise();
    const { options, configurations } = getBuildTarget(newTree);

    expect(options.aot).toBeUndefined();
    expect(configurations?.one.aot).toBeUndefined();
    expect(configurations?.two.aot).toBeFalse();
  });

  it(`should remove value from "configuration" section when value is the same as that of "options"`, async () => {
    const newTree = await schematicRunner.runSchematicAsync(schematicName, {}, tree).toPromise();
    const { options, configurations } = getBuildTarget(newTree);

    expect(options.aot).toBeUndefined();
    expect(configurations?.one.aot).toBeUndefined();
    expect(configurations?.two.aot).toBeFalse();
  });

  it(`should add value in "options" section when option was not defined`, async () => {
    const newTree = await schematicRunner.runSchematicAsync(schematicName, {}, tree).toPromise();
    const { options, configurations } = getBuildTarget(newTree);

    expect(options.sourceMap).toBeTrue();
    expect(configurations?.one.sourceMap).toBeUndefined();
    expect(configurations?.two.sourceMap).toBeUndefined();
    expect(configurations?.two.optimization).toBeFalse();
  });

  it(`should not remove value in "options" when value is not the new default`, async () => {
    const newTree = await schematicRunner.runSchematicAsync(schematicName, {}, tree).toPromise();
    const { options } = getBuildTarget(newTree);

    expect(options.namedChunks).toBeTrue();
    expect(options.buildOptimizer).toBeFalse();
  });

  it('migration should be idempotent', async () => {
    const { options } = getBuildTarget(tree);
    expect(options.aot).toBeTrue();

    // First run
    const newTree1 = await schematicRunner.runSchematicAsync(schematicName, {}, tree).toPromise();
    const { options: options1 } = getBuildTarget(newTree1);
    expect(options1.aot).toBeUndefined();

    // Second run
    const newTree2 = await schematicRunner
      .runSchematicAsync(schematicName, {}, newTree1)
      .toPromise();
    const { options: options2 } = getBuildTarget(newTree2);
    expect(options2.aot).toBeUndefined();
  });
});


text:
<title>Alternate Keywords - Using the GNU Compiler Collection (GCC)</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using the GNU Compiler Collection (GCC)">
<meta name="generator" content="makeinfo 4.7">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="C-Extensions.html#C-Extensions" title="C Extensions">
<link rel="prev" href="Explicit-Reg-Vars.html#Explicit-Reg-Vars" title="Explicit Reg Vars">
<link rel="next" href="Incomplete-Enums.html#Incomplete-Enums" title="Incomplete Enums">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Incomplete Enums,
Previous: Explicit Reg Vars,
Up: C Extensions

5.41 Alternate Keywords

-ansi and the various -std options disable certain
keywords.  This causes trouble when you want to use GNU C extensions, or
a general-purpose header file that should be usable by all programs,
including ISO C programs.  The keywords asm, typeof and
inline are not available in programs compiled with
-ansi or -std (although inline can be used in a
program compiled with -std=c99).  The ISO C99 keyword
restrict is only available when -std=gnu99 (which will
eventually be the default) or -std=c99 (or the equivalent
-std=iso9899:1999) is used.

The way to solve these problems is to put __ at the beginning and
end of each problematical keyword.  For example, use __asm__
instead of asm, and __inline__ instead of inline.

Other C compilers won't accept these alternative keywords; if you want to
compile with another compiler, you can define the alternate keywords as
macros to replace them with the customary keywords.  It looks like this:

     #ifndef __GNUC__
     #define __asm__ asm
     #endif

-pedantic and other options cause warnings for many GNU C extensions.
You can
prevent such warnings within one expression by writing
__extension__ before the expression.  __extension__ has no
effect aside from this.

redpajama_set_name: RedPajamaGithub


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82_goodG2B.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806.label.xml
Template File: sources-sink-82_goodG2B.tmpl.cpp
*/
/*
 * @description
 * CWE: 122 Heap Based Buffer Overflow
 * BadSource:  Initialize data as a large string
 * GoodSource: Initialize data as a small string
 * Sinks: loop
 *    BadSink : Copy data to string using a loop
 * Flow Variant: 82 Data flow: data passed in a parameter to a virtual method called via a pointer
 *
 * */
#ifndef OMITGOOD

#include "std_testcase.h"
#include "CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82.h"

namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82
{

void CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82_goodG2B::action(wchar_t * data)
{
    {
        wchar_t dest[50] = L"";
        size_t i, dataLen;
        dataLen = wcslen(data);
        /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
        for (i = 0; i < dataLen; i++)
        {
            dest[i] = data[i];
        }
        dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */
        printWLine(data);
        delete [] data;
    }
}

}
#endif /* OMITGOOD */


text:
set -ex

go get -t ./...
if [ ${TESTMODE} == "lint" ]; then
  go get github.com/alecthomas/gometalinter
  gometalinter --install
  gometalinter --deadline=300s --tests ./...
fi

if [ ${TESTMODE} == "unit" ]; then
  ginkgo -r -v -cover -randomizeAllSpecs -randomizeSuites -trace -skipPackage integrationtests,benchmark
fi

if [ ${TESTMODE} == "integration" ]; then
  # run benchmark tests
  ginkgo -randomizeAllSpecs -randomizeSuites -trace benchmark -- -samples=1
  # run benchmark tests with the Go race detector
  # The Go race detector only works on amd64.
  if [ ${TRAVIS_GOARCH} == 'amd64' ]; then
    ginkgo -race -randomizeAllSpecs -randomizeSuites -trace benchmark -- -samples=1 -size=10
  fi
  # run integration tests
  ginkgo -r -v -randomizeAllSpecs -randomizeSuites -trace -skipPackage chrome integrationtests
fi


text:
using System.Text;

namespace Cake.MsDeploy.Providers.MsDeployProviders
{
    /// <summary>
    /// .NET 64-bit root Web configuration
    /// </summary>
    /// <code>
    /// msdeploy.exe -verb:dump -source:rootWebConfig64="Default Web Site"
    /// </code>
    public class RootWebConfig64Provider : MsDeployProvider
    {
        public override string Type
        {
            get
            {
                return "rootWebConfig64";
            }
        }

        /// <summary>
        /// Provider setting used to specify which .NET framework version to use with given provider.
        /// </summary>
        public string NetFxVersion { get; set; }

        protected override void AdditionalSettings(StringBuilder sb)
        {
            if (!string.IsNullOrWhiteSpace(NetFxVersion))
                sb.AppendFormat(",netFxVersion=\"{0}\"", NetFxVersion);
        }
    }
}


text:
package org.yeastrc.xlink.www.cached_data_mgmt;

public class CacheCurrentSizeMaxSizeResult {

	private long currentSize;
	private long maxSize;

	public long getCurrentSize() {
		return currentSize;
	}
	public void setCurrentSize(long currentSize) {
		this.currentSize = currentSize;
	}
	public long getMaxSize() {
		return maxSize;
	}
	public void setMaxSize(long maxSize) {
		this.maxSize = maxSize;
	}
}


text:
#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "dsa-compat.h"

int
dsa_sha256_sign_digest(const struct dsa_public_key *pub,
		       const struct dsa_private_key *key,
		       void *random_ctx, nettle_random_func *random,
		       const uint8_t *digest,
		       struct dsa_signature *signature)
{
  return dsa_sign((const struct dsa_params *) pub, key->x,
		  random_ctx, random,
		  SHA256_DIGEST_SIZE, digest, signature);
}

int
dsa_sha256_sign(const struct dsa_public_key *pub,
		const struct dsa_private_key *key,
		void *random_ctx, nettle_random_func *random,
		struct sha256_ctx *hash,
		struct dsa_signature *signature)
{
  uint8_t digest[SHA256_DIGEST_SIZE];
  sha256_digest(hash, sizeof(digest), digest);

  return dsa_sign((const struct dsa_params *) pub, key->x,
		  random_ctx, random,
		  sizeof(digest), digest, signature);
}


text:
namespace OrderUsings.Tests.OrderAndSpacingDetermination.TwoSpecificThenDefaultThenAliases
{
    using NUnit.Framework;

    public class WhenThreeImports : TwoGroupsThenAliasesBase
    {
        [Test]
        public void AllMatchingFirstProducesOneGroup()
        {
            Verify(
                new[]
                {
                    ImportSystem,
                    ImportSystemCollectionsGeneric,
                    ImportSystemLinq
                },
                new[]
                {
                    new[] { ImportSystem, ImportSystemCollectionsGeneric, ImportSystemLinq }
                });
        }

        [Test]
        public void AllMatchingSecondProducesOneGroup()
        {
            Verify(
                new[]
                {
                    ImportSystem,
                    ImportSystemCollectionsGeneric,
                    ImportSystemLinq
                },
                new[]
                {
                    new[] { ImportSystem, ImportSystemCollectionsGeneric, ImportSystemLinq }
                });
        }

        [Test]
        public void AllMatchingFirstAndSecondInOrderProducesOneGroup()
        {
            Verify(
                new[]
                {
                    ImportSystem,
                    ImportSystemCollectionsGeneric,
                    ImportSystemLinq,
                    ImportMicrosoftCSharp
                },
                new[]
                {
                    new[] { ImportSystem, ImportSystemCollectionsGeneric, ImportSystemLinq, ImportMicrosoftCSharp }
                });
        }

        [Test]
        public void AllMatchingFirstAndSecondOutOfOrderProducesOneGroup()
        {
            Verify(
                new[]
                {
                    ImportSystem,
                    ImportMicrosoftCSharp,
                    ImportSystemCollectionsGeneric,
                    ImportSystemLinq
                },
                new[]
                {
                    new[] { ImportSystem, ImportSystemCollectionsGeneric, ImportSystemLinq, ImportMicrosoftCSharp }
                });
        }

        [Test]
        public void AllMatchNamespaceFallbackProducesOneGroup()
        {
            Verify(
                new[]
                {
                    ImportOther,
                    ImportOtherA,
                    ImportOtherB
                },
                new[]
                {
                    new[] { ImportOther, ImportOtherA, ImportOtherB }
                });
        }

        [Test]
        public void TwoMatchFirstOneMatchesFallbackProducesTwoGroups()
        {
            Verify(
                new[]
                {
                    ImportSystem,
                    ImportSystemLinq,
                    ImportOther
                },
                new[]
                {
                    new[] { ImportSystem, ImportSystemLinq },
                    new[] { ImportOther }
                });
        }
    }
}


text:
/**
 * Account.
 * http://doc.api.navi.cc/v3/accounts/
 * @param $api TBD
 * @return {Object}
 *
 * @description
 * Return current account resource
 */
function NaviccResourceAccount($api) {
    console.log("NaviccResourceAccount(", $api, ")");
    /**
     * Retrieves the current top dvd rentals.
     * http://developer.rottentomatoes.com/docs/json/v10/Top_Rentals
     * @param {Object} [params] The accepted request parameters.
     * @param {Integer} [param.limit] Limits the number of returned data.
     * @param {String} [param.country] The country to get data.
     * @return {HttpPromise}
     */
     function get(params) {
         console.log("NaviccResourceAccount:get(", params, ")");
         return $api.request('/account', params, []);
         //   return $api.request('/lists/dvds/top_rentals.json', params,
         //     ['limit', 'country']);
     }

    return {
        get: get
    };
}


text:
package org.elasticsearch.mapper.attachments;

import org.apache.lucene.util.LuceneTestCase.SuppressFileSystems;
import org.apache.lucene.util.TestUtil;
import org.apache.tika.metadata.Metadata;
import org.elasticsearch.test.ESTestCase;

import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * Evil test-coverage cheat, we parse a bunch of docs from tika
 * so that we have a nice grab-bag variety, and assert some content
 * comes back and no exception.
 */
@SuppressFileSystems("ExtrasFS") // don't try to parse extraN
public class TikaDocTests extends ESTestCase {

    /** some test files from tika test suite, zipped up */
    static final String TIKA_FILES = "/org/elasticsearch/index/mapper/attachment/test/tika-files.zip";

    public void testFiles() throws Exception {
        Path tmp = createTempDir();
        TestUtil.unzip(getClass().getResourceAsStream(TIKA_FILES), tmp);

        try (DirectoryStream<Path> stream = Files.newDirectoryStream(tmp)) {
            for (Path doc : stream) {
              logger.debug("parsing: {}", doc);
              assertParseable(doc);
            }
        }
    }

    void assertParseable(Path fileName) throws Exception {
        try {
            byte bytes[] = Files.readAllBytes(fileName);
            String parsedContent = TikaImpl.parse(bytes, new Metadata(), -1);
            assertNotNull(parsedContent);
            assertFalse(parsedContent.isEmpty());
            logger.debug("extracted content: {}", parsedContent);
        } catch (Throwable e) {
            throw new RuntimeException("parsing of filename: " + fileName.getFileName() + " failed", e);
        }
    }
}


text:
<?php declare(strict_types=1);

namespace Star\Component\State\Transitions;

use PHPUnit\Framework\TestCase;
use Star\Component\State\Stub\RegistrySpy;

final class OneToOneTransitionTest extends TestCase
{
    private OneToOneTransition $transition;

    public function setUp(): void
    {
        $this->transition = new OneToOneTransition('name', 'from', 'to');
    }

    public function test_it_should_have_a_name(): void
    {
        $this->assertSame('name', $this->transition->getName());
    }

    public function test_it_should_register_the_from_and_to_states(): void
    {
        $registry = new RegistrySpy();

        $this->transition->onRegister($registry);

        $this->assertCount(1, $registry->states['name']['start']);
        $this->assertCount(1, $registry->states['name']['destination']);
    }
}


text:
import React, { Component, PropTypes } from 'react';
import { Modal, Popconfirm, message } from 'antd';

import styles from './styles';

export default class List extends Component{

	static propTypes = {
		structureData: PropTypes.object,
		changeAttrValue: PropTypes.func,
	}

	state = {
		modalTitle: '',
		modalVisible: false,
		currentItemId: '',
	}

	deleteItem(id){
		message.success('删除成功');
	}

	cancelHandle(msg){
		message.error(msg + '操作已取消');
	}

	cancelModalHandle(msg){
		this.setState({'modalTitle':'','modalVisible':false});
		this.cancelHandle(msg);
	}

	modalOkHandle(){
		console.log('ssdsdsdd');
	}

	updateItem(id, name){
		this.setState({'currentItemId':id,'modalTitle':'更新《' + name + '》', 'modalVisible':true});
	}

	_createItem(key, value){
		return
this.props.changeAttrValue(key) : ''}>

{value.name}

							<If condition={value.btn.delete}>
								<Popconfirm title={'确定要删除该项吗?'} onConfirm={this.deleteItem.bind(this,key)} onCancel={this.cancelHandle.bind(this,'删除')}>

								</Popconfirm>
							</If>
							<If condition={value.btn.update}>

							</If>

	}

	_ergodicItem(obj){
		if (!obj) {
			return false;
		};
		let items = [];
		for ( let index in obj ){
			items.push(this._createItem(index, obj[index]));
		}
		return items;
	}

	render(){
		return 	<div className={`${styles}`}>

								{this._ergodicItem(this.props.structureData)}

							<Modal title={this.state.modalTitle} visible={this.state.modalVisible} onOk={this.modalOkHandle.bind(this)} onCancel={this.cancelModalHandle.bind(this,'修改')}>

							    新值:

							      <input type="text" className="ant-input" id="cate-input" placeholder='新值' />

							</Modal>

	}
}


text:
/*
 *
 * LegendShop 多用户商城系统
 *
 *  版权所有,并保留所有权利。
 *
 */
package com.legendshop.plugins;

import java.util.List;

import javax.servlet.ServletContext;

/**
 * The Interface PluginManager. 插件管理器
 */
public interface PluginManager {

	/**
	 * Gets the plugins. 在线的插件
	 *
	 * @return the plugins
	 */
	public List<Plugin> getPlugins();

	/**
	 * Register plugins. 注册插件
	 *
	 * @param plugin
	 *            the plugin
	 */
	public void registerPlugins(Plugin plugin);

	/**
	 * 插件上线.
	 *
	 * @param pluginId
	 *            the plugin id
	 */
	public String turnOn(String pluginId);

	/**
	 * 插件是否在运行
	 *
	 * @param pluginId
	 * @return
	 */
	public boolean isPluginRunning(String pluginId);

	/**
	 * 插件下线.
	 *
	 * @param pluginId
	 *            the plugin id
	 */
	public String turnOff(String pluginId);

	/**
	 * Start plugins. 启动插件
	 *
	 * @param servletContext
	 *            the servlet context
	 */
	public void startPlugins(ServletContext servletContext);

	/**
	 * Stop plugins. 停止插件
	 *
	 * @param servletContext
	 *            the servlet context
	 */
	public void stopPlugins(ServletContext servletContext);

	/**
	 * Save plugin. 保存插件
	 *
	 * @param plugin
	 *            the plugin
	 */
	public void savePlugin(PluginConfig plugin);

	/**
	 * Gets the plugin config from db. 得到数据库中的插件
	 *
	 * @return the plugin config from db
	 */
	public List<PluginConfig> getPluginConfigFromDb();
}


text:
"""Tests for py_guide_parser."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

from tensorflow.python.platform import test
from tensorflow.tools.docs import py_guide_parser

class TestPyGuideParser(py_guide_parser.PyGuideParser):

  def __init__(self):
    self.calls = []
    py_guide_parser.PyGuideParser.__init__(self)

  def process_title(self, line_number, title):
    self.calls.append((line_number, 't', title))

  def process_section(self, line_number, section_title, tag):
    self.calls.append((line_number, 's', '%s : %s' % (section_title, tag)))

  def process_in_blockquote(self, line_number, line):
    self.calls.append((line_number, 'b', line))
    self.replace_line(line_number, line + ' BQ')

  def process_line(self, line_number, line):
    self.calls.append((line_number, 'l', line))

class PyGuideParserTest(test.TestCase):

  def testBasics(self):
    tmp = os.path.join(test.get_temp_dir(), 'py_guide_parser_test.md')
    f = open(tmp, 'w')
    f.write("""# a title
a line
## a section
```shell
in a blockquote
```
out of blockquote
""")
    f.close()
    parser = TestPyGuideParser()
    result = parser.process(tmp)
    expected = """# a title
a line
## a section
```shell BQ
in a blockquote BQ
```
out of blockquote
"""
    self.assertEqual(expected, result)
    expected = [(0, 't', 'a title'),
                (1, 'l', 'a line'),
                (2, 's', 'a section : a_section'),
                (3, 'b', '```shell'),
                (4, 'b', 'in a blockquote'),
                (5, 'l', '```'),
                (6, 'l', 'out of blockquote'),
                (7, 'l', '')]
    self.assertEqual(expected, parser.calls)

if __name__ == '__main__':
  test.main()


text:
<?php
/**
 *
 * Ñïèñîê ðàçäåëîâ.
 *
 */
class Special_Vtor_Organization_Sections_Corr extends Dune_Mysqli_Abstract_Connect
{

    public static $table = 'unity_organization_sections';
    public static $tableCorr = 'unity_organization_sections_corr';

    protected $_organazation = null;
    protected $_order = '';

	public function __construct($organazation = null)
	{
        $this->_organazation = $organazation;
	    $this->_initDB();
	}

	/**
	 *
	 * @param unknown_type $type
	 */
	public function setOrganagation($value)
	{
	    $this->_organazation = $value;
	    return $this;
	}

    public function getOneFirst()
    {
        if (is_null($this->_organazation))
            return false;

	    $q = 'SELECT `sections`.* FROM `' . self::$table . '` as `sections`, `' . self::$tableCorr . '` as `corr`';
        $q .= ' WHERE `sections`.`id` = `corr`.`section_id`';
        $q .= ' AND `corr`.`text_id` = ?i';

	    $q .= ' ' . $this->_order . ' LIMIT 1';
	    $result = $this->_DB->query($q, array($this->_organazation), Dune_MysqliSystem::RESULT_ROWASSOC);
	    return $result;
    }

    public function clearCorr()
    {
        if (is_null($this->_organazation))
            return false;
        $q = 'DELETE FROM `' . self::$tableCorr . '` WHERE `text_id` = ?i';
        $result = $this->_DB->query($q, array($this->_organazation), Dune_MysqliSystem::RESULT_AR);
    }

    public function setCorrOne($section)
    {
        if (is_null($this->_organazation))
            return false;
        $q = 'INSERT INTO `' . self::$tableCorr . '` SET `text_id` = ?i, `section_id` = ?i';
        $result = $this->_DB->query($q, array($this->_organazation, $section), Dune_MysqliSystem::RESULT_AR);
    }

}


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var React = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _utils = require("@material-ui/utils");

var _ownerDocument = _interopRequireDefault(require("../utils/ownerDocument"));

var _useForkRef = _interopRequireDefault(require("../utils/useForkRef"));

var _useEventCallback = _interopRequireDefault(require("../utils/useEventCallback"));

var _jsxRuntime = require("react/jsx-runtime");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

// TODO: return `EventHandlerName extends `on${infer EventName}` ? Lowercase<EventName> : never` once generatePropTypes runs with TS 4.1
function mapEventPropToEvent(eventProp) {
  return eventProp.substring(2).toLowerCase();
}

function clickedRootScrollbar(event, doc) {
  return doc.documentElement.clientWidth < event.clientX || doc.documentElement.clientHeight < event.clientY;
}

/**
 * Listen for click events that occur somewhere in the document, outside of the element itself.
 * For instance, if you need to hide a menu when people click anywhere else on your page.
 *
 * Demos:
 *
 * - [Click Away Listener](https://material-ui.com/components/click-away-listener/)
 * - [Menus](https://material-ui.com/components/menus/)
 *
 * API:
 *
 * - [ClickAwayListener API](https://material-ui.com/api/click-away-listener/)
 */
function ClickAwayListener(props) {
  const {
    children,
    disableReactTree = false,
    mouseEvent = 'onClick',
    onClickAway,
    touchEvent = 'onTouchEnd'
  } = props;
  const movedRef = React.useRef(false);
  const nodeRef = React.useRef(null);
  const activatedRef = React.useRef(false);
  const syntheticEventRef = React.useRef(false);
  React.useEffect(() => {
    // Ensure that this component is not "activated" synchronously.
    // https://github.com/facebook/react/issues/20074
    setTimeout(() => {
      activatedRef.current = true;
    }, 0);
    return () => {
      activatedRef.current = false;
    };
  }, []);
  const handleRef = (0, _useForkRef.default)( // @ts-expect-error TODO upstream fix
  children.ref, nodeRef); // The handler doesn't take event.defaultPrevented into account:
  //
  // event.preventDefault() is meant to stop default behaviors like
  // clicking a checkbox to check it, hitting a button to submit a form,
  // and hitting left arrow to move the cursor in a text input etc.
  // Only special HTML elements have these default behaviors.

  const handleClickAway = (0, _useEventCallback.default)(event => {
    // Given developers can stop the propagation of the synthetic event,
    // we can only be confident with a positive value.
    const insideReactTree = syntheticEventRef.current;
    syntheticEventRef.current = false;
    const doc = (0, _ownerDocument.default)(nodeRef.current); // 1. IE11 support, which trigger the handleClickAway even after the unbind
    // 2. The child might render null.
    // 3. Behave like a blur listener.

    if (!activatedRef.current || !nodeRef.current || 'clientX' in event && clickedRootScrollbar(event, doc)) {
      return;
    } // Do not act if user performed touchmove

    if (movedRef.current) {
      movedRef.current = false;
      return;
    }

    let insideDOM; // If not enough, can use https://github.com/DieterHolvoet/event-propagation-path/blob/master/propagationPath.js

    if (event.composedPath) {
      insideDOM = event.composedPath().indexOf(nodeRef.current) > -1;
    } else {
      insideDOM = !doc.documentElement.contains( // @ts-expect-error returns `false` as intended when not dispatched from a Node
      event.target) || nodeRef.current.contains( // @ts-expect-error returns `false` as intended when not dispatched from a Node
      event.target);
    }

    if (!insideDOM && (disableReactTree || !insideReactTree)) {
      onClickAway(event);
    }
  }); // Keep track of mouse/touch events that bubbled up through the portal.

  const createHandleSynthetic = handlerName => event => {
    syntheticEventRef.current = true;
    const childrenPropsHandler = children.props[handlerName];

    if (childrenPropsHandler) {
      childrenPropsHandler(event);
    }
  };

  const childrenProps = {
    ref: handleRef
  };

  if (touchEvent !== false) {
    childrenProps[touchEvent] = createHandleSynthetic(touchEvent);
  }

  React.useEffect(() => {
    if (touchEvent !== false) {
      const mappedTouchEvent = mapEventPropToEvent(touchEvent);
      const doc = (0, _ownerDocument.default)(nodeRef.current);

      const handleTouchMove = () => {
        movedRef.current = true;
      };

      doc.addEventListener(mappedTouchEvent, handleClickAway);
      doc.addEventListener('touchmove', handleTouchMove);
      return () => {
        doc.removeEventListener(mappedTouchEvent, handleClickAway);
        doc.removeEventListener('touchmove', handleTouchMove);
      };
    }

    return undefined;
  }, [handleClickAway, touchEvent]);

  if (mouseEvent !== false) {
    childrenProps[mouseEvent] = createHandleSynthetic(mouseEvent);
  }

  React.useEffect(() => {
    if (mouseEvent !== false) {
      const mappedMouseEvent = mapEventPropToEvent(mouseEvent);
      const doc = (0, _ownerDocument.default)(nodeRef.current);
      doc.addEventListener(mappedMouseEvent, handleClickAway);
      return () => {
        doc.removeEventListener(mappedMouseEvent, handleClickAway);
      };
    }

    return undefined;
  }, [handleClickAway, mouseEvent]);
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(React.Fragment, {
    children: /*#__PURE__*/React.cloneElement(children, childrenProps)
  });
}

process.env.NODE_ENV !== "production" ? ClickAwayListener.propTypes
/* remove-proptypes */
= {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit TypeScript types and run "yarn proptypes"  |
  // ----------------------------------------------------------------------

  /**
   * The wrapped element.
   */
  children: _utils.elementAcceptingRef.isRequired,

  /**
   * If `true`, the React tree is ignored and only the DOM tree is considered.
   * This prop changes how portaled elements are handled.
   * @default false
   */
  disableReactTree: _propTypes.default.bool,

  /**
   * The mouse event to listen to. You can disable the listener by providing `false`.
   * @default 'onClick'
   */
  mouseEvent: _propTypes.default.oneOf(['onClick', 'onMouseDown', 'onMouseUp', false]),

  /**
   * Callback fired when a "click away" event is detected.
   */
  onClickAway: _propTypes.default.func.isRequired,

  /**
   * The touch event to listen to. You can disable the listener by providing `false`.
   * @default 'onTouchEnd'
   */
  touchEvent: _propTypes.default.oneOf(['onTouchEnd', 'onTouchStart', false])
} : void 0;

if (process.env.NODE_ENV !== 'production') {
  // eslint-disable-next-line
  ClickAwayListener['propTypes' + ''] = (0, _utils.exactProp)(ClickAwayListener.propTypes);
}

var _default = ClickAwayListener;
exports.default = _default;


text:
OroActivityListBundle
=====================
The `OroActivityListBundle` provide ability to show all activities in one widget.

Table of content
----------------
- [Fundamentals](#fundamentals)
- [Add widget into a page](#add-widget-into-a-page)
- [Register a new entity](#register-a-new-entity)
- [Configuration](#configuration)

Fundamentals
------------

Examples of activities that can be added to other entities are:
- Emails
- Calendar events
- Notes

Visualization of Activity list defined as widget block. It shows activities related to the entity record, currently being viewed, in a single list with ability to filter by activity type (multiselect) and date (daterange filter).

Each activity row shows base information about itself: type of activity, who and when have created and update it, also you have access to the full activity record via "expand" action. By default is displayed 25 records, sorted by update date in descending order. The limitation and sorting can be changed in [UI](#configuration) .

The widget currently displayed in "Record activities" placeholder block on an entities view page.

**Example UI within contact page**
![An example of widget](./Resources/doc/example.png)

Add widget into a page
----------------------
Generally widget will be rendered in placeholder "view_content_data_activities". But in case of extending or using view template different from 'OroUIBundle:actions:view.html.twig' you will have to define placeholder in it, e.g.:

```
  {%- set activitiesData -%}
    {% placeholder view_content_data_activities with {entity: entity} %}
  {%- endset -%}
  {% set dataBlocks = dataBlocks|merge([{
    'title': 'Title',
    'subblocks': [{
        'spanClass': 'empty',
        'data': [activitiesData]
    }]
  }]) %}
```

Show widget and it button on specific page (view/edit)
----------------------------------------
To show a widget and it button on specific pages you should set entity annotation.
Widget can be displayed on `view` and/or `update` pages. Allowed values see in `\Oro\Bundle\ActivityBundle\EntityConfig\ActivityScope` e.g.:
```
/**
...
 * @Config(
 *      defaultValues={
 *          ...
 *          "activity"={
 *              "show_on_page"="\Oro\Bundle\ActivityBundle\EntityConfig\ActivityScope::UPDATE_PAGE"
 *          }
 *          ...
 *      }
 * )
 */
class CustomerUserRole extends AbstractRole { ... }
```

Register a new entity
----------------------
To add a new entity to be displayed within widget you need to register a service that implements **ActivityListProviderInterface** and tagged as **oro_activity_list.provider**. Working example can be found in EmailBundle or CalendarBundle:
```
    oro_calendar.activity_list.provider:
        class: %oro_calendar.activity_list.provider.class%
        arguments:
           - @oro_entity.doctrine_helper
           - @doctrine
        tags:
           - {name: oro_activity_list.provider, priority: 50}
```
This will add your provider class into a bunch of providers (**ActivityListChainProvider**) that will be invoked to fetch data ordering by priority (added in service definition). For now 'priority' do not have much sense, but it may be useful in future implementations or in case of overriding some existing providers in 3rd party bundles.

Each activity entity has its own row template for UI component. Generally you are free to place it anywhere you want, only requirement is: it's path should be returned in Provider via method getTemplate(). E.g.
```
class CalendarEventActivityListProvider implements ActivityListProviderInterface
{
...
/**
* {@inheritdoc}
*/
public function getTemplate()
{
   return 'OroCalendarBundle:CalendarEvent:js/activityItemTemplate.html.twig';
}
...

```

Configuration
-------------
Sorting and limitation could be changed in UI: System -> Configuration -> Display settings -> section "Activity lists".

 - Sort by field - sorting available by "Created date" or "Updated date"(default).
 - Sort direction - Ascending or Descending(default).
 - Items Per Page By Default - number of activities displayed in list. Default is 25.


text:
namespace LoadTest {
    public enum HttpVerbs {
        Get,
        Post,
        Put,
        Delete,
        Head,
        Patch,
        Options
    }
}


text:
                <alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</alert>

                    <form novalidate name="adminForm" class="css-form">

 This search is broken for now because of Schema changes

Will fix when we know what to do with it -- (re-design symptoms!)

                            <input ng-model="$parent.email" type="email" focus-on="focusSearch"
                                class="form-control login-field" value=""
                                placeholder="Email" id="login-name"
                                name="email" required />

                    </form>

                        <button type="button" ng-click="getForms()"
                            class="btn btn-primary btn-lg btn-block">Your History</button>

You're an Event Coordinator for

{{form.eventName}}

                            <button type="button" ng-click="sendMail(form)"
                                class="btn btn-primary btn-small comp">Recover Coordinator Link</button>

                                <button type="button" class="btn btn-primary btn-small">
                                    Go to form
                                </button>

You've Volunteered for

{{form.eventName}}

                            <button type="button" class="btn btn-primary btn-small">
                                Go to form
                            </button>

No Forms


text: Check if you wish to publish Gradle-generated ivy.xml descriptor files to Artifactory.


text:
@interface TMPTaskCompletionManager(TestSupport)
@property (nonatomic) NSMutableArray *taskIdentifiers;
@property (nonatomic) NSMutableArray *eTasks;
@property (nonatomic) NSOperationQueue *defaultTaskQueue;

- (void)applicationWillTerminate;
@end

SPEC_BEGIN(TMPTaskCompletionManagerSpec)

typedef void (^task_t)();

describe(@"TMPTaskCompletionManagerSpec", ^{
  context(@"for calling runBackgroundTask:taskQueue:expirationTask", ^{
    __block TMPTaskCompletionManager *taskCompletion;

    beforeEach(^{
        taskCompletion = [TMPTaskCompletionManager sharedManager];
        taskCompletion.taskIdentifiers = nil;
        taskCompletion.eTasks = nil;
      });

    it(@"should register specified task to defaultQueue.", ^{
        NSOperationQueue *dQ = [NSOperationQueue mock];
        taskCompletion.defaultTaskQueue = dQ;

        task_t t0 = ^{};
        task_t t1 = ^{};
        task_t e0 = ^{};
        task_t e1 = ^{};
        UIBackgroundTaskIdentifier btid;

        [[dQ should]
          receive:@selector(addOperation:)
          withCount:2];

        btid = [taskCompletion
          runBackgroundTask:t0
                  taskQueue:nil
             expirationTask:e0];
        [[theValue([taskCompletion.taskIdentifiers count])
             should] equal:theValue(1)];
        [[taskCompletion.taskIdentifiers[0] should] equal:@(btid)];
        [[theValue([taskCompletion.eTasks count])
             should] equal:theValue(1)];

        btid = [taskCompletion
          runBackgroundTask:t1
                  taskQueue:nil
             expirationTask:e1];
        [[theValue([taskCompletion.taskIdentifiers count])
             should] equal:theValue(2)];
        [[taskCompletion.taskIdentifiers[1] should] equal:@(btid)];
        [[theValue([taskCompletion.eTasks count])
             should] equal:theValue(2)];
    });

    it(@"should register specified task to specified queue.", ^{
        NSOperationQueue *dQ = [NSOperationQueue mock];
        taskCompletion.defaultTaskQueue = dQ;
        NSOperationQueue *mQ = [NSOperationQueue mock];

        task_t t0 = ^{};
        task_t t1 = ^{};
        task_t e0 = ^{};
        task_t e1 = ^{};
        UIBackgroundTaskIdentifier btid;

        [[dQ should]
          receive:@selector(addOperation:)
          withCount:0];
        [[mQ should]
          receive:@selector(addOperation:)
          withCount:2];

        btid = [taskCompletion
          runBackgroundTask:t0
                  taskQueue:mQ
             expirationTask:e0];
        [[theValue([taskCompletion.taskIdentifiers count])
             should] equal:theValue(1)];
        [[taskCompletion.taskIdentifiers[0] should] equal:@(btid)];
        [[theValue([taskCompletion.eTasks count])
             should] equal:theValue(1)];

        btid = [taskCompletion
          runBackgroundTask:t1
                  taskQueue:mQ
             expirationTask:e1];
        [[theValue([taskCompletion.taskIdentifiers count])
             should] equal:theValue(2)];
        [[taskCompletion.taskIdentifiers[1] should] equal:@(btid)];
        [[theValue([taskCompletion.eTasks count])
             should] equal:theValue(2)];
    });
  });

  context(@"for calling runBackgroundOperation:taskQueue:expirationTask", ^{
    __block TMPTaskCompletionManager *taskCompletion;

    beforeEach(^{
        taskCompletion = [TMPTaskCompletionManager sharedManager];
        taskCompletion.taskIdentifiers = nil;
        taskCompletion.eTasks = nil;
      });

    it(@"should cancel eTask if operation finished correctly.", ^{
        taskCompletion.defaultTaskQueue = [NSOperationQueue new];

        __block NSString *o0Expired = nil;
        NSBlockOperation *o0 =
          [NSBlockOperation blockOperationWithBlock:^{
              [NSThread sleepForTimeInterval:1];
              o0Expired = @"done";
            }];
        task_t e0 = ^{o0Expired = @"expired";};

        __block NSString *o1Expired = nil;
        NSBlockOperation *o1 =
          [NSBlockOperation blockOperationWithBlock:^{
              [NSThread sleepForTimeInterval:3];
              o1Expired = @"done";
            }];
        task_t e1 = ^{o1Expired = @"expired";};

        UIBackgroundTaskIdentifier btid;
        btid = [taskCompletion
          runBackgroundOperation:o0
                       taskQueue:nil
                  expirationTask:e0];
        [[theValue([taskCompletion.taskIdentifiers count])
             should] equal:theValue(1)];
        [[taskCompletion.taskIdentifiers[0] should] equal:@(btid)];
        [[theValue([taskCompletion.eTasks count])
             should] equal:theValue(1)];

        btid = [taskCompletion
          runBackgroundOperation:o1
                  taskQueue:nil
             expirationTask:e1];
        [[theValue([taskCompletion.taskIdentifiers count])
             should] equal:theValue(2)];
        [[taskCompletion.taskIdentifiers[1] should] equal:@(btid)];
        [[theValue([taskCompletion.eTasks count])
             should] equal:theValue(2)];

        [[expectFutureValue(theValue([taskCompletion.eTasks count]))
             shouldEventuallyBeforeTimingOutAfter(2.0)]
          equal:theValue(1)];
        [[expectFutureValue(o0Expired)
             shouldEventuallyBeforeTimingOutAfter(2.0)]
          equal:@"done"];

        [[expectFutureValue(theValue([taskCompletion.eTasks count]))
             shouldEventuallyBeforeTimingOutAfter(4.0)]
          equal:theValue(0)];
        [[expectFutureValue(o1Expired)
             shouldEventuallyBeforeTimingOutAfter(4.0)]
          equal:@"done"];
    });

    it(@"should invoke eTask if operation did not finish.", ^{
        taskCompletion.defaultTaskQueue = [NSOperationQueue new];

        __block NSString *o0Expired = nil;
        NSBlockOperation *o0 =
          [NSBlockOperation blockOperationWithBlock:^{
              [NSThread sleepForTimeInterval:5];
              o0Expired = @"done";
            }];
        task_t e0 = ^{o0Expired = @"expired";};

        __block NSString *o1Expired = nil;
        NSBlockOperation *o1 =
          [NSBlockOperation blockOperationWithBlock:^{
              [NSThread sleepForTimeInterval:5];
              o1Expired = @"done";
            }];
        task_t e1 = ^{o1Expired = @"expired";};

        [taskCompletion
          runBackgroundOperation:o0
                       taskQueue:nil
                  expirationTask:e0];
        [taskCompletion
          runBackgroundOperation:o1
                  taskQueue:nil
             expirationTask:e1];

        [taskCompletion applicationWillTerminate];

        [[expectFutureValue(o0Expired)
             shouldEventually]
          equal:@"expired"];
        [[expectFutureValue(o1Expired)
             shouldEventually]
          equal:@"expired"];
    });
  });

  context(@"for calling cancelBackgroundTask", ^{
    __block TMPTaskCompletionManager *taskCompletion;

    beforeEach(^{
        taskCompletion = [TMPTaskCompletionManager sharedManager];
        taskCompletion.taskIdentifiers = nil;
        taskCompletion.eTasks = nil;
      });

    it(@"should ignore if there no registered task.", ^{
        UIApplication *a = [UIApplication sharedApplication];
        [[a shouldEventually]
          receive:@selector(endBackgroundTask:)
          withCount:0];
        [taskCompletion cancelBackgroundTask:1];
    });

    it(@"should ignore if specified task is not registered.", ^{
        UIApplication *a = [UIApplication sharedApplication];
        [taskCompletion.taskIdentifiers addObject:@(1)];
        [taskCompletion.eTasks addObject:@"foo"];
        [[a shouldEventually]
          receive:@selector(endBackgroundTask:)
          withCount:0];
        [taskCompletion cancelBackgroundTask:2];
    });

    it(@"should cancel specified task.", ^{
        UIApplication *a = [UIApplication sharedApplication];
        [taskCompletion.taskIdentifiers addObject:@(1)];
        [taskCompletion.taskIdentifiers addObject:@(2)];
        [taskCompletion.eTasks addObject:@"foo"];
        [taskCompletion.eTasks addObject:@"bar"];
        [[theValue([taskCompletion.taskIdentifiers count])
             should] equal:theValue(2)];
        [[theValue([taskCompletion.eTasks count])
             should] equal:theValue(2)];

        [[a shouldEventually]
          receive:@selector(endBackgroundTask:)
          withCount:1];
        [taskCompletion cancelBackgroundTask:1];
        [[expectFutureValue(theValue([taskCompletion.taskIdentifiers count]))
             shouldEventually] equal:theValue(1)];
        [[expectFutureValue(taskCompletion.taskIdentifiers[0])
             shouldEventually] equal:@(2)];
        [[expectFutureValue(taskCompletion.eTasks[0])
             shouldEventually] equal:@"bar"];
    });
  });

  context(@"for calling cancelAllBackgroundTasks", ^{
    __block TMPTaskCompletionManager *taskCompletion;

    beforeEach(^{
        taskCompletion = [TMPTaskCompletionManager sharedManager];
        taskCompletion.taskIdentifiers = nil;
        taskCompletion.eTasks = nil;
      });

    it(@"should ignore if there no registered task.", ^{
        UIApplication *a = [UIApplication sharedApplication];
        [[a should]
          receive:@selector(endBackgroundTask:)
          withCount:0];
        [taskCompletion cancelAllBackgroundTasks];
    });

    it(@"should cancel all registered tasks.", ^{
        UIApplication *a = [UIApplication sharedApplication];
        [taskCompletion.taskIdentifiers addObject:@(1)];
        [taskCompletion.taskIdentifiers addObject:@(2)];
        [taskCompletion.eTasks addObject:@"foo"];
        [taskCompletion.eTasks addObject:@"bar"];
        [[theValue([taskCompletion.taskIdentifiers count])
             should] equal:theValue(2)];
        [[theValue([taskCompletion.eTasks count])
             should] equal:theValue(2)];

        [[a shouldEventually]
          receive:@selector(endBackgroundTask:)
          withCount:2];
        [taskCompletion cancelAllBackgroundTasks];
        [[expectFutureValue(theValue([taskCompletion.taskIdentifiers count]))
             shouldEventually] equal:theValue(0)];
        [[expectFutureValue(theValue([taskCompletion.eTasks count]))
             shouldEventually] equal:theValue(0)];
    });
  });
});

SPEC_END

// EOF


text:
package sds.classfile.attribute

import scala.annotation.tailrec
import collection.mutable.{ArrayBuffer => Buffer}
import sds.classfile.{ClassfileStream => Stream}
import sds.classfile.bytecode.{OpcodeInfo => Opcode}
import sds.classfile.constant_pool.{ConstantInfo => CInfo, Utf8Info => Utf8}

class Code(data: Stream, pool: Array[CInfo]) extends AttributeInfo {
    val maxStack:  Int = data.short
    val maxLocals: Int = data.short
    val opcodes: Array[Opcode] = initOpcodes()
    val exTable: Array[(Array[Int], String)] = (0 until data.short).map((_: Int) => {
        // 0: start, 1: end, 2: handle
        val indexes: Array[Int] = (0 until 3).map((_: Int) => data.short).toArray
        val catchType: Int = data.short
        val target: String = if(catchType == 0) "any" else extract(catchType, pool)
        (indexes, target)
    }).toArray
    val attributes: Array[AttributeInfo] = (0 until data.short).map((_: Int) => {
        val name: Int = data.short
        val utf8: Utf8 = pool(name - 1).asInstanceOf[Utf8]
        AttributeInfo(utf8.value, data, pool, opcodes)
    }).toArray

    private def initOpcodes(): Array[Opcode] = {
        val len: Int = data.int
        val pointer: Int = data.pointer
        readOpcode(len, pointer, data, pool, Buffer[Opcode]())
    }

    @tailrec
    private def readOpcode(len: Int, pointer: Int, data: Stream, pool: Array[CInfo], buffer: Buffer[Opcode]):
    Array[Opcode] = {
        val index: Int = data.pointer
        if(index >= (len + pointer)) {
            return buffer.toArray
        }
        val pc: Int = index - pointer
        val info: Opcode = Opcode(pc, data, pool)
        readOpcode(len, pointer, data, pool, buffer += info)
    }
}


text:
import algolia from './algolia.js';
import parseQuery from './parse-query.js';

let jsDelivrIndex = algolia.initIndex('jsDelivr');

export default function (queryString, page = 0, hitsPerPage = 10) {
	return Promise.resolve().then(() => {
		let parsed = parseQuery(queryString);
		let options = { page, hitsPerPage };
		let promise;

		if (parsed.facetFilters) {
			options.facetFilters = parsed.facetFilters;
		}

		if (parsed.query || options.facetFilters) {
			promise = jsDelivrIndex.search(parsed.query, options);
		} else {
			promise = jsDelivrIndex.browse(options.page, hitsPerPage);
		}

		return promise.then((response) => {
			let load = [];

			response.hits.forEach((project) => {
				project.selectedVersion = project.lastversion;

				if (!project.assets.length) {
					load.push(project);
				}
			});

			if (!load.length) {
				return {
					response: $.extend(true, {}, response),
					queryString,
				};
			}

			algolia.startQueriesBatch();

			load.forEach((project) => {
				algolia.addQueryInBatch('jsDelivr_assets', '', {
					hitsPerPage: 100,
					facetFilters: `name: ${project.name}`,
				});
			});

			return algolia.sendQueriesBatch().then((content) => {
				load.forEach((project, index) => {
					project.assets = content.results[index].hits;
				});

				return {
					response: $.extend(true, {}, response),
					queryString,
				};
			});
		});
	});
}


text:
namespace ash {
namespace internal {

namespace tray {
class NetworkDefaultView;
class NetworkDetailedView;
class NetworkMessages;
class NetworkMessageView;
class NetworkNotificationView;
class NetworkTrayView;
}

class TrayNetwork : public SystemTrayItem,
                    public NetworkObserver {
 public:
  enum DetailedViewType {
    LIST_VIEW,
    WIFI_VIEW,
  };

  explicit TrayNetwork(SystemTray* system_tray);
  virtual ~TrayNetwork();

  // Overridden from SystemTrayItem.
  virtual views::View* CreateTrayView(user::LoginStatus status) OVERRIDE;
  virtual views::View* CreateDefaultView(user::LoginStatus status) OVERRIDE;
  virtual views::View* CreateDetailedView(user::LoginStatus status) OVERRIDE;
  virtual views::View* CreateNotificationView(
      user::LoginStatus status) OVERRIDE;
  virtual void DestroyTrayView() OVERRIDE;
  virtual void DestroyDefaultView() OVERRIDE;
  virtual void DestroyDetailedView() OVERRIDE;
  virtual void DestroyNotificationView() OVERRIDE;
  virtual void UpdateAfterLoginStatusChange(user::LoginStatus status) OVERRIDE;
  virtual void UpdateAfterShelfAlignmentChange(
      ShelfAlignment alignment) OVERRIDE;

  // Overridden from NetworkObserver.
  virtual void OnNetworkRefresh(const NetworkIconInfo& info) OVERRIDE;
  virtual void SetNetworkMessage(NetworkTrayDelegate* delegate,
                                 MessageType message_type,
                                 NetworkType network_type,
                                 const string16& title,
                                 const string16& message,
                                 const std::vector<string16>& links) OVERRIDE;
  virtual void ClearNetworkMessage(MessageType message_type) OVERRIDE;
  virtual void OnWillToggleWifi() OVERRIDE;

 private:
  friend class tray::NetworkMessageView;
  friend class tray::NetworkNotificationView;

  void LinkClicked(MessageType message_type, int link_id);

  const tray::NetworkMessages* messages() const { return messages_.get(); }

  tray::NetworkTrayView* tray_;
  tray::NetworkDefaultView* default_;
  tray::NetworkDetailedView* detailed_;
  tray::NetworkNotificationView* notification_;
  scoped_ptr<tray::NetworkMessages> messages_;
  bool request_wifi_view_;

  DISALLOW_COPY_AND_ASSIGN(TrayNetwork);
};

}  // namespace internal
}  // namespace ash

#endif  // ASH_SYSTEM_CHROMEOS_NETWORK_TRAY_NETWORK_H


text:
package hw1;

import java.io.*;
import java.net.*;
import java.util.Random;

public class UDPServer {
	public static void main(String[] args) throws IOException {

		// Generate randomInt between 1 and 10
		int randomInt = randInt(1, 10);

		// Server setup
		DatagramSocket serverSocket = new DatagramSocket(4160);
		byte[] rbuf = new byte[256];
		DatagramPacket packet = new DatagramPacket(rbuf, rbuf.length);
		serverSocket.receive(packet);
		ByteArrayInputStream bin = new ByteArrayInputStream(rbuf, 0, packet.getLength());
		DataInputStream dis = new DataInputStream(bin);
		String playerName = dis.readUTF();
		InetAddress address = packet.getAddress();
		int port = packet.getPort();

		// Send response
		String line = "Hello " + playerName + ", time to play the GUESSING GAME. " +
					  playerName + ", please enter a number between 1 and 10.";
		byte[] sbuf = new byte[256];
		sbuf = line.getBytes();
		packet = new DatagramPacket(sbuf, sbuf.length, address, port);
		serverSocket.send(packet);

//		// Start the game
//		int playerGuess = 0; // BUGBUG initialize playerGuess to an incorrect guess
//		while (playerGuess != randomInt) {

		// Start Game
		line = "Incorrect"; // BUGBUG initialize response as incorrect
		while (!line.equals("YOU WIN!!!")) {
			rbuf = new byte[256];
			packet = new DatagramPacket(rbuf, rbuf.length);
			serverSocket.receive(packet);
			bin = new ByteArrayInputStream(rbuf, 0, packet.getLength());
			dis = new DataInputStream(bin);
			int i = dis.readInt();
			if (i < randomInt) {
				line = "Too Small, Guess Again";
			} else if (i > randomInt) {
				line = "Too Big, Guess Again";
			} else {
				line = "YOU WIN!!!";
			}
			sbuf = line.getBytes();
			packet = new DatagramPacket(sbuf, sbuf.length, address, port);
			serverSocket.send(packet);
		}

		// End Game
		serverSocket.close();
		System.exit(0);
	}

	/**
	 * Returns a pseudo-random number between min and max, inclusive.
	 * The difference between min and max can be at most
	 * Integer.MAX_VALUE - 1. Use this for a random number between
	 * 1 and 10 for your Hi Low game
	 *
	 * @param min Minimum value
	 * @param max Maximum value.  Must be greater than min.
	 * @return Integer between min and max, inclusive.
	 * @see java.util.Random#nextInt(int)
	 */
	public static int randInt(int min, int max) {

	    // NOTE: Usually this should be a field rather than a method
	    // variable so that it is not re-seeded every call.
	    Random rand = new Random();

	    // nextInt is normally exclusive of the top value,
	    // so add 1 to make it inclusive
	    int randomNum = rand.nextInt((max - min) + 1) + min;

	    return randomNum;
	}
}


text:
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/gorilla/mux"
	"github.com/pkg/errors"

	"github.com/lxc/lxd/client"
	"github.com/lxc/lxd/lxd/cluster"
	"github.com/lxc/lxd/lxd/db"
	deviceConfig "github.com/lxc/lxd/lxd/device/config"
	"github.com/lxc/lxd/lxd/instance"
	"github.com/lxc/lxd/lxd/instance/instancetype"
	"github.com/lxc/lxd/lxd/lifecycle"
	"github.com/lxc/lxd/lxd/project"
	"github.com/lxc/lxd/lxd/request"
	"github.com/lxc/lxd/lxd/response"
	"github.com/lxc/lxd/lxd/util"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/api"
	log "github.com/lxc/lxd/shared/log15"
	"github.com/lxc/lxd/shared/version"
)

var profilesCmd = APIEndpoint{
	Path: "profiles",

	Get:  APIEndpointAction{Handler: profilesGet, AccessHandler: allowProjectPermission("profiles", "view")},
	Post: APIEndpointAction{Handler: profilesPost, AccessHandler: allowProjectPermission("profiles", "manage-profiles")},
}

var profileCmd = APIEndpoint{
	Path: "profiles/{name}",

	Delete: APIEndpointAction{Handler: profileDelete, AccessHandler: allowProjectPermission("profiles", "manage-profiles")},
	Get:    APIEndpointAction{Handler: profileGet, AccessHandler: allowProjectPermission("profiles", "view")},
	Patch:  APIEndpointAction{Handler: profilePatch, AccessHandler: allowProjectPermission("profiles", "manage-profiles")},
	Post:   APIEndpointAction{Handler: profilePost, AccessHandler: allowProjectPermission("profiles", "manage-profiles")},
	Put:    APIEndpointAction{Handler: profilePut, AccessHandler: allowProjectPermission("profiles", "manage-profiles")},
}

// swagger:operation GET /1.0/profiles profiles profiles_get
//
// Get the profiles
//
// Returns a list of profiles (URLs).
//
// ---
// produces:
//   - application/json
// parameters:
//   - in: query
//     name: project
//     description: Project name
//     type: string
//     example: default
// responses:
//   "200":
//     description: API endpoints
//     schema:
//       type: object
//       description: Sync response
//       properties:
//         type:
//           type: string
//           description: Response type
//           example: sync
//         status:
//           type: string
//           description: Status description
//           example: Success
//         status_code:
//           type: integer
//           description: Status code
//           example: 200
//         metadata:
//           type: array
//           description: List of endpoints
//           items:
//             type: string
//           example: |-
//             [
//               "/1.0/profiles/default",
//               "/1.0/profiles/foo"
//             ]
//   "403":
//     $ref: "#/responses/Forbidden"
//   "500":
//     $ref: "#/responses/InternalServerError"

// swagger:operation GET /1.0/profiles?recursion=1 profiles profiles_get_recursion1
//
// Get the profiles
//
// Returns a list of profiles (structs).
//
// ---
// produces:
//   - application/json
// parameters:
//   - in: query
//     name: project
//     description: Project name
//     type: string
//     example: default
// responses:
//   "200":
//     description: API endpoints
//     schema:
//       type: object
//       description: Sync response
//       properties:
//         type:
//           type: string
//           description: Response type
//           example: sync
//         status:
//           type: string
//           description: Status description
//           example: Success
//         status_code:
//           type: integer
//           description: Status code
//           example: 200
//         metadata:
//           type: array
//           description: List of profiles
//           items:
//             $ref: "#/definitions/Profile"
//   "403":
//     $ref: "#/responses/Forbidden"
//   "500":
//     $ref: "#/responses/InternalServerError"
func profilesGet(d *Daemon, r *http.Request) response.Response {
	projectName, _, err := project.ProfileProject(d.State().Cluster, projectParam(r))
	if err != nil {
		return response.SmartError(err)
	}

	recursion := util.IsRecursionRequest(r)

	var result interface{}
	err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
		filter := db.ProfileFilter{
			Project: &projectName,
		}
		if recursion {
			profiles, err := tx.GetProfiles(filter)
			if err != nil {
				return err
			}
			apiProfiles := make([]*api.Profile, len(profiles))
			for i, profile := range profiles {
				apiProfiles[i] = db.ProfileToAPI(&profile)
				apiProfiles[i].UsedBy = project.FilterUsedBy(r, apiProfiles[i].UsedBy)
			}

			result = apiProfiles
		} else {
			result, err = tx.GetProfileURIs(filter)
		}
		return err
	})
	if err != nil {
		return response.SmartError(err)
	}

	return response.SyncResponse(true, result)
}

// swagger:operation POST /1.0/profiles profiles profiles_post
//
// Add a profile
//
// Creates a new profile.
//
// ---
// consumes:
//   - application/json
// produces:
//   - application/json
// parameters:
//   - in: query
//     name: project
//     description: Project name
//     type: string
//     example: default
//   - in: body
//     name: profile
//     description: Profile
//     required: true
//     schema:
//       $ref: "#/definitions/ProfilesPost"
// responses:
//   "200":
//     $ref: "#/responses/EmptySyncResponse"
//   "400":
//     $ref: "#/responses/BadRequest"
//   "403":
//     $ref: "#/responses/Forbidden"
//   "500":
//     $ref: "#/responses/InternalServerError"
func profilesPost(d *Daemon, r *http.Request) response.Response {
	projectName, _, err := project.ProfileProject(d.State().Cluster, projectParam(r))
	if err != nil {
		return response.SmartError(err)
	}

	req := api.ProfilesPost{}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		return response.BadRequest(err)
	}

	// Quick checks.
	if req.Name == "" {
		return response.BadRequest(fmt.Errorf("No name provided"))
	}

	if strings.Contains(req.Name, "/") {
		return response.BadRequest(fmt.Errorf("Profile names may not contain slashes"))
	}

	if shared.StringInSlice(req.Name, []string{".", ".."}) {
		return response.BadRequest(fmt.Errorf("Invalid profile name %q", req.Name))
	}

	err = instance.ValidConfig(d.os, req.Config, false, instancetype.Any)
	if err != nil {
		return response.BadRequest(err)
	}

	// At this point we don't know the instance type, so just use instancetype.Any type for validation.
	err = instance.ValidDevices(d.State(), d.cluster, projectName, instancetype.Any, deviceConfig.NewDevices(req.Devices), false)
	if err != nil {
		return response.BadRequest(err)
	}

	// Update DB entry.
	err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
		current, _ := tx.GetProfile(projectName, req.Name)
		if current != nil {
			return fmt.Errorf("The profile already exists")
		}

		profile := db.Profile{
			Project:     projectName,
			Name:        req.Name,
			Description: req.Description,
			Config:      req.Config,
			Devices:     req.Devices,
		}
		_, err = tx.CreateProfile(profile)
		return err
	})
	if err != nil {
		return response.SmartError(errors.Wrapf(err, "Error inserting %q into database", req.Name))
	}

	requestor := request.CreateRequestor(r)
	d.State().Events.SendLifecycle(projectName, lifecycle.ProfileCreated.Event(req.Name, projectName, requestor, nil))

	return response.SyncResponseLocation(true, nil, fmt.Sprintf("/%s/profiles/%s", version.APIVersion, req.Name))
}

// swagger:operation GET /1.0/profiles/{name} profiles profile_get
//
// Get the profile
//
// Gets a specific profile.
//
// ---
// produces:
//   - application/json
// parameters:
//   - in: query
//     name: project
//     description: Project name
//     type: string
//     example: default
// responses:
//   "200":
//     description: Profile
//     schema:
//       type: object
//       description: Sync response
//       properties:
//         type:
//           type: string
//           description: Response type
//           example: sync
//         status:
//           type: string
//           description: Status description
//           example: Success
//         status_code:
//           type: integer
//           description: Status code
//           example: 200
//         metadata:
//           $ref: "#/definitions/Profile"
//   "403":
//     $ref: "#/responses/Forbidden"
//   "500":
//     $ref: "#/responses/InternalServerError"
func profileGet(d *Daemon, r *http.Request) response.Response {
	projectName, _, err := project.ProfileProject(d.State().Cluster, projectParam(r))
	if err != nil {
		return response.SmartError(err)
	}

	name := mux.Vars(r)["name"]

	var resp *api.Profile

	err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
		profile, err := tx.GetProfile(projectName, name)
		if err != nil {
			return errors.Wrap(err, "Fetch profile")
		}

		resp = db.ProfileToAPI(profile)
		resp.UsedBy = project.FilterUsedBy(r, resp.UsedBy)

		return nil
	})
	if err != nil {
		return response.SmartError(err)
	}

	etag := []interface{}{resp.Config, resp.Description, resp.Devices}
	return response.SyncResponseETag(true, resp, etag)
}

// swagger:operation PUT /1.0/profiles/{name} profiles profile_put
//
// Update the profile
//
// Updates the entire profile configuration.
//
// ---
// consumes:
//   - application/json
// produces:
//   - application/json
// parameters:
//   - in: query
//     name: project
//     description: Project name
//     type: string
//     example: default
//   - in: body
//     name: profile
//     description: Profile configuration
//     required: true
//     schema:
//       $ref: "#/definitions/ProfilePut"
// responses:
//   "200":
//     $ref: "#/responses/EmptySyncResponse"
//   "400":
//     $ref: "#/responses/BadRequest"
//   "403":
//     $ref: "#/responses/Forbidden"
//   "412":
//     $ref: "#/responses/PreconditionFailed"
//   "500":
//     $ref: "#/responses/InternalServerError"
func profilePut(d *Daemon, r *http.Request) response.Response {
	projectName, _, err := project.ProfileProject(d.State().Cluster, projectParam(r))
	if err != nil {
		return response.SmartError(err)
	}

	name := mux.Vars(r)["name"]

	if isClusterNotification(r) {
		// In this case the ProfilePut request payload contains information about the old profile, since
		// the new one has already been saved in the database.
		old := api.ProfilePut{}
		err := json.NewDecoder(r.Body).Decode(&old)
		if err != nil {
			return response.BadRequest(err)
		}

		err = doProfileUpdateCluster(d, projectName, name, old)
		return response.SmartError(err)
	}

	var id int64
	var profile *api.Profile

	err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
		current, err := tx.GetProfile(projectName, name)
		if err != nil {
			return errors.Wrapf(err, "Failed to retrieve profile %q", name)
		}

		profile = db.ProfileToAPI(current)
		id = int64(current.ID)

		return nil
	})
	if err != nil {
		return response.SmartError(err)
	}

	// Validate the ETag.
	etag := []interface{}{profile.Config, profile.Description, profile.Devices}
	err = util.EtagCheck(r, etag)
	if err != nil {
		return response.PreconditionFailed(err)
	}

	req := api.ProfilePut{}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		return response.BadRequest(err)
	}

	err = doProfileUpdate(d, projectName, name, id, profile, req)

	if err == nil && !isClusterNotification(r) {
		// Notify all other nodes. If a node is down, it will be ignored.
		notifier, err := cluster.NewNotifier(d.State(), d.endpoints.NetworkCert(), d.serverCert(), cluster.NotifyAlive)
		if err != nil {
			return response.SmartError(err)
		}

		err = notifier(func(client lxd.InstanceServer) error {
			return client.UseProject(projectName).UpdateProfile(name, profile.ProfilePut, "")
		})
		if err != nil {
			return response.SmartError(err)
		}
	}

	requestor := request.CreateRequestor(r)
	d.State().Events.SendLifecycle(projectName, lifecycle.ProfileUpdated.Event(name, projectName, requestor, nil))

	return response.SmartError(err)
}

// swagger:operation PATCH /1.0/profiles/{name} profiles profile_patch
//
// Partially update the profile
//
// Updates a subset of the profile configuration.
//
// ---
// consumes:
//   - application/json
// produces:
//   - application/json
// parameters:
//   - in: query
//     name: project
//     description: Project name
//     type: string
//     example: default
//   - in: body
//     name: profile
//     description: Profile configuration
//     required: true
//     schema:
//       $ref: "#/definitions/ProfilePut"
// responses:
//   "200":
//     $ref: "#/responses/EmptySyncResponse"
//   "400":
//     $ref: "#/responses/BadRequest"
//   "403":
//     $ref: "#/responses/Forbidden"
//   "412":
//     $ref: "#/responses/PreconditionFailed"
//   "500":
//     $ref: "#/responses/InternalServerError"
func profilePatch(d *Daemon, r *http.Request) response.Response {
	projectName, _, err := project.ProfileProject(d.State().Cluster, projectParam(r))
	if err != nil {
		return response.SmartError(err)
	}

	name := mux.Vars(r)["name"]

	var id int64
	var profile *api.Profile

	err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
		current, err := tx.GetProfile(projectName, name)
		if err != nil {
			return errors.Wrapf(err, "Failed to retrieve profile=%q", name)
		}

		profile = db.ProfileToAPI(current)
		id = int64(current.ID)

		return nil
	})
	if err != nil {
		return response.SmartError(err)
	}

	// Validate the ETag.
	etag := []interface{}{profile.Config, profile.Description, profile.Devices}
	err = util.EtagCheck(r, etag)
	if err != nil {
		return response.PreconditionFailed(err)
	}

	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return response.InternalError(err)
	}

	rdr1 := ioutil.NopCloser(bytes.NewBuffer(body))
	rdr2 := ioutil.NopCloser(bytes.NewBuffer(body))

	reqRaw := shared.Jmap{}
	if err := json.NewDecoder(rdr1).Decode(&reqRaw); err != nil {
		return response.BadRequest(err)
	}

	req := api.ProfilePut{}
	if err := json.NewDecoder(rdr2).Decode(&req); err != nil {
		return response.BadRequest(err)
	}

	// Get Description.
	_, err = reqRaw.GetString("description")
	if err != nil {
		req.Description = profile.Description
	}

	// Get Config.
	if req.Config == nil {
		req.Config = profile.Config
	} else {
		for k, v := range profile.Config {
			_, ok := req.Config[k]
			if !ok {
				req.Config[k] = v
			}
		}
	}

	// Get Devices.
	if req.Devices == nil {
		req.Devices = profile.Devices
	} else {
		for k, v := range profile.Devices {
			_, ok := req.Devices[k]
			if !ok {
				req.Devices[k] = v
			}
		}
	}

	requestor := request.CreateRequestor(r)
	d.State().Events.SendLifecycle(projectName, lifecycle.ProfileUpdated.Event(name, projectName, requestor, nil))

	return response.SmartError(doProfileUpdate(d, projectName, name, id, profile, req))
}

// swagger:operation POST /1.0/profiles/{name} profiles profile_post
//
// Rename the profile
//
// Renames an existing profile.
//
// ---
// consumes:
//   - application/json
// produces:
//   - application/json
// parameters:
//   - in: query
//     name: project
//     description: Project name
//     type: string
//     example: default
//   - in: body
//     name: profile
//     description: Profile rename request
//     required: true
//     schema:
//       $ref: "#/definitions/ProfilePost"
// responses:
//   "200":
//     $ref: "#/responses/EmptySyncResponse"
//   "400":
//     $ref: "#/responses/BadRequest"
//   "403":
//     $ref: "#/responses/Forbidden"
//   "500":
//     $ref: "#/responses/InternalServerError"
func profilePost(d *Daemon, r *http.Request) response.Response {
	projectName, _, err := project.ProfileProject(d.State().Cluster, projectParam(r))
	if err != nil {
		return response.SmartError(err)
	}

	name := mux.Vars(r)["name"]
	if name == "default" {
		return response.Forbidden(errors.New(`The "default" profile cannot be renamed`))
	}

	req := api.ProfilePost{}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		return response.BadRequest(err)
	}

	// Quick checks.
	if req.Name == "" {
		return response.BadRequest(fmt.Errorf("No name provided"))
	}

	if strings.Contains(req.Name, "/") {
		return response.BadRequest(fmt.Errorf("Profile names may not contain slashes"))
	}

	if shared.StringInSlice(req.Name, []string{".", ".."}) {
		return response.BadRequest(fmt.Errorf("Invalid profile name %q", req.Name))
	}

	err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
		// Check that the name isn't already in use.
		_, err = tx.GetProfile(projectName, req.Name)
		if err == nil {
			return fmt.Errorf("Name %q already in use", req.Name)
		}

		return tx.RenameProfile(projectName, name, req.Name)
	})
	if err != nil {
		return response.SmartError(err)
	}

	requestor := request.CreateRequestor(r)
	d.State().Events.SendLifecycle(projectName, lifecycle.ProfileRenamed.Event(req.Name, projectName, requestor, log.Ctx{"old_name": name}))

	return response.SyncResponseLocation(true, nil, fmt.Sprintf("/%s/profiles/%s", version.APIVersion, req.Name))
}

// swagger:operation DELETE /1.0/profiles/{name} profiles profile_delete
//
// Delete the profile
//
// Removes the profile.
//
// ---
// produces:
//   - application/json
// parameters:
//   - in: query
//     name: project
//     description: Project name
//     type: string
//     example: default
// responses:
//   "200":
//     $ref: "#/responses/EmptySyncResponse"
//   "400":
//     $ref: "#/responses/BadRequest"
//   "403":
//     $ref: "#/responses/Forbidden"
//   "500":
//     $ref: "#/responses/InternalServerError"
func profileDelete(d *Daemon, r *http.Request) response.Response {
	projectName, _, err := project.ProfileProject(d.State().Cluster, projectParam(r))
	if err != nil {
		return response.SmartError(err)
	}

	name := mux.Vars(r)["name"]
	if name == "default" {
		return response.Forbidden(errors.New(`The "default" profile cannot be deleted`))
	}

	err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
		profile, err := tx.GetProfile(projectName, name)
		if err != nil {
			return err
		}
		if len(profile.UsedBy) > 0 {
			return fmt.Errorf("Profile is currently in use")
		}

		return tx.DeleteProfile(projectName, name)
	})
	if err != nil {
		return response.SmartError(err)
	}

	requestor := request.CreateRequestor(r)
	d.State().Events.SendLifecycle(projectName, lifecycle.ProfileDeleted.Event(name, projectName, requestor, nil))

	return response.EmptySyncResponse
}


text:
<?php
$settings = GetSettings();
?>
<!DOCTYPE HTML>

	<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
	<meta id="viewport" name="viewport" content="width=device-width, initial-scale=1"/>

	<meta name="description" content="<?php echo($section['description']);?>"/>
	<meta name="keywords" content="<?php echo($section['keywords']);?>"/>

	<meta name="author" content="<?php echo($settings['header']);?>"/>
	<meta name="coder" content="Alexander Gluschenko"/>
	<meta name="designer" content="Alexander Gluschenko"/>
	<meta name="robots" content="all"/>

	<meta name="theme-color" content="#e84c3d"/>
	<meta name="msapplication-TileColor" content="#e84c3d"/>
    <meta name="msapplication-TileImage" content="<?php echo($section['preview_image'] != "" ? $section['preview_image'] : "/modules/wide_template/assets/logo/og_logo.png");?>"/>

	<meta property="og:title" content="<?php echo($section['title']);?>"/>
	<meta property="og:site_name" content="<?php echo($settings['header']);?>"/>
	<meta property="og:description" content="<?php echo($section['description']);?>"/>
	<meta property="og:image" content="<?php echo($section['preview_image'] != "" ? $section['preview_image'] : "/modules/wide_template/assets/logo/og_logo.png");?>"/>
	<meta property="og:type" content="website"/>

	<title><?php echo($section['title']);?></title>

	<link rel="stylesheet" href="/engine/assets/common.css?1" type="text/css" />
	<link rel="stylesheet" href="/modules/wide_template/assets/site.css?1" type="text/css" />

	<link rel="shortcut icon" href="<?php echo($section['icon'] != "" ? $section['icon'] : "/modules/wide_template/favicon.ico");?>" type="image/x-icon"/>

	<?
	DrawStyleSheets();
	DrawNodeVars();
	DrawJavaScripts();
	?>

Window title

					[content]

State panel

	<?php Draw(Markup("global_markup"));?>

		<div id='scroll_top' class='scroll_top' style='display: <?php Draw(isTrue($section['layout'] != 3, "block", "none"));?>;' onclick='ScrollTo("scroll_top");'>

		<div id='header_wrap' style='display: <?php Draw(isTrue($section['header_wrap_type'] == 1, "block", "none"));?>;'>
			<? Draw(GetPinnedNews(Markup("pin_markup"))); ?>

							<? Draw(BlocksBar("header_menu", "{content}", "{content}", Markup("header_menu_link"))); ?>

							<div class='header_text fore3 logo_text pointer' title='<? echo $settings['slogan']; ?>'><?php echo($settings['header']);?>

						Обсуждения

					<input class="text_input big_input search_field" onkeypress="SearchPages(this.value);" placeholder="Поиск">

		<div id='admin_header_wrap' style='display: <?php Draw(isTrue($section['header_wrap_type'] == 2, "block", "none"));?>;'>

				<?php Draw(Markup("admin_menu_markup"));?>

		<div id='no_header_wrap' style='display: <?php Draw(isTrue($section['header_wrap_type'] == 0, "block", "none"));?>;'>

		<div id='empty_header_wrap' style='display: <?php Draw(isTrue($section['header_wrap_type'] == -1, "block", "none"));?>;'>

		<div id='default_layout' style='display: <?php Draw(isEqually($section['layout'], 0, "block", "none"));?>;'>

							<?php Draw(BlocksBar("left_menu", Markup("left_markup"), Markup("left_links"), Markup("left_menu_link"))); ?>

							<div id='default_title_wrap' style='display: <?php Draw(isEqually($section['title_wrap_enabled'], true, "block", "none"));?>;'>

<?php echo($section['header']);?>

								<?php Draw(isEqually($section['layout'], 0, "{markup}", ""));?>

			<?php Draw(Markup("big_footer_markup"));?>

		<div id='wide_layout' style='display: <?php Draw(isEqually($section['layout'], 1, "block", "none"));?>;'>

						<div id='wide_title_wrap' style='display: <?php Draw(isEqually($section['title_wrap_enabled'], true, "block", "none"));?>;'>

<?php echo($section['header']);?>

							<?php Draw(isEqually($section['layout'], 1, "{markup}", ""));?>

			<?php Draw(Markup("big_footer_markup"));?>

		<div id='narrow_layout' style='display: <?php Draw(isEqually($section['layout'], 2, "block", "none"));?>;'>

					<div id='narrow_title_wrap' style='display: <?php Draw(isEqually($section['title_wrap_enabled'], true, "block", "none"));?>;'>

<?php echo($section['header']);?>

						<?php Draw(isEqually($section['layout'], 2, "{markup}", ""));?>

			<?php Draw(Markup("footer_markup"));?>

		<div id='huge_layout' style='width: 98%; margin: auto; display: <?php Draw(isEqually($section['layout'], 3, "block", "none"));?>;'>

				<div id='huge_title_wrap' style='display: <?php Draw(isEqually($section['title_wrap_enabled'], true, "block", "none"));?>;'>

<?php echo($section['header']);?>

					<?php Draw(isEqually($section['layout'], 3, "{markup}", ""));?>

			<?php Draw(Markup("footer_markup"));?>

		<div id='full_layout' style='width: 100%; margin: auto; display: <?php Draw(isEqually($section['layout'], 4, "block", "none"));?>;'>

				<?php Draw(isEqually($section['layout'], 4, "{markup}", ""));?>

		<div id='semi_full_layout' style='text-align: center; display: <?php Draw(isEqually($section['layout'], 5, "block", "none"));?>;'>

				<?php Draw(isEqually($section['layout'], 5, "{markup}", ""));?>


text:
package main.structural_design_patterns.flyweight;

import java.awt.Color;
import java.awt.Graphics;

public class Oval implements Shape {
	private boolean fill;

	public Oval(boolean f) {
		this.fill = f;
		System.out.print("Creating Oval object with fill=" + f);
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void draw(Graphics circle, int x, int y, int width, int height, Color color) {
		circle.setColor(color);
		circle.drawOval(x, y, width, height);
		if (fill) {
			circle.fillOval(x, y, width, height);
		}

	}

}


text:
from django import forms
from django.contrib import admin

from markedit.admin import MarkEditAdmin

from pycon.models import (PyConProposalCategory, PyConSponsorTutorialProposal,
                          PyConTalkProposal, PyConTutorialProposal,
                          PyConPosterProposal, PyConLightningTalkProposal,
                          PyConOpenSpaceProposal)

class ProposalMarkEditAdmin(MarkEditAdmin):
    class MarkEdit:
        fields = ['abstract', 'additional_notes', 'outline', 'more_info']
        options = {
            'preview': 'below'
        }

class TalkAdmin(ProposalMarkEditAdmin):
    list_display = [
        'title',
        'kind',
        'status',
        'duration',
        'submitted',
        'speaker',
        'category',
        'audience_level',
        'cancelled',
    ]

class TutorialAdmin(ProposalMarkEditAdmin):
    list_display = [
        'title',
        'kind',
        'overall_status',
        'status',  # result.status
        'submitted',
        'speaker',
        'category',
        'audience_level',
        'domain_level',
        '_registration_count',
        'cancelled',
    ]
    list_filter = ['result__status', 'cancelled', 'category']
    list_select_related = True
    search_fields = ['title']

    def status(self, obj):
        try:
            return obj.result.status
        except:
            return "undecided"
    status.admin_order_field = 'result__status'

    def _registration_count(self, obj):
        kwargs = {'count': obj.registration_count, 'max': obj.max_attendees}
        if obj.max_attendees:
            if obj.registration_count == obj.max_attendees:
                return '
{count} of {max}
'.format(**kwargs)
            elif obj.registration_count > obj.max_attendees:
                return '
{count} of {max}
'.format(**kwargs)
            else:
                return '{count} of {max}'.format(**kwargs)
        else:
            return '{count}'.format(**kwargs)
    _registration_count.allow_tags = True

class LightningTalkAdminForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(LightningTalkAdminForm, self).__init__(*args, **kwargs)
        # TODO: This is a hack to populate the field...
        self.fields['category'].initial = PyConProposalCategory.objects.all()[0]
        self.fields['audience_level'].initial = PyConLightningTalkProposal.AUDIENCE_LEVEL_NOVICE

    class Meta:
        model = PyConLightningTalkProposal
        exclude = ['abstract']

class LightningTalkAdmin(MarkEditAdmin):
    class MarkEdit:
        fields = ['additional_notes']
        options = {
            'preview': 'below'
        }

    form = LightningTalkAdminForm
    list_display = [
        'title',
        'kind',
        'status',
        'submitted',
        'speaker',
        'cancelled',
    ]

class PosterAdmin(ProposalMarkEditAdmin):
    list_display = [
        'title',
        'kind',
        'status',
        'submitted',
        'speaker',
        'category',
        'audience_level',
        'cancelled',
    ]

class OpenSpaceAdmin(ProposalMarkEditAdmin):
    list_display = [
        'title',
        'kind',
        'status',
        'submitted',
        'speaker',
        'cancelled'
    ]

class SponsorTutorialAdmin(ProposalMarkEditAdmin):
    list_display = [
        'title',
        'kind',
        'status',
        'submitted',
        'speaker',
        'cancelled',
    ]

admin.site.register(PyConProposalCategory)
admin.site.register(PyConTalkProposal, TalkAdmin)
admin.site.register(PyConTutorialProposal, TutorialAdmin)
admin.site.register(PyConPosterProposal, PosterAdmin)
admin.site.register(PyConOpenSpaceProposal, OpenSpaceAdmin)
admin.site.register(PyConSponsorTutorialProposal, SponsorTutorialAdmin)
admin.site.register(PyConLightningTalkProposal, LightningTalkAdmin)

from account.models import Account, EmailAddress

from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin

class AccountInline(admin.StackedInline):
    model = Account
    extra = 0

class EmailAddressInline(admin.StackedInline):
    model = EmailAddress
    extra = 0

class HasAccountListFilter(admin.SimpleListFilter):
    title = "has associated Account"
    parameter_name = "has_account"

    def lookups(self, request, model_admin):
        return (
            (1, "Yes"),
            (0, "No"),
        )

    def queryset(self, request, queryset):
        if self.value() not in [None, ""]:
            if self.value() == "1":
                return queryset.exclude(account=None)
            if self.value() == "0":
                return queryset.filter(account=None)
        return queryset

class HasEmailAddressListFilter(admin.SimpleListFilter):
    title = "has associated EmailAddress"
    parameter_name = "has_emailaddress"

    def lookups(self, request, model_admin):
        return (
            (1, "Yes"),
            (0, "No"),
        )

    def queryset(self, request, queryset):
        if self.value() not in [None, ""]:
            if self.value() == "1":
                return queryset.exclude(emailaddress=None)
            if self.value() == "0":
                return queryset.filter(emailaddress=None)
        return queryset

class PyConUserAdmin(UserAdmin):
    inlines = list(UserAdmin.inlines) + [AccountInline, EmailAddressInline]
    search_fields = list(UserAdmin.search_fields) + ['emailaddress__email']
    list_filter = list(UserAdmin.list_filter) + [HasAccountListFilter, HasEmailAddressListFilter]

admin.site.unregister(User)
admin.site.register(User, PyConUserAdmin)

# HACK HACK - monkey patch User because the username field is useless
# when using django-user-accounts
def user_unicode(self):
    # Use full name if any, else email
    return self.get_full_name() or self.email
User.__unicode__ = user_unicode

# Also monkey patch the sort order
User._meta.ordering = ['last_name', 'first_name']


text:
package com.zfgc.rules;

import com.zfgc.exception.ZfgcValidationException;
import com.zfgc.model.BaseZfgcModel;
import com.zfgc.model.users.Users;

public abstract class AbstractRulesChecker<T extends BaseZfgcModel> {
	public abstract void rulesCheck(T model, Users user) throws RuntimeException;

	protected void checkErrorsFound(String typeName, T model) throws ZfgcValidationException{
		if(model.getErrors().getRequiredFieldsErrors().size() > 0){
			throw new ZfgcValidationException(typeName);
		}
	}
}


text:
objax.io package
================

.. currentmodule:: objax.io

.. autosummary::

    Checkpoint
    load_var_collection
    save_var_collection

.. autoclass:: Checkpoint
    :members:

.. autofunction:: load_var_collection

.. autofunction:: save_var_collection


text:
oo_video.getPixels = function() {
  var image      = new oo._support.CanvasImage(videoSrc);
  var imageData  = image.getImageData();
  var pixels     = imageData.data;

  // Clean up
  image.removeCanvas();

  return pixels;
};

oo_video.getPixelCount = function() {
  var image = new oo._support.CanvasImage(videoSrc);

  // Clean up
  image.removeCanvas();

  return image.getPixelCount();
};


text:
=====================
Example RDS v2 Stacks
=====================

This directory contains configs for testing out version 2 of the RDS stack
framework.


text:
from swgpy.object import *

def create(kernel):
	result = Static()

	result.template = "object/static/particle/shared_pt_waterfalling_slow.iff"
	result.attribute_template_id = -1
	result.stfName("obj_n","unknown_object")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
require_dependency "nsa_panel/application_controller"

module NsaPanel
  class UsersController < ApplicationController
    def index
      @users = NsaPanel.user.all
    end

    def show
      @user = NsaPanel.user.find(params[:id])
    end

    def order_drone_strike
      @user = NsaPanel.user.find(params[:id])

      redirect_to users_path, notice: "Drone strike for #{@user.name} (##{@user.id}) was successfully ordered."
    end
  end
end


text:
perl ../../../thirdparty/HBehrens-obj2opengl/obj2opengl.pl -noScale -noMove -nameOfObject psmovebody PSMoveMotionControllerBody.obj
perl ../../../thirdparty/HBehrens-obj2opengl/obj2opengl.pl -noScale -noMove -nameOfObject psmovebulb PSMoveMotionControllerBulb.obj
pause


text:
/*
 * Knetik Platform API Documentation latest
 * This is the spec for the Knetik API.  Use this in conjunction with the documentation found at https://knetikcloud.com.
 *
 * OpenAPI spec version: latest
 * Contact: support@knetik.com
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */

package com.knetikcloud.api;

import com.knetikcloud.client.ApiException;
import com.knetikcloud.model.PageResourceSimpleReferenceResourceobject;
import com.knetikcloud.model.Result;
import com.knetikcloud.model.VariableTypeResource;
import org.junit.Test;
import org.junit.Ignore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * API tests for RuleEngineVariablesApi
 */
@Ignore
public class RuleEngineVariablesApiTest {

    private final RuleEngineVariablesApi api = new RuleEngineVariablesApi();

    /**
     * Get a list of variable types available
     *
     * Types include integer, string, user and invoice. These are used to qualify trigger parameters and action variables with strong typing.

Permissions Needed: BRE_RULE_ENGINE_VARIABLES_USER
     *
     * @throws ApiException
     *          if the Api call fails
     */
    @Test
    public void getBREVariableTypesTest() throws ApiException {
        List<VariableTypeResource> response = api.getBREVariableTypes();

        // TODO: test validations
    }

    /**
     * List valid values for a type
     *
     * Used to lookup users to fill in a user constant for example. Only types marked as enumerable are suppoorted here. <br><br><b>Permissions Needed:</b> BRE_RULE_ENGINE_VARIABLES_USER
     *
     * @throws ApiException
     *          if the Api call fails
     */
    @Test
    public void getBREVariableValuesTest() throws ApiException {
        String name = null;
        String filterName = null;
        Integer size = null;
        Integer page = null;
        PageResourceSimpleReferenceResourceobject response = api.getBREVariableValues(name, filterName, size, page);

        // TODO: test validations
    }

}


text:
            <button class="btn btn-sm btn-primary active" ng-click="vm.refresh()">
            </button>
            modified classes

            <scrollbar ng-style="{height:vm.maxHeight}" class="classess-list">

 {{k}}

            </scrollbar>

            <uib-tabset active="active">
                <uib-tab index="0" heading="Current Code">
                    <scrollbar ng-style="{maxHeight:vm.maxHeight}">

                    </scrollbar>

                </uib-tab>
                <uib-tab index="1">
                    <uib-tab-heading>
                        Origin Code
                    </uib-tab-heading>
                    <scrollbar ng-style="{maxHeight:vm.maxHeight}">

                    </scrollbar>
                </uib-tab>
                <uib-tab index="2" select="vm.viewInfo()">
                    <uib-tab-heading>
                        Info
                    </uib-tab-heading>

		    <button ng-click="vm.recoverClass()" class="btn btn-sm btn-primary">Recover Class</button>

		    Related Information:
                    <scrollbar ng-style="{maxHeight:vm.maxHeight}">
                        <json-formatter class="json-content" open="1" json="vm.detailInfo"></json-formatter>

                    </scrollbar>
                </uib-tab>
            </uib-tabset>


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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.cloudresourcemanager.model;

/**
 * A status object which is used as the `metadata` field for the Operation returned by
 * CreateProject. It provides insight for when significant phases of Project creation have
 * completed.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Resource Manager API. For a detailed
 * explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class CreateProjectMetadata extends com.google.api.client.json.GenericJson {

  /**
   * Creation time of the project creation workflow.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private String createTime;

  /**
   * True if the project can be retrieved using `GetProject`. No other operations on the project are
   * guaranteed to work until the project creation is complete.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean gettable;

  /**
   * True if the project creation process is complete.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean ready;

  /**
   * Creation time of the project creation workflow.
   * @return value or {@code null} for none
   */
  public String getCreateTime() {
    return createTime;
  }

  /**
   * Creation time of the project creation workflow.
   * @param createTime createTime or {@code null} for none
   */
  public CreateProjectMetadata setCreateTime(String createTime) {
    this.createTime = createTime;
    return this;
  }

  /**
   * True if the project can be retrieved using `GetProject`. No other operations on the project are
   * guaranteed to work until the project creation is complete.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getGettable() {
    return gettable;
  }

  /**
   * True if the project can be retrieved using `GetProject`. No other operations on the project are
   * guaranteed to work until the project creation is complete.
   * @param gettable gettable or {@code null} for none
   */
  public CreateProjectMetadata setGettable(java.lang.Boolean gettable) {
    this.gettable = gettable;
    return this;
  }

  /**
   * True if the project creation process is complete.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getReady() {
    return ready;
  }

  /**
   * True if the project creation process is complete.
   * @param ready ready or {@code null} for none
   */
  public CreateProjectMetadata setReady(java.lang.Boolean ready) {
    this.ready = ready;
    return this;
  }

  @Override
  public CreateProjectMetadata set(String fieldName, Object value) {
    return (CreateProjectMetadata) super.set(fieldName, value);
  }

  @Override
  public CreateProjectMetadata clone() {
    return (CreateProjectMetadata) super.clone();
  }

}


text:
.class public Landroid/renderscript/Byte2;
.super Ljava/lang/Object;
.source "Byte2.java"

# instance fields
.field public x:B

.field public y:B

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 28
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 29
    return-void
.end method

.method public constructor <init>(BB)V
    .locals 0
    .parameter "initX"
    .parameter "initY"

    .prologue
    .line 31
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 32
    iput-byte p1, p0, Landroid/renderscript/Byte2;->x:B

    .line 33
    iput-byte p2, p0, Landroid/renderscript/Byte2;->y:B

    .line 34
    return-void
.end method


text:
UINT HexFileCloseNotify(HWND hwndMain, HWND hwndHV);
BOOL HexSetCurFile(HWND hwndMain, int iItem, BOOL fSetFocus);
BOOL HexCreateNewFile(MAINWND *mainWnd);
BOOL HexCloseFile(MAINWND *mainWnd, int iItem);
void UpdateCurFileName(HWND hwndMain, HWND hwndHV, LPCTSTR szFileName, BOOL fChanged);

BOOL HexOpenFile(HWND hwndMain, LPCTSTR szFileName, DWORD fHexViewFlags);
BOOL HexeditOpenFile(HWND hwnd, LPCTSTR szFile, DWORD openFlags);
void HandleDropFiles(HWND hwnd, HDROP hDrop);
BOOL HexSaveAs(HWND hwndMain, LPCTSTR szFileName);
BOOL HexSaveCurrent(HWND hwndMain);
HWND EnumHexView(HWND hwndMain, int idx);

#endif