text:
<?php
/**
 * The main template file.
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * For example, it puts together the home page when no home.php file exists.
 *
 * Learn more: http://codex.wordpress.org/Template_Hierarchy
 *
 * @package WordPress
 * @subpackage Boss
 * @since Boss 1.0.0
 */

get_header(); ?>

<?php if ( is_active_sidebar('sidebar') ) : ?>

<?php else : ?>

<?php endif; ?>

		<?php
		if ( 'page' == get_option('show_on_front') && get_option('page_for_posts') && is_home() ) : the_post();
			$page_for_posts_id = get_option('page_for_posts');
			setup_postdata(get_page($page_for_posts_id));
		?>

<?php single_post_title(); ?>

					<?php the_content(); ?>

		<?php rewind_posts(); endif; ?>

		<?php if ( have_posts() ) : ?>

			<?php /* Start the Loop */ ?>
			<?php while ( have_posts() ) : the_post(); ?>
				<?php get_template_part( 'content', get_post_format() ); ?>
			<?php endwhile; ?>

				<?php buddyboss_pagination(); ?>

		<?php else : ?>

			<?php if ( current_user_can( 'edit_posts' ) ) :
				// Show a different message to a logged-in user who can add posts.
			?>

<?php _e( 'No posts to display', 'boss' ); ?>

<?php printf( __( 'Ready to publish your first post? Get started here.', 'boss' ), admin_url( 'post-new.php' ) ); ?>

			<?php else :
				// Show the default message to everyone else.
			?>

<?php _e( 'Nothing Found', 'boss' ); ?>

<?php _e( 'Apologies, but no results were found. Perhaps searching will help find a related post.', 'boss' ); ?>

					<?php get_search_form(); ?>

			<?php endif; // end current_user_can() check ?>

		<?php endif; // end have_posts() check ?>

<?php if ( is_active_sidebar('sidebar')) :
    get_sidebar('sidebar');
endif; ?>

<?php get_footer(); ?>


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

/* THIS IS CLASS FOR API LIBRARY */
class Getmeb extends CI_Controller
{
	/* FOR GETTING ERROR MESSAGE OR SUCCESS MESSAGE */
	public $messages = array();

	function __construct() {
		header('Access-Control-Allow-Origin: *');
		header("Access-Control-Allow-Headers: X-API-KEY, X-AUTH, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
		header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
		$method = $_SERVER['REQUEST_METHOD'];
		if($method == "OPTIONS") {
			die();
		}

		parent::__construct();
	}

	function _check_token()
	{
		$jwt 	= $this->input->server('HTTP_TOKEN');
		$auth 	= $this->input->server('HTTP_AUTHENTICATION');
		try {
			$data = json_decode(urlsafeB64Decode($auth));

		} catch (Exception $e) {
			return $e->getMessage();
		}
		return TRUE;
	}

	function _decrypt_data($auth = NULL)
	{
        if ($auth !== NULL)
        {
            if (strpos(strtolower($auth), 'bearer') === 0)
            {
                list($user_id, $client_id, $org_id, $role_id) = explode(':', base64_decode(substr($auth, 7)));
				$GLOBALS['identifier'] = [
					'user_id' 	=> $user_id,
					'client_id'	=> $client_id,
					'org_id'	=> $org_id,
					'role_id'	=> $role_id
				];
				return TRUE;
            }
			throw new Exception("This Data Authorization is invalid.");
        }
		throw new Exception("Data Authorization cannot be empty.");
		return FALSE;
	}

	function set_message($message)
	{
		$this->messages[] = $message;

		return $message;
	}

	function messages()
	{
		$_output = '';
		foreach ($this->messages as $message)
		{
			$messageLang = $this->lang->line($message) ? $this->lang->line($message) : '##' . $message . '##';
			$_output .= '<p>' . $messageLang . '</p>';
		}

		return $_output;
	}

	function getAPI($method, $function, $params = [], $keep = TRUE)
	{
		$params = is_array($params) ? $params : (array) $params;
		$params = (count($params) < 1) ? '' : '?'.http_build_query($params);

		$headers  = [
			'X-API-KEY'	=> APPLICATION_KEY,
			'TOKEN' => $this->session->userdata('token')
		];
		$response = Requests::get(API_URL.$method.'/'.$function.$params, $headers);
		$result   = json_decode($response->body);

		// UPDATE TOKEN TO SESSION
		if (! empty($result->token))
			if ((bool)$this->session->userdata('user_id'))
				$this->session->set_userdata('token', $result->token);

		$output['execution_time_api'] = $result->execution_time;
		$output['environment_api'] = $result->environment;
		$output['data']	= $result->data;

		// OUTPUT
		if (! $keep)
			xresponse($result->status, $output, $response->status_code);
		else
			return $result;
	}

	function postAPI($method, $function, $data = [], $keep = TRUE)
	{
		$headers  = [
			'X-API-KEY'	=> APPLICATION_KEY,
			'TOKEN' => $this->session->userdata('token')
		];
		$response = Requests::post(API_URL.$method.'/'.$function, $headers, $data);
		$result = json_decode($response->body);

		// UPDATE TOKEN TO SESSION
		if (! empty($result->token))
			if ((bool)$this->session->userdata('user_id'))
				$this->session->set_userdata('token', $result->token);

		$output['execution_time_api'] = $result->execution_time;
		$output['environment_api'] = $result->environment;
		$output['message']	= $result->message;

		// OUTPUT
		if (! $keep)
			xresponse($result->status, $output, $response->status_code);
		else
			return $result;
	}

	function putAPI($method, $function, $params = [], $data = [], $keep = TRUE)
	{
		$params = is_array($params) ? $params : (array) $params;
		$params = (count($params) < 1) ? '' : '?'.http_build_query($params);

		$headers  = [
			'X-API-KEY'	=> APPLICATION_KEY,
			'TOKEN' => $this->session->userdata('token')
		];
		$response = Requests::put(API_URL.$method.'/'.$function.$params, $headers, $data);
		$result = json_decode($response->body);

		// UPDATE TOKEN TO SESSION
		if (! empty($result->token))
			if ((bool)$this->session->userdata('user_id'))
				$this->session->set_userdata('token', $result->token);

		$output['execution_time_api'] = $result->execution_time;
		$output['environment_api'] = $result->environment;
		$output['message']	= $result->message;

		// OUTPUT
		if (! $keep)
			xresponse($result->status, $output, $response->status_code);
		else
			return $result;
	}

	function deleteAPI($method, $function, $params = [], $keep = TRUE)
	{
		$params = is_array($params) ? $params : (array) $params;
		$params = (count($params) < 1) ? '' : '?'.http_build_query($params);

		$headers  = [
			'X-API-KEY'	=> APPLICATION_KEY,
			'TOKEN' => $this->session->userdata('token')
		];
		$response = Requests::delete(API_URL.$method.'/'.$function.$params, $headers);
		$result = json_decode($response->body);

		// UPDATE TOKEN TO SESSION
		if (! empty($result->token))
			if ((bool)$this->session->userdata('user_id'))
				$this->session->set_userdata('token', $result->token);

		$output['execution_time_api'] = $result->execution_time;
		$output['environment_api'] = $result->environment;
		$output['message']	= $result->message;

		// OUTPUT
		if (! $keep)
			xresponse($result->status, $output, $response->status_code);
		else
			return $result;
	}

	function xresponse($status=TRUE, $response=array(), $statusHeader=200)
	{
		$BM =& load_class('Benchmark', 'core');

		$statusHeader = empty($statusHeader) ? 200 : $statusHeader;
		if (! is_numeric($statusHeader))
			show_error('Status codes must be numeric', 500);

		$elapsed = $BM->elapsed_time('total_execution_time_start', 'total_execution_time_end');

		$output['status'] = $status;
		$output['execution_time'] = $elapsed;
		$output['environment'] = ENVIRONMENT;

		header("HTTP/1.0 $statusHeader");
		header('Content-Type: application/json');
		echo json_encode(array_merge($output, $response));
		exit();
	}

}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

#include "PropertyEditing.h"
#include "PropertyCustomizationHelpers.h"

class FEnvTraceDataCustomization : public IPropertyTypeCustomization
{
public:
	/** Makes a new instance of this detail layout class for a specific detail view requesting it */
	static TSharedRef<IPropertyTypeCustomization> MakeInstance();

	// Begin IPropertyTypeCustomization interface
	virtual void CustomizeHeader( TSharedRef<class IPropertyHandle> StructPropertyHandle, class FDetailWidgetRow& HeaderRow, IPropertyTypeCustomizationUtils& StructCustomizationUtils ) override;
	virtual void CustomizeChildren( TSharedRef<class IPropertyHandle> StructPropertyHandle, class IDetailChildrenBuilder& StructBuilder, IPropertyTypeCustomizationUtils& StructCustomizationUtils ) override;
	// End IPropertyTypeCustomization interface

protected:

	void CacheTraceModes(TSharedRef<class IPropertyHandle> StructPropertyHandle);

	/** cached names of trace modes */
	struct FTextIntPair
	{
		FText Text;
		int32 Int;

		FTextIntPair() {}
		FTextIntPair(FText InText, int32 InInt) : Text(InText), Int(InInt) {}
	};
	TArray<FTextIntPair> TraceModes;
	bool bCanShowProjection;
	uint8 ActiveMode;

	TSharedPtr<IPropertyHandle> PropTraceMode;
	TSharedPtr<IPropertyHandle> PropTraceShape;
	TSharedPtr<IPropertyHandle> PropTraceChannel;
	TSharedPtr<IPropertyHandle> PropTraceChannelSerialized;

	void OnTraceChannelChanged();
	void OnTraceModeChanged(int32 Index);
	TSharedRef<SWidget> OnGetTraceModeContent();
	FText GetCurrentTraceModeDesc() const;
	FText GetShortDescription() const;

	EVisibility GetGeometryVisibility() const;
	EVisibility GetNavigationVisibility() const;
	EVisibility GetProjectionVisibility() const;
	EVisibility GetExtentX() const;
	EVisibility GetExtentY() const;
	EVisibility GetExtentZ() const;
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
类 javax.management.Attribute 的使用 (Java Platform SE 6)
</TITLE>

<META NAME="date" CONTENT="2007-03-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      概述
      软件包
      类
    使用
      树
      已过时
      索引
      帮助

JavaTM Platform
Standard Ed. 6

 上一个
 下一个

  框架
 无框架

  所有类

类 javax.management.Attribute
的使用

使用 Attribute 的软件包

javax.management
提供 Java Management Extensions 的核心类。

javax.management.modelmbean
提供了 ModelMBean 类的定义。

javax.management 中 Attribute 的使用

返回变量类型为 Attribute 的类型的 javax.management 中的方法

 List<Attribute>
AttributeList.asList()

          以 List<Attribute> 的形式返回此列表的视图。

参数类型为 Attribute 的 javax.management 中的方法

 void
AttributeList.add(Attribute object)

          添加指定的 Attribute 作为列表的最后一个元素。

 void
AttributeList.add(int index,
    Attribute object)

          插入指定的属性作为指定位置处的元素。

 void
AttributeList.set(int index,
    Attribute object)

          将指定位置的元素设置为指定的属性。

 void
DynamicMBean.setAttribute(Attribute attribute)

          设置 Dynamic MBean 的特定属性的值。

 void
StandardMBean.setAttribute(Attribute attribute)

 void
MBeanServer.setAttribute(ObjectName name,
             Attribute attribute)

 void
MBeanServerConnection.setAttribute(ObjectName name,
             Attribute attribute)

          设置指定 MBean 的特定属性值。

类型变量类型为 Attribute 的 javax.management 中的构造方法参数

AttributeList(List<Attribute> list)

          构造一个包含指定 List 的元素的 AttributeList,这些元素按 List 的迭代器返回的顺序排列。

javax.management.modelmbean 中 Attribute 的使用

参数类型为 Attribute 的 javax.management.modelmbean 中的方法

 void
ModelMBeanNotificationBroadcaster.sendAttributeChangeNotification(Attribute oldValue,
                                Attribute newValue)

          将包含属性的原有值和新值的 attributeChangeNotification 发送到 ModelMBean 上已注册的 AttributeChangeNotification 侦听器。

 void
RequiredModelMBean.sendAttributeChangeNotification(Attribute inOldVal,
                                Attribute inNewVal)

 void
RequiredModelMBean.setAttribute(Attribute attribute)

          设置指定的 ModelMBean 的指定属性值。

