text:
@implementation UIView (CraryFrame)

- (CGSize)cr_size
{
    return self.frame.size;
}

- (void)setCr_size:(CGSize)size
{
    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
}

- (CGFloat)cr_width
{
    return self.frame.size.width;
}

- (void)setCr_width:(CGFloat)width
{
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}

- (CGFloat)cr_height
{
    return self.frame.size.height;
}

- (void)setCr_height:(CGFloat)height
{
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}

- (CGPoint)cr_origin
{
    return self.frame.origin;
}

- (void)setCr_origin:(CGPoint)origin
{
    CGRect frame = self.frame;
    frame.origin = origin;
    self.frame = frame;
}

- (CGFloat)cr_left
{
    return self.frame.origin.x;
}

- (void)setCr_left:(CGFloat)left
{
    CGRect frame = self.frame;
    frame.origin.x = left;
    self.frame = frame;
}

- (CGFloat)cr_right
{
    return self.frame.origin.x + self.frame.size.width;
}

- (void)setCr_right:(CGFloat)right
{
    CGRect frame = self.frame;
    frame.origin.x = right - self.frame.size.width;
    self.frame = frame;
}

- (CGFloat)cr_top
{
    return self.frame.origin.y;
}

- (void)setCr_top:(CGFloat)top
{
    CGRect frame = self.frame;
    frame.origin.y = top;
    self.frame = frame;
}

- (CGFloat)cr_bottom
{
    return self.frame.origin.y + self.frame.size.height;
}

- (void)setCr_bottom:(CGFloat)bottom
{
    CGRect frame = self.frame;
    frame.origin.y = bottom - self.frame.size.height;
    self.frame = frame;
}

- (CGFloat)cr_centerX
{
    return self.cr_left + self.cr_width / 2;
}

- (void)setCr_centerX:(CGFloat)centerX
{
    CGRect frame = self.frame;
    frame.origin.x = centerX - frame.size.width / 2;
    self.frame = frame;
}

- (CGFloat)cr_centerY
{
    return self.cr_top + self.cr_height / 2;
}

- (void)setCr_centerY:(CGFloat)centerY
{
    CGRect frame = self.frame;
    frame.origin.y = centerY - frame.size.height / 2;
    self.frame = frame;
}

- (void)cr_widthToFit
{
    CGRect rect = self.frame;
    [self sizeToFit];
    rect.size.width = self.frame.size.width;
    self.frame = rect;
}

- (void)cr_heightToFit
{
    CGRect rect = self.frame;
    [self sizeToFit];
    rect.size.height = self.frame.size.height;
    self.frame = rect;
}

@end


