text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.269
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Table.Properties {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("USB2.0 PC CAMERA")]
        public string VideoDevice {
            get {
                return ((string)(this["VideoDevice"]));
            }
            set {
                this["VideoDevice"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("USB2.0 MIC")]
        public string AudioDevice {
            get {
                return ((string)(this["AudioDevice"]));
            }
            set {
                this["AudioDevice"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("00:00:15")]
        public global::System.TimeSpan PressClipLength {
            get {
                return ((global::System.TimeSpan)(this["PressClipLength"]));
            }
            set {
                this["PressClipLength"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Research question")]
        public string ResearchQuestion {
            get {
                return ((string)(this["ResearchQuestion"]));
            }
            set {
                this["ResearchQuestion"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute(@"Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions Round one instructions ")]
        public string Round_1_Instructions {
            get {
                return ((string)(this["Round_1_Instructions"]));
            }
            set {
                this["Round_1_Instructions"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Round two instructions")]
        public string Round_2_Instructions {
            get {
                return ((string)(this["Round_2_Instructions"]));
            }
            set {
                this["Round_2_Instructions"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Round three instructions")]
        public string Round_3_Instructions {
            get {
                return ((string)(this["Round_3_Instructions"]));
            }
            set {
                this["Round_3_Instructions"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Round four instructions")]
        public string Round_4_Instructions {
            get {
                return ((string)(this["Round_4_Instructions"]));
            }
            set {
                this["Round_4_Instructions"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Round five instructions")]
        public string Round_5_Instructions {
            get {
                return ((string)(this["Round_5_Instructions"]));
            }
            set {
                this["Round_5_Instructions"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Round six instructions")]
        public string Round_6_Instructions {
            get {
                return ((string)(this["Round_6_Instructions"]));
            }
            set {
                this["Round_6_Instructions"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("00:00:10")]
        public global::System.TimeSpan Round_2_Time {
            get {
                return ((global::System.TimeSpan)(this["Round_2_Time"]));
            }
            set {
                this["Round_2_Time"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("00:00:10")]
        public global::System.TimeSpan Round_3_Time {
            get {
                return ((global::System.TimeSpan)(this["Round_3_Time"]));
            }
            set {
                this["Round_3_Time"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("00:00:10")]
        public global::System.TimeSpan Round_4_Time {
            get {
                return ((global::System.TimeSpan)(this["Round_4_Time"]));
            }
            set {
                this["Round_4_Time"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("00:00:10")]
        public global::System.TimeSpan Round_5_Time {
            get {
                return ((global::System.TimeSpan)(this["Round_5_Time"]));
            }
            set {
                this["Round_5_Time"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("00:00:10")]
        public global::System.TimeSpan Round_6_Time {
            get {
                return ((global::System.TimeSpan)(this["Round_6_Time"]));
            }
            set {
                this["Round_6_Time"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Video processing instructions")]
        public string Video_Processing_Instructions {
            get {
                return ((string)(this["Video_Processing_Instructions"]));
            }
            set {
                this["Video_Processing_Instructions"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Complete instructions")]
        public string Complete_Instructions {
            get {
                return ((string)(this["Complete_Instructions"]));
            }
            set {
                this["Complete_Instructions"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("238, 127, 0")]
        public global::System.Drawing.Color User0Colour {
            get {
                return ((global::System.Drawing.Color)(this["User0Colour"]));
            }
            set {
                this["User0Colour"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("64, 189, 185")]
        public global::System.Drawing.Color User1Colour {
            get {
                return ((global::System.Drawing.Color)(this["User1Colour"]));
            }
            set {
                this["User1Colour"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("122, 181, 29")]
        public global::System.Drawing.Color User2Colour {
            get {
                return ((global::System.Drawing.Color)(this["User2Colour"]));
            }
            set {
                this["User2Colour"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("226, 0, 122")]
        public global::System.Drawing.Color User3Colour {
            get {
                return ((global::System.Drawing.Color)(this["User3Colour"]));
            }
            set {
                this["User3Colour"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("00:00:10")]
        public global::System.TimeSpan Round_1_Time {
            get {
                return ((global::System.TimeSpan)(this["Round_1_Time"]));
            }
            set {
                this["Round_1_Time"] = value;
            }
        }
    }
}


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/loot/loot_schematic/shared_utensils_schematic.iff"
	result.attribute_template_id = -1
	result.stfName("craft_item_ingredients_n","utensils")

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

	return result

redpajama_set_name: RedPajamaGithub


text:
  If a man does what is good, let him do it again; let him delight
  in it: happiness is the outcome of good. 118


text:
module Gitcommand
  VERSION = "0.1.1"
end


text:
using FluentAssertions;
using FunctionalSharp.OptionTypes;
using TypescriptGeneration.Model;
using Xunit;

namespace TypescriptGeneration.Test
{
    public class InterfaceWritingTest
    {
        [Fact]
        public void WriteSimpleInterface()
        {
            var expectedResult =
@"interface TestInterface {
}
";
            var testInterface = new TypescriptInterface
            {
                Name = "TestInterface"
            };
            AssertThatWritingInterfaceGivesTheExpectedResult(expectedResult, testInterface);
        }

        [Fact]
        public void WriteInterfaceWithGenericsAndPropertiesAndFunctions()
        {
            var expectedResult =
@"interface TestInterface<T> {
    TestProperty: number;
    TestMethodGenericT<T>(): void;
    TestMethodNumber(): number;
}
";
            var tsInterface = new TypescriptInterface
            {
                Name = "TestInterface",
                GenricTypeParameters = new TypescriptGenericTypeParameters { new TypescriptGenericTypeParameter { Name = "T" } }
            };
            tsInterface.Content.Add(TestData.TestPropertyNumber);
            tsInterface.Content.Add(TestData.TestMethodWithGenericTParameter);
            tsInterface.Content.Add(TestData.TestMethodSignatureReturningNumber);

            AssertThatWritingInterfaceGivesTheExpectedResult(expectedResult, tsInterface);
        }

        [Fact]
        public void WriteInterfaceWithBaseInterface()
        {
            var expectedResult =
@"interface TestInterface extends BaseInterface {
}
";
            var testInterface = new TypescriptInterface
            {
                Name = "TestInterface",
                BaseType = new TypescriptInterfaceBaseTypes
                {
                    new TypescriptBaseInterface
                {
                    Name = "BaseInterface"
                }.ToTypescriptInterfaceBaseType()
                }
            };

            AssertThatWritingInterfaceGivesTheExpectedResult(expectedResult, testInterface);
        }

        [Fact]
        public void WriteInterfaceWithBaseClass()
        {
            var expectedResult =
@"interface TestInterface extends BaseClass {
}
";
            var testInterface = new TypescriptInterface
            {
                Name = "TestInterface",
                BaseType = new TypescriptInterfaceBaseTypes { new TypescriptBaseClass
                    {
                        Name = "BaseClass"
                    }
                }
            };

            AssertThatWritingInterfaceGivesTheExpectedResult(expectedResult, testInterface);
        }

        private static void AssertThatWritingInterfaceGivesTheExpectedResult(string expectedresult, TypescriptInterface tsInterface)
        {
            var writer = new TypescriptWriter();
            writer.WriteInterface(tsInterface);
            var result = writer.ToString();

            result.ShouldBeEquivalentTo(expectedresult);
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Plato - JavaScript Introspection</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">

  <link href="assets/css/vendor/bootstrap-3.0.0-wip.css" rel="stylesheet">
  <link href="assets/css/vendor/font-awesome.css" rel="stylesheet">
  <link href="assets/css/vendor/font-awesome-ie7.css" rel="stylesheet">
  <link href="assets/css/vendor/morris.css" rel="stylesheet">
  <link href="assets/css/plato.css" rel="stylesheet">
  <link href="assets/css/plato-overview.css" rel="stylesheet">

    Plato on Github

        Report Home

JavaScript Source Analysis

Summary

Total/Average Lines

62 / 62

Average Maintainability

71.33

Maintainability

Lines of code

Estimated errors in implementation

Lint errors

Files

        index.js

.


text:
1. [Setup guide] [setup]
2. [Technical documentation] [tech-docs]
3. [Table definition] [table-def]

All the above can be found on the [wiki] [wiki].

## Getting started with Hive

Once you have setup EmrEtlRunner to transform your SnowPlow data into a format optimized for querying in Hive, the next step is to query it. An introduction to getting started can be found in the [analytics section] [analysis].

[setup]: https://github.com/snowplow/snowplow/wiki/s3-hive-storage-setup
[tech-docs]: https://github.com/snowplow/snowplow/wiki/s3%20apache%20hive%20storage
[wiki]: https://github.com/snowplow/snowplow/wiki
[table-def]: https://github.com/snowplow/snowplow/blob/master/4-storage/hive-storage/table-def.q
[analysis]: https://github.com/snowplow/snowplow/tree/master/5-analytics/hive


text:
// Template Source: Enum.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;

/**
 * The Enum Role Assignment Schedule Instance Filter By Current User Options.
*/
public enum RoleAssignmentScheduleInstanceFilterByCurrentUserOptions
{
    /**
    * principal
    */
    PRINCIPAL,
    /**
    * unknown Future Value
    */
    UNKNOWN_FUTURE_VALUE,
    /**
    * For RoleAssignmentScheduleInstanceFilterByCurrentUserOptions values that were not expected from the service
    */
    UNEXPECTED_VALUE
}


text:
$packageName = 'regfromapp'
$url = 'http://www.nirsoft.net/utils/regfromapp.zip'
$checksum = '9895b295444b813971b5661b355960bb9bec2d69'
$checksumType = 'sha1'
$url64 = 'http://www.nirsoft.net/utils/regfromapp-x64.zip'
$checksum64 = '73b8de9b40733a3bd9b1009182ce9af15a3b1317'
$checksumType64 = 'sha1'
$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$installFile = Join-Path $toolsDir "$($packageName).exe"

Install-ChocolateyZipPackage -PackageName "$packageName" `
                             -Url "$url" `
                             -UnzipLocation "$toolsDir" `
                             -Url64bit "$url64" `
                             -Checksum "$checksum" `
                             -ChecksumType "$checksumType" `
                             -Checksum64 "$checksum64" `
                             -ChecksumType64 "$checksumType64"

Set-Content -Path ("$installFile.gui") `
            -Value $null


text:
extern __init void ks8695_map_io(void);
extern __init void ks8695_init_irq(void);
extern struct sys_timer ks8695_timer;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
  ~
  ~ 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.
  -->

<!--
    A comprehensive example of Hazelcast configuration with advanced network configuration.

    Hazelcast resolves configuration using the following approach:

    1. First is checks to see if the 'hazelcast.config' system property is set. If it is, then the value is used as the path.

       The config option can be set by adding the following to the java command: -Dhazelcast.config=path_to_the_hazelcast.xml.

       The value can be a normal file path, but can also be a classpath reference if it is prefixed with 'classpath:'.

    2. Otherwise it checks if there is a 'hazelcast.xml' in the working directory.

    3. After that it checks if there is a 'hazelcast.xml' in the root of the classpath.

    4. If a configuration cannot be found, Hazelcast will use the default hazelcast configuration
       'hazelcast-default.xml', which is included in the the Hazelcast jar
-->
<hazelcast xmlns="http://www.hazelcast.com/schema/config"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.hazelcast.com/schema/config
           http://www.hazelcast.com/schema/config/hazelcast-config-4.1.xsd">

    <import resource="hazelcast-fullconfig-without-network.xml"/>

    <advanced-network enabled="true">
        <join>
            <auto-detection enabled="false"/>
            <multicast enabled="true" loopbackModeEnabled="true">
                <multicast-group>1.2.3.4</multicast-group>
                <multicast-port>12345</multicast-port>
                <multicast-timeout-seconds>5</multicast-timeout-seconds>
                <multicast-time-to-live>10</multicast-time-to-live>
                <trusted-interfaces>
                    <interface>10.10.1.*</interface>
                    <interface>10.10.2.*</interface>
                </trusted-interfaces>
            </multicast>
            <tcp-ip enabled="false" connection-timeout-seconds="123">
                <required-member>dummy</required-member>
                <member>dummy1</member>
                <member>dummy2</member>
                <interface>127.0.0.10</interface>
                <members>dummy3,dummy4</members>
                <member-list>
                    <member>dummy5</member>
                    <member>dummy6</member>
                </member-list>
            </tcp-ip>
            <aws enabled="false">
                <access-key>my-access-key</access-key>
                <secret-key>my-secret-key</secret-key>
                <iam-role>dummy</iam-role>
                <!--optional, default is us-east-1 -->
                <region>us-west-1</region>
                <!--optional, default is ec2.amazonaws.com. If set, region shouldn't be set as it will override this property -->
                <host-header>ec2.amazonaws.com</host-header>
                <!-- optional, only instances belonging to this group will be discovered, default will try all running instances -->
                <security-group-name>hazelcast-sg</security-group-name>
                <tag-key>type</tag-key>
                <tag-value>hz-nodes</tag-value>
                <use-public-ip>true</use-public-ip>
            </aws>
            <gcp enabled="false">
                <zones>us-east1-b,us-east1-c</zones>
            </gcp>
            <azure enabled="false">
                <instance-metadata-available>false</instance-metadata-available>
                <client-id>CLIENT_ID</client-id>
                <client-secret>CLIENT_SECRET</client-secret>
                <tenant-id>TENANT_ID</tenant-id>
                <subscription-id>SUB_ID</subscription-id>
                <resource-group>RESOURCE-GROUP-NAME</resource-group>
                <scale-set>SCALE-SET-NAME</scale-set>
                <tag>TAG-NAME=HZLCAST001</tag>
            </azure>
            <kubernetes enabled="false">
                <namespace>MY-KUBERNETES-NAMESPACE</namespace>
                <service-name>MY-SERVICE-NAME</service-name>
                <service-label-name>MY-SERVICE-LABEL-NAME</service-label-name>
                <service-label-value>MY-SERVICE-LABEL-VALUE</service-label-value>
            </kubernetes>
            <eureka enabled="false">
                <self-registration>true</self-registration>
                <namespace>hazelcast</namespace>
            </eureka>
<!--            <discovery-strategies>
                <node-filter class="DummyFilterClass"/>
                <discovery-strategy class="DummyClass" enabled="true">
                    <properties>
                        <property name="foo">bar</property>
                    </properties>
                </discovery-strategy>
            </discovery-strategies>-->
        </join>
        <member-address-provider enabled="false">
            <class-name>DummyMemberAddressProvider</class-name>
            <properties>
                <property name="foo">bar</property>
            </properties>
        </member-address-provider>
        <failure-detector>
            <icmp enabled="false">
                <timeout-milliseconds>1000</timeout-milliseconds>
                <fail-fast-on-startup>true</fail-fast-on-startup>
                <interval-milliseconds>1000</interval-milliseconds>
                <max-attempts>2</max-attempts>
                <parallel-mode>true</parallel-mode>
                <ttl>255</ttl>
            </icmp>
        </failure-detector>
        <!-- cluster protocol server socket -->
        <member-server-socket-endpoint-config>
            <outbound-ports>
                <ports>33000-35000</ports>
                <ports>37000,37001,37002,37003</ports>
                <ports>38000,38500-38600</ports>
            </outbound-ports>
            <interfaces enabled="true">
                <interface>10.10.1.*</interface>
            </interfaces>
            <ssl enabled="true">
                <factory-class-name>com.hazelcast.examples.MySSLContextFactory</factory-class-name>
                <properties>
                    <property name="foo">bar</property>
                </properties>
            </ssl>
            <socket-interceptor enabled="true">
                <class-name>com.hazelcast.examples.MySocketInterceptor</class-name>
                <properties>
                    <property name="foo">bar</property>
                </properties>
            </socket-interceptor>
            <socket-options>
                <buffer-direct>true</buffer-direct>
                <tcp-no-delay>true</tcp-no-delay>
                <keep-alive>true</keep-alive>
                <connect-timeout-seconds>64</connect-timeout-seconds>
                <send-buffer-size-kb>25</send-buffer-size-kb>
                <receive-buffer-size-kb>33</receive-buffer-size-kb>
                <linger-seconds>99</linger-seconds>
            </socket-options>
            <port auto-increment="true" port-count="100">5701</port>
            <public-address>dummy</public-address>
            <!-- If the address should be reused. See NetworkConfig.setReuseAddress for more information. -->
            <reuse-address>true</reuse-address>
        </member-server-socket-endpoint-config>
        <!-- server socket listening for connections from hazelcast clients -->
        <client-server-socket-endpoint-config>
            <outbound-ports>
                <ports>38000,38500-38600</ports>
            </outbound-ports>
            <interfaces enabled="false">
                <interface>10.10.1.*</interface>
            </interfaces>
            <ssl enabled="true">
                <factory-class-name>com.hazelcast.examples.MySSLContextFactory</factory-class-name>
                <properties>
                    <property name="foo">bar</property>
                </properties>
            </ssl>
            <socket-interceptor enabled="true">
                <class-name>com.hazelcast.examples.MySocketInterceptor</class-name>
                <properties>
                    <property name="foo">bar</property>
                </properties>
            </socket-interceptor>
            <port auto-increment="true" port-count="100">9999</port>
            <public-address>10.10.0.10</public-address>
            <reuse-address>true</reuse-address>
        </client-server-socket-endpoint-config>
        <!-- create a server socket for REST API -->
        <rest-server-socket-endpoint-config name="internal-server-socket">
            <interfaces enabled="false">
                <interface>10.10.1.*</interface>
            </interfaces>
            <port auto-increment="false">8080</port>
            <public-address>192.168.1.10</public-address>
            <reuse-address>true</reuse-address>
            <endpoint-groups>
                <endpoint-group name="WAN" enabled="true"/>
                <endpoint-group name="CLUSTER_READ" enabled="true"/>
                <endpoint-group name="CLUSTER_WRITE" enabled="false"/>
                <endpoint-group name="HEALTH_CHECK" enabled="true"/>
            </endpoint-groups>
        </rest-server-socket-endpoint-config>
        <!-- specify SSL config to be used for outgoing connections -->
        <wan-endpoint-config name="endpoint-tokyo">
            <ssl enabled="true">
                <factory-class-name>com.hazelcast.examples.MySSLContextFactory</factory-class-name>
                <properties>
                    <property name="foo">bar</property>
                </properties>
            </ssl>
        </wan-endpoint-config>
        <wan-endpoint-config name="endpoint-london">
            <symmetric-encryption enabled="true">
                <algorithm>Algorithm</algorithm>
                <salt>thesalt</salt>
                <password>thepassword</password>
                <iteration-count>1000</iteration-count>
            </symmetric-encryption>
        </wan-endpoint-config>
        <wan-server-socket-endpoint-config name="wan-server-socket-config">
            <interfaces enabled="false">
                <interface>192.168.8.101</interface>
                <interface>10.20.10.100</interface>
            </interfaces>
        </wan-server-socket-endpoint-config>
        <memcache-server-socket-endpoint-config name="memcache">
            <port auto-increment="false" port-count="10">6000</port>
        </memcache-server-socket-endpoint-config>
    </advanced-network>

</hazelcast>


text:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Paciente;

class Habito extends Model
{
    protected $fillable = [
		'paciente_id', 'sono_repouso', 'horas_sono', 'atividade_fisica', 'qtde_atividade_fisica', 'frutas_verduras', 'carne_vermelha', 'carne_branca', 'suco_habitos', 'agua_habitos', 'cha_habitos', 'outras_informacoes'
	];

    public function pacientes(){
    	return $this->belongsTo(Paciente::class);
    }
}


text:
import argparse
import logging
from logging.config import fileConfig

from tqdm import tqdm

import catconv.operations as co
import catconv.stabi as sb

parser = argparse.ArgumentParser()
parser.add_argument("source")
parser.add_argument("-u", "--update", help="overwrite previous results",
                    action="store_true")
parser.add_argument("-b", "--binarize", help="create binary images",
                    action="store_true")
parser.add_argument("-s", "--segment", help="extract text lines",
                    action="store_true")
parser.add_argument("-p", "--predict", help="predict text", required=False)
parser.add_argument("-e", "--ext", help="file-extesion", required=False)
args = parser.parse_args()

source = sb.op.normpath(args.source)
data_dir, cat_name = sb.op.split(source)
catalog = sb.load_catalog(source, {'ext': args.ext}, text_box=True, text=True)
pages = catalog['pages']
# pages = map(sb.page_from_path, sb.catalog_pages(source))

fileConfig('logging_config.ini')
logger = logging.getLogger()
logger.info('Processing {}'.format(catalog['name']))
logger.info("Number of pages {}".format( len(pages)))

# limit the amount of pages for testing
amount = min(len(pages),100)
step_size = len(pages) // amount

for page in tqdm(pages):
    png = page["path"]
    bin_png = sb.change_path(png, ext=".bin.png")
    seg_png = sb.change_path(png, ext=".pseg.png")
    bin_job = co.binarize(png)
    seg_job = co.segment(bin_png)

    if args.binarize and (not sb.op.exists(bin_png) or args.update) :
        co.execute_job(bin_job)
    if args.segment and (not sb.op.exists(seg_png) or args.update):
        co.execute_job(seg_job)

if args.predict:
    print("Predicting text lines")
    lines = sb.op.join(args.source, "*", "????????", "??????.bin.png")
    pred_job = co.predict(lines, args.predict, 7)
    co.execute_job(pred_job)


text:
[![Build Status](https://travis-ci.org/emicklei/proto.png)](https://travis-ci.org/emicklei/dot)
[![Go Report Card](https://goreportcard.com/badge/github.com/emicklei/dot)](https://goreportcard.com/report/github.com/emicklei/dot)
[![GoDoc](https://pkg.go.dev/badge/github.com/emicklei/dot)](https://pkg.go.dev/github.com/emicklei/dot)
[![codecov](https://codecov.io/gh/emicklei/dot/branch/master/graph/badge.svg)](https://codecov.io/gh/emicklei/dot)

[DOT language](http://www.graphviz.org/doc/info/lang.html)

	package main

	import (
		"fmt"
		"github.com/emicklei/dot"
	)

	// go run main.go | dot -Tpng  > test.png && open test.png

	func main() {
		g := dot.NewGraph(dot.Directed)
		n1 := g.Node("coding")
		n2 := g.Node("testing a little").Box()

		g.Edge(n1, n2)
		g.Edge(n2, n1, "back").Attr("color", "red")

		fmt.Println(g.String())
	}

Output

	digraph {
		node [label="coding"]; n1;
		node [label="testing a little",shape="box"]; n2;
		n1 -> n2;
		n2 -> n1 [color="red", label="back"];
	}

Chaining edges

	g.Node("A").Edge(g.Node("B")).Edge(g.Node("C"))

	A -> B -> C

	g.Node("D").BidirectionalEdge(g.Node("E))

	D <-> E

Subgraphs

	s := g.Subgraph("cluster")
	s.Attr("style","filled")

Initializers

	g := dot.NewGraph(dot.Directed)
	g.NodeInitializer(func(n dot.Node) {
		n.Attr("shape", "rectangle")
		n.Attr("fontname", "arial")
		n.Attr("style", "rounded,filled")
	})

	g.EdgeInitializer(func(e dot.Edge) {
		e.Attr("fontname", "arial")
		e.Attr("fontsize", "9")
		e.Attr("arrowsize", "0.8")
		e.Attr("arrowhead", "open")
	})

HTML and Literal values

	node.Attr("label", Literal(`"left-justified text\l"`))
	graph.Attr("label", HTML("<B>Hi</B>"))

## cluster example

![](./doc/cluster.png)

	di := dot.NewGraph(dot.Directed)
	outside := di.Node("Outside")

	// A
	clusterA := di.Subgraph("Cluster A", dot.ClusterOption{})
	insideOne := clusterA.Node("one")
	insideTwo := clusterA.Node("two")

	// B
	clusterB := di.Subgraph("Cluster B", dot.ClusterOption{})
	insideThree := clusterB.Node("three")
	insideFour := clusterB.Node("four")

	// edges
	outside.Edge(insideFour).Edge(insideOne).Edge(insideTwo).Edge(insideThree).Edge(outside)

## About dot attributes

https://graphviz.gitlab.io/doc/info/attrs.html

## display your graph

	go run main.go | dot -Tpng  > test.png && open test.png

## mermaid

Output a dot Graph using the [mermaid](https://mermaid-js.github.io/mermaid/#/README) syntax.
Only Graph and Flowchart are supported. See MermaidGraph and MermaidFlowchart.

```
g := dot.NewGraph(dot.Directed)
...
fmt.Println(dot.MermaidGraph(g, dot.MermaidTopToBottom))
```

### testing

	go test -coverprofile=coverage.out ./...
	go tool cover -html=coverage.out

(c) 2015-2022, http://ernestmicklei.com. MIT License.


text:
describe PDF::Reader::Filter::Flate do
  describe "#filter" do
    context "an RFC1950 (zlib) deflated stream" do
      let(:deflated_path) {
        File.dirname(__FILE__) + "/../../data/hello-world.z"
      }
      let(:deflated_data) { binread(deflated_path) }
      it "inflates correctly" do
        filter = PDF::Reader::Filter::Flate.new
        expect(filter.filter(deflated_data)).to eql("hello world, 2020 is quite the year")
      end
    end

    context "an RFC1950 (zlib) deflated stream with an extra byte on the end" do
      let(:deflated_path) {
        File.dirname(__FILE__) + "/../../data/stream-with-extra-byte.z"
      }
      let(:deflated_data) { binread(deflated_path) }
      it "inflates correctly" do
        filter = PDF::Reader::Filter::Flate.new
        result = filter.filter(deflated_data)
        expect(result).to start_with("q")
        expect(result).to end_with("ET\n")
      end
    end

    context "a raw RFC1951 deflated stream" do
      let(:deflated_path) {
        File.dirname(__FILE__) + "/../../data/hello-world.deflate"
      }
      let(:deflated_data) { binread(deflated_path) }
      it "inflates correctly" do
        filter = PDF::Reader::Filter::Flate.new
        expect(filter.filter(deflated_data)).to eql("hello world, 2020 is quite the year")
      end
    end

    # I'm not sure this is strictly required by the PDF spec, but zlib can do it and no doubt
    # someone, somewhere has accidentally made a PDF using gzip
    context "an RFC1952 (gzip) deflated stream" do
      let(:deflated_path) {
        File.dirname(__FILE__) + "/../../data/hello-world.gz"
      }
      let(:deflated_data) { binread(deflated_path) }
      it "inflates correctly" do
        filter = PDF::Reader::Filter::Flate.new
        expect(filter.filter(deflated_data)).to eql("hello world, 2020 is quite the year")
      end
    end

    context "deflated stream with PNG predictors" do
      let(:deflated_path) {
        File.dirname(__FILE__) + "/../../data/deflated_with_predictors.dat"
      }
      let(:depredicted_path) {
        File.dirname(__FILE__) + "/../../data/deflated_with_predictors_result.dat"
      }
      let(:deflated_data) { binread(deflated_path) }
      let(:depredicted_data) { binread(depredicted_path) }

      it "inflates the data" do
        filter = PDF::Reader::Filter::Flate.new(
          :Columns => 5,
          :Predictor => 12
        )
        expect(filter.filter(deflated_data)).to eql(depredicted_data)
      end
    end

    context "deflated stream with tiff predictors" do
      let(:original_data) { "abcabcabcabcabcabcabcabcabcabc" }
      let(:predicted_data)  {
        "abc\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00abc\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
      }

      it "inflates the data" do
        filter = PDF::Reader::Filter::Flate.new(
          :Columns => 5,
          :Predictor => 2,
          :Colors => 3
        )
        deflated_data = Zlib::Deflate.deflate(predicted_data)

        expect(filter.filter(deflated_data)).to eql(original_data)
      end
    end
  end
end


text:
window.Params = {
  init: function(canvas) {
    var draw      = canvas.getContext('2d'),
        audio     = new AudioContext(),
        startTime = audio.currentTime,
        osc       = audio.createOscillator(),
        analyser  = audio.createAnalyser(),
        data      = new Float32Array(analyser.frequencyBinCount),
        gainNode  = audio.createGain();
        duration  = 3,
        param     = gainNode.gain;

    osc.connect(gainNode);
    gainNode.connect(analyser);
    analyser.connect(audio.destination);
    osc.start();

    param.setValueAtTime(1, audio.currentTime);

    param.linearRampToValueAtTime(0.01, audio.currentTime + duration / 2);
    param.setValueAtTime(0.01, audio.currentTime + duration / 2);
    param.exponentialRampToValueAtTime(1, audio.currentTime + duration);

    var toCoords = function(e) {
      var canvasRect = canvas.getClientRects()[0];
      return {
        s: ((e.x - canvasRect.left) / canvasRect.width) * duration,
        v: ((e.y - canvasRect.top) / canvasRect.height)
      };
    };

    canvas.onmousemove = function(e) {
      var coords = toCoords(e);
      s.innerText = coords.s;
      v.innerText = coords.v;
    };

    canvas.onclick = function(e) {
      toCoords(e)
    };

    draw.strokeStyle = 'red';
    draw.textBaseline = 'bottom';
    draw.strokeText('0s',0,1 * canvas.height);
    draw.textAlign = 'end';
    draw.strokeText(duration + 's', canvas.width, 1 * canvas.height);
    draw.text
    draw.strokeStyle = 'black';
    draw.moveTo(0, param.value * canvas.height);
    draw.beginPath();

    var loop = function(){
      analyser.getFloatTimeDomainData(data);
      draw.lineTo(
        ((audio.currentTime - startTime) / duration) * canvas.width,
        (1 - Math.max.apply(null,data)) * canvas.height
      );
      draw.stroke();
      if(audio.currentTime > startTime + duration)
        osc.stop();
      else
        requestAnimationFrame(loop);
    };
    requestAnimationFrame(loop);
  }
};


text:
export { default as clickOutsideHandler } from "./src/bindings/clickoutsidehandler";
export { default as injectCssTransitionDisabler } from "./src/bindings/injectcsstransitiondisabler";
export { default as submitHandler } from "./src/bindings/submithandler";

export { default as BodyCollection } from "./src/editorui/bodycollection";

export { default as ButtonView } from "./src/button/buttonview";
export { default as SwitchButtonView } from "./src/button/switchbuttonview";

export * from "./src/colorgrid/utils";
export { default as ColorGridView } from "./src/colorgrid/colorgrid";
export { default as ColorTileView } from "./src/colorgrid/colortile";

export { default as DropdownButtonView } from "./src/dropdown/button/dropdownbuttonview";
export { default as SplitButtonView } from "./src/dropdown/button/splitbuttonview";
export * from "./src/dropdown/utils";

export { default as EditorUIView } from "./src/editorui/editoruiview";
export { default as BoxedEditorUIView } from "./src/editorui/boxed/boxededitoruiview";
export { default as InlineEditableUIView } from "./src/editableui/inline/inlineeditableuiview";

export { default as FormHeaderView } from "./src/formheader/formheaderview";
export { default as FocusCycler } from "./src/focuscycler";

export { default as IconView } from "./src/icon/iconview";
export { default as InputTextView } from "./src/inputtext/inputtextview";

export { default as LabelView } from "./src/label/labelview";
export { default as LabeledFieldView } from "./src/labeledfield/labeledfieldview";
export * from "./src/labeledfield/utils";

export { default as ListItemView } from "./src/list/listitemview";
export { default as ListView } from "./src/list/listview";

export { default as Notification } from "./src/notification/notification";

export { default as Model } from "./src/model";
export { default as BalloonPanelView } from "./src/panel/balloon/balloonpanelview";
export { default as ContextualBalloon } from "./src/panel/balloon/contextualballoon";
export { default as StickyPanelView } from "./src/panel/sticky/stickypanelview";

export { default as TooltipView } from "./src/tooltip/tooltipview";
export { default as Template } from "./src/template";

export { default as ToolbarView } from "./src/toolbar/toolbarview";
export { default as ToolbarSeparatorView } from "./src/toolbar/toolbarseparatorview";
export { default as enableToolbarKeyboardFocus } from "./src/toolbar/enabletoolbarkeyboardfocus";
export { default as normalizeToolbarConfig } from "./src/toolbar/normalizetoolbarconfig";
export { default as BalloonToolbar } from "./src/toolbar/balloon/balloontoolbar";
export { default as BlockToolbar } from "./src/toolbar/block/blocktoolbar";

export { default as View } from "./src/view";
export { default as ViewCollection } from "./src/viewcollection";


text:
"""Simulation model with batteries included."""

from contextlib import closing
from multiprocessing import Process, Queue, cpu_count
from pprint import pprint
from threading import Thread
from types import TracebackType
from typing import (
    TYPE_CHECKING,
    Any,
    Callable,
    Dict,
    List,
    Optional,
    Sequence,
    Type,
    Union,
)
import json
import os
import random
import shutil
import timeit

import simpy
import yaml

from desmod.config import ConfigDict, ConfigFactor, factorial_config
from desmod.progress import (
    ProgressTuple,
    consume_multi_progress,
    get_multi_progress_manager,
    standalone_progress_manager,
)
from desmod.timescale import parse_time, scale_time
from desmod.tracer import TraceManager

if TYPE_CHECKING:
    from desmod.component import Component  # noqa: F401

ResultDict = Dict[str, Any]

class SimEnvironment(simpy.Environment):
    """Simulation Environment.

    The :class:`SimEnvironment` class is a :class:`simpy.Environment` subclass
    that adds some useful features:

     - Access to the configuration dictionary (`config`).
     - Access to a seeded pseudo-random number generator (`rand`).
     - Access to the simulation timescale (`timescale`).
     - Access to the simulation duration (`duration`).

    Some models may need to share additional state with all its
    :class:`desmod.component.Component` instances. SimEnvironment may be
    subclassed to add additional members to achieve this sharing.

    :param dict config: A fully-initialized configuration dictionary.

    """

    def __init__(self, config: ConfigDict) -> None:
        super().__init__()
        #: The configuration dictionary.
        self.config = config

        #: The pseudo-random number generator; an instance of
        #: :class:`random.Random`.
        self.rand = random.Random()
        seed = config.setdefault('sim.seed', None)
        self.rand.seed(seed, version=1)

        timescale_str = self.config.setdefault('sim.timescale', '1 s')

        #: Simulation timescale ``(magnitude, units)`` tuple. The current
        #: simulation time is ``now * timescale``.
        self.timescale = parse_time(timescale_str)

        duration = config.setdefault('sim.duration', '0 s')

        #: The intended simulation duration, in units of :attr:`timescale`.
        self.duration = scale_time(parse_time(duration), self.timescale)

        #: The simulation runs "until" this event. By default, this is the
        #: configured "sim.duration", but may be overridden by subclasses.
        self.until = self.duration

        #: From 'meta.sim.index', the simulation's index when running multiple
        #: related simulations or `None` for a standalone simulation.
        self.sim_index: Optional[int] = config.get('meta.sim.index')

        #: :class:`TraceManager` instance.
        self.tracemgr = TraceManager(self)

    def time(self, t: Optional[float] = None, unit: str = 's') -> Union[int, float]:
        """The current simulation time scaled to specified unit.

        :param float t: Time in simulation units. Default is :attr:`now`.
        :param str unit: Unit of time to scale to. Default is 's' (seconds).
        :returns: Simulation time scaled to to `unit`.

        """
        target_scale = parse_time(unit)
        ts_mag, ts_unit = self.timescale
        sim_time = ((self.now if t is None else t) * ts_mag, ts_unit)
        return scale_time(sim_time, target_scale)

    def get_progress(self) -> ProgressTuple:
        if isinstance(self.until, SimStopEvent):
            t_stop = self.until.t_stop
        else:
            t_stop = self.until
        return self.sim_index, self.now, t_stop, self.timescale

class SimStopEvent(simpy.Event):
    """Event appropriate for stopping the simulation.

    An instance of this event may be used to override `SimEnvironment.until` to
    dynamically choose when to stop the simulation. The simulation may be
    stopped by calling :meth:`schedule()`. The optional `delay` parameter may
    be used to schedule the simulation to stop at an offset from the current
    simulation time.

    """

    def __init__(self, env: SimEnvironment) -> None:
        super().__init__(env)
        self.t_stop: Optional[Union[int, float]] = None

    def schedule(self, delay: Union[int, float] = 0) -> None:
        assert not self.triggered
        assert delay >= 0
        self._ok = True
        self._value = None
        self.env.schedule(self, simpy.events.URGENT, delay)
        self.t_stop = self.env.now + delay

class _Workspace:
    """Context manager for workspace directory management."""

    def __init__(self, config: ConfigDict) -> None:
        self.workspace: str = config.setdefault(
            'meta.sim.workspace', config.setdefault('sim.workspace', os.curdir)
        )
        self.overwrite: bool = config.setdefault('sim.workspace.overwrite', False)
        self.prev_dir: str = os.getcwd()

    def __enter__(self) -> '_Workspace':
        if os.path.relpath(self.workspace) != os.curdir:
            workspace_exists = os.path.isdir(self.workspace)
            if self.overwrite and workspace_exists:
                shutil.rmtree(self.workspace)
            if self.overwrite or not workspace_exists:
                os.makedirs(self.workspace)
            os.chdir(self.workspace)
        return self

    def __exit__(
        self,
        exc_type: Optional[Type[BaseException]],
        exc_value: Optional[BaseException],
        traceback: Optional[TracebackType],
    ) -> Optional[bool]:
        os.chdir(self.prev_dir)
        return None

def simulate(
    config: ConfigDict,
    top_type: Type['Component'],
    env_type: Type[SimEnvironment] = SimEnvironment,
    reraise: bool = True,
    progress_manager=standalone_progress_manager,
) -> ResultDict:
    """Initialize, elaborate, and run a simulation.

     All exceptions are caught by `simulate()` so they can be logged and
     captured in the result file. By default, any unhandled exception caught by
     `simulate()` will be re-raised. Setting `reraise` to False prevents
     exceptions from propagating to the caller. Instead, the returned result
     dict will indicate if an exception occurred via the 'sim.exception' item.

    :param dict config: Configuration dictionary for the simulation.
    :param top_type: The model's top-level Component subclass.
    :param env_type: :class:`SimEnvironment` subclass.
    :param bool reraise: Should unhandled exceptions propogate to the caller.
    :returns:
        Dictionary containing the model-specific results of the simulation.
    """
    t0 = timeit.default_timer()
    result: ResultDict = {}
    result_file = config.setdefault('sim.result.file')
    config_file = config.setdefault('sim.config.file')
    try:
        with _Workspace(config):
            env = env_type(config)
            with closing(env.tracemgr):
                try:
                    top_type.pre_init(env)
                    env.tracemgr.flush()
                    with progress_manager(env):
                        top = top_type(parent=None, env=env)
                        top.elaborate()
                        env.tracemgr.flush()
                        env.run(until=env.until)
                        env.tracemgr.flush()
                        top.post_simulate()
                        env.tracemgr.flush()
                        top.get_result(result)
                except BaseException as e:
                    env.tracemgr.trace_exception()
                    result['sim.exception'] = repr(e)
                    raise
                else:
                    result['sim.exception'] = None
                finally:
                    env.tracemgr.flush()
                    result['config'] = config
                    result['sim.now'] = env.now
                    result['sim.time'] = env.time()
                    result['sim.runtime'] = timeit.default_timer() - t0
                    _dump_dict(config_file, config)
                    _dump_dict(result_file, result)
    except BaseException as e:
        if reraise:
            raise
        result.setdefault('config', config)
        result.setdefault('sim.runtime', timeit.default_timer() - t0)
        if result.get('sim.exception') is None:
            result['sim.exception'] = repr(e)
    return result

def simulate_factors(
    base_config: ConfigDict,
    factors: List[ConfigFactor],
    top_type: Type['Component'],
    env_type: Type[SimEnvironment] = SimEnvironment,
    jobs: Optional[int] = None,
    config_filter: Optional[Callable[[ConfigDict], bool]] = None,
) -> List[ResultDict]:
    """Run multi-factor simulations in separate processes.

    The `factors` are used to compose specialized config dictionaries for the
    simulations.

    The :mod:`python:multiprocessing` module is used run each simulation with a
    separate Python process. This allows multi-factor simulations to run in
    parallel on all available CPU cores.

    :param dict base_config: Base configuration dictionary to be specialized.
    :param list factors: List of factors.
    :param top_type: The model's top-level Component subclass.
    :param env_type: :class:`SimEnvironment` subclass.
    :param int jobs: User specified number of concurent processes.
    :param function config_filter:
        A function which will be passed a config and returns a bool to filter.
    :returns: Sequence of result dictionaries for each simulation.

    """
    configs = list(factorial_config(base_config, factors, 'meta.sim.special'))
    ws = base_config.setdefault('sim.workspace', os.curdir)
    overwrite = base_config.setdefault('sim.workspace.overwrite', False)

    for index, config in enumerate(configs):
        config['meta.sim.index'] = index
        config['meta.sim.workspace'] = os.path.join(ws, str(index))
    if config_filter is not None:
        configs[:] = filter(config_filter, configs)
    if overwrite and os.path.relpath(ws) != os.curdir and os.path.isdir(ws):
        shutil.rmtree(ws)
    return simulate_many(configs, top_type, env_type, jobs)

def simulate_many(
    configs: Sequence[ConfigDict],
    top_type: Type['Component'],
    env_type: Type[SimEnvironment] = SimEnvironment,
    jobs: Optional[int] = None,
) -> List[ResultDict]:
    """Run multiple experiments in separate processes.

    The :mod:`python:multiprocessing` module is used run each simulation with a
    separate Python process. This allows multi-factor simulations to run in
    parallel on all available CPU cores.

    :param dict configs: list of configuration dictionary for the simulation.
    :param top_type: The model's top-level Component subclass.
    :param env_type: :class:`SimEnvironment` subclass.
    :param int jobs: User specified number of concurent processes.
    :returns: Sequence of result dictionaries for each simulation.

    """
    if jobs is not None and jobs < 1:
        raise ValueError(f'Invalid number of jobs: {jobs}')

    progress_enable = any(
        config.setdefault('sim.progress.enable', False) for config in configs
    )

    progress_queue: Optional[
        Queue[ProgressTuple]
    ] = Queue() if progress_enable else None
    result_queue: Queue[ResultDict] = Queue()
    config_queue: Queue[Optional[ConfigDict]] = Queue()

    workspaces = set()
    max_width = 0
    for index, config in enumerate(configs):
        max_width = max(config.setdefault('sim.progress.max_width', 0), max_width)

        workspace = os.path.normpath(
            config.setdefault(
                'meta.sim.workspace', config.setdefault('sim.workspace', os.curdir)
            )
        )
        if workspace in workspaces:
            raise ValueError(f'Duplicate workspace: {workspace}')
        workspaces.add(workspace)

        config.setdefault('meta.sim.index', index)
        config['sim.progress.enable'] = progress_enable
        config_queue.put(config)

    num_workers = min(len(configs), cpu_count())
    if jobs is not None:
        num_workers = min(num_workers, jobs)

    workers = []
    for i in range(num_workers):
        worker = Process(
            name=f'sim-worker-{i}',
            target=_simulate_worker,
            args=(
                top_type,
                env_type,
                False,
                progress_queue,
                config_queue,
                result_queue,
            ),
        )
        worker.daemon = True  # Workers die if main process dies.
        worker.start()
        workers.append(worker)
        config_queue.put(None)  # A stop sentinel for each worker.

    if progress_enable:
        progress_thread = Thread(
            target=consume_multi_progress,
            args=(progress_queue, num_workers, len(configs), max_width),
        )
        progress_thread.daemon = True
        progress_thread.start()

    results = [result_queue.get() for _ in configs]

    if progress_enable:
        # Although this is a daemon thread, we still make a token attempt to
        # join with it. This avoids a race with certain testing frameworks
        # (ahem, py.test) that may monkey-patch and close stderr while
        # progress_thread is still using it.
        progress_thread.join(1)

    for worker in workers:
        worker.join(5)

    return sorted(results, key=lambda r: r['config']['meta.sim.index'])

def _simulate_worker(
    top_type: Type['Component'],
    env_type: Type[SimEnvironment],
    reraise: bool,
    progress_queue: Optional['Queue[ProgressTuple]'],
    config_queue: 'Queue[Optional[ConfigDict]]',
    result_queue: 'Queue[ResultDict]',
):
    progress_manager = get_multi_progress_manager(progress_queue)
    while True:
        config = config_queue.get()
        if config is None:
            break
        result = simulate(config, top_type, env_type, reraise, progress_manager)
        result_queue.put(result)

def _dump_dict(filename: str, dump_dict: Dict[str, Any]):
    if filename is not None:
        _, ext = os.path.splitext(filename)
        if ext not in ['.yaml', '.yml', '.json', '.py']:
            raise ValueError(f'Invalid extension: {ext}')
        with open(filename, 'w') as dump_file:
            if ext in ['.yaml', '.yml']:
                yaml.safe_dump(dump_dict, stream=dump_file)
            elif ext == '.json':
                json.dump(dump_dict, dump_file, sort_keys=True, indent=2)
            else:
                assert ext == '.py'
                pprint(dump_dict, stream=dump_file)


text:
<?php

namespace Oro\Bundle\ConfigBundle\Config\Tree;

class FieldNodeDefinition extends AbstractNodeDefinition
{
    /**
     * @return string
     */
    public function getPropertyPath()
    {
        return isset($this->definition['property_path']) ? $this->definition['property_path'] : $this->getName();
    }

    /**
     * Return field type
     *
     * @return string
     */
    public function getType()
    {
        return $this->definition['type'];
    }

    /**
     * Return acl resource name if defined
     *
     * @return bool|string
     */
    public function getAclResource()
    {
        if (!empty($this->definition['acl_resource'])) {
            return $this->definition['acl_resource'];
        }

        return false;
    }

    /**
     * Get field options
     *
     * @return array
     */
    public function getOptions()
    {
        return $this->definition['options'];
    }

    /**
     * Set field options
     *
     * @param array $options
     *
     * @return $this
     */
    public function setOptions(array $options)
    {
        $this->definition['options'] = $options;

        return $this;
    }

    /**
     * Replace field option by name
     *
     * @param string $name
     * @param mixed  $value
     *
     * @return $this
     */
    public function replaceOption($name, $value)
    {
        $this->definition['options'][$name] = $value;

        return $this;
    }

    /**
     * @return bool
     */
    public function needsPageReload()
    {
        return $this->definition['page_reload'];
    }

    /**
     * {@inheritdoc}
     */
    protected function prepareDefinition(array $definition)
    {
        if (!isset($definition['options'])) {
            $definition['options'] = [];
        }

        return parent::prepareDefinition($definition);
    }
}


text:
Writing of the code to convert PDF to text from URL in cURL can be done by developers of any level using ByteScout Cloud API Server. PDF to text API in cURL can be applied with ByteScout Cloud API Server. ByteScout Cloud API Server is the ready to deploy Web API Server that can be deployed in less than thirty minutes into your own in-house Windows server (no Internet connnection is required to process data!) or into private cloud server. Can store data on in-house local server based storage or in Amazon AWS S3 bucket. Processing data solely on the server using built-in ByteScout powered engine, no cloud services are used to process your data!.

This simple and easy to understand sample source code in cURL for ByteScout Cloud API Server contains different functions and options you should do calling the API to implement PDF to text API. For implementation of this functionality, please copy and paste the code below into your app using code editor. Then compile and run your app. Writing cURL application mostly includes various stages of the software development so even if the functionality works please check it with your data and the production environment.

ByteScout Cloud API Server - free trial version is available on our website. Also, there are other code samples to help you with your cURL application included into trial version.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Cloud%20API%20Server%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Cloud%20API%20Server%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### ****ConvertPdfToTextFromUrl.cmd:**

```
@echo off

:: Path of the cURL executable
set CURL="curl.exe"

:: Direct URL of source PDF file.
set SOURCE_FILE_URL=https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-to-text/sample.pdf
:: Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
set PAGES=
:: PDF document password. Leave empty for unprotected documents.
set PASSWORD=
:: Result TXT file name
set RESULT_FILE_NAME=result.txt

:: Please NOTE: In this sample we're assuming Cloud Api Server is hosted at "https://localhost".
:: If it's not then please replace this with with your hosting url.

:: Prepare URL for `PDF To Text` API call
set QUERY="https://localhost/pdf/convert/to/text?name=%RESULT_FILE_NAME%&password=%PASSWORD%&pages=%PAGES%&url=%SOURCE_FILE_URL%"

:: Perform request and save response to a file
%CURL% -# -X GET %QUERY% >response.json

:: Display the response
type response.json

:: Use any convenient way to parse JSON response and get URL of generated file(s)

echo.
pause
```

<!-- code block end -->


text:
VM on GCE
=========

Scripts to help bootstrapping VMs on [Google Compute
Engine (GCE)](http://cloud.google.com/compute) to run a self-updating
[Go](https://golang.org) webserver:

  - [make_startup](make_startup) generates customized startup
    [script](https://cloud.google.com/compute/docs/startupscript). This
    simplifies quickly deploying from vanilla stock image:
    - Golang [facebookgo/grace](https://github.com/facebookgo/grace)
      based service transparent zero-downtime service restart via [Github
      webhooks](https://developer.github.com/webhooks/) using
      [phayes/hookserve](https://github.com/phayes/hookserve).
    - Google [Domains Dynamic
      DNS](https://support.google.com/domains/answer/6147083); hostname updated
      on boot.
    - Google [Cloud Logging](https://cloud.google.com/logging/); streams logs to
      your Cloud console.
    - Really simple to use, doesn't require a CI, doesn't use a docker image.
      Just `git push` and your server is immediately rebuilt and restarted.
  - [create](create.md) easily create a VM with the right ports opened and
    using the startup script.

Usage
-----

First, create a startup.sh script, then create the VM to use it. Here's an
example how to start a [godoc.org](https://godoc.org) clone:

    ./make_startup --help

    ./make_startup \
      --gd-user <gdomains user> --gd-pwd <gdomains pwd> --gd-host godoc.example.com \
      --go-get-url github.com/golang/gddo/gddo-server \
      --pkg redis-server,mercurial

    ./create godoc

    # Wait a few seconds then browse http://godoc.example.com or:
    ssh godoc.example.com

Project setup
-------------

### 1. Install and setup `gcloud`

Install `gcloud` and restart your shell:

    curl https://sdk.cloud.google.com | bash

Make sure you [created a project and enabled billing (with free
trial)](https://console.developers.google.com/) then initialize `gcloud`:

    gcloud init --console-only
    gcloud config set compute/zone us-central1-f
    gcloud auth list
    gcloud config list

### 2. Enable APIs

You'll want to enable a few APIs. Enabling the API is itself free:

    - Google Cloud Monitoring
    - Google Cloud Logging

### 2. Open ports in the firewall

Setup the [firewall](https://cloud.google.com/compute/docs/networking) as by
default almost all ports are closed.

    gcloud compute firewall-rules create allow-http --description "Incoming http allowed" --allow tcp:80
    gcloud compute firewall-rules create allow-https --description "Incoming https allowed" --allow tcp:443
    gcloud compute firewall-rules create allow-tcp9000 --description "Incoming tcp:9000 allowed" --allow tcp:9000

    gcloud compute firewall-rules list
    gcloud compute networks list

### 3. Push your SSH key

_(Optional, only if you have a ssh key)_

Setup [your ssh key to your Google Cloud
project](https://cloud.google.com/compute/docs/networking), this way you can ssh
natively to your instances from any workstation with your ssh key configured.
[Doc at Canonical](https://wiki.ubuntu.com/GoogleComputeEngineSSHKeys).

    echo -n "$USER " > key.pub
    cat ~/.ssh/id_rsa.pub >> key.pub
    gcloud compute project-info add-metadata --metadata-from-file sshKeys=key.pub
    rm key.pub


text: Set of analysis / verification examples


text:
title: Amazon Dash
category: archive
layout: post
tags:
 - amazon
 - iot
 - dash
 - physical
---

![amazon-dash](/images/amazon-dash.jpeg)

A few days ago [Amazon Dash](https://www.amazon.com/oc/dash-button) launched. While initially thinking it was an April Fool's joke, it turned out to be real and I've been incredibly excited about it ever since.

If you don't know, Amazon Dash is a new product that is essentially a physical button that when pressed, orders a particular item for you. It's an extension of what they've done with [subscription orders](http://www.amazon.com/gp/subscribe-and-save/details/), but now with more control and in real life.

Initially Dash is just physical buttons that Amazon is giving away, but they've also opened up an [API for developers](https://www.amazon.com/oc/dash-replenishment-service) so that certain devices with sensors can automatically reorder things for you. Like [this coffee machine (Poppy)](https://poppyhome.com/pour-over) that will reorder beans for you when you're running low.

This brings me back to my post about [devices talking to other devices](/2014/09/10/internet-of-things/). It's great that Amazon is leading the way on this and although Dash has yet to come out, it seems like a really elegant first step towards pushing this to reality.

Awesome stuff — I've ordered one and looking forward to seeing more interesting stuff coming out of this.


text:
import re

import flask
import memcache

from driverlog.openstack.common import log as logging

LOG = logging.getLogger(__name__)

def _build_projects_map(default_data):
    projects_map = {}
    for project in default_data['projects']:
        projects_map[project['id']] = project
    return projects_map

def _build_releases_map(default_data):
    releases_map = {}
    for release in default_data['releases']:
        releases_map[release['id'].lower()] = release
    return releases_map

def _extend_drivers_info():
    for driver in get_vault()['drivers_map'].values():
        releases_info = []
        for release in driver['releases'].keys():
            if release in get_vault()['releases_map']:
                releases_info.append(
                    {
                        'release_id': release.lower(),
                        'name': release.capitalize(),
                        'wiki': get_vault()['releases_map'][release]['wiki']
                    })
        driver['releases_info'] = sorted(releases_info,
                                         key=lambda x: x['name'])
        if 'maintainer' in driver:
            if 'email' in driver['maintainer']:
                del driver['maintainer']['email']

        driver['project_name'] = (get_vault()['projects_map']
                                  [driver['project_id']]['name'])

def get_vault():
    vault = getattr(flask.current_app, 'driverlog_vault', None)
    if not vault:
        try:
            if 'CONF' not in flask.current_app.config:
                LOG.critical('Configure environment variable DRIVERLOG_CONF '
                             'with path to config file')
                flask.abort(500)

            vault = {}
            conf = flask.current_app.config['CONF']

            MEMCACHED_URI_PREFIX = r'^memcached:\/\/'
            stripped = re.sub(MEMCACHED_URI_PREFIX, '',
                              conf.runtime_storage_uri)

            memcached_uri = stripped.split(',')
            memcached = memcache.Client(memcached_uri)
            vault['memcached'] = memcached

            flask.current_app.driverlog_vault = vault
        except Exception as e:
            LOG.critical('Failed to initialize application: %s', e)
            LOG.exception(e)
            flask.abort(500)

    if not getattr(flask.request, 'driverlog_updated', None):
        flask.request.driverlog_updated = True

        memcached = vault['memcached']
        update_time = memcached.get('driverlog:update_time')

        if vault.get('update_time') != update_time:
            vault['update_time'] = update_time

            default_data = memcached.get('driverlog:default_data')
            vault['default_data'] = default_data

            projects_map = _build_projects_map(default_data)
            vault['projects_map'] = projects_map

            releases_map = _build_releases_map(default_data)
            vault['releases_map'] = releases_map

            vault['drivers_map'] = default_data['drivers']

            _extend_drivers_info()

        if not vault.get('default_data'):
            raise Exception('Memcached is not initialized. '
                            'Please run the processor')

    return vault


text:
package org.firstinspires.ftc.robotcontroller.external.samples;

import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.LightSensor;
import com.qualcomm.robotcore.util.ElapsedTime;

/**
 * This file illustrates the concept of driving a path based on time.
 * It uses the common Pushbot hardware class to define the drive on the robot.
 * The code is structured as a LinearOpMode
 *
 * The code assumes that you do NOT have encoders on the wheels,
 *   otherwise you would use: PushbotAutoDriveByEncoder;
 *
 *   The desired path in this example is:
 *   - Drive forward for 3 seconds
 *   - Spin rightMotorPower for 1.3 seconds
 *   - Drive Backwards for 1 Second
 *   - Stop and close the claw.
 *
 *  The code is written in a simple form with no optimizations.
 *  However, there are several ways that this type of sequence could be streamlined,
 *
 * Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name.
 * Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list
 */

@Autonomous(name="Pushbot: Auto Drive By Time", group="Pushbot")
@Disabled
public class PushbotAutoDriveByTime_Linear extends LinearOpMode {

    /* Declare OpMode members. */
    HardwarePushbot         robot   = new HardwarePushbot();   // Use a Pushbot's hardware
    private ElapsedTime     runtime = new ElapsedTime();

    static final double     FORWARD_SPEED = 0.6;
    static final double     TURN_SPEED    = 0.5;

    @Override
    public void runOpMode() {

        /*
         * Initialize the drive system variables.
         * The init() method of the hardware class does all the work here
         */
        robot.init(hardwareMap);

        // Send telemetry message to signify robot waiting;
        telemetry.addData("Status", "Ready to run");    //
        telemetry.update();

        // Wait for the game to start (driver presses PLAY)
        waitForStart();

        // Step through each leg of the path, ensuring that the Auto mode has not been stopped along the way

        // Step 1:  Drive forward for 3 seconds
        robot.leftMotor.setPower(FORWARD_SPEED);
        robot.rightMotor.setPower(FORWARD_SPEED);
        runtime.reset();
        while (opModeIsActive() && (runtime.seconds() < 3.0)) {
            telemetry.addData("Path", "Leg 1: %2.5f S Elapsed", runtime.seconds());
            telemetry.update();
        }

        // Step 2:  Spin rightMotorPower for 1.3 seconds
        robot.leftMotor.setPower(TURN_SPEED);
        robot.rightMotor.setPower(-TURN_SPEED);
        runtime.reset();
        while (opModeIsActive() && (runtime.seconds() < 1.3)) {
            telemetry.addData("Path", "Leg 2: %2.5f S Elapsed", runtime.seconds());
            telemetry.update();
        }

        // Step 3:  Drive Backwards for 1 Second
        robot.leftMotor.setPower(-FORWARD_SPEED);
        robot.rightMotor.setPower(-FORWARD_SPEED);
        runtime.reset();
        while (opModeIsActive() && (runtime.seconds() < 1.0)) {
            telemetry.addData("Path", "Leg 3: %2.5f S Elapsed", runtime.seconds());
            telemetry.update();
        }

        // Step 4:  Stop and close the claw.
        robot.leftMotor.setPower(0);
        robot.rightMotor.setPower(0);
        robot.leftClaw.setPosition(1.0);
        robot.rightClaw.setPosition(0.0);

        telemetry.addData("Path", "Complete");
        telemetry.update();
        sleep(1000);
    }
}


text:
/*
 * Utils that wrap vue-intl functions in a way that makes them accessible to Perseus
 */

import createFragment from 'react-addons-create-fragment';
import { removeBackslashesInString } from '../../translationUtils';
import translator from './translator';

// We sometimes need to translate messages without filling in their values
// Use this to generate the options for a translation that leaves the ICU format
// intact
// This may break for more complex ICU messages, but we don't have any in the KA
// specific strings as they are generated from simpler ngettext strings
const getVarOptions = message => {
  const options = {};
  const reg = /(?:\{([^}]+)\})/g;
  let match;
  while ((match = reg.exec(message))) {
    options[match[1].trim()] = match[0];
  }
  return options;
};

// Some KA messages have TeX inlined, which can include curly braces
// This confuses our format message machinery, so find the names that we
// need to in fill here
const getTexCurlyBraceOptions = message => {
  // This regex does not catch escaped $ signs, so could fail.
  const reg = /\$([^$]+)\$/g;
  let match;
  const options = {};
  while ((match = reg.exec(message))) {
    Object.assign(options, getVarOptions(match[1]));
  }
  return options;
};

// Adapted from perseus/lib/i18n.js

const interpolationMarker = /{ *([\w_]+) *}/g;
/**
 * Performs ICU-like { name } replacement on str, and returns a React
 * fragment of the string interleaved with those replacements. The replacements
 * can be any valid React node including strings and numbers.
 *
 * For example:
 *  interpolateStringToFragment("test", {}) ->
 *      test
 *  interpolateStringToFragment("test { num }", {num: 5}) ->
 *      test 5
 *  interpolateStringToFragment("test { num }", {num: <Count />}) ->
 *      test <Count />
 */
const interpolateStringToFragment = (str, options = {}) => {
  // Translate string, but without any values to preserve placeholders.
  str = removeBackslashesInString(str);
  str = translator.$tr(str, getVarOptions(str));

  // Split the string into its language fragments and substitutions
  const split = str.split(interpolationMarker);

  const result = { text_0: split[0] };

  let key, replaceWith, j;

  // Replace the substitutions with the appropriate option
  for (let i = 1; i < split.length; i += 2) {
    key = split[i];
    replaceWith = options[key];
    if (replaceWith === undefined) {
      replaceWith = '%(' + key + ')s';
    }

    // We prefix each substitution key with a number that increments each
    // time it's used, so "test { num } { fruit } and { num } again" turns
    // into an object with keys:
    // [text_0, 0_num, text_2, 0_fruit, text_4, 1_num, text_6]
    // This is better than just using the array index in the case that we
    // switch between two translated strings with the same variables.
    // Admittedly, an edge case.
    j = 0;
    while ('' + j + '_' + key in result) {
      j++;
    }

    result['' + j + '_' + key] = replaceWith;
    // Because the regex has one capturing group, the `split` array always
    // has an odd number of elements, so this always stays in bounds.
    result['text_' + (i + 1)] = split[i + 1];
  }

  return createFragment(result);
};

export const $_ = (...args) => {
  const options = args[0];
  const str = args[1];
  if (args.length !== 2 || typeof str !== 'string') {
    return '<$_> must have exactly one child, which must be a string';
  }

  return interpolateStringToFragment(str, options);
};

/**
 * Simple i18n method with ICU-like { name } replacement
 * To be used like so:
 *   i18n._("Some string")
 *   i18n._("Hello { name }", {name: "John"})
 */
export const _ = (str, options = {}) => {
  // Sometimes we're given an argument that's meant for ngettext().  This
  // happens if the same string is used in both i18n._() and i18n.ngettext()
  // (.g. a = i18n._(foo); b = i18n.ngettext("foo", "bar", count);
  // In such cases, only the plural form ends up in the .po file, and
  // then it gets sent to us for the i18n._() case too.  No problem, though:
  // we'll just take the singular arg.
  if (typeof str === 'object' && str.messages) {
    str = str.messages[0];
  }

  Object.assign(options, getTexCurlyBraceOptions(str));

  str = removeBackslashesInString(str);
  return translator.$tr(str, options);
};


text:
import { Actions } from '../constants';

export default {
  close() {
    return (dispatch) => {
      dispatch({ type: Actions.CloseMainMenu });
    };
  },

  open() {
    return (dispatch) => {
      dispatch({ type: Actions.OpenMainMenu });
    };
  },

  toggle() {
    return (dispatch, getState) => {
      const { isMainMenuOpen } = getState();
      if (isMainMenuOpen) {
        dispatch({ type: Actions.CloseMainMenu });
      } else {
        dispatch({ type: Actions.OpenMainMenu });
      }
    };
  }
};


text:
module ActiveMerchant #:nodoc:
  module Billing #:nodoc:
    #
    # CardStream supports the following credit cards, which are auto-detected by
    # the gateway based on the card number used:
    # * AM American Express
    # * Diners Club
    # * Electron
    # * JCB
    # * UK Maestro
    # * Maestro International
    # * Mastercard
    # * Solo
    # * Style
    # * Switch
    # * Visa Credit
    # * Visa Debit
    # * Visa Purchasing
    #
    class CardStreamGateway < Gateway
      URL = 'https://gateway.cardstream.com/process.ashx'

      self.money_format = :cents
      self.default_currency = 'GBP'
      self.supported_countries = ['GB']
      self.supported_cardtypes = [:visa, :master, :american_express, :diners_club, :discover, :jcb, :maestro, :solo, :switch]
      self.homepage_url = 'http://www.cardstream.com/'
      self.display_name = 'CardStream'

      APPROVED = '00'

      CURRENCY_CODES = {
        "AUD"=> '036',
        "CAD"=> '124',
        "CZK"=> '203',
        "DKK"=> '208',
        "HKD"=> '344',
        "ICK"=> '352',
        "JPY"=> '392',
        "NOK"=> '578',
        "SGD"=> '702',
        "SEK"=> '752',
        "CHF"=> '756',
        "GBP"=> '826',
        "USD"=> '840',
        "EUR"=> '978'
      }

      TRANSACTIONS = {
        :purchase => 'ESALE_KEYED',
        :refund => 'EREFUND_KEYED',
        :authorization => 'ESALE_KEYED'
      }

      CVV_CODE = {
        '0' => 'U',
        '1' => 'P',
        '2' => 'M',
        '4' => 'N'
      }

      # 0 - No additional information available.
      # 1 - Postcode not checked.
      # 2 - Postcode matched.
      # 4 - Postcode not matched.
      # 8 - Postcode partially matched.
      AVS_POSTAL_MATCH = {
        "0" => nil,
        "1" => nil,
        "2" => "Y",
        "4" => "N",
        "8" => "N"
      }

      # 0 - No additional information available.
      # 1 - Address numeric not checked.
      # 2 - Address numeric matched.
      # 4 - Address numeric not matched.
      # 8 - Address numeric partially matched.
      AVS_STREET_MATCH = {
        "0" => nil,
        "1" => nil,
        "2" => "Y",
        "4" => "N",
        "8" => "N"
      }

      def initialize(options = {})
        requires!(options, :login, :password)
        @options = options
        super
      end

      def purchase(money, credit_card, options = {})
        requires!(options, :order_id)

        post = {}

        add_amount(post, money, options)
        add_invoice(post, money, credit_card, options)
        add_credit_card(post, credit_card)
        add_address(post, options)
        add_customer_data(post, options)

        commit(:purchase, post)
      end

      private

      def add_amount(post, money, options)
        add_pair(post, :Amount, amount(money), :required => true)
        add_pair(post, :CurrencyCode, currency_code(options[:currency] || currency(money)), :required => true)
      end

      def add_customer_data(post, options)
        add_pair(post, :BillingEmail, options[:email])
        add_pair(post, :BillingPhoneNumber, options[:phone])
      end

      def add_address(post, options)
        address = options[:billing_address] || options[:address]

        return if address.nil?

        add_pair(post, :BillingStreet, address[:address1])
        add_pair(post, :BillingHouseNumber, address[:address2])
        add_pair(post, :BillingCity, address[:city])
        add_pair(post, :BillingState, address[:state])
        add_pair(post, :BillingPostCode, address[:zip])
      end

      def add_invoice(post, money, credit_card, options)
        add_pair(post, :TransactionUnique, options[:order_id], :required => true)
        add_pair(post, :OrderDesc, options[:description] || options[:order_id], :required => true)

        if [ 'american_express', 'diners_club' ].include?(card_brand(credit_card).to_s)
          add_pair(post, :AEIT1Quantity,  1)
          add_pair(post, :AEIT1Description,  (options[:description] || options[:order_id]).slice(0, 15))
          add_pair(post, :AEIT1GrossValue, amount(money))
        end
      end

      def add_credit_card(post, credit_card)
        add_pair(post, :CardName, credit_card.name, :required => true)
        add_pair(post, :CardNumber, credit_card.number, :required => true)

        add_pair(post, :ExpiryDateMM, format(credit_card.month, :two_digits), :required => true)
        add_pair(post, :ExpiryDateYY, format(credit_card.year, :two_digits), :required => true)

        if requires_start_date_or_issue_number?(credit_card)
          add_pair(post, :StartDateMM, format(credit_card.start_month, :two_digits))
          add_pair(post, :StartDateYY, format(credit_card.start_year, :two_digits))

          add_pair(post, :IssueNumber, credit_card.issue_number)
        end

        add_pair(post, :CV2, credit_card.verification_value)
      end

      def commit(action, parameters)
        response = parse( ssl_post(URL, post_data(action, parameters)) )

        Response.new(response[:response_code] == APPROVED, message_from(response), response,
          :test => test?,
          :authorization => response[:cross_reference],
          :cvv_result => CVV_CODE[ response[:avscv2_response_code].to_s[0, 1] ],
          :avs_result => {
            :street_match => AVS_STREET_MATCH[ response[:avscv2_response_code].to_s[2, 1] ],
            :postal_match => AVS_POSTAL_MATCH[ response[:avscv2_response_code].to_s[1, 1] ]
          }
        )
      end

      def message_from(results)
        results[:response_code] == APPROVED ? "APPROVED" : results[:message]
      end

      def post_data(action, parameters = {})
        parameters.update(
          :MerchantPassword => @options[:password],
          :MerchantID => @options[:login],
          :MessageType => TRANSACTIONS[action],
          :CallBack => "disable",
          :DuplicateDelay => "0",
          :EchoCardType => "YES",
          :EchoAmount => "YES",
          :EchoAVSCV2ResponseCode => "YES",
          :ReturnAVSCV2Message => "YES",
          :CountryCode => '826' # 826 for UK based merchant
        )

        add_pair(parameters, :Dispatch, action == :authorization ? "LATER" : "NOW")

        parameters.collect { |key, value| "VP#{key}=#{CGI.escape(value.to_s)}" }.join("&")
      end

      # VPCrossReference
      # The value in VPCrossReference on a success transaction will contain
      # a unique reference that you may use to run future transactions.
      # Please note that cross reference transactions must come a static IP
      # addressed that has been pre-registered with Cardstream. To
      # register an IP address please send it to support@cardstream.com
      # with your Cardstream issued merchant ID and it will be added to
      # your account.
      def parse(body)
        result = {}
        pairs = body.split("&")
        pairs.each do |pair|
          a = pair.split("=")
          result[a[0].gsub(/^VP/,'').underscore.to_sym] = a[1]
        end

        result
      end

      def test?
        @options[:test] || Base.gateway_mode == :test
      end

      def currency_code(currency)
        CURRENCY_CODES[currency]
      end

      def add_pair(post, key, value, options = {})
        post[key] = value if !value.blank? || options[:required]
      end
    end
  end
end


text:
package phineas

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/levicook/slog"
)

type MarkdownResource struct {
	buildRoot   string
	contentRoot string
	contentPath string
}

func (r *MarkdownResource) Build() error {
	buildPath := r.BuildPath()

	if err := ensureDirectoryExists(filepath.Dir(buildPath)); err != nil {
		return err
	}

	file, err := os.Create(buildPath)
	defer file.Close()
	return err
}

func (r *MarkdownResource) BuildPath() string {
	// TODO rebuild w/ root() and base()?

	path, err := filepath.Rel(r.contentRoot, r.contentPath)
	slog.PanicIf(err)

	base := strings.TrimSuffix(filepath.Base(path), ".md")
	base = strings.Replace(base, "-", string(os.PathSeparator), 3)

	return filepath.Join(
		r.buildRoot,
		filepath.Dir(path),
		base,
		fmt.Sprintf("index.html"),
	)
}

func (r *MarkdownResource) base() string {
	return filepath.Base(r.contentPath)
}

func (r *MarkdownResource) root() string {
	root, err := filepath.Rel(r.contentRoot, filepath.Dir(r.contentPath))
	slog.PanicIf(err)
	return root
}

func (r *MarkdownResource) dayArchiveId() string {
	return filepath.Join(r.root(), r.base()[:10])
}

func (r *MarkdownResource) monthArchiveId() string {
	return filepath.Join(r.root(), r.base()[:7])
}

func (r *MarkdownResource) yearArchiveId() string {
	return filepath.Join(r.root(), r.base()[:4])
}


text:
<?php

namespace RegularLabs\Library\Condition;

defined('_JEXEC') or die;

/**
 * Class DateMonth
 * @package RegularLabs\Library\Condition
 */
class DateMonth
	extends Date
	implements \RegularLabs\Library\Api\ConditionInterface
{
	public function pass()
	{
		$month = $this->date->format('m', true); // 01 (for January) through 12 (for December)

		return $this->passSimple((int) $month);
	}
}


text:
k-Means
=======

.. figure:: icons/k-means.png

Groups items using the k-Means clustering algorithm.

Signals
-------

**Inputs**:

-  **Data**

   A data set.

**Outputs**:

-  **Data**

   A data set with cluster index as a class attribute.

Description
-----------

The widget applies the `k-Means clustering <https://en.wikipedia.org/wiki/K-means_clustering>`_
algorithm to the data and outputs a new data set in which the cluster
index is used as a class attribute. The original class attribute, if it
exists, is moved to meta attributes. Scores of clustering results for
various k are also shown in the widget.

.. figure:: images/kMeans-stamped.png

1. Select the number of clusters.

   -  **Fixed**: algorithm clusters data in a specified number of
      clusters.
   -  **Optimized**: widget shows clustering scores for the selected
      cluster range.
   -  `Silhouette <https://en.wikipedia.org/wiki/Silhouette_(clustering)>`_
      (contrasts average distance to elements in the same cluster with
      the average distance to elements in other clusters)
   -  **Inter-cluster distance** (measures distances between clusters,
      normally between centroids)
   -  **Distance to**
      `centroids <https://en.wikipedia.org/wiki/Centroid>`_ (measures
      distances to the arithmetic means of clusters)

2. Select the initialization method (the way the algorithm begins
   clustering):

   -  `k-Means++ <https://en.wikipedia.org/wiki/K-means%2B%2B>`_
      (first center is selected randomly, subsequent are chosen from the
      remaining points with probability proportioned to squared distance
      from the closest center)
   -  **Random initialization** (clusters are assigned randomly at first
      and then updated with further iterations)

   **Re-runs** (how many times the algorithm is run) and **maximal
   iterations** (the maximum number of iteration within each algorithm
   run) can be set manually.
3. The widget outputs a new data set with appended cluster information.
   Select how to append cluster information (as class, feature or meta
   attribute) and name the column.
4. If *Apply Automatically* is ticked, the widget will commit changes
   automatically. Alternatively, click *Apply*.
5. Produce a report.
6. Check scores of clustering results for various k.

Examples
--------

We are going to explore the widget with the following schema.

.. figure:: images/K-MeansClustering-Schema.png

First, we load the *Iris* data set, divide it into three clusters and
show it in the :doc:`Data Table <../data/datatable>`, where we can observe which instance went into
which cluster. The interesting parts are the :doc:`Scatter Plot <../visualize/scatterplot>` and
:doc:`Select Rows <../data/selectrows>`.

Since **k-Means** added the cluster index as a class attribute, the scatter plot
will color the points according to the clusters they are in.

.. figure:: images/kMeans-Scatterplot.png

What we are really interested in is how well the clusters induced by the
(unsupervised) clustering algorithm match the actual classes in the
data. We thus take :doc:`Select Rows <../data/selectrows>` widget, in which we can select
individual classes and have the corresponding points marked in the
scatter plot. The match is perfect for *setosa*, and pretty good for the
other two classes.

.. figure:: images/K-MeansClustering-Example.png

You may have noticed that we left the **Remove unused
values/attributes** and **Remove unused classes** in :doc:`Select Rows <../data/selectrows>`
unchecked. This is important: if the widget modifies the attributes, it
outputs a list of modified instances and the scatter plot cannot compare
them to the original data.

Perhaps a simpler way to test the match between clusters and the
original classes is to use the  :doc:`Distributions <../visualize/distributions>` widget.

.. figure:: images/K-MeansClustering-Schema2.png

The only (minor) problem here is that this widget only visualizes
normal (and not meta) attributes. We solve this by using
:doc:`Select Columns <../data/selectcolumns>`: we reinstate the original class *Iris* as the class
and put the cluster index among the attributes.

The match is perfect for *setosa*: all instances of setosa are in the
third cluster (blue). 48 *versicolors* are in the second cluster (red),
while two ended up in the first. For *virginicae*, 36 are in the first
cluster and 14 in the second.

.. figure:: images/K-MeansClustering-Example2.png


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bolm Soc. broteriana 2: 26 (1924)

#### Original name
Physalospora sampaioi Gonz. Frag.

### Remarks
null