      概述
      软件包
      类
    使用
      树
      已过时
      索引
      帮助

JavaTM Platform
Standard Ed. 6

 上一个
 下一个

  框架
 无框架

  所有类

提交错误或意见
有关更多的 API 参考资料和开发人员文档,请参阅 Java SE 开发人员文档。该文档包含更详细的、面向开发人员的描述,以及总体概述、术语定义、使用技巧和工作代码示例。
版权所有 2007 Sun Microsystems, Inc. 保留所有权利。 请遵守许可证条款。另请参阅文档重新分发政策。


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>expand_hexstring (OpenSSL::X509::Name::RFC2253DN)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../../../../.././rdoc-style.css" type="text/css" media="screen" />

# File lib/openssl/x509.rb, line 94
        def expand_hexstring(str)
          return nil unless str
          der = str.gsub(HexPair){|hex| Integer("0x#{hex}").chr }
          a1 = OpenSSL::ASN1.decode(der)
          return a1.value, a1.tag
        end


text:
package org.mandfer.tools.xml;

/**
 * @author marcandreuf on 24/10/2014.
 */
public class XMLWriterTest {

//    private final String fileName = "test.xml";
//    private DomLoader domLoader = ToolsBoxFactory.createDomLoader();
//    private XMLWriter xmlWriter = ToolsBoxFactory.createXMLWriter();
//
//    @Test
//    public void saveDocumentToFileTest() throws Exception{
//        String testFileLocation = "src/test/resources/writerTestFile.xml";
//        Document doc = domLoader.loadDocument(fileName);
//        File fileTest = new File(testFileLocation);
//        xmlWriter.writeDocumentToFile(doc, fileTest);
//        File assertFile = new File(testFileLocation);
//        assertEquals(true, assertFile.exists());
//        fileTest.delete();
//    }
}


text:
/// <reference types="node" />

import {DepGraph} from 'dependency-graph';
import * as os from 'os';
import * as ts from 'typescript';

import {AbsoluteFsPath, FileSystem, absoluteFrom, dirname, getFileSystem, resolve} from '../../src/ngtsc/file_system';

import {CommonJsDependencyHost} from './dependencies/commonjs_dependency_host';
import {DependencyResolver, InvalidEntryPoint, PartiallyOrderedEntryPoints, SortedEntryPointsInfo} from './dependencies/dependency_resolver';
import {EsmDependencyHost} from './dependencies/esm_dependency_host';
import {ModuleResolver} from './dependencies/module_resolver';
import {UmdDependencyHost} from './dependencies/umd_dependency_host';
import {DirectoryWalkerEntryPointFinder} from './entry_point_finder/directory_walker_entry_point_finder';
import {TargetedEntryPointFinder} from './entry_point_finder/targeted_entry_point_finder';
import {AnalyzeEntryPointsFn, CreateCompileFn, Executor, PartiallyOrderedTasks, Task, TaskProcessingOutcome, TaskQueue} from './execution/api';
import {ClusterExecutor} from './execution/cluster/executor';
import {ClusterPackageJsonUpdater} from './execution/cluster/package_json_updater';
import {AsyncSingleProcessExecutor, SingleProcessExecutor} from './execution/single_process_executor';
import {ParallelTaskQueue} from './execution/task_selection/parallel_task_queue';
import {SerialTaskQueue} from './execution/task_selection/serial_task_queue';
import {ConsoleLogger, LogLevel} from './logging/console_logger';
import {Logger} from './logging/logger';
import {hasBeenProcessed, markAsProcessed} from './packages/build_marker';
import {NgccConfiguration} from './packages/configuration';
import {EntryPoint, EntryPointJsonProperty, EntryPointPackageJson, SUPPORTED_FORMAT_PROPERTIES, getEntryPointFormat} from './packages/entry_point';
import {makeEntryPointBundle} from './packages/entry_point_bundle';
import {Transformer} from './packages/transformer';
import {PathMappings} from './utils';
import {FileWriter} from './writing/file_writer';
import {InPlaceFileWriter} from './writing/in_place_file_writer';
import {NewEntryPointFileWriter} from './writing/new_entry_point_file_writer';
import {DirectPackageJsonUpdater, PackageJsonUpdater} from './writing/package_json_updater';

/**
 * The options to configure the ngcc compiler for synchronous execution.
 */
export interface SyncNgccOptions {
  /** The absolute path to the `node_modules` folder that contains the packages to process. */
  basePath: string;

  /**
   * The path to the primary package to be processed. If not absolute then it must be relative to
   * `basePath`.
   *
   * All its dependencies will need to be processed too.
   */
  targetEntryPointPath?: string;

  /**
   * Which entry-point properties in the package.json to consider when processing an entry-point.
   * Each property should hold a path to the particular bundle format for the entry-point.
   * Defaults to all the properties in the package.json.
   */
  propertiesToConsider?: string[];

  /**
   * Whether to process all formats specified by (`propertiesToConsider`)  or to stop processing
   * this entry-point at the first matching format. Defaults to `true`.
   */
  compileAllFormats?: boolean;

  /**
   * Whether to create new entry-points bundles rather than overwriting the original files.
   */
  createNewEntryPointFormats?: boolean;

  /**
   * Provide a logger that will be called with log messages.
   */
  logger?: Logger;

  /**
   * Paths mapping configuration (`paths` and `baseUrl`), as found in `ts.CompilerOptions`.
   * These are used to resolve paths to locally built Angular libraries.
   */
  pathMappings?: PathMappings;

  /**
   * Provide a file-system service that will be used by ngcc for all file interactions.
   */
  fileSystem?: FileSystem;