text:
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace WebService
{
    using System.Web.Http;

    public static class RouteConfig
    {
        /// <summary>
        ///     Routing registration.
        /// </summary>
        /// <param name="routes"></param>
        public static void RegisterRoutes(HttpRouteCollection routes)
        {
            routes.MapHttpRoute(
                "Default",
                "api/{controller}/{id}",
                new {controller = "Default", id = RouteParameter.Optional},
                new {}
                );
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.anji.nn;

/**
 * Signed sinusoidal activation function implemented as cos(theta).
 *
 * @author Brian Woolley
 */
public class CosineActivationFunction implements ActivationFunction {

	/**
	 * identifying string
	 */
	public final static String NAME = ActivationFunctionType.COSINE.toString();

	/**
	 * @see Object#toString()
	 */
	public String toString() {
		return NAME;
	}

	/**
	 * This class should only be instantiated by the ActivationFunction enumeration.
	 * @see com.anji.activationFunction.ActivationFunction
	 */
	protected CosineActivationFunction() {}

	/**
	 * Return input with no transformation.
	 *
	 * @see com.anji.activationFunction.ActivationFunctionStrategy#apply(double)
	 */
	public double apply( double input ) {
		return Math.cos(input);
	}

	/**
	 * @see com.anji.activationFunction.ActivationFunctionStrategy#getMaxValue()
	 */
	public double getMaxValue() {
		return 1.0;
	}

	/**
	 * @see com.anji.activationFunction.ActivationFunctionStrategy#getMinValue()
	 */
	public double getMinValue() {
		return -1.0;
	}

	/**
	 * @see com.anji.activationFunction.ActivationFunctionStrategy#cost()
	 */
	public long cost() {
		return 42;
	}
}


text:
package org.ohdsi.webapi.cohortcharacterization.converter;

import org.ohdsi.webapi.cohortcharacterization.dto.CcExportDTO;
import org.springframework.stereotype.Component;

@Component
public class CcToCcExportDTOConverter extends BaseCcToCcExportDTOConverter<CcExportDTO> {

  @Override
  protected CcExportDTO createResultObject() {
    return new CcExportDTO();
  }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.networknt</groupId>
    <artifactId>ac</artifactId>
    <packaging>jar</packaging>
    <name>ac</name>
    <version>1.0.0</version>

    <properties>
        <java.version>11</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.main.class>com.networknt.server.Server</project.main.class>
        <version.light-4j>2.0.16-SNAPSHOT</version.light-4j>
        <version.jackson>2.10.4</version.jackson>
        <version.slf4j>1.7.25</version.slf4j>
        <version.jose4j>0.6.3</version.jose4j>
        <version.logback>1.2.3</version.logback>
        <version.junit>4.12</version.junit>
        <version.undertow>2.1.3.Final</version.undertow>
        <version.json-schema-validator>1.0.29</version.json-schema-validator>
        <version.fastscanner>2.18.1</version.fastscanner>

        <versions.maven-version>2.4</versions.maven-version>
        <version.javadoc-packagelist-plugin>1.0.0</version.javadoc-packagelist-plugin>
        <version.maven-javadoc>3.1.0</version.maven-javadoc>
        <version.maven-jar>3.1.2</version.maven-jar>
        <version.maven-shade>3.2.1</version.maven-shade>
        <version.maven-compiler>3.8.1</version.maven-compiler>
        <version.maven-deploy>2.8.2</version.maven-deploy>
        <version.exec-maven>1.6.0</version.exec-maven>
        <version.maven-surefire>2.22.2</version.maven-surefire>
        <version.maven-source>3.1.0</version.maven-source>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>config</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>utility</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>security</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>client</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>audit</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>info</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>health</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>status</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>exception</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>body</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>dump</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>mask</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>metrics</artifactId>
            <version>${version.light-4j}</version>
        </dependency>

        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>handler</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>sanitizer</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>traceability</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>correlation</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>service</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>registry</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>balance</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>cluster</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>consul</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>decryptor</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>server</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>json-schema-validator</artifactId>
            <version>${version.json-schema-validator}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>openapi-parser</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>openapi-meta</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>openapi-security</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>openapi-validator</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.networknt</groupId>
            <artifactId>specification</artifactId>
            <version>${version.light-4j}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${version.logback}</version>
        </dependency>
        <dependency>
            <groupId>io.undertow</groupId>
            <artifactId>undertow-core</artifactId>
            <version>${version.undertow}</version>
        </dependency>
        <dependency>
            <groupId>io.github.lukehutch</groupId>
            <artifactId>fast-classpath-scanner</artifactId>
            <version>${version.fastscanner}</version>
        </dependency>

        <!-- Test Dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${version.junit}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <defaultGoal>install</defaultGoal>
        <directory>target</directory>
        <finalName>${project.artifactId}-${project.version}</finalName>
        <plugins>
            <plugin>
                <groupId>com.networknt</groupId>
                <artifactId>javadoc-packagelist-maven-plugin</artifactId>
                <version>${version.javadoc-packagelist-plugin}</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>gen-package-list</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${version.maven-compiler}</version>
                <configuration>
                    <release>${java.version}</release>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>versions-maven-plugin</artifactId>
                <version>${versions.maven-version}</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${version.maven-surefire}</version>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-junit47</artifactId>
                        <version>${version.maven-surefire}</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>${version.maven-jar}</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>${project.main.class}</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>

        <pluginManagement>
            <plugins>
                <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>
                                            org.apache.maven.plugins
                                        </groupId>
                                        <artifactId>
                                            maven-compiler-plugin
                                        </artifactId>
                                        <versionRange>
                                            [3.3,)
                                        </versionRange>
                                        <goals>
                                            <goal>compile</goal>
                                            <goal>testCompile</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore></ignore>
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>

    </build>

    <repositories>
        <repository>
            <id>sonatype-snapshots</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

    <profiles>
        <profile>
            <id>release</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-shade-plugin</artifactId>
                        <version>${version.maven-shade}</version>
                        <executions>
                            <execution>
                                <phase>package</phase>
                                <goals>
                                    <goal>shade</goal>
                                </goals>
                                <configuration>
                                    <dependencyReducedPomLocation>${project.build.directory}/dependency-reduced-pom.xml</dependencyReducedPomLocation>
                                    <filters>
                                        <filter>
                                            <artifact>*:*</artifact>
                                            <excludes>
                                                <exclude>META-INF/*.SF</exclude>
                                                <exclude>META-INF/*.DSA</exclude>
                                                <exclude>META-INF/*.RSA</exclude>
                                            </excludes>
                                        </filter>
                                    </filters>
                                    <transformers>
                                        <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                                    </transformers>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-source-plugin</artifactId>
                        <version>${version.maven-source}</version>
                        <executions>
                            <execution>
                                <id>attach-sources</id>
                                <goals>
                                    <goal>jar</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-javadoc-plugin</artifactId>
                        <version>${version.maven-javadoc}</version>
                        <executions>
                            <execution>
                                <id>attach-javadocs</id>
                                <goals>
                                    <goal>jar</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
                        <version>${version.exec-maven}</version>
                        <configuration>
                            <executable>java</executable>
                            <arguments>
                                <argument>-jar</argument>
                                <argument>${project.build.directory}/${project.build.finalName}.${project.packaging}</argument>
                            </arguments>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>debug</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <java.debug.argument>-Xdebug</java.debug.argument>
                <java.debug.agent>-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n</java.debug.agent>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
                        <version>${version.exec-maven}</version>
                        <configuration>
                            <workingDirectory>${project.build.directory}</workingDirectory>
                            <executable>java</executable>
                            <arguments>
                                <argument>-cp</argument>
                                <classpath />
                                <argument>${java.debug.argument}</argument>
                                <argument>${java.debug.agent}</argument>
                                <argument>${project.main.class}</argument>
                            </arguments>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
(function() {
  'use strict';

  angular.module('myApp')
    .factory('sampleService', SampleService)
    .factory('dummyService', DummyService);

  function SampleService($http, $q, dummyService) {
    var service = {
      foo: 'bar',
      bar: bar,
      baz: baz,
      getData: getData,
      getResults: getResults,
      useAnotherMethod: useAnotherMethod
    };

    return service;

    function bar() {
      service.foo = 'baz';
    }

    function baz() {
      return dummyService.someMethod();
    }

    function getData() {
      return $http.get('/api/something')
        .success(function(result) {
          return result;
        })
        .error(function(reason) {
          return $q.reject(reason);
        });
    }

    function getResults(index) {
      var result = [1, 2, 3, 4, 5],
          resultLen = result.length;
      var deferred = $q.defer();

      if (index >= 0 && index < result.length) {
        deferred.resolve(result[index]);
      }

      deferred.reject('Do not exist');

      return deferred.promise;
    }

    function useAnotherMethod() {
      return dummyService.anotherMethod().then(function(result) {
        return result;
      });
    }
  }

  SampleService.$inject = ['$http', '$q', 'dummyService'];

  function DummyService($q) {
    var service = {
      someMethod: someMethod,
      anotherMethod: anotherMethod
    };

    return service;

    function someMethod() {
      return 'bla';
    }

    function anotherMethod() {
      var deferred = $q.defer();

      deferred.resolve([1, 2, 3]);

      return deferred.promise;
    }
  }

  DummyService.$inject = ['$q'];
}());


text:
layout: post
title: "AI Inside"
posturl: http://www.commitstrip.com/en/2017/06/07/ai-inside/
tags:
- Comics
- Fun
---

{% include post_info_header.md %}

"I knew it. It's just 'IFs'"

<!--more-->
{% include post_info_footer.md %}


text:
%% TODO: Need to remove this routine.
function fns_region_write(rgnfile,rgn)
%
% This routine write the region information to the HDF5 file
%
% rgnfile The output region file.
% rgn The region of interest data structure.

% @author Hung Dang, July 13, 2010

% Write the description of stored data to the output file
hdf5write(rgnfile,'/region/info',rgn.info);

% Write the locations matrix to the /region/locations dataset
hdf5write(rgnfile,'/region/locations',rgn.locations,'WriteMode', ...
          'append');

% Write the gridlocs matrix  to the /region/gridlocs dataset
hdf5write(rgnfile,'/region/gridlocs',rgn.gridlocs,'WriteMode', ...
          'append');

% Write the voxel_sizes vector to the /region/voxel_sizes dataset
hdf5write(rgnfile,'/region/voxel_sizes',rgn.voxel_sizes, ...
          'WriteMode','append');

% Write the node_sizes vector  to the /region/node_sizes dataset
hdf5write(rgnfile,'/region/node_sizes',rgn.node_sizes,'WriteMode', ...
          'append');

% Write the status vector  to the /region/status dataset
hdf5write(rgnfile,'/region/status',rgn.status,'WriteMode', ...
          'append');

% Write the values vector  to the /region/status dataset
hdf5write(rgnfile,'/region/values',rgn.values,'WriteMode', ...
          'append');


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using OpenRiaServices.DomainServices.Client.Test;
using DataTests.AdventureWorks.LTS;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DescriptionAttribute = Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute;

namespace OpenRiaServices.Controls.DomainServices.Test
{
    /// <summary>
    /// Tests that the <see cref="CollectionViewConverter"/> can convert
    /// values properly.
    /// </summary>
    [TestClass]
    public class CollectionViewConverterTests
    {
        private static readonly CollectionViewConverter Converter = new CollectionViewConverter();

        [TestMethod]
        [Description("The ConvertBack method should throw a NotImplementedException")]
        public void ConvertBackIsNotImplemented()
        {
            ExceptionHelper.ExpectException<NotImplementedException>(() => Converter.ConvertBack(null, null, null, CultureInfo.CurrentCulture));
        }

        [TestMethod]
        [Description("An array of products should be reported as an enumerable entity type (using the HasElementType code path)")]
        public void ProductArrayIsEnumerableEntityType()
        {
            IEnumerable<Product> products = new Product[0];

            Type entityType;
            Assert.IsTrue(CollectionViewConverter.IsEnumerableEntityType(products.GetType(), out entityType));
            Assert.AreEqual<Type>(typeof(Product), entityType);
        }

        [TestMethod]
        [Description("A list of products should be reported as an enumerable entity type (using the IsGenericType code path)")]
        public void ProductListIsEnumerableEntityType()
        {
            IEnumerable<Product> products = new List<Product>();

            Type entityType;
            Assert.IsTrue(CollectionViewConverter.IsEnumerableEntityType(products.GetType(), out entityType));
            Assert.AreEqual<Type>(typeof(Product), entityType);
        }

        [TestMethod]
        [Description("The designer uses surrogate types to represent lists.  Mimic that behavior and ensure the type is an enumerable entity type.")]
        public void DesignInstanceListIsEnumerableEntityType()
        {
            IEnumerable<Product> products = new DesignInstanceListOfProducts();

            Type entityType;
            Assert.IsTrue(CollectionViewConverter.IsEnumerableEntityType(products.GetType(), out entityType));
            Assert.AreEqual<Type>(typeof(Product), entityType);
        }

        [TestMethod]
        [Description("A product array should get converted to a collection view")]
        public void CanConvertProductArrayToCollectionView()
        {
            Product first = new Product();
            Product second = new Product();
            IEnumerable<Product> products = new Product[] { first, second };

            object view = Converter.Convert(products, null, null, CultureInfo.CurrentCulture);
            Assert.IsInstanceOfType(view, typeof(PagedEntityCollectionView<Product>));
            Assert.IsTrue(products.SequenceEqual((PagedEntityCollectionView<Product>)view));
        }

        [TestMethod]
        [Description("A product list should get converted to a collection view")]
        public void CanConvertProductListToCollectionView()
        {
            Product first = new Product();
            Product second = new Product();
            IEnumerable<Product> products = new List<Product> { first, second };

            object view = Converter.Convert(products, null, null, CultureInfo.CurrentCulture);
            Assert.IsInstanceOfType(view, typeof(PagedEntityCollectionView<Product>));
            Assert.IsTrue(products.SequenceEqual((IEnumerable<Product>)view));
        }

        [TestMethod]
        [Description("A string array should not get reported as an enumerable entity type")]
        public void StringArrayIsNotEnumerableEntityType()
        {
            IEnumerable<string> strings = new string[0];

            Type entityType;
            Assert.IsFalse(CollectionViewConverter.IsEnumerableEntityType(strings.GetType(), out entityType));
            Assert.IsNull(entityType);
        }

        [TestMethod]
        [Description("A string list should not get reported as an enumerable entity type")]
        public void StringListIsNotEnumerableEntityType()
        {
            IEnumerable<string> strings = new List<string>();

            Type entityType;
            Assert.IsFalse(CollectionViewConverter.IsEnumerableEntityType(strings.GetType(), out entityType));
            Assert.IsNull(entityType);
        }

        [TestMethod]
        [Description("A string array should not get converted, and it should be returned as-is")]
        public void CannotConvertStringArrayToCollectionView()
        {
            IEnumerable<string> strings = new string[0];
            Assert.AreSame(strings, Converter.Convert(strings, null, null, CultureInfo.CurrentCulture));
        }

        [TestMethod]
        [Description("A string list should not get converted, and it should be returned as-is")]
        public void CannotConvertStringListToCollectionView()
        {
            IEnumerable<string> strings = new List<string>();
            Assert.AreSame(strings, Converter.Convert(strings, null, null, CultureInfo.CurrentCulture));
        }

        [TestMethod]
        [Description("A null value should be returned as null")]
        public void ConvertingNullReturnsNull()
        {
            Assert.IsNull(Converter.Convert(null, null, null, CultureInfo.CurrentCulture));
        }

        [TestMethod]
        [Description("Converting an ICollectionView will return the value as-is")]
        public void ConvertingICollectionViewReturnsValue()
        {
            ICollectionView view = new DomainDataSource().DataView;
            Assert.AreSame(view, Converter.Convert(view, null, null, CultureInfo.CurrentCulture));
        }

        [TestMethod]
        [Description("ICollectionViewFactory is supported, calling CreateView to construct the ICollectionView")]
        public void ConvertingICollectionViewFactoryCallsCreateView()
        {
            bool createViewCalled = false;
            ICollectionView view = new DomainDataSource().DataView;

            MockCollectionViewFactory factory = new MockCollectionViewFactory(() =>
                {
                    createViewCalled = true;
                    return view;
                });

            Assert.AreSame(view, Converter.Convert(factory, null, null, CultureInfo.CurrentCulture));
            Assert.IsTrue(createViewCalled);
        }

        #region Mocks

        private class MockCollectionViewFactory : ICollectionViewFactory
        {
            private readonly Func<ICollectionView> _createViewCallback;

            public MockCollectionViewFactory(Func<ICollectionView> createViewCallback)
            {
                this._createViewCallback = createViewCallback;
            }

            public ICollectionView CreateView()
            {
                return this._createViewCallback();
            }
        }

        private class DesignInstanceListOfProducts : List<Product>
        {
        }

        #endregion
    }
}


text:
namespace ClojSharp.Core.Forms
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using ClojSharp.Core.Language;

    public class Str : BaseForm
    {
        public override int RequiredArity { get { return 0; } }

        public override bool VariableArity { get { return true; } }

        public override object EvaluateForm(IContext context, IList<object> arguments)
        {
            string result = string.Empty;

            foreach (var argument in arguments)
                if (argument != null)
                    result += argument.ToString();

            return result;
        }
    }
}


text:
import { Attachment24 } from "../../";

export = Attachment24;


text:
#!/bin/bash

# /************************************************************************/
# /*                                                                      */
# /* Package:  CrkTools                                                   */
# /* Module:   send-corsika-mail.sh                                       */
# /*                                                                      */
# /************************************************************************/
# /* Authors:  Hernán Asorey                                              */
# /* e-mail:   asoreyh@cab.cnea.gov.ar                                    */
# /*                                                                      */
# /************************************************************************/
# /* Comments: Check simulation status in a non-cluster array of nodes    */
# /*           To be used in combination with check-corsika.sh            */
# /*                                                                      */
# /************************************************************************/
# /*
#
# Copyright 2013
# Hernán Asorey
# Lab DPR (CAB-CNEA), Argentina
# Grupo Halley (UIS), Colombia
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#    1. Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#
#    2. Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL LAB DPR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are
# those of the authors and should not be interpreted as representing
# official policies, either expressed or implied, of Lab DPR.
#
# */
# /************************************************************************/
VERSION="v3r0";
send=false
mail=""
wdir=""
prjt=""
bin=/work/asoreyh/bin
log=""

showhelp() {
  echo; echo -e "$0 version $VERSION"; echo "USAGE: $0 -w <wdir> -p <project base name> -s <mail direction>"; echo
}

while getopts ':w:p:s:' opt; do
  case $opt in
    w)
      wdir=$OPTARG
      echo -e "#  Working dir              = $wdir"
      ;;
    p)
      prjt=$OPTARG
      echo -e "#  Project base name        = $prjt"
      ;;
    s)
      send=true
      mail=$OPTARG
      echo -e "#  Status will be mailed to = $mail"
      ;;
    ?)
      showhelp
      exit 1
  esac