  /**
   * Whether the compilation should run and return asynchronously. Allowing asynchronous execution
   * may speed up the compilation by utilizing multiple CPU cores (if available).
   *
   * Default: `false` (i.e. run synchronously)
   */
  async?: false;
}

/**
 * The options to configure the ngcc compiler for asynchronous execution.
 */
export type AsyncNgccOptions = Omit<SyncNgccOptions, 'async'>& {async: true};

/**
 * The options to configure the ngcc compiler.
 */
export type NgccOptions = AsyncNgccOptions | SyncNgccOptions;

const EMPTY_GRAPH = new DepGraph<EntryPoint>();

/**
 * This is the main entry-point into ngcc (aNGular Compatibility Compiler).
 *
 * You can call this function to process one or more npm packages, to ensure
 * that they are compatible with the ivy compiler (ngtsc).
 *
 * @param options The options telling ngcc what to compile and how.
 */
export function mainNgcc(options: AsyncNgccOptions): Promise<void>;
export function mainNgcc(options: SyncNgccOptions): void;
export function mainNgcc(
    {basePath, targetEntryPointPath, propertiesToConsider = SUPPORTED_FORMAT_PROPERTIES,
     compileAllFormats = true, createNewEntryPointFormats = false,
     logger = new ConsoleLogger(LogLevel.info), pathMappings, async = false}: NgccOptions): void|
    Promise<void> {
  // Execute in parallel, if async execution is acceptable and there are more than 1 CPU cores.
  const inParallel = async && (os.cpus().length > 1);

  // Instantiate common utilities that are always used.
  // NOTE: Avoid eagerly instantiating anything that might not be used when running sync/async or in
  //       master/worker process.
  const fileSystem = getFileSystem();
  // NOTE: To avoid file corruption, ensure that each `ngcc` invocation only creates _one_ instance
  //       of `PackageJsonUpdater` that actually writes to disk (across all processes).
  //       This is hard to enforce automatically, when running on multiple processes, so needs to be
  //       enforced manually.
  const pkgJsonUpdater = getPackageJsonUpdater(inParallel, fileSystem);

  // The function for performing the analysis.
  const analyzeEntryPoints: AnalyzeEntryPointsFn = () => {
    logger.debug('Analyzing entry-points...');
    const startTime = Date.now();

    const supportedPropertiesToConsider = ensureSupportedProperties(propertiesToConsider);

    const moduleResolver = new ModuleResolver(fileSystem, pathMappings);
    const esmDependencyHost = new EsmDependencyHost(fileSystem, moduleResolver);
    const umdDependencyHost = new UmdDependencyHost(fileSystem, moduleResolver);
    const commonJsDependencyHost = new CommonJsDependencyHost(fileSystem, moduleResolver);
    const dependencyResolver = new DependencyResolver(fileSystem, logger, {
      esm5: esmDependencyHost,
      esm2015: esmDependencyHost,
      umd: umdDependencyHost,
      commonjs: commonJsDependencyHost
    });

    const absBasePath = absoluteFrom(basePath);
    const config = new NgccConfiguration(fileSystem, dirname(absBasePath));
    const {entryPoints, graph} = getEntryPoints(
        fileSystem, pkgJsonUpdater, logger, dependencyResolver, config, absBasePath,
        targetEntryPointPath, pathMappings, supportedPropertiesToConsider, compileAllFormats);

    const unprocessableEntryPointPaths: string[] = [];
    // The tasks are partially ordered by virtue of the entry-points being partially ordered too.
    const tasks: PartiallyOrderedTasks = [] as any;

    for (const entryPoint of entryPoints) {
      const packageJson = entryPoint.packageJson;
      const hasProcessedTypings = hasBeenProcessed(packageJson, 'typings', entryPoint.path);
      const {propertiesToProcess, equivalentPropertiesMap} =
          getPropertiesToProcess(packageJson, supportedPropertiesToConsider, compileAllFormats);
      let processDts = !hasProcessedTypings;

      if (propertiesToProcess.length === 0) {
        // This entry-point is unprocessable (i.e. there is no format property that is of interest
        // and can be processed). This will result in an error, but continue looping over
        // entry-points in order to collect all unprocessable ones and display a more informative
        // error.
        unprocessableEntryPointPaths.push(entryPoint.path);
        continue;
      }

      for (const formatProperty of propertiesToProcess) {
        const formatPropertiesToMarkAsProcessed = equivalentPropertiesMap.get(formatProperty) !;
        tasks.push({entryPoint, formatProperty, formatPropertiesToMarkAsProcessed, processDts});

        // Only process typings for the first property (if not already processed).
        processDts = false;
      }
    }

    // Check for entry-points for which we could not process any format at all.
    if (unprocessableEntryPointPaths.length > 0) {
      throw new Error(
          'Unable to process any formats for the following entry-points (tried ' +
          `${propertiesToConsider.join(', ')}): ` +
          unprocessableEntryPointPaths.map(path => `\n  - ${path}`).join(''));
    }

    const duration = Math.round((Date.now() - startTime) / 1000);
    logger.debug(
        `Analyzed ${entryPoints.length} entry-points in ${duration}s. ` +
        `(Total tasks: ${tasks.length})`);

    return getTaskQueue(inParallel, tasks, graph);
  };

  // The function for creating the `compile()` function.
  const createCompileFn: CreateCompileFn = onTaskCompleted => {
    const fileWriter = getFileWriter(fileSystem, pkgJsonUpdater, createNewEntryPointFormats);
    const transformer = new Transformer(fileSystem, logger);

    return (task: Task) => {
      const {entryPoint, formatProperty, formatPropertiesToMarkAsProcessed, processDts} = task;

      const isCore = entryPoint.name === '@angular/core';  // Are we compiling the Angular core?
      const packageJson = entryPoint.packageJson;
      const formatPath = packageJson[formatProperty];
      const format = getEntryPointFormat(fileSystem, entryPoint, formatProperty);

      // All properties listed in `propertiesToProcess` are guaranteed to point to a format-path
      // (i.e. they are defined in `entryPoint.packageJson`). Furthermore, they are also guaranteed
      // to be among `SUPPORTED_FORMAT_PROPERTIES`.
      // Based on the above, `formatPath` should always be defined and `getEntryPointFormat()`
      // should always return a format here (and not `undefined`).
      if (!formatPath || !format) {
        // This should never happen.
        throw new Error(
            `Invariant violated: No format-path or format for ${entryPoint.path} : ` +
            `${formatProperty} (formatPath: ${formatPath} | format: ${format})`);
      }

      // The format-path which the property maps to is already processed - nothing to do.
      if (hasBeenProcessed(packageJson, formatProperty, entryPoint.path)) {
        logger.debug(`Skipping ${entryPoint.name} : ${formatProperty} (already compiled).`);
        onTaskCompleted(task, TaskProcessingOutcome.AlreadyProcessed);
        return;
      }

      const bundle = makeEntryPointBundle(
          fileSystem, entryPoint, formatPath, isCore, format, processDts, pathMappings, true);

      logger.info(`Compiling ${entryPoint.name} : ${formatProperty} as ${format}`);

      const result = transformer.transform(bundle);
      if (result.success) {
        if (result.diagnostics.length > 0) {
          logger.warn(ts.formatDiagnostics(result.diagnostics, bundle.src.host));
        }
        fileWriter.writeBundle(bundle, result.transformedFiles, formatPropertiesToMarkAsProcessed);
      } else {
        const errors = ts.formatDiagnostics(result.diagnostics, bundle.src.host);
        throw new Error(
            `Failed to compile entry-point ${entryPoint.name} due to compilation errors:\n${errors}`);
      }

      onTaskCompleted(task, TaskProcessingOutcome.Processed);
    };
  };

  // The executor for actually planning and getting the work done.
  const executor = getExecutor(async, inParallel, logger, pkgJsonUpdater);

  return executor.execute(analyzeEntryPoints, createCompileFn);
}

function ensureSupportedProperties(properties: string[]): EntryPointJsonProperty[] {
  // Short-circuit the case where `properties` has fallen back to the default value:
  // `SUPPORTED_FORMAT_PROPERTIES`
  if (properties === SUPPORTED_FORMAT_PROPERTIES) return SUPPORTED_FORMAT_PROPERTIES;

  const supportedProperties: EntryPointJsonProperty[] = [];

  for (const prop of properties as EntryPointJsonProperty[]) {
    if (SUPPORTED_FORMAT_PROPERTIES.indexOf(prop) !== -1) {
      supportedProperties.push(prop);
    }
  }

  if (supportedProperties.length === 0) {
    throw new Error(
        `No supported format property to consider among [${properties.join(', ')}]. ` +
        `Supported properties: ${SUPPORTED_FORMAT_PROPERTIES.join(', ')}`);
  }

  return supportedProperties;
}

function getPackageJsonUpdater(inParallel: boolean, fs: FileSystem): PackageJsonUpdater {
  const directPkgJsonUpdater = new DirectPackageJsonUpdater(fs);
  return inParallel ? new ClusterPackageJsonUpdater(directPkgJsonUpdater) : directPkgJsonUpdater;
}

function getFileWriter(
    fs: FileSystem, pkgJsonUpdater: PackageJsonUpdater,
    createNewEntryPointFormats: boolean): FileWriter {
  return createNewEntryPointFormats ? new NewEntryPointFileWriter(fs, pkgJsonUpdater) :
                                      new InPlaceFileWriter(fs);
}

function getTaskQueue(
    inParallel: boolean, tasks: PartiallyOrderedTasks, graph: DepGraph<EntryPoint>): TaskQueue {
  return inParallel ? new ParallelTaskQueue(tasks, graph) : new SerialTaskQueue(tasks);
}

function getExecutor(
    async: boolean, inParallel: boolean, logger: Logger,
    pkgJsonUpdater: PackageJsonUpdater): Executor {
  if (inParallel) {
    // Execute in parallel (which implies async).
    // Use up to 8 CPU cores for workers, always reserving one for master.
    const workerCount = Math.min(8, os.cpus().length - 1);
    return new ClusterExecutor(workerCount, logger, pkgJsonUpdater);
  } else {
    // Execute serially, on a single thread (either sync or async).
    return async ? new AsyncSingleProcessExecutor(logger, pkgJsonUpdater) :
                   new SingleProcessExecutor(logger, pkgJsonUpdater);
  }
}

function getEntryPoints(
    fs: FileSystem, pkgJsonUpdater: PackageJsonUpdater, logger: Logger,
    resolver: DependencyResolver, config: NgccConfiguration, basePath: AbsoluteFsPath,
    targetEntryPointPath: string | undefined, pathMappings: PathMappings | undefined,
    propertiesToConsider: string[], compileAllFormats: boolean):
    {entryPoints: PartiallyOrderedEntryPoints, graph: DepGraph<EntryPoint>} {
  const {entryPoints, invalidEntryPoints, graph} = (targetEntryPointPath !== undefined) ?
      getTargetedEntryPoints(
          fs, pkgJsonUpdater, logger, resolver, config, basePath, targetEntryPointPath,
          propertiesToConsider, compileAllFormats, pathMappings) :
      getAllEntryPoints(fs, config, logger, resolver, basePath, pathMappings);
  logInvalidEntryPoints(logger, invalidEntryPoints);
  return {entryPoints, graph};
}

function getTargetedEntryPoints(
    fs: FileSystem, pkgJsonUpdater: PackageJsonUpdater, logger: Logger,
    resolver: DependencyResolver, config: NgccConfiguration, basePath: AbsoluteFsPath,
    targetEntryPointPath: string, propertiesToConsider: string[], compileAllFormats: boolean,
    pathMappings: PathMappings | undefined): SortedEntryPointsInfo {
  const absoluteTargetEntryPointPath = resolve(basePath, targetEntryPointPath);
  if (hasProcessedTargetEntryPoint(
          fs, absoluteTargetEntryPointPath, propertiesToConsider, compileAllFormats)) {
    logger.debug('The target entry-point has already been processed');
    return {
      entryPoints: [] as unknown as PartiallyOrderedEntryPoints,
      invalidEntryPoints: [],
      ignoredDependencies: [],
      graph: EMPTY_GRAPH,
    };
  }
  const finder = new TargetedEntryPointFinder(
      fs, config, logger, resolver, basePath, absoluteTargetEntryPointPath, pathMappings);
  const entryPointInfo = finder.findEntryPoints();
  const invalidTarget = entryPointInfo.invalidEntryPoints.find(
      i => i.entryPoint.path === absoluteTargetEntryPointPath);
  if (invalidTarget !== undefined) {
    throw new Error(
        `The target entry-point "${invalidTarget.entryPoint.name}" has missing dependencies:\n` +
        invalidTarget.missingDependencies.map(dep => ` - ${dep}\n`));
  }
  if (entryPointInfo.entryPoints.length === 0) {
    markNonAngularPackageAsProcessed(fs, pkgJsonUpdater, absoluteTargetEntryPointPath);
  }
  return entryPointInfo;
}

function getAllEntryPoints(
    fs: FileSystem, config: NgccConfiguration, logger: Logger, resolver: DependencyResolver,
    basePath: AbsoluteFsPath, pathMappings: PathMappings | undefined): SortedEntryPointsInfo {
  const finder =
      new DirectoryWalkerEntryPointFinder(fs, config, logger, resolver, basePath, pathMappings);
  return finder.findEntryPoints();
}

function hasProcessedTargetEntryPoint(
    fs: FileSystem, targetPath: AbsoluteFsPath, propertiesToConsider: string[],
    compileAllFormats: boolean) {
  const packageJsonPath = resolve(targetPath, 'package.json');
  // It might be that this target is configured in which case its package.json might not exist.
  if (!fs.exists(packageJsonPath)) {
    return false;
  }
  const packageJson = JSON.parse(fs.readFile(packageJsonPath));

  for (const property of propertiesToConsider) {
    if (packageJson[property]) {
      // Here is a property that should be processed
      if (hasBeenProcessed(packageJson, property as EntryPointJsonProperty, targetPath)) {
        if (!compileAllFormats) {
          // It has been processed and we only need one, so we are done.
          return true;
        }
      } else {
        // It has not been processed but we need all of them, so we are done.
        return false;
      }
    }
  }
  // Either all formats need to be compiled and there were none that were unprocessed,
  // Or only the one matching format needs to be compiled but there was at least one matching
  // property before the first processed format that was unprocessed.
  return true;
}

/**
 * If we get here, then the requested entry-point did not contain anything compiled by
 * the old Angular compiler. Therefore there is nothing for ngcc to do.
 * So mark all formats in this entry-point as processed so that clients of ngcc can avoid
 * triggering ngcc for this entry-point in the future.
 */
function markNonAngularPackageAsProcessed(
    fs: FileSystem, pkgJsonUpdater: PackageJsonUpdater, path: AbsoluteFsPath) {
  const packageJsonPath = resolve(path, 'package.json');
  const packageJson = JSON.parse(fs.readFile(packageJsonPath));

  // Note: We are marking all supported properties as processed, even if they don't exist in the
  //       `package.json` file. While this is redundant, it is also harmless.
  markAsProcessed(pkgJsonUpdater, packageJson, packageJsonPath, SUPPORTED_FORMAT_PROPERTIES);
}

function logInvalidEntryPoints(logger: Logger, invalidEntryPoints: InvalidEntryPoint[]): void {
  invalidEntryPoints.forEach(invalidEntryPoint => {
    logger.debug(
        `Invalid entry-point ${invalidEntryPoint.entryPoint.path}.`,
        `It is missing required dependencies:\n` +
            invalidEntryPoint.missingDependencies.map(dep => ` - ${dep}`).join('\n'));
  });
}

/**
 * This function computes and returns the following:
 * - `propertiesToProcess`: An (ordered) list of properties that exist and need to be processed,
 *   based on the provided `propertiesToConsider`, the properties in `package.json` and their
 *   corresponding format-paths. NOTE: Only one property per format-path needs to be processed.
 * - `equivalentPropertiesMap`: A mapping from each property in `propertiesToProcess` to the list of
 *   other format properties in `package.json` that need to be marked as processed as soon as the
 *   former has been processed.
 */
function getPropertiesToProcess(
    packageJson: EntryPointPackageJson, propertiesToConsider: EntryPointJsonProperty[],
    compileAllFormats: boolean): {
  propertiesToProcess: EntryPointJsonProperty[];
  equivalentPropertiesMap: Map<EntryPointJsonProperty, EntryPointJsonProperty[]>;
} {
  const formatPathsToConsider = new Set<string>();

  const propertiesToProcess: EntryPointJsonProperty[] = [];
  for (const prop of propertiesToConsider) {
    const formatPath = packageJson[prop];

    // Ignore properties that are not defined in `package.json`.
    if (typeof formatPath !== 'string') continue;

    // Ignore properties that map to the same format-path as a preceding property.
    if (formatPathsToConsider.has(formatPath)) continue;

    // Process this property, because it is the first one to map to this format-path.
    formatPathsToConsider.add(formatPath);
    propertiesToProcess.push(prop);

    // If we only need one format processed, there is no need to process any more properties.
    if (!compileAllFormats) break;
  }

  const formatPathToProperties: {[formatPath: string]: EntryPointJsonProperty[]} = {};
  for (const prop of SUPPORTED_FORMAT_PROPERTIES) {
    const formatPath = packageJson[prop];

    // Ignore properties that are not defined in `package.json`.
    if (typeof formatPath !== 'string') continue;

    // Ignore properties that do not map to a format-path that will be considered.
    if (!formatPathsToConsider.has(formatPath)) continue;

    // Add this property to the map.
    const list = formatPathToProperties[formatPath] || (formatPathToProperties[formatPath] = []);
    list.push(prop);
  }

  const equivalentPropertiesMap = new Map<EntryPointJsonProperty, EntryPointJsonProperty[]>();
  for (const prop of propertiesToConsider) {
    const formatPath = packageJson[prop] !;
    const equivalentProperties = formatPathToProperties[formatPath];
    equivalentPropertiesMap.set(prop, equivalentProperties);
  }

  return {propertiesToProcess, equivalentPropertiesMap};
}


text:
import * as React from "react";
import Done = require("react-icons/lib/md/check-box");
import Todo = require("react-icons/lib/md/check-box-outline-blank");
import Sort = require("react-icons/lib/md/sort");
import { connect } from "react-redux";

import IconedButton from "./IconedButton";
import NoBoxButton from "./NoBoxButton";
import PagesMenu from "./PagesMenu";
import Settings from "./Settings";
import "./style/ItemsMenu.css";

export interface IProps {
    createItem: JSX.Element;
    done: boolean;
    doneButtonText?: string;
    pointerAvailable: boolean;
    makeItemListSortable: () => void;
    todoButtonText?: string;
    onItemsStateChange: (done: boolean) => void;
}

class ItemsMenu extends React.Component<IProps> {
    public render() {
        const {
             createItem, children, done, doneButtonText, pointerAvailable,
            makeItemListSortable, todoButtonText, onItemsStateChange,
        } = this.props;

        return (

 event.stopPropagation()}>

                        <PagesMenu />

                                <NoBoxButton
                                    className={!done && "ItemsMenu-state-highlighted"}
                                    icon={<Todo />}
                                    onClick={() => onItemsStateChange(false)}
                                >
                                    {todoButtonText || "to do"}
                                </NoBoxButton>
                                <NoBoxButton
                                    className={done && "ItemsMenu-state-highlighted"}
                                    icon={<Done />}
                                    onClick={() => onItemsStateChange(true)}
                                >
                                    {doneButtonText || "done"}
                                </NoBoxButton>

                            {!done && createItem}
                            {!pointerAvailable &&
                                <IconedButton
                                    className="ItemsMenu-sort-button"
                                    icon={<Sort />}
                                    onClick={makeItemListSortable}
                                >
                                    sort
                                </IconedButton>}
                            {children}

                        <Settings />

        );
    }
}

export default connect(({ environment }) => environment)(ItemsMenu);


text:
"""
  Purpose: ccoin Point Module
  Author:  xczh <christopher.winnie2012@gmail.com>

  Copyright (c) 2015 xczh. All rights reserved.
"""

from Base import BaseModule
import json
import time

class PointModule(BaseModule):

    point_url = r'https://coding.net/api/point/points'

    def run(self):
        r = self.http_get(self.point_url)
        if r.status_code == 200:
            ret = json.loads(r.text)
            if ret['code'] == 0:
                self.logger.info('Get point info success.')
                self.logger.info('user:%s point_left:%.2f point_total:%.2f' %(self.mArgs['global_key'],ret['data']['points_left'],ret['data']['points_total']))
                self.mInfoAdd('point_left',ret['data']['points_left'])
                self.mInfoAdd('point_total',ret['data']['points_total'])
                return True
            else:
                self.logger.error('Get point Failed. Server response: %s' %ret)
                return False
        else:
            self.logger.error('HTTP error while get point. URL: %s \n HTTP Code: %s' %(self.point_url,r.status_code))
            return False


text:
import src.bot as bot

__IDENTIFY__ = ''

if __name__ == "__main__":
    gbot = bot.IRCBot(server="chat.freenode.com", nick="grbot", port=6667, realName='gbot', identify=__IDENTIFY__, debug=True, connectDelay=4, identVerifyCall='ACC')
    gbot.setDefaultChannels({'##gbot': ''})
    gbot.addAdmin("shortdudey123", True)
    gbot.loadModules(['opme', 'coreVersion', 'moduleInfo', 'help'])
    gbot.run()


text:
@import CoreTelephony;
@import JavaScriptCore;

@protocol JSBNSObject;

@protocol JSBCTSubscriber <JSExport, JSBNSObject>

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"

@property (nonatomic, readonly, retain) NSData *carrierToken;

#pragma clang diagnostic pop

@end


text:
try:
    import asyncio
except ImportError:
    # Trollius >= 0.3 was renamed
    import trollius as asyncio

from os import environ
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner

class Component(ApplicationSession):
    """
    An application component that subscribes and receives events, and
    stop after having received 5 events.
    """

    @asyncio.coroutine
    def onJoin(self, details):

        self.received = 0

        def on_event(i):
            print("Got event: {}".format(i))
            self.received += 1
            if self.received > 5:
                self.leave()

        yield from self.subscribe(on_event, u'com.myapp.topic1')

    def onDisconnect(self):
        asyncio.get_event_loop().stop()

if __name__ == '__main__':
    runner = ApplicationRunner(
        environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"),
        u"crossbardemo",
    )
    runner.run(Component)


text:
'use strict'
let aws = require('aws-sdk')
let secureBackup = require('../')
let path = require('path')
let s3 = require('../lib/handlers/s3.js')
let pgHandler = require('../lib/handlers/pg')

let bp = secureBackup({
  pubKeyPath: path.resolve(__dirname, './public.pem'),
  outputName: 'backup.sql',
  outputPath: '/home/oscar/code/backup/',
  compress: true,
  pg: pgHandler({
    user: 'postgres',
    database: 'tourip'
  }),
  s3: s3({
    handler: new aws.S3({
      signatureVersion: 'v4'
    }),
    bucket: 'tourip'
  })
})

console.log(bp)


text:
"""Tests for server."""

import asyncio
import http
import http.client
import os
import threading
import unittest
import urllib.parse

from absl import flags
from absl import logging
from absl.testing import absltest
import tensorflow as tf

from google.longrunning import operations_pb2
from fcp.demo import server
from fcp.demo import test_utils
from fcp.protos import plan_pb2
from fcp.protos.federatedcompute import task_assignments_pb2
from fcp.tensorflow import external_dataset

POPULATION_NAME = 'test/population'
CAP_TENSOR_NAME = 'cap'
COUNT_TENSOR_NAME = 'count'

def create_plan() -> plan_pb2.Plan:
  """Creates a test plan that counts examples, with a per-client cap."""

  with tf.compat.v1.Graph().as_default() as client_graph:
    dataset_token = tf.compat.v1.placeholder(tf.string, shape=())
    input_filepath = tf.compat.v1.placeholder(tf.string, shape=())
    output_filepath = tf.compat.v1.placeholder(tf.string, shape=())
    ds = external_dataset.ExternalDataset(token=dataset_token, selector=b'')
    cap = tf.raw_ops.Restore(
        file_pattern=input_filepath, tensor_name=CAP_TENSOR_NAME, dt=tf.int32)
    count = ds.take(tf.cast(cap, dtype=tf.int64)).reduce(0, lambda x, _: x + 1)
    target_node = tf.raw_ops.Save(
        filename=output_filepath,
        tensor_names=[COUNT_TENSOR_NAME],
        data=[count])

  with tf.compat.v1.Graph().as_default() as server_graph:
    filename = tf.compat.v1.placeholder(tf.string, shape=())
    contribution_cap = tf.Variable(0, dtype=tf.int32)
    count = tf.Variable(0, dtype=tf.int32)
    load_initial_count = count.assign(
        tf.raw_ops.Restore(
            file_pattern=filename, tensor_name=COUNT_TENSOR_NAME, dt=tf.int32),
        read_value=False)
    load_contribution_cap = contribution_cap.assign(
        tf.raw_ops.Restore(
            file_pattern=filename, tensor_name=CAP_TENSOR_NAME, dt=tf.int32),
        read_value=False)
    with tf.control_dependencies([load_initial_count, load_contribution_cap]):
      restore_server_savepoint = tf.no_op()
    write_client_init = tf.raw_ops.Save(
        filename=filename,
        tensor_names=[CAP_TENSOR_NAME],
        data=[contribution_cap])

    intermediate_acc = tf.Variable(0, dtype=tf.int32)
    update_intermediate_acc = intermediate_acc.assign_add(
        tf.raw_ops.Restore(
            file_pattern=filename, tensor_name=COUNT_TENSOR_NAME, dt=tf.int32))
    save_intermediate_acc = tf.raw_ops.Save(
        filename=filename,
        tensor_names=[COUNT_TENSOR_NAME],
        data=[intermediate_acc])

    read_intermediate_update = count.assign_add(
        tf.raw_ops.Restore(
            file_pattern=filename, tensor_name=COUNT_TENSOR_NAME, dt=tf.int32))
    save_count = tf.raw_ops.Save(
        filename=filename, tensor_names=[COUNT_TENSOR_NAME], data=[count])

  plan = plan_pb2.Plan(
      phase=[
          plan_pb2.Plan.Phase(
              client_phase=plan_pb2.ClientPhase(
                  tensorflow_spec=plan_pb2.TensorflowSpec(
                      dataset_token_tensor_name=dataset_token.op.name,
                      input_tensor_specs=[
                          tf.TensorSpec.from_tensor(
                              input_filepath).experimental_as_proto(),
                          tf.TensorSpec.from_tensor(
                              output_filepath).experimental_as_proto(),
                      ],
                      target_node_names=[target_node.name]),
                  federated_compute=plan_pb2.FederatedComputeIORouter(
                      input_filepath_tensor_name=input_filepath.op.name,
                      output_filepath_tensor_name=output_filepath.op.name)),
              server_phase=plan_pb2.ServerPhase(
                  phase_init_op=intermediate_acc.initializer.name,
                  write_client_init=plan_pb2.CheckpointOp(
                      saver_def=tf.compat.v1.train.SaverDef(
                          filename_tensor_name=filename.name,
                          save_tensor_name=write_client_init.name)),
                  read_update=plan_pb2.CheckpointOp(
                      saver_def=tf.compat.v1.train.SaverDef(
                          filename_tensor_name=filename.name,
                          restore_op_name=update_intermediate_acc.name)),
                  write_intermediate_update=plan_pb2.CheckpointOp(
                      saver_def=tf.compat.v1.train.SaverDef(
                          filename_tensor_name=filename.name,
                          save_tensor_name=save_intermediate_acc.name)),
                  read_intermediate_update=plan_pb2.CheckpointOp(
                      saver_def=tf.compat.v1.train.SaverDef(
                          filename_tensor_name=filename.name,
                          restore_op_name=read_intermediate_update.name))))
      ],
      server_savepoint=plan_pb2.CheckpointOp(
          saver_def=tf.compat.v1.train.SaverDef(
              filename_tensor_name=filename.name,
              save_tensor_name=save_count.name,
              restore_op_name=restore_server_savepoint.name)),
      version=1)
  plan.client_graph_bytes.Pack(client_graph.as_graph_def())
  plan.server_graph_bytes.Pack(server_graph.as_graph_def())
  return plan

class ServerTest(absltest.TestCase, unittest.IsolatedAsyncioTestCase):

  def setUp(self):
    super().setUp()
    self.server = server.InProcessServer(
        population_name=POPULATION_NAME,
        host='localhost',
        port=0)
    self._server_thread = threading.Thread(target=self.server.serve_forever)
    self._server_thread.start()
    self.conn = http.client.HTTPConnection(
        self.server.server_name, port=self.server.server_port)

  def tearDown(self):
    self.server.shutdown()
    self._server_thread.join()
    self.server.server_close()
    super().tearDown()

  async def wait_for_task(self):
    """Polls the server until a task is being served."""
    pop = urllib.parse.quote(POPULATION_NAME, safe='')
    url = f'/v1/populations/{pop}/taskassignments/test:start?%24alt=proto'
    request = task_assignments_pb2.StartTaskAssignmentRequest()
    while True:
      self.conn.request('POST', url, request.SerializeToString())
      http_response = self.conn.getresponse()
      if http_response.status == http.HTTPStatus.OK:
        op = operations_pb2.Operation.FromString(http_response.read())
        response = task_assignments_pb2.StartTaskAssignmentResponse()
        op.response.Unpack(response)
        if response.HasField('task_assignment'):
          logging.info('wait_for_task received assignment to %s',
                       response.task_assignment.task_name)
          break
      await asyncio.sleep(0.5)

  async def test_run_computation(self):
    initial_count = 100
    cap = 10
    examples_per_client = [1, 5, 15]
    checkpoint = test_utils.create_checkpoint({
        CAP_TENSOR_NAME: cap,
        COUNT_TENSOR_NAME: initial_count,
    })
    run_computation_task = asyncio.create_task(
        self.server.run_computation('task/name', create_plan(), checkpoint,
                                    len(examples_per_client)))

    # Wait for task assignment to return a task.
    wait_task = asyncio.create_task(self.wait_for_task())
    await asyncio.wait([run_computation_task, wait_task],
                       timeout=10,
                       return_when=asyncio.FIRST_COMPLETED)
    self.assertTrue(wait_task.done())
    # `run_computation` should not be done since no clients have reported.
    self.assertFalse(run_computation_task.done())

    client_runner = os.path.join(
        flags.FLAGS.test_srcdir,
        'com_google_fcp',
        'fcp',
        'client',
        'client_runner_main')
    server_url = f'http://{self.server.server_name}:{self.server.server_port}/'
    clients = []
    for num_examples in examples_per_client:
      subprocess = asyncio.create_subprocess_exec(
          client_runner, f'--server={server_url}',
          f'--population={POPULATION_NAME}',
          f'--num_empty_examples={num_examples}', '--sleep_after_round_secs=0',
          '--use_http_federated_compute_protocol')
      clients.append(asyncio.create_task((await subprocess).wait()))

    # Wait for the computation to complete.
    await asyncio.wait([run_computation_task] + clients, timeout=10)
    self.assertTrue(run_computation_task.done())
    for client in clients:
      self.assertTrue(client.done())
      self.assertEqual(client.result(), 0)