done

if [ "X$wdir" == "X" ]; then
  echo; echo -e "ERROR: You have to set the working directory"
  showhelp
  exit 1;
fi

if [ "X$prjt" == "X" ]; then
  echo; echo -e "ERROR: You have to provide a project base name"
  showhelp
  exit 1;
fi

if $send; then
  if [ "X$mail" == "X" ]; then
    echo; echo -e "ERROR: You have to provide a valid mail direction"
    showhelp
    exit 1;
  fi
fi

log=${prjt}
rm ${wdir}/${log}.log
echo >> ${wdir}/${log}.log
echo>> ${wdir}/${log}.log
date >> ${wdir}/${log}.log
echo >> ${wdir}/${log}.log

## NOTE: This is valid only for Bariloche server structure. Please modify according to your
##       architecture

for i in $(seq 3 6); do
sc=$(ssh asoreyh@10.73.22.10${i} screen -ls | grep $prjt | wc -l)
echo "tep"${i}": "$sc" sessions running" >> ${wdir}/${log}.log
tot=$[tot+sc]
done
echo "TOTAL: "$tot" sessions running" >> ${wdir}/${log}.log

run=0
for i in $(seq 3 6); do
  tmp=$(echo $wdir | sed -e "s/tep6/tep${i}/")
  ls -1 $tmp/run*.sh >> ${wdir}/${log}.log
  b=$(ls -1 $tmp/run*.sh | wc -l)
  run=$[run+b]
done;
echo >> ${wdir}/${log}.log
echo "ALL INSTANCES RUNNING: $run." >> ${wdir}/${log}.log
echo >> ${wdir}/${log}.log
echo >> ${wdir}/${log}.log

# ll=0
# ul=50
# for i in $(seq $ll $ul); do
#   printf -v a "%02d" $i
#   [ -f ${wdir}/${prjt}${a}/inject ] && check-corsika.sh -w $wdir -p ${prjt}
# done >> ${wdir}/${log}.log

$bin/check-corsika.sh -w $wdir -p ${prjt} >> ${wdir}/${log}.log

echo >> ${wdir}/${log}.log
# van=`for i in $(seq 1 ${ul}); do printf -v a "%02d" $i; [ -f ${wdir}/${prjt}${a}/inject ] && head -1 $wdir/${prjt}${a}/inject; done | awk '{t+=$3/60}END{printf("\n%d minutos (%.1f horas)\n\n", t, t/60)}'`
# echo $van >> ${wdir}/${log}.log
total=`for i in $wdir/${prjt}*; do head -1 $i/inject; done | awk '{t+=$3/60}END{printf("\n%d minutos (%.1f horas)\n\n", t, t/60)}'`
echo $total >> ${wdir}/${log}.log
echo >> ${wdir}/${log}.log

if $send; then
  cat ${wdir}/${log}.log | mail -s "CORSIKA simulation ${log}" $mail; sleep 1
else
  cat ${wdir}/${log}.log
fi


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is part of the DITA Open Toolkit project.

Copyright 2004, 2005 IBM Corporation

See the accompanying LICENSE file for applicable license.
-->

<strings xml:lang="uk-ua">        <!-- Ukrainian -->

<!-- various labels (not author controlled) -->
<str name="Figure">Мал.</str>
<str name="Table">Табл.</str>
<str name="Next topic">Наступна тема</str>
<str name="Previous topic">Попередня тема</str>
<str name="Parent topic">На рівень догори</str>
<str name="Required cleanup">Необхідна чистка</str>
<str name="Draft comment">Зауваження у чорновому варіанті</str>
<str name="Option">Опція</str>
<str name="Description">Опис</str>
<str name="Optional">За бажанням</str>
<str name="Required">Обов'язково</str>
<str name="Skip visual syntax diagram">Пропустити візуальну синтаксичну діаграму</str>
<str name="Read syntax diagram">Прочитати синтаксичну діаграму</str>
<str name="Start of change">Початок зміни</str>
<str name="End of change">Кінець зміни</str>
<str name="Index">Покажчик</str>
<str name="Special characters">Спеціальні символи</str>
<str name="Numerics">Числа</str>
<str name="End notes">Кінцеві примітки</str>
<str name="Artwork">Оформлення</str>
<str name="Syntax">Синтаксис</str>
<str name="Type">Тип</str>
<str name="Value">Значення</str>
<!-- Text that goes before a link to a topic -->
<str name="intro-to-topic-link"></str>

<!-- peril notice labels -->
<str name="Note">Примітка</str>
<str name="Notes">Примітки</str>
<str name="Tip">Порада</str>
<str name="Fastpath">Короткий шлях</str>
<str name="Important">Важливо</str>
<str name="Attention">Увага</str>
<str name="Caution">ОБЕРЕЖНО</str>
<str name="Danger">НЕБЕЗПЕЧНО</str>
<str name="Remember">Запам'ятайте</str>
<str name="Restriction">Обмеження</str>
<str name="Warning">Попередження</str>

<!-- default title text for section level generated sections -->
<str name="Contents">Зміст</str>
<str name="Related concepts">Споріднені ідеї</str>
<str name="Related tasks">Пов'язані задачі</str>
<str name="Related reference">Відповідні посилання</str>
<str name="Related information">Інформація з пов'язаних питань</str>

<str name="Prerequisite">Необхідна вимога</str>
<str name="Prerequisites">Необхідні вимоги</str>
<str name="or">або</str>
<str name="figure-number-separator"> </str>

<!--Task section labels -->
<str name="task_context">Інформація про завдання</str>
<str name="task_example">Приклад</str>
<str name="task_postreq">Подальші дії</str>
<str name="task_prereq">Підготовчі дії</str>
<str name="task_procedure">Процедура</str>
<str name="task_procedure_unordered">Процедура</str>
<str name="task_results">Результати</str>

<str name="Copyright">Copyright</str>

<!-- Symbols -->
<str name="OpenQuote">"</str>
<str name="CloseQuote">"</str>
<str name="ColonSymbol">:</str>

</strings>


text:
layout: page
title: Rain Archive Group Trade Fair
date: 2016-05-24
author: Angela Simon
tags: weekly links, java
status: published
summary: Nam porta dictum quam, eu volutpat.
banner: images/banner/office-01.jpg
booking:
  startDate: 10/13/2018
  endDate: 10/14/2018
  ctyhocn: PITCAHX
  groupCode: RAGTF
published: true
---
Mauris elementum ligula non luctus maximus. Aenean cursus orci est, sed ornare velit pharetra non. Maecenas vitae ex non eros consequat interdum quis id metus. Mauris bibendum efficitur tristique. Donec luctus consectetur arcu vel mattis. Nulla posuere porttitor nisl, in sagittis neque mattis sit amet. Vivamus pulvinar mauris vel sapien fermentum malesuada. Donec maximus, lacus gravida faucibus ultrices, urna lectus fermentum lectus, id convallis quam enim a quam. Nam lobortis tincidunt semper. Pellentesque orci sapien, malesuada ac interdum vel, fermentum ut nisi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Maecenas consectetur vestibulum dui, eu posuere velit vestibulum at. In hac habitasse platea dictumst. Etiam magna libero, pharetra ac consequat a, elementum quis eros.

* Cras id lacus eu ex finibus imperdiet
* Phasellus porttitor arcu eget commodo porttitor.

Donec tempor ex ligula, nec cursus mi volutpat suscipit. In nec erat at nunc malesuada imperdiet eu eget metus. Vestibulum ac quam finibus, mollis nisl nec, facilisis ante. Quisque euismod nibh suscipit dui aliquam ullamcorper. Aliquam quis dapibus metus. Donec eget elit in nulla venenatis sodales. Nam egestas enim in accumsan ornare. Nulla consectetur pharetra accumsan. Quisque non congue justo. Nullam ullamcorper a urna sed efficitur. Nulla et libero velit. Quisque eget tortor fringilla, dapibus dui quis, laoreet purus. Donec nec ultricies tellus. Integer volutpat finibus nisl.


text:
package org.jruyi.osgi.log;

import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

final class LogServiceImpl implements LogService {

	private final Logger m_logger;

	LogServiceImpl(Bundle bundle) {
		m_logger = LoggerFactory.getLogger(bundle.getSymbolicName());
	}

	@Override
	public void log(int level, String message) {
		switch (level) {
		case LogService.LOG_DEBUG:
			m_logger.debug(message);
			break;
		case LogService.LOG_INFO:
			m_logger.info(message);
			break;
		case LogService.LOG_WARNING:
			m_logger.warn(message);
			break;
		case LogService.LOG_ERROR:
			m_logger.error(message);
			break;
		}
	}