    # Verify the sum in the checkpoint.
    result = test_utils.read_tensor_from_checkpoint(
        run_computation_task.result(), COUNT_TENSOR_NAME, tf.int32)
    self.assertEqual(
        result, initial_count + sum([min(n, cap) for n in examples_per_client]))

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


text:
/**
 * @defgroup Types
 * @addtogroup Types
 * @{
 */

#ifndef CSP_TYPES_H_
#define CSP_TYPES_H_

#include <csp/csp_autoconfig.h>

/* Make bool for compilers without stdbool.h */
#ifdef CSP_HAVE_STDBOOL_H
#include <stdbool.h>
#else
#define bool int
#define false 0
#define true !false
#endif

/**
 * RESERVED PORTS (SERVICES)
 */

enum csp_reserved_ports_e {
	CSP_CMP				= 0,
	CSP_PING			= 1,
	CSP_PS			  	= 2,
	CSP_MEMFREE		 	= 3,
	CSP_REBOOT		  	= 4,
	CSP_BUF_FREE		= 5,
	CSP_UPTIME			= 6,
	CSP_ANY			 	= (CSP_MAX_BIND_PORT + 1),
	CSP_PROMISC		 	= (CSP_MAX_BIND_PORT + 2)
};

typedef enum {
	CSP_PRIO_CRITICAL	= 0,
	CSP_PRIO_HIGH		= 1,
	CSP_PRIO_NORM 		= 2,
	CSP_PRIO_LOW		= 3,
} csp_prio_t;

#define CSP_PRIORITIES			(1 << CSP_ID_PRIO_SIZE)

#ifdef CSP_USE_QOS
#define CSP_RX_QUEUE_LENGTH		(CSP_CONN_QUEUE_LENGTH / CSP_PRIORITIES)
#define CSP_ROUTE_FIFOS			CSP_PRIORITIES
#define CSP_RX_QUEUES			CSP_PRIORITIES
#else
#define CSP_RX_QUEUE_LENGTH 	CSP_CONN_QUEUE_LENGTH
#define CSP_ROUTE_FIFOS			1
#define CSP_RX_QUEUES			1
#endif

/** Size of bit-fields in CSP header */
#define CSP_ID_PRIO_SIZE		2
#define CSP_ID_HOST_SIZE		5
#define CSP_ID_PORT_SIZE		6
#define CSP_ID_FLAGS_SIZE		8

#define CSP_HEADER_BITS			(CSP_ID_PRIO_SIZE + 2 * CSP_ID_HOST_SIZE + 2 * CSP_ID_PORT_SIZE + CSP_ID_FLAGS_SIZE)
#define CSP_HEADER_LENGTH		(CSP_HEADER_BITS/8)

#if CSP_HEADER_BITS != 32 && __GNUC__
#error "Header length must be 32 bits"
#endif

/** Highest number to be entered in field */
#define CSP_ID_PRIO_MAX			((1 << (CSP_ID_PRIO_SIZE)) - 1)
#define CSP_ID_HOST_MAX			((1 << (CSP_ID_HOST_SIZE)) - 1)
#define CSP_ID_PORT_MAX			((1 << (CSP_ID_PORT_SIZE)) - 1)
#define CSP_ID_FLAGS_MAX		((1 << (CSP_ID_FLAGS_SIZE)) - 1)

/** Identifier field masks */
#define CSP_ID_PRIO_MASK		((uint32_t) CSP_ID_PRIO_MAX 	<< (CSP_ID_FLAGS_SIZE + 2 * CSP_ID_PORT_SIZE + 2 * CSP_ID_HOST_SIZE))
#define CSP_ID_SRC_MASK	 		((uint32_t) CSP_ID_HOST_MAX 	<< (CSP_ID_FLAGS_SIZE + 2 * CSP_ID_PORT_SIZE + 1 * CSP_ID_HOST_SIZE))
#define CSP_ID_DST_MASK	 		((uint32_t) CSP_ID_HOST_MAX 	<< (CSP_ID_FLAGS_SIZE + 2 * CSP_ID_PORT_SIZE))
#define CSP_ID_DPORT_MASK   	((uint32_t) CSP_ID_PORT_MAX 	<< (CSP_ID_FLAGS_SIZE + 1 * CSP_ID_PORT_SIZE))
#define CSP_ID_SPORT_MASK   	((uint32_t) CSP_ID_PORT_MAX 	<< (CSP_ID_FLAGS_SIZE))
#define CSP_ID_FLAGS_MASK		((uint32_t) CSP_ID_FLAGS_MAX 	<< (0))

#define CSP_ID_CONN_MASK		(CSP_ID_SRC_MASK | CSP_ID_DST_MASK | CSP_ID_DPORT_MASK | CSP_ID_SPORT_MASK)

/** @brief This union defines a CSP identifier and allows access to the individual fields or the entire identifier */
typedef union {
	uint32_t ext;
	struct __attribute__((__packed__)) {
#if defined(CSP_BIG_ENDIAN) && !defined(CSP_LITTLE_ENDIAN)
		unsigned int pri : CSP_ID_PRIO_SIZE;
		unsigned int src : CSP_ID_HOST_SIZE;
		unsigned int dst : CSP_ID_HOST_SIZE;
		unsigned int dport : CSP_ID_PORT_SIZE;
		unsigned int sport : CSP_ID_PORT_SIZE;
		unsigned int flags : CSP_ID_FLAGS_SIZE;
#elif defined(CSP_LITTLE_ENDIAN) && !defined(CSP_BIG_ENDIAN)
		unsigned int flags : CSP_ID_FLAGS_SIZE;
		unsigned int sport : CSP_ID_PORT_SIZE;
		unsigned int dport : CSP_ID_PORT_SIZE;
		unsigned int dst : CSP_ID_HOST_SIZE;
		unsigned int src : CSP_ID_HOST_SIZE;
		unsigned int pri : CSP_ID_PRIO_SIZE;
#else
		#error "Must define one of CSP_BIG_ENDIAN or CSP_LITTLE_ENDIAN in csp_platform.h"
#endif
	};
} csp_id_t;

/** Broadcast address */
#define CSP_BROADCAST_ADDR	CSP_ID_HOST_MAX

/** Default routing address */
#define CSP_DEFAULT_ROUTE	(CSP_ID_HOST_MAX + 1)

/** CSP Flags */
#define CSP_FRES1			0x80 				// Reserved for future use
#define CSP_FRES2			0x40 				// Reserved for future use
#define CSP_FRES3			0x20 				// Reserved for future use
#define CSP_FFRAG			0x10 				// Use fragmentation
#define CSP_FHMAC 			0x08 				// Use HMAC verification
#define CSP_FXTEA 			0x04 				// Use XTEA encryption
#define CSP_FRDP			0x02 				// Use RDP protocol
#define CSP_FCRC32 			0x01 				// Use CRC32 checksum

/** CSP Socket options */
#define CSP_SO_NONE 		0x0000				// No socket options
#define CSP_SO_RDPREQ  		0x0001				// Require RDP
#define CSP_SO_RDPPROHIB	0x0002				// Prohibit RDP
#define CSP_SO_HMACREQ 		0x0004				// Require HMAC
#define CSP_SO_HMACPROHIB	0x0008				// Prohibit HMAC
#define CSP_SO_XTEAREQ 		0x0010				// Require XTEA
#define CSP_SO_XTEAPROHIB	0x0020				// Prohibit HMAC
#define CSP_SO_CRC32REQ		0x0040				// Require CRC32
#define CSP_SO_CRC32PROHIB	0x0080				// Prohibit CRC32
#define CSP_SO_CONN_LESS	0x0100				// Enable Connection Less mode

/** CSP Connect options */
#define CSP_O_NONE  		CSP_SO_NONE			// No connection options
#define CSP_O_RDP  			CSP_SO_RDPREQ		// Enable RDP
#define CSP_O_NORDP			CSP_SO_RDPPROHIB	// Disable RDP
#define CSP_O_HMAC 			CSP_SO_HMACREQ		// Enable HMAC
#define CSP_O_NOHMAC		CSP_SO_HMACPROHIB	// Disable HMAC
#define CSP_O_XTEA 			CSP_SO_XTEAREQ		// Enable XTEA
#define CSP_O_NOXTEA		CSP_SO_XTEAPROHIB	// Disable XTEA
#define CSP_O_CRC32			CSP_SO_CRC32REQ		// Enable CRC32
#define CSP_O_NOCRC32		CSP_SO_CRC32PROHIB	// Disable CRC32

/**
 * CSP PACKET STRUCTURE
 * Note: This structure is constructed to fit
 * with all interface frame types in order to
 * have buffer reuse
 */
typedef struct __attribute__((__packed__)) {
	uint8_t padding[CSP_PADDING_BYTES];	/**< Interface dependent padding */
	uint16_t length;					/**< Length field must be just before CSP ID */
	csp_id_t id;						/**< CSP id must be just before data */
	union {
		uint8_t data[0];				/**< This just points to the rest of the buffer, without a size indication. */
		uint16_t data16[0];				/**< The data 16 and 32 types makes it easy to reference an integer (properly aligned) */
		uint32_t data32[0];				/**< without the compiler warning about strict aliasing rules. */
	};
} csp_packet_t;

/** Interface TX function */
struct csp_iface_s;
typedef int (*nexthop_t)(struct csp_iface_s * interface, csp_packet_t *packet, uint32_t timeout);

/** Interface struct */
typedef struct csp_iface_s {
	const char *name;			/**< Interface name (keep below 10 bytes) */
	void * driver;				/**< Pointer to interface handler structure */
	nexthop_t nexthop;			/**< Next hop function */
	uint16_t mtu;				/**< Maximum Transmission Unit of interface */
	uint8_t split_horizon_off;	/**< Disable the route-loop prevention on if */
	uint32_t tx;				/**< Successfully transmitted packets */
	uint32_t rx;				/**< Successfully received packets */
	uint32_t tx_error;			/**< Transmit errors */
	uint32_t rx_error;			/**< Receive errors */
	uint32_t drop;				/**< Dropped packets */
	uint32_t autherr; 			/**< Authentication errors */
	uint32_t frame;				/**< Frame format errors */
	uint32_t txbytes;			/**< Transmitted bytes */
	uint32_t rxbytes;			/**< Received bytes */
	uint32_t irq;				/**< Interrupts */
	struct csp_iface_s *next;	/**< Next interface */
} csp_iface_t;

/**
 * This define must be equal to the size of the packet overhead in csp_packet_t.
 * It is used in csp_buffer_get() to check the allocated buffer size against
 * the required buffer size.
 */
#define CSP_BUFFER_PACKET_OVERHEAD 	(sizeof(csp_packet_t) - sizeof(((csp_packet_t *)0)->data))

/** Forward declaration of socket and connection structures */
typedef struct csp_conn_s csp_socket_t;
typedef struct csp_conn_s csp_conn_t;

#define CSP_HOSTNAME_LEN	20
#define CSP_MODEL_LEN		30

/* CSP_REBOOT magic values */
#define CSP_REBOOT_MAGIC		0x80078007
#define CSP_REBOOT_SHUTDOWN_MAGIC	0xD1E5529A

#endif /* CSP_TYPES_H_ */

/* @} */


text:
angular.module('media_manager')
.directive('dropletThumb', [function(){
  return {
    scope: {
      image: '=ngModel'
    },
    restrict: 'EA',
    replace: true,
    template: '<img ng-src="{{ image.thumb_url || image.image_url }}" class="droplet-preview" />'
  };
}]);


text:
module Nexpose
  # The latest version of the Nexpose gem
  VERSION = '0.9.7'
end


text:
class Spinach::Features::ProjectIssues < Spinach::FeatureSteps
  include SharedAuthentication
  include SharedProject
  include SharedNote
  include SharedPaths
  include SharedMarkdown

  step 'I should see "Release 0.4" in issues' do
    page.should have_content "Release 0.4"
  end

  step 'I should not see "Release 0.3" in issues' do
    page.should_not have_content "Release 0.3"
  end

  step 'I should not see "Tweet control" in issues' do
    page.should_not have_content "Tweet control"
  end

  step 'I click link "Closed"' do
    click_link "Closed"
  end

  step 'I should see "Release 0.3" in issues' do
    page.should have_content "Release 0.3"
  end

  step 'I should not see "Release 0.4" in issues' do
    page.should_not have_content "Release 0.4"
  end

  step 'I click link "All"' do
    click_link "All"
  end

  step 'I click link "Release 0.4"' do
    click_link "Release 0.4"
  end

  step 'I should see issue "Release 0.4"' do
    page.should have_content "Release 0.4"
  end

  step 'I click link "New Issue"' do
    click_link "New Issue"
  end

  step 'I submit new issue "500 error on profile"' do
    fill_in "issue_title", with: "500 error on profile"
    click_button "Submit new issue"
  end

  step 'I submit new issue "500 error on profile" with label \'bug\'' do
    fill_in "issue_title", with: "500 error on profile"
    select 'bug', from: "Labels"
    click_button "Submit new issue"
  end

  step 'I click link "500 error on profile"' do
    click_link "500 error on profile"
  end

  step 'I should see label \'bug\' with issue' do
    within '.issue-show-labels' do
      page.should have_content 'bug'
    end
  end

  step 'I should see issue "500 error on profile"' do
    issue = Issue.find_by(title: "500 error on profile")
    page.should have_content issue.title
    page.should have_content issue.author_name
    page.should have_content issue.project.name
  end

  step 'I fill in issue search with "Re"' do
    filter_issue "Re"
  end

  step 'I fill in issue search with "Bu"' do
    filter_issue "Bu"
  end

  step 'I fill in issue search with ".3"' do
    filter_issue ".3"
  end

  step 'I fill in issue search with "Something"' do
    filter_issue "Something"
  end

  step 'I fill in issue search with ""' do
    filter_issue ""
  end

  step 'project "Shop" has milestone "v2.2"' do

    milestone = create(:milestone, title: "v2.2", project: project)

    3.times { create(:issue, project: project, milestone: milestone) }
  end

  step 'project "Shop" has milestone "v3.0"' do

    milestone = create(:milestone, title: "v3.0", project: project)

    3.times { create(:issue, project: project, milestone: milestone) }
  end

  When 'I select milestone "v3.0"' do
    select "v3.0", from: "milestone_id"
  end

  step 'I should see selected milestone with title "v3.0"' do
    issues_milestone_selector = "#issue_milestone_id_chzn > a"
    find(issues_milestone_selector).should have_content("v3.0")
  end

  When 'I select first assignee from "Shop" project' do

    first_assignee = project.users.first
    select first_assignee.name, from: "assignee_id"
  end

  step 'I should see first assignee from "Shop" as selected assignee' do
    issues_assignee_selector = "#issue_assignee_id_chzn > a"

    assignee_name = project.users.first.name
    find(issues_assignee_selector).should have_content(assignee_name)
  end

  step 'project "Shop" have "Release 0.4" open issue' do

    create(:issue,
           title: "Release 0.4",
           project: project,
           author: project.users.first,
           description: "# Description header"
          )
  end

  step 'project "Shop" have "Tweet control" open issue' do
    create(:issue,
           title: "Tweet control",
           project: project,
           author: project.users.first)
  end

  step 'project "Shop" have "Release 0.3" closed issue' do
    create(:closed_issue,
           title: "Release 0.3",
           project: project,
           author: project.users.first)
  end

  step 'project "Shop" has "Tasks-open" open issue with task markdown' do
    create_taskable(:issue, 'Tasks-open')
  end

  step 'project "Shop" has "Tasks-closed" closed issue with task markdown' do
    create_taskable(:closed_issue, 'Tasks-closed')
  end

  step 'empty project "Empty Project"' do
    create :empty_project, name: 'Empty Project', namespace: @user.namespace
  end

  When 'I visit empty project page' do
    project = Project.find_by(name: 'Empty Project')
    visit project_path(project)
  end

  step 'I see empty project details with ssh clone info' do
    project = Project.find_by(name: 'Empty Project')
    all(:css, '.git-empty .clone').each do |element|
      element.text.should include(project.url_to_repo)
    end
  end

  When "I visit empty project's issues page" do
    project = Project.find_by(name: 'Empty Project')
    visit project_issues_path(project)
  end

  step 'I leave a comment with code block' do
    within(".js-main-target-form") do
      fill_in "note[note]", with: "```\nCommand [1]: /usr/local/bin/git , see [text](doc/text)\n```"
      click_button "Add Comment"
      sleep 0.05
    end
  end

  step 'The code block should be unchanged' do
    page.should have_content("```\nCommand [1]: /usr/local/bin/git , see [text](doc/text)\n```")
  end

  step 'project \'Shop\' has issue \'Bugfix1\' with description: \'Description for issue1\'' do
    issue = create(:issue, title: 'Bugfix1', description: 'Description for issue1', project: project)
  end

  step 'project \'Shop\' has issue \'Feature1\' with description: \'Feature submitted for issue1\'' do
    issue = create(:issue, title: 'Feature1', description: 'Feature submitted for issue1', project: project)
  end

  step 'I fill in issue search with \'Description for issue1\'' do
    filter_issue 'Description for issue'
  end

  step 'I fill in issue search with \'issue1\'' do
    filter_issue 'issue1'
  end

  step 'I fill in issue search with \'Rock and roll\'' do
    filter_issue 'Description for issue'
  end

  step 'I should see \'Bugfix1\' in issues' do
    page.should have_content 'Bugfix1'
  end

  step 'I should see \'Feature1\' in issues' do
    page.should have_content 'Feature1'
  end

  step 'I should not see \'Bugfix1\' in issues' do
    page.should_not have_content 'Bugfix1'
  end

  step 'issue \'Release 0.4\' has label \'bug\'' do
    label = project.labels.create!(name: 'bug', color: '#990000')
    issue = Issue.find_by!(title: 'Release 0.4')
    issue.labels << label
  end

  step 'I click label \'bug\'' do
    within ".issues-list" do
      click_link 'bug'
    end
  end