	@Override
	public void log(int level, String message, Throwable t) {
		switch (level) {
		case LogService.LOG_DEBUG:
			m_logger.debug(message, t);
			break;
		case LogService.LOG_INFO:
			m_logger.info(message, t);
			break;
		case LogService.LOG_WARNING:
			m_logger.warn(message, t);
			break;
		case LogService.LOG_ERROR:
			m_logger.error(message, t);
			break;
		}
	}

	@Override
	public void log(ServiceReference sr, int level, String message) {
		log(level, message);
	}

	@Override
	public void log(ServiceReference sr, int level, String message, Throwable t) {
		log(level, message, t);
	}
}


text:
package com.gs.fw.finder;

public interface TemporalTransactionalDomainList<E> extends DomainList<E>
{
    public void insertAll();

    public void cascadeInsertAll();

    public void bulkInsertAll();

    public void terminateAll();

    public void purgeAll();
}


text:
using Diversion.Reflection;
using System;
using Mono.Cecil;
using Mono.Cecil.Rocks;
using System.Diagnostics;

namespace Diversion.Cecil
{
    public class ReflectionInfoFactory : IReflectionInfoFactory
    {
        public ITypeReference GetReference(Mono.Cecil.TypeReference type)
        {
            return type is GenericParameter ? new GenericParameterInfo(this, type as GenericParameter) : new TypeReference(this, type);
        }

        public ITypeReference GetReference(TypeDefinition type)
        {
            return new TypeReference(this, type);
        }

        public IMemberInfo GetInfo(MethodDefinition member)
        {
            return (member.IsConstructor) ? (IMemberInfo)new ConstructorInfo(this, member) : new MethodInfo(this, member);
        }

        public IMemberInfo GetInfo(FieldDefinition member)
        {
            return new FieldInfo(this, member);
        }

        public IMemberInfo GetInfo(PropertyDefinition member)
        {
            return new PropertyInfo(this, member);
        }

        public IMemberInfo GetInfo(EventDefinition member)
        {
            return new EventInfo(this, member);
        }

        public ITypeInfo GetInfo(TypeDefinition type)
        {
            return new TypeInfo(this, type);
        }

        public IAttributeInfo GetInfo(CustomAttribute attribute)
        {
            return new AttributeInfo(this, attribute);
        }

        public IParameterInfo GetInfo(ParameterDefinition parameter)
        {
            return new ParameterInfo(this, parameter);
        }
    }

}


text:
import MangleItController from './mangle-it-controller';

export default class MangleItDirective implements ng.IDirective {

    public static factory(): MangleItDirective {
        return new MangleItDirective();
    }

    public controller = MangleItController;
    public controllerAs = 'mangleItCtrl';
    public replace = true;
    public restrict = 'E';
    public templateUrl = 'templates/mangle-it.html';

}


text:
<?php

final class HeraldCallWebhookAction extends HeraldAction {

  const ACTIONCONST = 'webhook';
  const DO_WEBHOOK = 'do.call-webhook';

  public function getHeraldActionName() {
    return pht('Call webhooks');
  }

  public function getActionGroupKey() {
    return HeraldUtilityActionGroup::ACTIONGROUPKEY;
  }

  public function supportsObject($object) {
    if (!$this->getAdapter()->supportsWebhooks()) {
      return false;
    }

    return true;
  }

  public function supportsRuleType($rule_type) {
    return ($rule_type !== HeraldRuleTypeConfig::RULE_TYPE_PERSONAL);
  }

  public function applyEffect($object, HeraldEffect $effect) {
    $adapter = $this->getAdapter();
    $rule = $effect->getRule();
    $target = $effect->getTarget();

    foreach ($target as $webhook_phid) {
      $adapter->queueWebhook($webhook_phid, $rule->getPHID());
    }

    $this->logEffect(self::DO_WEBHOOK, $target);
  }

  public function getHeraldActionStandardType() {
    return self::STANDARD_PHID_LIST;
  }

  protected function getActionEffectMap() {
    return array(
      self::DO_WEBHOOK => array(
        'icon' => 'fa-cloud-upload',
        'color' => 'green',
        'name' => pht('Called Webhooks'),
      ),
    );
  }

  public function renderActionDescription($value) {
    return pht('Call webhooks: %s.', $this->renderHandleList($value));
  }

  protected function renderActionEffectDescription($type, $data) {
    return pht('Called webhooks: %s.', $this->renderHandleList($data));
  }

  protected function getDatasource() {
    return new HeraldWebhookDatasource();
  }

  public function getPHIDsAffectedByAction(HeraldActionRecord $record) {
    return $record->getTarget();
  }

}


text:
module Dugway
  module Drops
    class ProductDrop < BaseDrop
      def created_at
        Time.parse(source['created_at'])
      end

      def price
        nil # price is deprecated in favor of default_price
      end

      def min_price
        @min_price ||= price_min_max.first
      end

      def max_price
        @max_price ||= price_min_max.last
      end

      def variable_pricing
        @variable_pricing ||= min_price != max_price
      end

      def has_default_option
        @has_default_option ||= options.size == 1 && option.name.downcase == 'default'
      end

      def option
        @option ||= options.blank? ? nil : options.first
      end

      def options
        @options ||= source['options'].each_with_index.map { |o,i| ProductOptionDrop.new(o.update('position' => i+1, 'product' => self)) }
      end

      def options_in_stock
        @options_in_stock ||= options.reject { |o| o.sold_out }
      end

      def shipping
        @shipping ||= source['shipping'].present? ? source['shipping'].map { |o| ShippingOptionDrop.new(o.update('product' => self)) } : []
      end

      def image
        @image ||= images.blank? ? nil : images.first
      end

      def images
        @images ||= source['images'].present? ? source['images'].map { |image| ImageDrop.new(image) } : []
      end

      def image_count
        @image_count ||= images.size
      end

      def previous_product
        @previous_product ||= begin
          if previous_product = store.previous_product(permalink)
            ProductDrop.new(previous_product)
          else
            nil
          end
        end
      end

      def next_product
        @next_product ||= begin
          if next_product = store.next_product(permalink)
            ProductDrop.new(next_product)
          else
            nil
          end
        end
      end

      def edit_url
        'http://bigcartel.com'
      end

      def categories
        @categories ||= source['categories'].map { |c| CategoryDrop.new(c) } rescue []
      end

      def artists
        @artists ||= source['artists'].map { |a| ArtistDrop.new(a) } rescue []
      end

      def css_class
        @css_class ||= begin
          c = 'product'
          c += ' sold' if status == 'sold-out'
          c += ' soon' if status == 'coming-soon'
          c += ' sale' if on_sale
          c
        end
      end

      private

      def price_min_max
        @price_min_max ||= options.collect(&:price).uniq.minmax
      end
    end
  end
end


text:
schema: default
title: >-
  Politician Data: Vatican City — Pontifical Commission
organization: EveryPolitician
notes: >-
  Data on the people within the Pontifical Commission legislature of Vatican City.
resources:
  - name: How To Use The Data
    url: 'http://docs.everypolitician.org/use_the_data.html'
    format: info
  - name: View on EveryPolitician
    url: 'http://everypolitician.org/vatican-city/'
    format: info
  - name: All Data as Popolo JSON
    url: >-
      https://cdn.rawgit.com/everypolitician/everypolitician-data/e08159b2aa5d49c8a9d1e8e0ece4c3926c56cf9a/data/Vatican_City/Pontifical_Commission/ep-popolo-v1.0.json
    format: json
  - name: >-
      2016–: From 2016-06-11
    url: >-
      https://cdn.rawgit.com/everypolitician/everypolitician-data/554a6cb306153130ac5558e4c015471d63e57cb7/data/Vatican_City/Pontifical_Commission/term-2016.csv
    format: csv
  - name: >-
      2011–2016: 2011-10-01 to 2016-06-10
    url: >-
      https://cdn.rawgit.com/everypolitician/everypolitician-data/554a6cb306153130ac5558e4c015471d63e57cb7/data/Vatican_City/Pontifical_Commission/term-2011.csv
    format: csv
  - name: Python
    url: 'https://github.com/everypolitician/everypolitician-popolo-python'
    format: library
  - name: Ruby
    url: 'https://github.com/everypolitician/everypolitician-popolo'
    format: library
  - name: R
    url: 'https://github.com/ajparsons/everypoliticianR'
    format: library
last_modified: 2019-03-08T10:52:00
license: ''
category:
  - Vatican City
  - People
  - Groups & Bodies
maintainer: EveryPolitician
maintainer_email: team@everypolitician.org
more_info: http://docs.everypolitician.org
---


text:
package edu.upenn.library.xmlaminar.solr;

import edu.upenn.library.xmlaminar.cli.Command;
import edu.upenn.library.xmlaminar.cli.CommandFactory;
import edu.upenn.library.xmlaminar.cli.CommandType;
import edu.upenn.library.xmlaminar.cli.Flags;
import edu.upenn.library.xmlaminar.cli.InitCommand;
import edu.upenn.library.xmlaminar.cli.InputCommandFactory;
import edu.upenn.library.xmlaminar.parallel.QueueSourceXMLFilter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.regex.Pattern;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrServer;
import org.xml.sax.InputSource;
import org.xml.sax.XMLFilter;

/**
 *
 * @author magibney
 */
class SolrPostCommandFactory extends CommandFactory {

    static {
        registerCommandFactory(new SolrPostCommandFactory());
    }

    @Override
    public Command newCommand(boolean first, boolean last) {
        return new SplitCommand(first, last);
    }

    @Override
    public String getKey() {
        return "solrpost";
    }

    @Override
    public CommandFactory getConfiguringXMLFilter(boolean first, InitCommand inputBase, CommandType maxType) {
        return null;
    }

    private static class SplitCommand implements Command<InputCommandFactory.InputCommand> {