  def filter_issue(text)
    fill_in 'issue_search', with: text
  end
end


text:
<?php

namespace App\SecurityModule\Config;

use \Nette\DI\CompilerExtension,
    \Nette\PhpGenerator\ClassType,
    \App\Config\BaseModuleExtension,
    \App\SystemModule\Model\Service\Menu\ItemData,
    \Kdyby\Translation\DI\ITranslationProvider,
    \App\SystemModule\Model\Service\Menu\IAdminMenuDataProvider,
    \App\SystemModule\Model\Service\Menu\IProtectedMenuDataProvider,
    \App\SystemModule\Model\Service\Menu\IPublicMenuDataProvider,
    \Kdyby\Doctrine\DI\IDatabaseTypeProvider;

/**
 * SecurityModuleExtension
 *
 * @author Michal Fučík <michal.fuca.fucik(at)gmail.com>
 */
final class SecurityModuleExtension extends BaseModuleExtension implements
ITranslationProvider, IAdminMenuDataProvider, IProtectedMenuDataProvider, IPublicMenuDataProvider, IDatabaseTypeProvider {

    private $defaults = [
	"defRoleAppEvents"	=> "player",
	"defCommentAppEvents"	=> "created by system",
	"deleteOldPositions"	=> false,
	    "init"  =>	[
		"turnOff"=>false,
		"roles"	=>  ["admin","player"]]];

    public function loadConfiguration() {
	parent::loadConfiguration();

	$config = $this->getConfig($this->defaults);

	$builder = $this->getContainerBuilder();

	// načtení konfiguračního souboru pro rozšíření
	$this->compiler->parseServices($builder, $this->loadFromFile(__DIR__ . '/config.neon'));

	// Listener of Season application's events setup
	$builder->getDefinition($this->prefix("applicationsListener"))
		->addSetup("setDefaultRoleName", [$config["defRoleAppEvents"]])
		->addSetup("setDefaultComment", [$config["defCommentAppEvents"]]);

	///$rValues = array_unique(array_merge($config["init"]["roles"], [$config["defRoleAppEvents"]], ["admin","authenticated"]));
	$rValues = $config["init"]["roles"] + [$config["defRoleAppEvents"]];
	$initializer = $builder->getDefinition($this->prefix("initializer"))
		->addSetup("setRolesValues", [$rValues])
		->addSetup("setDefaultUserEmail", [$config["defaultUserEmail"]]);

	if (!$config["init"]["turnOff"])
	    $initializer->addSetup("rolesInit")
		->addSetup("positionsInit")
		->addSetup("rulesInit");
    }

    public function getTranslationResources() {
	return [__DIR__ . "/../".self::LOCALE_DIR];
    }

    public function beforeCompile() {
	parent::beforeCompile();
    }

    public function afterCompile(ClassType $class) {
	parent::afterCompile($class);
    }

    public function getAdminItemsResources() {
	$i = new ItemData();
	$i->setLabel("securityModule.adminMenuItem.label");
	$i->setUrl(":Security:Admin:default");
	$i->setData(["desc"=>"securityModule.adminMenuItem.description"]);
	return [$i];
    }

    public function getPublicItemsResources() {
	$i = new ItemData();
	$i->setLabel("securityModule.public.menu.contacts.label");
	$i->setUrl(":Security:Public:default");
	$i->setData(["desc"=>"securityModule.public.menu.contacts.description"]);
	return [$i];
    }

    public function getProtectedItemsResources() {
	$i = new ItemData();
	$i->setLabel("securityModule.protectedMenuItem.label");
	$i->setUrl(":Security:Auth:out");
	$i->setData(["separate"=>true,"headOnly"=>true, "desc"=>"securityModule.protectedMenuItem.description"]);
	return [$i];
    }

    public function getDatabaseTypes() {
	return ["AclMode"   =>	"App\Model\Misc\Enum\AclMode",
		"AclPrivilege"	=>  "App\Model\Misc\Enum\AclPrivilege"];
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:elevation="10dp"
    app:cardCornerRadius="2dp">

    <View
        android:id="@+id/viewColorTag"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="1dp"
        android:layout_marginLeft="5dp"
        android:background="@color/colorWhite"
        android:paddingBottom="5dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="5dp"
            android:background="?android:attr/selectableItemBackground"
            android:clickable="true"
            android:padding="5dp">

            <TextView
                android:id="@+id/textTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:text="Title"
                android:textColor="@color/litherGray"
                android:textSize="11sp"
                android:visibility="gone" />

            <TextView
                android:id="@+id/txtShowTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_below="@+id/textTitle"
                android:layout_marginRight="5dp"
                android:layout_toLeftOf="@+id/txtShowCategory"
                android:ellipsize="end"
                android:maxLines="1"
                android:text="@string/task_title"
                android:textColor="#303030"
                android:textSize="20sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/textTask"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_below="@+id/txtShowTitle"
                android:layout_marginTop="12dp"
                android:text="Task"
                android:textColor="@color/litherGray"
                android:textSize="11sp"
                android:visibility="gone" />

            <TextView
                android:id="@+id/txtShowTask"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_below="@+id/textTask"
                android:layout_marginTop="4dp"
                android:ellipsize="end"
                android:maxLines="1"
                android:text="@string/task_title"
                android:textColor="@color/colorBlack"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/txtShowCategory"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:ellipsize="end"
                android:maxLines="1"
                android:maxWidth="80dp"
                android:text="@string/category"
                android:textColor="@color/litherGray"
                android:textSize="11sp" />

            <TextView
                android:id="@+id/textDate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_below="@+id/txtShowTask"
                android:layout_marginTop="15dp"
                android:text="Date"
                android:textColor="@color/litherGray"
                android:textSize="11sp"
                android:visibility="gone" />

            <TextView
                android:id="@+id/txtShowDate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_below="@+id/textDate"
                android:text="22-12-2017"
                android:textColor="@color/colorBlack"
                android:visibility="gone" />

            <TextView
                android:id="@+id/textTime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_below="@+id/txtShowTask"
                android:layout_marginTop="15dp"
                android:text="Time"
                android:textColor="@color/litherGray"
                android:textSize="11sp"
                android:visibility="gone" />

            <TextView
                android:id="@+id/txtShowTime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_below="@+id/textTime"
                android:text="22:12 AM"
                android:textColor="@color/colorBlack"
                android:visibility="gone" />

        </RelativeLayout>

    </RelativeLayout>

</android.support.v7.widget.CardView>


text:
/**
 * UCSC Xena Client
 * http://xena.ucsc.edu
 *
 * Standard Xena action button, providing custom "text" button styles to the Mui ButtonBase component.
 */

// Core dependencies, components
import {Box, ButtonBase, makeStyles} from '@material-ui/core';
import React from 'react';
import {xenaColor} from '../xenaColor';

const useStyles = makeStyles(theme => ({
	root: sx => ({
		...theme.typography.caption,
		...sx,
		color: xenaColor.ACCENT,
		'&:disabled': {
			color: theme.palette.action.disabled,
		},
	}),
}));

export default function XActionButton({children, onClick, sx, ...props}) {
	const classes = useStyles(sx);
	return (
		<Box
			component={ButtonBase}
			classes={{root: classes.root}}
			disableRipple
			onClick={onClick}
			{...props}>
			{children}
		</Box>
	);
};


text:
function experiment = exportKClAnalysis(experiment, varargin)
% EXPORTKCLANALYSIS exports data from the KCL analysis
%
% USAGE:
%    experiment = exportKClAnalysis(experiment, varargin)
%
% INPUT arguments:
%    experiment - experiment structure
%
% INPUT optional arguments ('key' followed by its value):
%    see: exportBaseGroupOptions
%
% OUTPUT arguments:
%    experiment - experiment structure
%
% EXAMPLE:
%    experiment = exportFluorescenceFeatures(experiment)
%
% Copyright (C) 2016-2018, Javier G. Orlandi <javiergorlandi@gmail.com>

% EXPERIMENT PIPELINE
% name: export KCl analysis results
% parentGroups: protocols: KCl analysis: exports
% optionsClass: exportBaseGroupOptions
% requiredFields: KClProtocolData, ROI, folder, name

[params, var] = processFunctionStartup(exportBaseGroupOptions, varargin{:});
% Define additional optional argument pairs
params.pbar = [];
params.verbose = true;
params = parse_pv_pairs(params, var);
params = barStartup(params, 'Exporting KCl analysis results', true);
%--------------------------------------------------------------------------

% Fix in case for some reason the group is a cell
if(iscell(params.group))
  mainGroup = params.group{1};
else
  mainGroup = params.group;
end

% Create the exports folder
switch params.exportFolder
  case 'experiment'
    mainFolder = experiment.folder;
  case 'project'
    mainFolder = [experiment.folder '..' filesep];
end
if(~exist(mainFolder, 'dir'))
  mkdir(mainFolder);
end
dataFolder = [mainFolder 'exports' filesep];
if(~exist(dataFolder, 'dir'))
  mkdir(dataFolder);
end
outputFileName = [dataFolder, experiment.name, '_KClAnalysisData' params.exportFileTag];

% Get ALL subgroups in case of parents
if(strcmpi(mainGroup, 'all'))
  groupList = getExperimentGroupsNames(experiment);
else
  groupList = getExperimentGroupsNames(experiment, mainGroup);
end

% Empty check
if(isempty(groupList))
  logMsg(sprintf('Group %s not found on experiment %s', mainGroup, experiment.name), 'w');
  barCleanup(params);
  return;
end

% Find maximum number of segments
maxSegments = 0;
for git = 1:length(groupList)
  [~, groupName, groupIdx] = getExperimentGroupMembers(experiment, groupList{git});
  maxSegments = max([maxSegments; experiment.KClProtocolData.(groupName){groupIdx}.responseFitSegments]);
end

%labels = {'baseLine', 'reactionTime', 'maxResponse', 'maxResponseTime', 'decay', 'decayTime', 'recoveryTime', 'endValue', 'lastResponseValue'};

originalLabels = {'baseLine', 'reactionTime', 'maxResponse', 'maxResponseTime', ...
          'decay', 'decayTime', 'responseDuration', 'recoveryTime', 'recovered', ...
          'protocolEndValue', 'lastResponseValue', ...
          'responseFitSegments', 'responseFitSegmentsMaxFluorescenceIncrease', 'responseFitSegmentsMaxSlope'};
labels = originalLabels;
for it = 1:maxSegments
  labels = [labels, {sprintf('seg: %d F inc', it), sprintf('seg: %d dur', it), sprintf('seg: %d slope', it)}];
end

labels = [labels, {'ROI', 'group', 'experiment'}];

%%% Preparing the CSV export
outputFile = [outputFileName '.csv'];
fID = fopen(outputFile, 'W');
% Create and write the header
fmt = repmat('%s, ',1, length(labels));
fmt = [fmt(1:end-2) '\n'];
fprintf(fID, fmt, labels{:});

%fmt = [repmat([params.numericFormat, ', '], 1, length(labels)-2) '%s, %d\n'];
fmt = [repmat([params.numericFormat, ', '], 1, length(labels)-2) '%d'];
fmtEnd = '%s, %s\n';
%fmtEnd = '%s, %s, %d\n';

% Main loop for the export data
ROIid = getROIid(experiment.ROI);
% Time to iterate through all the groups
for git = 1:length(groupList)
  [members, groupName, groupIdx] = getExperimentGroupMembers(experiment, groupList{git});
  ncbar.setBarTitle(sprintf('Exporting KCl analysis results from group: %s', groupList{git}));
  exportData = nan(length(members), length(labels)-2);
  % Copy info from original labels
  for it = 1:length(originalLabels)
    exportData(:, it) = experiment.KClProtocolData.(groupName){groupIdx}.(originalLabels{it});
  end
  exportData(:, end) = ROIid(members);

  %[exportData, ~] = getKClFeatures(experiment, groupList{git}, 'ROI ID');
  for j = 1:size(exportData, 1)
    % Now let's add segment info
    curPos = length(originalLabels);
    for it = 1:experiment.KClProtocolData.(groupName){groupIdx}.responseFitSegments(j)
      curPos = curPos+1;
      exportData(j, curPos) = experiment.KClProtocolData.(groupName){groupIdx}.responseFitSegmentsFluorescenceIncrease{j}(it);
      curPos = curPos+1;
      exportData(j, curPos) = experiment.KClProtocolData.(groupName){groupIdx}.responseFitSegmentsDuration{j}(it);
      curPos = curPos+1;
      exportData(j, curPos) = experiment.KClProtocolData.(groupName){groupIdx}.responseFitSegmentsSlope{j}(it);
    end
    fprintf(fID, fmt, exportData(j, :));
    fprintf(fID, fmtEnd, groupList{git}, experiment.name);
    %fprintf(fID, fmtEnd, groupList{git}, experiment.name, checkedExperiments(itt));
  end
end

fclose(fID);

%--------------------------------------------------------------------------
barCleanup(params);
%--------------------------------------------------------------------------

end


text:
using MoreCollection.Extensions;
using Neutronium.Core.Binding.Builder;
using Neutronium.Core.Binding.CollectionChanges;
using Neutronium.Core.Binding.Listeners;
using Neutronium.Core.JavascriptFramework;
using Neutronium.Core.WebBrowserEngine.JavascriptObject;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;

namespace Neutronium.Core.Binding.GlueObject
{
    internal class JsArray : GlueBase, IJsCsCachableGlue
    {
        private readonly Type _IndividualType;

        public object CValue { get; }
        public List<IJsCsGlue> Items { get; private set; }
        public JsCsGlueType Type => JsCsGlueType.Array;
        public virtual IJavascriptObject CachableJsValue => JsValue;
        public uint JsId { get; private set; }

        void IJsCsCachableGlue.SetJsId(uint jsId) => JsId = jsId;

        public JsArray(IEnumerable collection, Type individual)
        {
            CValue = collection;
            _IndividualType = individual;
        }

        internal void SetChildren(List<IJsCsGlue> values)
        {
            Items = values;
        }

        public void VisitDescendants(Func<IJsCsGlue, bool> visit)
        {
            if (!visit(this))
                return;

            foreach (var item in Items)
            {
                item.VisitDescendants(visit);
            }
        }

        public void VisitChildren(Action<IJsCsGlue> visit)
        {
            foreach (var item in Items)
                visit(item);
        }

        public void RequestBuildInstruction(IJavascriptObjectBuilder builder)
        {
            builder.RequestArrayCreation(Items);
        }

        public virtual void SetJsValue(IJavascriptObject value, IJavascriptSessionCache sessionCache)
        {
            SetJsValue(value);
            sessionCache.Cache(this);
        }

        public CollectionChanges.CollectionChanges GetChanger(JavascriptCollectionChanges changes, IJavascriptToCSharpConverter bridge)
        {
            return new CollectionChanges.CollectionChanges(bridge, changes, _IndividualType);
        }

        private void ReplayChanges(IndividualCollectionChange change, IList list)
        {
            switch (change.CollectionChangeType)
            {
                case CollectionChangeType.Add:
                    if (change.Index == list.Count)
                    {
                        list.Add(change.Object.CValue);
                        Items.Add(change.Object);
                    }
                    else
                    {
                        list.Insert(change.Index, change.Object.CValue);
                        Items.Insert(change.Index, change.Object);
                    }
                    break;

                case CollectionChangeType.Remove:
                    list.RemoveAt(change.Index);
                    Items.RemoveAt(change.Index);
                    break;
            }
        }

        public void UpdateEventArgsFromJavascript(CollectionChanges.CollectionChanges collectionChanges, BridgeUpdater updater)
        {
            if (!(CValue is IList list))
                return;

            collectionChanges.IndividualChanges.ForEach(c => ReplayChanges(c, list));

            collectionChanges.IndividualChanges.Where(ch => ch.CollectionChangeType == CollectionChangeType.Add)
                .ForEach(ch => ch.Object.AddRef());

            collectionChanges.IndividualChanges.Where(ch => ch.CollectionChangeType == CollectionChangeType.Remove)
                .ForEach(ch => CheckForRemove(updater, ch.Object));
        }

        public BridgeUpdater GetAddUpdater(IJsCsGlue glue, int index)
        {
            Items.Insert(index, glue);
            glue.AddRef();
            return new BridgeUpdater(viewModelUpdater => Splice(viewModelUpdater, index, 0, glue));
        }

        public BridgeUpdater GetAddUpdater(IList<IJsCsGlue> glues, int startIndex)
        {
            var index = startIndex;
            glues.ForEach(glue =>
            {
                Items.Insert(index++, glue);
                glue.AddRef();
            });
            return new BridgeUpdater(viewModelUpdater => Splice(viewModelUpdater, startIndex, 0, glues));
        }

        private static BridgeUpdater CheckForRemove(BridgeUpdater updater, IJsCsGlue glue)
        {
            if (glue.Release())
                updater.Remove(glue);
            return updater;
        }

        private static BridgeUpdater CheckForRemove(BridgeUpdater updater, List<IJsCsGlue> glues)
        {
            glues.ForEach(glue =>
            {
                if (glue.Release())
                    updater.Remove(glue);
            });
            return updater;
        }

        public BridgeUpdater GetReplaceUpdater(IJsCsGlue glue, int index)
        {
            var bridgeUpdater = new BridgeUpdater(viewModelUpdater => Splice(viewModelUpdater, index, 1, glue));
            var old = Items[index];
            Items[index] = glue.AddRef();
            return CheckForRemove(bridgeUpdater, old);
        }

        public BridgeUpdater GetReplaceUpdater(List<IJsCsGlue> glues, int index)
        {
            var bridgeUpdater = new BridgeUpdater(viewModelUpdater => Splice(viewModelUpdater, index, glues.Count, glues));

            var oldChildren = glues.Select((glue, idx) =>
            {
                var currentIndex = index + idx;
                var old = Items[currentIndex];
                Items[currentIndex] = glue.AddRef();
                return old;
            }).ToList();
            return CheckForRemove(bridgeUpdater, oldChildren);
        }

        public BridgeUpdater GetMoveUpdater(int oldIndex, int newIndex)
        {
            var item = Items[oldIndex];
            Items.RemoveAt(oldIndex);
            Items.Insert(newIndex, item);
            return new BridgeUpdater(viewModelUpdater => MoveJavascriptCollection(viewModelUpdater, item.GetJsSessionValue(), oldIndex, newIndex));
        }

        public BridgeUpdater GetRemoveUpdater(int index, int count)
        {
            var bridgeUpdater = new BridgeUpdater(viewModelUpdater => Splice(viewModelUpdater, index, count));
            var oldChildren = Enumerable.Range(0, count).Select(_ =>
            {
                var old = Items[index];
                Items.RemoveAt(index);
                return old;
            }).ToList();
            return CheckForRemove(bridgeUpdater, oldChildren);
        }

        public BridgeUpdater GetResetUpdater()
        {
            var bridgeUpdater = new BridgeUpdater(ClearAllJavascriptCollection);
            foreach (var item in Items)
            {
                CheckForRemove(bridgeUpdater, item);
            }
            Items.Clear();
            return bridgeUpdater;
        }

        private void Splice(IJavascriptViewModelUpdater viewModelUpdater, int index, int number, IJsCsGlue glue)
        {
            viewModelUpdater?.SpliceCollection(CachableJsValue, index, number, glue.GetJsSessionValue());
        }

        private void Splice(IJavascriptViewModelUpdater viewModelUpdater, int index, int number, IList<IJsCsGlue> glues)
        {
            viewModelUpdater?.SpliceCollection(CachableJsValue, index, number, glues.Select(glue => glue.GetJsSessionValue()).ToArray());
        }

        private void Splice(IJavascriptViewModelUpdater viewModelUpdater, int index, int number)
        {
            viewModelUpdater?.SpliceCollection(CachableJsValue, index, number);
        }

        private void MoveJavascriptCollection(IJavascriptViewModelUpdater viewModelUpdater, IJavascriptObject item, int oldIndex, int newIndex)
        {
            viewModelUpdater?.MoveCollectionItem(CachableJsValue, item, oldIndex, newIndex);
        }

        private void ClearAllJavascriptCollection(IJavascriptViewModelUpdater viewModelUpdater)
        {
            viewModelUpdater?.ClearAllCollection(CachableJsValue);
        }

        protected override void ComputeString(IDescriptionBuilder context)
        {
            context.Append("[");
            var count = 0;
            foreach (var it in Items)
            {
                if (count != 0)
                    context.Append(",");

                using (context.PushContext(count++))
                {
                    it.BuilString(context);
                }
            }
            context.Append("]");
        }

        public void ApplyOnListenable(IObjectChangesListener listener)
        {
            if (!(CValue is INotifyCollectionChanged notifyCollectionChanged))
                return;

            listener.OnCollection(notifyCollectionChanged);
        }
    }
}


text:
package org.kasource.validation.phone.impl;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.easymock.EasyMock.*;

import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintValidatorContext.ConstraintViolationBuilder;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.kasource.commons.collection.builder.ListBuilder;
import org.kasource.commons.reflection.annotation.AnnotationBuilder;

import org.kasource.validation.phone.Phone;
import org.unitils.UnitilsJUnit4TestClassRunner;
import org.unitils.easymock.EasyMockUnitils;
import org.unitils.easymock.annotation.Mock;
import org.unitils.inject.annotation.TestedObject;

@RunWith(UnitilsJUnit4TestClassRunner.class)
public class IterableArrayPhoneValidatorTest {
    @Mock
    private ConstraintValidatorContext context;

    @Mock
    private ConstraintViolationBuilder builder;

    @TestedObject
    private IterablePhoneValidator validator;

    @Test
    public void testGenericPhone() {
       EasyMockUnitils.replay();
       validator.initialize(new AnnotationBuilder<Phone>(Phone.class).build());

       assertTrue(validator.isValid(new ListBuilder<String>().add("+9432987342","243234234","434-4343 434","(687423) 687432").build(), context));
       assertFalse(validator.isValid(new ListBuilder<String>().add("243234234", "1232cd12").build(), context));
    }

    @Test
    public void testCountrySpecific() {
        context.disableDefaultConstraintViolation();
        expectLastCall();
        expect(context.buildConstraintViolationWithTemplate("{org.kasource.validation.phone.Phone} Sweden")).andReturn(builder);
        expect(builder.addConstraintViolation()).andReturn(context);

        EasyMockUnitils.replay();
        validator.initialize(new AnnotationBuilder<Phone>(Phone.class).attr("country", "SE").build());

        assertTrue(validator.isValid(new ListBuilder<String>().add("+46703834107", "243234234", "08-323 42 34").build(), context));
        assertFalse(validator.isValid(new ListBuilder<String>().add("+46703834107", "434-4343 434").build(), context));

    }
}


text:
author: slowe
categories: Information
comments: true
date: 2014-08-05T09:00:00Z
slug: sessions-at-the-fall-openstack-summit
tags:
- Docker
- KVM
- Libvirt
- Networking
- OpenStack
- Virtualization
- Linux
title: Sessions at the Fall OpenStack Summit
url: /2014/08/05/sessions-at-the-fall-openstack-summit/
wordpress_id: 3489
---

It's that time again---time for community voting on sessions for the fall OpenStack Summit, being held in Paris this year in early November. I wanted to take a moment and share some of the sessions in which I'm involved and/or that I think might be useful. It would be great if you could take a moment to add your votes for the sessions.

## My Sessions

I have a total of four session proposals submitted this year:

* [MIT and VMware: Taking IT to OpenStack Private Cloud](https://www.openstack.org/vote-paris/Presentation/mit-and-vmware-taking-it-to-openstack-private-cloud)

* [OpenStack for VMware Operators](https://www.openstack.org/vote-paris/Presentation/openstack-for-vmware-operators)

* [OpenStack Design Guide Panel](https://www.openstack.org/vote-paris/Presentation/panel-with-the-authors-of-the-openstack-design-guide)

* [Panel: Tips and Tools for Building a Successful OpenStack Group](https://www.openstack.org/vote-paris/Presentation/panel-tips-and-tools-for-building-a-successful-openstack-group)

## Congress Sessions

You may also be aware that I am involved with a project called Congress, which aims to bring an overarching policy service to OpenStack. Here are some sessions pertaining to Congress:

* [Congress: Policy as a Service](https://www.openstack.org/vote-paris/Presentation/congress-policy-as-a-service)

* [Policy and Security in the "Goldilocks" Zone](https://www.openstack.org/vote-paris/Presentation/policy-and-security-in-the-goldilocks-zone)

## VMware Sessions

Arvind Soni, one of the product managers for OpenStack at VMware, kindly pulled together [this list of VMware-related sessions](https://communities.vmware.com/community/vmtn/openstack/blog/2014/08/04/voting-for-openstack-paris-summit-talks), so feel free to have a look at any of these and vote on what sounds appealing to you.

## Other Sessions

There are _way_ too many sessions to list all the interesting ones, but here are a few that caught my eye:

* [Container Unification with libcontainer](https://www.openstack.org/vote-paris/Presentation/container-unification-with-libcontainer)

* [Orchestrating Docker with OpenStack](https://www.openstack.org/vote-paris/Presentation/orchestrating-docker-with-openstack)

* [Building the Cloud Ecosystem - OpenStack, Docker, Kubernetes](https://www.openstack.org/vote-paris/Presentation/building-the-cloud-ecosystem-openstack-docker-kubernetes)

* [New platforms with Open vSwitch: Docker, Hyper-V, and Intel DPDK](https://www.openstack.org/vote-paris/Presentation/new-platforms-with-open-vswitch-docker-hyper-v-and-intel-dpdk) _(this is also listed on the VMware sessions above, but as you can tell it's really not a "VMware" talk)_

* [Deploying and Auto-Scaling Applications on OpenStack with Heat](https://www.openstack.org/vote-paris/Presentation/deploying-and-auto-scaling-applications-on-openshift-with-heat)

* [Under the Hood: Libvirt/KVM Driver Juno Update](https://www.openstack.org/vote-paris/Presentation/libvirt-driver-update)

* [Under the Hood with Nova, Libvirt, and KVM, Part 2](https://www.openstack.org/vote-paris/Presentation/under-the-hood-with-nova-libvirt-and-kvm-part-two) _(coincidentally, not related to the previous session)_

* [Designate: An Overview of OpenStack DNSaaS](https://www.openstack.org/vote-paris/Presentation/designate-an-overview-of-openstack-dnsaas)

There are a bunch more that looked interesting to me, but I'll skip listing them all here---just hop over to the OpenStack site and vote for the sessions you want to see.


text:
:mod:`srddl.core.offset` Module
==============================

.. automodule:: srddl.core.offset
    :members:
    :undoc-members:
    :show-inheritance:


text:
from Metarouting.Algebra.Semiring import *

class Semimodule:
    zeroElt = None

    def __init__(self, val):
        self.elt = val

    def __add__(self, other):
        raise NotImplementedError("Additive law not implemented.")

    def __mul__(self, other):
        if(issubclass(other.__class__, Semiring)):
            return self.__lmul__(other)
        else:
            return NotImplemented

    def __lmul__(self, other):
        raise NotImplementedError("Scalar left-multiplicative law not implemented.")

    def __rmul__(self, other):
        raise NotImplementedError("Scalar right-multiplicative law not implemented.")

    # Representation related stuff
    def __repr__(self):
        raise NotImplementedError("Representation not specified.")

    @classmethod
    def zero(cls):
        return cls(cls.zeroElt)


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.PolicyInsights.Models
{
    /// <summary> Policy evaluation details. </summary>
    public partial class PolicyEvaluationDetails
    {
        /// <summary> Initializes a new instance of PolicyEvaluationDetails. </summary>
        internal PolicyEvaluationDetails()
        {
            EvaluatedExpressions = new ChangeTrackingList<ExpressionEvaluationDetails>();
        }

        /// <summary> Initializes a new instance of PolicyEvaluationDetails. </summary>
        /// <param name="evaluatedExpressions"> Details of the evaluated expressions. </param>
        /// <param name="ifNotExistsDetails"> Evaluation details of IfNotExists effect. </param>
        internal PolicyEvaluationDetails(IReadOnlyList<ExpressionEvaluationDetails> evaluatedExpressions, IfNotExistsEvaluationDetails ifNotExistsDetails)
        {
            EvaluatedExpressions = evaluatedExpressions;
            IfNotExistsDetails = ifNotExistsDetails;
        }

        /// <summary> Details of the evaluated expressions. </summary>
        public IReadOnlyList<ExpressionEvaluationDetails> EvaluatedExpressions { get; }
        /// <summary> Evaluation details of IfNotExists effect. </summary>
        public IfNotExistsEvaluationDetails IfNotExistsDetails { get; }
    }
}


text:
package com.example.http4s.ember

import _root_.io.circe._
import _root_.org.http4s.ember.server.EmberServerBuilder
import cats.effect._
import cats.syntax.all._
import com.comcast.ip4s._
import fs2._
import org.http4s._
import org.http4s.circe._
import org.http4s.dsl.Http4sDsl
import org.http4s.implicits._
import org.http4s.server.websocket.WebSocketBuilder
import org.http4s.websocket.WebSocketFrame

import scala.concurrent.duration._

object EmberServerSimpleExample extends IOApp {

  def run(args: List[String]): IO[ExitCode] = {
    val host = host"0.0.0.0"
    val port = port"8080"
    for {
      // Server Level Resources Here
      server <-
        EmberServerBuilder
          .default[IO]
          .withHost(host)
          .withPort(port)
          .withHttpWebSocketApp(service[IO])
          .build
    } yield server
  }.use(server =>
    IO.delay(println(s"Server Has Started at ${server.address}")) >>
      IO.never.as(ExitCode.Success)
  )

  def service[F[_]: Async](wsb: WebSocketBuilder[F]): HttpApp[F] = {
    val dsl = new Http4sDsl[F] {}
    import dsl._

    HttpRoutes
      .of[F] {
        case req @ POST -> Root =>
          for {
            json <- req.decodeJson[Json]
            resp <- Ok(json)
          } yield resp
        case GET -> Root =>
          Ok(Json.obj("root" -> Json.fromString("GET")))
        case GET -> Root / "hello" / name =>
          Ok(show"Hi $name!")
        case GET -> Root / "chunked" =>
          val body = Stream("This IS A CHUNK\n").repeat
            .take(100)
            .through(fs2.text.utf8.encode[F])
          Ok(body).map(_.withContentType(headers.`Content-Type`(MediaType.text.plain)))
        case GET -> Root / "ws" =>
          val send: Stream[F, WebSocketFrame] =
            Stream.awakeEvery[F](1.seconds).map(_ => WebSocketFrame.Text("text"))
          val receive: Pipe[F, WebSocketFrame, Unit] = _.evalMap {
            case WebSocketFrame.Text(text, _) => Sync[F].delay(println(text))
            case other => Sync[F].delay(println(other))
          }
          wsb.build(send, receive)
      }
      .orNotFound
  }
}


text:
/**
 * Defines specific text related enumerations.
 */
declare module "text" {
    /**
     * Defines the supported character encodings.
     */
    module encoding {
        /**
         * Denotes ISO-8859-1 character encoding.
         */
        export var ISO_8859_1: any;

        /**
         * Denotes US_ASCII character encoding.
         */
        export var US_ASCII: any;

        /**
         * Denotes UTF_16 character encoding.
         */
        export var UTF_16: any;

        /**
         * Denotes UTF_16BE character encoding.
         */
        export var UTF_16BE: any;

        /**
         * Denotes UTF_16LE character encoding.
         */
        export var UTF_16LE: any;

        /**
         * Denotes UTF_8 character encoding.
         */
        export var UTF_8: any;
    }
}