        private static final int DEFAULT_QUEUE_SIZE = 10;
        private static final Collection<String> QUEUE_SIZE_ARG = Arrays.asList("queue-size");
        private int queueSize;
        private final OptionSpec<Integer> threadCountSpec;
        private static final int DEFAULT_THREAD_COUNT = 4;
        private static final Collection<String> THREAD_COUNT_ARG = Arrays.asList("thread-count");
        private int threadCount;
        private final OptionSpec<String> solrUrlSpec;
        private static final Collection<String> SOLR_URL_ARG = Arrays.asList("solr-url");
        private String solrURL;
        private final OptionSpec<Integer> queueSizeSpec;

        private final OptionSpec verboseSpec;
        private final OptionSpec helpSpec;

        protected final OptionParser parser;

        protected final boolean first;
        protected final boolean last;

        private InputCommandFactory.InputCommand inputBase;

        public SplitCommand(boolean first, boolean last) {
            this.first = first;
            this.last = last;
            parser = new OptionParser();
            solrUrlSpec = parser.acceptsAll(SOLR_URL_ARG, "solr update server url")
                    .withRequiredArg().ofType(String.class);
            queueSizeSpec = parser.acceptsAll(QUEUE_SIZE_ARG, "solr update queue size")
                    .withRequiredArg().ofType(Integer.class).defaultsTo(DEFAULT_QUEUE_SIZE);
            threadCountSpec = parser.acceptsAll(THREAD_COUNT_ARG, "solr update thread count")
                    .withRequiredArg().ofType(Integer.class).defaultsTo(DEFAULT_THREAD_COUNT);
            verboseSpec = parser.acceptsAll(Flags.VERBOSE_ARG, "be more verbose");
            helpSpec = parser.acceptsAll(Flags.HELP_ARG, "show help").forHelp();
        }

        protected boolean init(OptionSet options, InputCommandFactory.InputCommand inputBase) {
            this.inputBase = inputBase;
            if (options.has(helpSpec)) {
                return false;
            }
            solrURL = options.valueOf(solrUrlSpec);
            threadCount = options.valueOf(threadCountSpec);
            queueSize = options.valueOf(queueSizeSpec);
            return true;
        }

        private static final boolean EXPECT_INPUT = true;

        @Override
        public XMLFilter getXMLFilter(ArgFactory arf, InputCommandFactory.InputCommand inputBase, CommandType maxType) {
            if (!init(parser.parse(arf.getArgs(parser.recognizedOptions().keySet())), inputBase)) {
                return null;
            }
            CommandFactory.conditionalInit(first, inputBase, EXPECT_INPUT);
            SAXSolrPoster ssp = new SAXSolrPoster();
            ssp.setServer(new ConcurrentUpdateSolrServer(solrURL, queueSize, threadCount));
            if (first && inputBase.getFilesFrom() != null) {
                ssp.setInputType(QueueSourceXMLFilter.InputType.indirect);
                if (inputBase.getDelim() != null) {
                    ssp.setDelimiterPattern(Pattern.compile(inputBase.getDelim(), Pattern.LITERAL));
                }
            }
            return ssp;
        }

        @Override
        public CommandType getCommandType() {
            return CommandType.PASS_THROUGH;
        }

        @Override
        public File getInputBase() {
            return inputBase.getInputBase();
        }

        @Override
        public boolean handlesOutput() {
            return true;
        }

        @Override
        public InitCommand inputHandler() {
            return inputBase;
        }

        @Override
        public InputSource getInput() throws FileNotFoundException {
            if (first) {
                return inputBase.getInput();
            } else {
                return null;
            }
        }

        @Override
        public void printHelpOn(OutputStream out) {
            try {
                parser.printHelpOn(out);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

}


text:
<?php

namespace ickx\fw2\compression\traits;

/**
 * 圧縮クラス特性
 *
 * @category	Flywheel2
 * @package		compression
 * @author		wakaba <wakabadou@gmail.com>
 * @license		http://opensource.org/licenses/MIT The MIT License MIT
 * @varsion		2.0.0
 */
trait CompressionTrait {
	/**
	 * 文字列を圧縮した後に、指定されたエンコードに変換してから返します。
	 *
	 * @param	string			$string	圧縮する文字列
	 * @param	string/callable	$encode	圧縮後に掛けるエンコード名 コールバック関数を指定した場合はそちらがコールバック関数でエンコードする
	 * @return	mixed			圧縮され指定されたエンコード変換後の文字列
	 */
	public static function CompressEncode ($string, $encode = null) {
		if ($encode === null) {
			return static::Compress($string);
		}
		if (is_callable($encode)) {
			return $encode(static::Compress($string));
		}
		$encode_func_list = static::GetEncodeFunction();
		if (!isset($encode_func_list[$encode][static::ENCODE])) {
			return static::Compress($string);
		}
		return $encode_func_list[$encode][static::ENCODE](static::Compress($string));
	}

	/**
	 * PHPの変数をシリアライズして圧縮します。
	 *
	 * @param	mixed			$var	PHPの変数
	 * @param	string/callable	$encode	圧縮後に掛けるエンコード名 コールバック関数を指定した場合はコールバック関数でエンコードする
	 * @return	mixed			圧縮され指定されたエンコード変換後の変数
	 */
	public static function CompressVariable ($var, $encode = null) {
		return static::CompressEncode(serialize($var), $encode);
	}

	/**
	 * バイナリを伸長した後に、指定されたエンコードで変換してから返します。
	 *
	 * @param	binary			$binary	圧縮されたバイナリ
	 * @param	string/callable	$decode	伸長後に掛けるデコーダ用エンコード名 コールバック関数を指定した場合はコールバック関数でデコードする
	 * @return	mixed			伸長されたバイナリ
	 */
	public static function UnCompressDecode ($binary, $decode = null) {
		if ($decode === null) {
			return static::UnCompress($binary);
		}
		if (is_callable($decode)) {
			return static::UnCompress($decode($binary));
		}
		$encode_func_list = static::GetEncodeFunction();
		if (!isset($encode_func_list[$decode][static::DECODE])) {
			return static::UnCompress($binary);
		}
		return static::UnCompress($encode_func_list[$decode][static::DECODE]($binary));
	}

	/**
	 * 指定されたエンコードでデコードしたのち、バイナリを伸長し、アンシリアライズしてPHPの変数として返します。
	 *
	 * @param	binary			$binary	圧縮されたバイナリ
	 * @param	string/callable	$decode	伸長後に掛けるデコーダ用エンコード名 コールバック関数を指定した場合はコールバック関数でデコードする
	 * @return	mixed			アンシリアライズされたPHP変数
	 */
	public static function UnCompressVariable ($string, $encode = null) {
		return unserialize(static::UnCompressDecode($string, $encode));
	}

	/**
	 * 指定されたエンコード名に紐付く、エンコーダー、デコーダーを返します。
	 *
	 * @return	array	指定されたエンコード名に紐付くエンコーダー、デコーダー
	 */
	public static function GetEncodeFunction () {
		return [
			static::ENCODE_BASE64	=> [
				static::ENCODE	=> 'base64_encode',
				static::DECODE	=> 'base64_decode',
			],
		];
	}
}


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

/// <summary>
/// Summary description for GeoOption
/// </summary>
public class GeoOption
{
    public string backgroundColor;
    public string defaultColor;
    public string displayMode;
    public string domain;
    public string resolution;

    public GeoOption(string backgroundColor = "white", string defaultColor = "#267114", string displayMode = "auto", string domain = null, string resolution = "countries")
    {
        this.backgroundColor = backgroundColor;
        this.defaultColor = defaultColor;
        this.displayMode = displayMode;
        this.domain = domain;
        this.resolution = resolution;
    }
}


text:
/* $Id: UIWizardExportAppDefs.h $ */
/** @file
 * VBox Qt GUI - UIWizardExportAppDefs class declaration.
 */

/*
 * Copyright (C) 2009-2012 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */

#ifndef __UIWizardExportAppDefs_h__
#define __UIWizardExportAppDefs_h__

/* Global includes: */
#include <QMetaType>
#include <QPointer>
#include <QListWidget>

/* Local includes: */
#include "UIApplianceExportEditorWidget.h"

/* Typedefs: */
enum StorageType { Filesystem, SunCloud, S3 };
Q_DECLARE_METATYPE(StorageType);

/* Typedefs: */
typedef QPointer<UIApplianceExportEditorWidget> ExportAppliancePointer;
Q_DECLARE_METATYPE(ExportAppliancePointer);

class VMListWidgetItem : public QListWidgetItem
{
public:

    VMListWidgetItem(QPixmap &pixIcon, QString &strText, QString strUuid, bool fInSaveState, QListWidget *pParent)
        : QListWidgetItem(pixIcon, strText, pParent)
        , m_strUuid(strUuid)
        , m_fInSaveState(fInSaveState)
    {
    }

    bool operator<(const QListWidgetItem &other) const
    {
        return text().toLower() < other.text().toLower();
    }

    QString uuid() { return m_strUuid; }
    bool isInSaveState() { return m_fInSaveState; }

private:

    QString m_strUuid;
    bool m_fInSaveState;
};

#endif /* __UIWizardExportAppDefs_h__ */


text:
require 'byebug/command'

module Byebug
  #
  # Edit a file from byebug's prompt.
  #
  class EditCommand < Command
    self.allow_in_control = true

    def regexp
      /^\s* ed(?:it)? (?:\s+(\S+))? \s*$/x
    end

    def execute
      if !@match[1]
        return errmsg(pr('edit.errors.state')) unless @state.file
        file = @state.file
        line = @state.line if @state.line
      elsif (@pos_match = /([^:]+)[:]([0-9]+)/.match(@match[1]))
        file, line = @pos_match.captures
      else
        file = @match[1]
      end

      editor = ENV['EDITOR'] || 'vim'
      file = File.expand_path(file)

      unless File.exist?(file)
        return errmsg(pr('edit.errors.not_exist', file: file))
      end
      unless File.readable?(file)
        return errmsg(pr('edit.errors.not_readable', file: file))
      end

      cmd = line ? "#{editor} +#{line} #{file}" : "#{editor} #{file}"

      system(cmd)
    end

    def description
      <<-EOD
        edit[ file:lineno] Edit specified files.

        With no argument, edits file containing most recent line listed. Editing
        targets can also be specified to start editing at a specific line in a
        specific file.
      EOD
    end
  end
end


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

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Medium Text"
            android:id="@+id/text" android:layout_gravity="center_horizontal"/>
</LinearLayout>


text:
package shortcuttool.gui.viewpanel;

import static shortcuttool.gui.toolbar.Toolbar.TRANSPARENT;

import java.awt.Color;
import java.awt.Font;
import java.awt.LayoutManager;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.List;

import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;

import shortcuttool.gui.toolbar.Toolbar;
import shortcuttool.util.function.Action;

public class GenericButton extends JPanel {

	public static final int IDLE = 0;
	public static final int MOUSEOVER = 1;
	public static final int PRESSED = 2;

	public static final Color[] BG = new Color[]{
			Toolbar.TRANSPARENT,
			new Color(1f, 1f, 1f, 0.3f),
			new Color(1f, 1f, 1f, 0.5f)
	};

	public int state = IDLE;

	public JLabel iconLabel;
	public JLabel label;

	public int index;

	public GenericButton(int index, LayoutManager layout, Icon icon, String text, Font font, Color fg, Action action){
		super(layout);
		this.index = index;

		setOpaque(true);
		setBackground(TRANSPARENT);

		iconLabel = new JLabel();
		iconLabel.setOpaque(true);
		iconLabel.setBackground(TRANSPARENT);
		iconLabel.setIcon(icon);

		add(iconLabel);

		label = new JLabel(text);
		label.setOpaque(true);
		label.setBackground(TRANSPARENT);
		label.setFont(font);
		label.setForeground(fg);

		add(label);

		addMouseListener(new MouseAdapter(){
			@Override
			public void mouseClicked(MouseEvent e){
				if(e.getButton() == MouseEvent.BUTTON1)action.call();
			}

			@Override
			public void mousePressed(MouseEvent e){
				setState(PRESSED);
			}

			@Override
			public void mouseReleased(MouseEvent e){
				setState(MOUSEOVER);
			}
		});

		addMouseMotionListener(new MouseMotionAdapter(){
			@Override
			public void mouseMoved(MouseEvent e){
				setState(MOUSEOVER);
			}
		});
	}

	public void setState(int state){
		if(state != this.state){
			if(state == IDLE){
				setBackground(BG[state]);
			}else if(state == MOUSEOVER || state == PRESSED){
				List<GenericButton> buttons = ((Card)getParent()).buttons;
				for(int i = 0; i < buttons.size(); i ++){
					if(i == index){
						setBackground(BG[state]);
					}else{
						buttons.get(i).setState(IDLE);
					}
				}

				ViewPanel.window.repaint();
			}

			this.state = state;
		}
	}

}


text:
<!doctype html>

    <meta charset="UTF-8">
    <title>Xin Demo: Simple</title>

    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />

    <link rel="stylesheet" type="text/css" href="../../css/xin.css" />
    <link rel="stylesheet" type="text/css" href="../../bower_components/naked/css/naked.css" />
    <link rel="stylesheet" type="text/css" href="../../bower_components/naked/css/naked.min.css" />
    <link rel="stylesheet" type="text/css" href="init.css" />

Wahyu Taufik

Profile

About

Contact


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

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.Iterator;

import org.jdbi.v3.core.generic.GenericTypes;
import org.jdbi.v3.core.statement.PreparedBatch;
import org.jdbi.v3.sqlobject.SingleValue;
import org.jdbi.v3.sqlobject.internal.ParameterUtil;

/**
 * Binds the annotated argument as a named parameter, and as a positional parameter.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
@SqlStatementCustomizingAnnotation(Bind.Factory.class)
public @interface Bind
{
    /**
     * The name to bind the argument to. If omitted, the name of the annotated parameter is used. It is an
     * error to omit the name when there is no parameter naming information in your class files.
     *
     * @return the name to which the argument will be bound.
     */
    String value() default "";

    class Factory implements SqlStatementCustomizerFactory {
        @Override
        public SqlStatementCustomizer createForParameter(Annotation annotation,
                                                         Class<?> sqlObjectType,
                                                         Method method,
                                                         Parameter param,
                                                         int index,
                                                         Object arg) {
            Bind b = (Bind) annotation;
            String nameFromAnnotation = b == null ? "" : b.value();
            final String name = ParameterUtil.getParameterName(b, nameFromAnnotation, param);

            return stmt -> {
                Type type = param.getParameterizedType();

                if (stmt instanceof PreparedBatch && !param.isAnnotationPresent(SingleValue.class)) {
                    Class<?> erasedType = GenericTypes.getErasedType(type);
                    if (Iterable.class.isAssignableFrom(erasedType)) {
                        type = GenericTypes.findGenericParameter(type, Iterable.class).get();
                    }
                    else if (Iterator.class.isAssignableFrom(erasedType)) {
                        type = GenericTypes.findGenericParameter(type, Iterator.class).get();
                    }
                    else if (GenericTypes.isArray(type)) {
                        type = ((Class<?>) type).getComponentType();
                    }
                }

                stmt.bindByType(index, arg, type);
                stmt.bindByType(name, arg, type);
            };
        }
    }
}


text:
package com.hubspot.singularity.hooks;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.Inject;
import com.hubspot.baragon.models.BaragonRequest;
import com.hubspot.baragon.models.BaragonRequestState;
import com.hubspot.baragon.models.BaragonResponse;
import com.hubspot.baragon.models.BaragonService;
import com.hubspot.baragon.models.BaragonServiceState;
import com.hubspot.baragon.models.RequestAction;
import com.hubspot.baragon.models.UpstreamInfo;
import com.hubspot.mesos.JavaUtils;
import com.hubspot.singularity.LoadBalancerRequestState;
import com.hubspot.singularity.LoadBalancerRequestType.LoadBalancerRequestId;
import com.hubspot.singularity.LoadBalancerUpstream;
import com.hubspot.singularity.Singularity;
import com.hubspot.singularity.SingularityDeploy;
import com.hubspot.singularity.SingularityLoadBalancerUpdate;
import com.hubspot.singularity.SingularityLoadBalancerUpdate.LoadBalancerMethod;
import com.hubspot.singularity.SingularityRequest;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.helpers.MesosProtosUtils;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.ListenableFuture;
import com.ning.http.client.Request;
import com.ning.http.client.Response;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BaragonLoadBalancerClientImpl extends LoadBalancerClient {
  private static final Logger LOG = LoggerFactory.getLogger(LoadBalancerClient.class);

  private static final String CONTENT_TYPE_JSON = "application/json";
  private static final String HEADER_CONTENT_TYPE = "Content-Type";
  private static final String ALREADY_ENQUEUED_ERROR =
    "is already enqueued with different parameters";

  private final String loadBalancerUri;
  private final Optional<Map<String, String>> loadBalancerQueryParams;
  private final long loadBalancerTimeoutMillis;

  private final AsyncHttpClient httpClient;
  private final ObjectMapper objectMapper;
  private final boolean preResolveUpstreamDNS;
  private final Set<String> skipDNSPreResolutionForRequests;

  private static final String OPERATION_URI = "%s/%s";

  @Inject
  public BaragonLoadBalancerClientImpl(
    SingularityConfiguration configuration,
    @Singularity ObjectMapper objectMapper,
    AsyncHttpClient httpClient,
    MesosProtosUtils mesosProtosUtils
  ) {
    super(configuration, mesosProtosUtils);
    this.httpClient = httpClient;
    this.objectMapper = objectMapper;
    this.loadBalancerUri = configuration.getLoadBalancerUri();
    this.loadBalancerTimeoutMillis = configuration.getLoadBalancerRequestTimeoutMillis();
    this.loadBalancerQueryParams = configuration.getLoadBalancerQueryParams();
    this.skipDNSPreResolutionForRequests =
      configuration.getSkipDNSPreResolutionForRequests();
    this.preResolveUpstreamDNS = configuration.isPreResolveUpstreamDNS();
  }

  public boolean isEnabled() {
    return true;
  }

  private String getStateUriFromRequestUri() {
    return loadBalancerUri.replace("request", "state");
  }

  private String getLoadBalancerStateUri(String singularityRequestId) {
    return String.format(
      OPERATION_URI,
      getStateUriFromRequestUri(),
      singularityRequestId
    );
  }

  public List<LoadBalancerUpstream> getUpstreamsForRequest(String singularityRequestId)
    throws IOException, InterruptedException, ExecutionException, TimeoutException {
    final String loadBalancerStateUri = getLoadBalancerStateUri(singularityRequestId);
    final BoundRequestBuilder requestBuilder = httpClient.prepareGet(
      loadBalancerStateUri
    );
    final Request request = requestBuilder.build();
    LOG.debug(
      "Sending load balancer {} request for {} to {}",
      request.getMethod(),
      singularityRequestId,
      request.getUrl()
    );
    ListenableFuture<Response> future = httpClient.executeRequest(request);
    Response response = future.get(loadBalancerTimeoutMillis, TimeUnit.MILLISECONDS);
    LOG.debug(
      "Load balancer {} request {} returned with code {}",
      request.getMethod(),
      singularityRequestId,
      response.getStatusCode()
    );
    Optional<BaragonServiceState> maybeBaragonServiceState = Optional.ofNullable(
      objectMapper.readValue(response.getResponseBodyAsBytes(), BaragonServiceState.class)
    );
    return maybeBaragonServiceState
      .map(BaragonServiceState::getUpstreams)
      .orElse(Collections.emptyList())
      .stream()
      .map(LoadBalancerUpstream::fromBaragonUpstream)
      .collect(Collectors.toList());
  }

  private String getLoadBalancerUri(LoadBalancerRequestId loadBalancerRequestId) {
    return String.format(OPERATION_URI, loadBalancerUri, loadBalancerRequestId);
  }

  private void addAllQueryParams(
    BoundRequestBuilder boundRequestBuilder,
    Map<String, String> queryParams
  ) {
    for (Map.Entry<String, String> entry : queryParams.entrySet()) {
      boundRequestBuilder.addQueryParam(entry.getKey(), entry.getValue());
    }
  }

  @Override
  public SingularityLoadBalancerUpdate getState(
    LoadBalancerRequestId loadBalancerRequestId
  ) {
    final String uri = getLoadBalancerUri(loadBalancerRequestId);

    final BoundRequestBuilder requestBuilder = httpClient.prepareGet(uri);

    loadBalancerQueryParams.ifPresent(
      stringStringMap -> addAllQueryParams(requestBuilder, stringStringMap)
    );

    return sendRequestWrapper(
      loadBalancerRequestId,
      LoadBalancerMethod.CHECK_STATE,
      requestBuilder.build(),
      BaragonRequestState.UNKNOWN
    );
  }

  private BaragonResponse readResponse(Response response) {
    try {
      return objectMapper.readValue(
        response.getResponseBodyAsBytes(),
        BaragonResponse.class
      );
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  private SingularityLoadBalancerUpdate sendRequestWrapper(
    LoadBalancerRequestId loadBalancerRequestId,
    LoadBalancerMethod method,
    Request request,
    BaragonRequestState onFailure
  ) {
    final long start = System.currentTimeMillis();
    final LoadBalancerUpdateHolder result = sendRequest(
      loadBalancerRequestId,
      request,
      onFailure
    );

    if (
      (
        method != LoadBalancerMethod.CHECK_STATE &&
        method != LoadBalancerMethod.PRE_ENQUEUE
      ) &&
      result.state == BaragonRequestState.FAILED &&
      result.message.orElse("").contains(ALREADY_ENQUEUED_ERROR)
    ) {
      LOG.info(
        "Baragon request {} already in the queue, will fetch current state instead",
        loadBalancerRequestId
      );
      return sendRequestWrapper(
        loadBalancerRequestId,
        LoadBalancerMethod.CHECK_STATE,
        request,
        onFailure
      );
    }

    LOG.debug(
      "LB {} request {} had result {} after {}",
      request.getMethod(),
      loadBalancerRequestId,
      result,
      JavaUtils.duration(start)
    );
    return new SingularityLoadBalancerUpdate(
      LoadBalancerRequestState.fromBaragonRequestState(result.state),
      loadBalancerRequestId,
      result.message,
      start,
      method,
      Optional.of(request.getUrl())
    );
  }

  private static class LoadBalancerUpdateHolder {
    private final Optional<String> message;
    private final BaragonRequestState state;

    public LoadBalancerUpdateHolder(BaragonRequestState state, Optional<String> message) {
      this.message = message;
      this.state = state;
    }

    @Override
    public String toString() {
      return "LoadBalancerUpdateHolder [message=" + message + ", state=" + state + "]";
    }
  }

  private SingularityLoadBalancerUpdate sendLoadBalancerRequest(
    LoadBalancerRequestId loadBalancerRequestId,
    BaragonRequest loadBalancerRequest,
    LoadBalancerMethod method
  ) {
    try {
      LOG.trace("Preparing to send request {}", loadBalancerRequest);

      final BoundRequestBuilder requestBuilder = httpClient
        .preparePost(loadBalancerUri)
        .addHeader(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON)
        .setBody(objectMapper.writeValueAsBytes(loadBalancerRequest));

      loadBalancerQueryParams.ifPresent(
        stringStringMap -> addAllQueryParams(requestBuilder, stringStringMap)
      );

      return sendRequestWrapper(
        loadBalancerRequestId,
        method,
        requestBuilder.build(),
        BaragonRequestState.FAILED
      );
    } catch (IOException e) {
      return new SingularityLoadBalancerUpdate(
        LoadBalancerRequestState.UNKNOWN,
        loadBalancerRequestId,
        Optional.of(e.getMessage()),
        System.currentTimeMillis(),
        method,
        Optional.of(loadBalancerUri)
      );
    }
  }

  private LoadBalancerUpdateHolder sendRequest(
    LoadBalancerRequestId loadBalancerRequestId,
    Request request,
    BaragonRequestState onFailure
  ) {
    try {
      LOG.trace(
        "Sending LB {} request for {} to {}",
        request.getMethod(),
        loadBalancerRequestId,
        request.getUrl()
      );

      ListenableFuture<Response> future = httpClient.executeRequest(request);

      Response response = future.get(loadBalancerTimeoutMillis, TimeUnit.MILLISECONDS);

      LOG.trace(
        "LB {} request {} returned with code {}",
        request.getMethod(),
        loadBalancerRequestId,
        response.getStatusCode()
      );

      if (response.getStatusCode() == 504) {
        return new LoadBalancerUpdateHolder(
          BaragonRequestState.UNKNOWN,
          Optional.of(
            String.format(
              "LB %s request %s timed out",
              request.getMethod(),
              loadBalancerRequestId
            )
          )
        );
      } else if (!JavaUtils.isHttpSuccess(response.getStatusCode())) {
        String body = response.getResponseBody();
        LOG.info(
          "LB {} request {} failed with code {}: {}",
          request.getMethod(),
          loadBalancerRequestId,
          response.getStatusCode(),
          body
        );
        return new LoadBalancerUpdateHolder(
          onFailure,
          Optional.of(
            String.format("Response status code %s: %s", response.getStatusCode(), body)
          )
        );
      }

      BaragonResponse lbResponse = readResponse(response);

      return new LoadBalancerUpdateHolder(
        lbResponse.getLoadBalancerState(),
        lbResponse.getMessage().toJavaUtil()
      );
    } catch (TimeoutException te) {
      LOG.trace(
        "LB {} request {} timed out after waiting {}",
        request.getMethod(),
        loadBalancerRequestId,
        JavaUtils.durationFromMillis(loadBalancerTimeoutMillis)
      );
      return new LoadBalancerUpdateHolder(
        BaragonRequestState.UNKNOWN,
        Optional.of(
          String.format(
            "Timed out after %s",
            JavaUtils.durationFromMillis(loadBalancerTimeoutMillis)
          )
        )
      );
    } catch (Throwable t) {
      LOG.error(
        "LB {} request {} to {} threw error",
        request.getMethod(),
        loadBalancerRequestId,
        request.getUrl(),
        t
      );
      return new LoadBalancerUpdateHolder(
        BaragonRequestState.UNKNOWN,
        Optional.of(
          String.format("Exception %s - %s", t.getClass().getSimpleName(), t.getMessage())
        )
      );
    }
  }

  @Override
  public SingularityLoadBalancerUpdate makeAndSendLoadBalancerRequest(
    LoadBalancerRequestId loadBalancerRequestId,
    List<LoadBalancerUpstream> addUpstreams,
    List<LoadBalancerUpstream> removeUpstreams,
    SingularityDeploy deploy,
    SingularityRequest request
  ) {
    final List<String> serviceOwners = request
      .getOwners()
      .orElse(Collections.emptyList());
    final Set<String> loadBalancerGroups = deploy
      .getLoadBalancerGroups()
      .orElse(Collections.emptySet());

    boolean enableDNSPreResolution;
    if (skipDNSPreResolutionForRequests.contains(request.getId())) {
      enableDNSPreResolution = false;
    } else {
      enableDNSPreResolution = preResolveUpstreamDNS;
    }

    final BaragonService lbService = new BaragonService(
      deploy.getLoadBalancerServiceIdOverride().orElse(request.getId()),
      serviceOwners,
      deploy.getServiceBasePath().get(),
      deploy.getLoadBalancerAdditionalRoutes().orElse(Collections.<String>emptyList()),
      loadBalancerGroups,
      deploy.getLoadBalancerOptions().orElse(null),
      com.google.common.base.Optional.fromJavaUtil(deploy.getLoadBalancerTemplate()),
      deploy.getLoadBalancerDomains().orElse(Collections.emptySet()),
      com.google.common.base.Optional.absent(),
      Collections.emptySet(),
      enableDNSPreResolution
    );
    final BaragonRequest loadBalancerRequest = new BaragonRequest(
      loadBalancerRequestId.toString(),
      lbService,
      addUpstreams
        .stream()
        .map(u -> singularityToBaragonUpstream(u, loadBalancerRequestId.toString()))
        .collect(Collectors.toList()),
      removeUpstreams
        .stream()
        .map(u -> singularityToBaragonUpstream(u, loadBalancerRequestId.toString()))
        .collect(Collectors.toList()),
      Collections.emptyList(),
      com.google.common.base.Optional.absent(),
      com.google.common.base.Optional.of(RequestAction.UPDATE),
      false,
      false,
      false,
      true
    );
    return sendLoadBalancerRequest(
      loadBalancerRequestId,
      loadBalancerRequest,
      LoadBalancerMethod.ENQUEUE
    );
  }

  private UpstreamInfo singularityToBaragonUpstream(
    LoadBalancerUpstream loadBalancerUpstream,
    String loadBalancerRequestId
  ) {
    return new UpstreamInfo(
      loadBalancerUpstream.getUpstream(),
      com.google.common.base.Optional.of(loadBalancerRequestId),
      com.google.common.base.Optional.fromJavaUtil(loadBalancerUpstream.getRackId()),
      com.google.common.base.Optional.absent(),
      com.google.common.base.Optional.of(loadBalancerUpstream.getGroup())
    );
  }

  @Override
  public SingularityLoadBalancerUpdate cancel(
    LoadBalancerRequestId loadBalancerRequestId
  ) {
    final String uri = getLoadBalancerUri(loadBalancerRequestId);

    final BoundRequestBuilder requestBuilder = httpClient.prepareDelete(uri);

    loadBalancerQueryParams.ifPresent(
      stringStringMap -> addAllQueryParams(requestBuilder, stringStringMap)
    );

    return sendRequestWrapper(
      loadBalancerRequestId,
      LoadBalancerMethod.CANCEL,
      requestBuilder.build(),
      BaragonRequestState.UNKNOWN
    );
  }

  @Override
  public SingularityLoadBalancerUpdate delete(
    LoadBalancerRequestId loadBalancerRequestId,
    String requestId,
    Set<String> loadBalancerGroups,
    String serviceBasePath
  ) {
    final BaragonService lbService = new BaragonService(
      requestId,
      Collections.emptyList(),
      serviceBasePath,
      loadBalancerGroups,
      Collections.emptyMap()
    );
    final BaragonRequest loadBalancerRequest = new BaragonRequest(
      loadBalancerRequestId.toString(),
      lbService,
      Collections.emptyList(),
      Collections.emptyList(),
      Collections.emptyList(),
      com.google.common.base.Optional.absent(),
      com.google.common.base.Optional.of(RequestAction.DELETE)
    );

    return sendLoadBalancerRequest(
      loadBalancerRequestId,
      loadBalancerRequest,
      LoadBalancerMethod.DELETE
    );
  }
}


text:
package com.hazelcast.jet.sql.impl.connector.test;

import com.hazelcast.jet.core.DAG;
import com.hazelcast.jet.core.ProcessorMetaSupplier;
import com.hazelcast.jet.core.Vertex;
import com.hazelcast.jet.impl.pipeline.transform.BatchSourceTransform;
import com.hazelcast.jet.pipeline.BatchSource;
import com.hazelcast.jet.pipeline.test.TestSources;
import com.hazelcast.jet.sql.impl.connector.SqlConnector;
import com.hazelcast.jet.sql.impl.ExpressionUtil;
import com.hazelcast.jet.sql.impl.schema.JetTable;
import com.hazelcast.jet.sql.impl.schema.MappingField;
import com.hazelcast.spi.impl.NodeEngine;
import com.hazelcast.sql.SqlService;
import com.hazelcast.sql.impl.QueryException;
import com.hazelcast.sql.impl.expression.Expression;
import com.hazelcast.sql.impl.schema.ConstantTableStatistics;
import com.hazelcast.sql.impl.schema.Table;
import com.hazelcast.sql.impl.schema.TableField;
import com.hazelcast.sql.impl.type.QueryDataType;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Map;

import static com.hazelcast.jet.impl.util.Util.toList;
import static java.time.ZoneOffset.UTC;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;

/**
 * A SQL source yielding a single row with all supported types.
 */
public class AllTypesSqlConnector implements SqlConnector {

    public static final String TYPE_NAME = "AllTypes";

    private static final List<MappingField> FIELD_LIST = asList(
            new MappingField("string", QueryDataType.VARCHAR),
            new MappingField("boolean", QueryDataType.BOOLEAN),
            new MappingField("byte", QueryDataType.TINYINT),
            new MappingField("short", QueryDataType.SMALLINT),
            new MappingField("int", QueryDataType.INT),
            new MappingField("long", QueryDataType.BIGINT),
            new MappingField("float", QueryDataType.REAL),
            new MappingField("double", QueryDataType.DOUBLE),
            new MappingField("decimal", QueryDataType.DECIMAL),
            new MappingField("time", QueryDataType.TIME),
            new MappingField("date", QueryDataType.DATE),
            new MappingField("timestamp", QueryDataType.TIMESTAMP),
            new MappingField("timestampTz", QueryDataType.TIMESTAMP_WITH_TZ_OFFSET_DATE_TIME),
            new MappingField("object", QueryDataType.OBJECT)

    );
    private static final List<TableField> FIELD_LIST2 = toList(FIELD_LIST, f -> new TableField(f.name(), f.type(), false));

    private static final Object[] VALUES = new Object[]{
            "string",
            true,
            (byte) 127,
            (short) 32767,
            2147483647,
            9223372036854775807L,
            1234567890.1f,
            123451234567890.1,
            new BigDecimal("9223372036854775.123"),
            LocalTime.of(12, 23, 34),
            LocalDate.of(2020, 4, 15),
            LocalDateTime.of(2020, 4, 15, 12, 23, 34, 1_000_000),
            OffsetDateTime.of(2020, 4, 15, 12, 23, 34, 200_000_000, UTC),
            null
    };

    public static void create(SqlService sqlService, String tableName) {
        sqlService.execute("CREATE MAPPING " + tableName + " TYPE " + AllTypesSqlConnector.TYPE_NAME);
    }

    @Override
    public String typeName() {
        return TYPE_NAME;
    }

    @Override
    public boolean isStream() {
        return false;
    }

    @Nonnull
    @Override
    public List<MappingField> resolveAndValidateFields(
            @Nonnull NodeEngine nodeEngine,
            @Nonnull Map<String, String> options,
            @Nonnull List<MappingField> userFields
    ) {
        if (userFields.size() > 0) {
            throw QueryException.error("Don't specify external fields, they are fixed");
        }
        return FIELD_LIST;
    }

    @Nonnull
    @Override
    public Table createTable(
            @Nonnull NodeEngine nodeEngine,
            @Nonnull String schemaName,
            @Nonnull String tableName,
            @Nonnull Map<String, String> options,
            @Nonnull List<MappingField> resolvedFields
    ) {
        return new AllTypesTable(this, schemaName, tableName);
    }

    @Override
    public boolean supportsFullScanReader() {
        return true;
    }

    @Nonnull
    @Override
    public Vertex fullScanReader(
            @Nonnull DAG dag,
            @Nonnull Table table,
            @Nullable Expression<Boolean> predicate,
            @Nonnull List<Expression<?>> projection
    ) {
        Object[] row = ExpressionUtil.evaluate(predicate, projection, VALUES);
        BatchSource<Object[]> source = TestSources.items(singletonList(row));
        ProcessorMetaSupplier pms = ((BatchSourceTransform<Object[]>) source).metaSupplier;
        return dag.newVertex(table.toString(), pms);
    }

    public static class AllTypesTable extends JetTable {

        public AllTypesTable(
                @Nonnull SqlConnector sqlConnector,
                @Nonnull String schemaName,
                @Nonnull String name
        ) {
            super(sqlConnector, FIELD_LIST2, schemaName, name, new ConstantTableStatistics(1));
        }

        @Override
        public String toString() {
            return "AllTypes" + "[" + getSchemaName() + "." + getSqlName() + "]";
        }
    }
}


text:
/*
Сей класс решает, что делать с полученным сообщением
*/

using System;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Router.Models;
using Router.Models.Data;
using Router.Models.Entities;

/*
Сейчас выбор робота закахркожен, позже будет получать из списка
*/

namespace Router.Services
{
  // Метод поиска комманд в сообщениях
  public static class MessageExtensions
  {
    public static bool HasCommand(this Message msg, string cm) => msg.Commands.Any(command => command == cm);
  }

  public class MessageProcessor
  {
    private IData data;
    private readonly ServerConnector _serverConnector;
    private readonly RobotConnector _robotConnector;
    // Комманды сообщений (см Протокол)
    private const string Mail = "<MAIL>";
    private const string Init = "<INIT>";

    public MessageProcessor(IData d)
    {
      data = d;
      _robotConnector = new RobotConnector(data);
      _serverConnector = new ServerConnector();
    }

    public async Task Proccess(string str)
    {
      /*
        Мы знаем, что все сообщения должны заканчиваться на <EOF>
      */
      string json = str.Replace("<EOF>", "");
      /*
        Также мы знаем, что все сообщения имеют общий вид
      */
      Message message = JsonConvert.DeserializeObject<Message>(json);

      /* сообщение от робота. Его нужно отправить в на Сервер в любом случае.
         Также мы должны начать отправлять эхо запросы и сделить, онлайн ли наш Робот или нет.
      */
      if (message.From != "0")
      {
        // Пока что все запросы идут на Сервер, в будущем будет не так.
        await _serverConnector.SendMessageToServer(message);

        // запрос на получение всех сообщений
        if (message.HasCommand(Mail))
        {
          Robot robot = data.Robots.First(x => x.Number == message.From);
          var messages = data.Messages.Where(x => x.Robot.RobotID == robot.RobotID);
          Console.WriteLine("We have {0} messages",messages.Count());
          foreach (var mes in messages.ToList())
          {
            await _robotConnector.SendMessageToRobotTask(mes.Text);
            await data.RemoveAsync(mes);
          }
        }

        /*
          Запускаем таску, которая шлет эхо сообщения на робота и
          останавливается, если при передаче происзошла ошибка.
        */
        Task heartBeating = Task.Factory.StartNew(() =>
        {
          _robotConnector.SendEcho(message.From).Start();
        });
      }
      // сообщение от сервера.
      else
      {
        // сначала найдем этого Робота в базе.
        Robot robot = data.Robots.First(x => x.Number == message.To);
        // если онлайн и сообщение до него дошло, то ОК.
        if (robot.isOnline && await _robotConnector.SendMessageToRobotTask(JsonConvert.SerializeObject(message)))
        {

        }
        // если Робот сейчас не online или недоступен, то сохраним сообщение в БД
        else
        {
          await data.AddAsync(new StoredMessage()
          {
            Robot = robot,
            Text = message.Text
          });
        }
      }
    }

  }
}


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

		<meta http-equiv="Content-type" content="text/html; charset=utf-8">
		<title>Namespace: dom - documentation</title>

Namespace: dom

Ancestry: Scroller# » dom

						Scroller v1.1.0 documentation

Navigation

Overview

Summary

Details

						<input type="hidden" name="show_private" value="0">
						Hiding private elements
							(toggle)

						<input type="hidden" name="show_extended" value="1">
						Showing extended elements
							(toggle)

DOM elements used by the class instance

			Scroller: Copyright 2011-2012 Allan Jardine, all rights reserved

			Documentation generated by JSDoc 3 on
			8th Aug 2012 - 22:54
			with the DataTables template.


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content" >

     <TableLayout
         android:id="@+id/tableLayout1"
         android:layout_width="match_parent"
         android:layout_height="wrap_content" >

         <TableRow >

             <TextView
                 android:id="@+id/headline"
                 android:layout_width="0px"
                 android:layout_height="wrap_content"
                 android:layout_weight="0.8"
                 android:padding="10dp"
                 android:textSize="20dp"
                 android:textColor="#FFF"/>

             <ImageView
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_gravity="center_vertical|right"
                 android:layout_marginRight="6dp"
                 android:src="@drawable/ic_launcher" />
         </TableRow>
     </TableLayout>
 </LinearLayout>