text:
/

#ifndef _FLOAT_H
#define _FLOAT_H

#include <SIBCMath.h>		// SI_EPSILON
#include "AnimatableType.h" // CSLAnimatableType

//! Class that allows modification of a float parameter in a template
class XSIEXPORT CSLFloatProxy : public CSLAnimatableType
{
public:
	/*! Constructor. Connects to a parameter in the parent template
		\param in_pTemplate Pointer to the parent template
		\param in_Index Index of the parameter in the template
		\param in_fThreshold Tolerance value used to determine equality between two floats.
		\sa CSLFloatProxy::Threshold
		\sa CSLFloatProxy::SetThreshold
	 */
    CSLFloatProxy(CdotXSITemplate *in_pTemplate, SI_Int in_nIndex, SI_Float in_fThreshold = SI_EPSILON);

	/*! Assignment operator. Assigns \p in_Value to the parameter referred by this proxy.
		\param	in_Value	The new value
		\return Reference to the current object.
	*/
    CSLFloatProxy& operator =(const CSLFloatProxy &in_Value);

	/*! Assignment operator. Assigns \p in_Value to the parameter referred by this proxy.
		\param	in_Value	The new value
		\return Reference to the current object.
	*/
    CSLFloatProxy& operator =(const SI_Float &in_Value);

	/*! Comparison operator.
		Compares \p in_ToCompare with the value of the parameter referred by this proxy.
		\param	in_ToCompare	The instance to compare values with
		\return	Whether or not the referred parameter and \p in_ToCompare are
		equal
		\note Comparison is performed with a threshold value.  You can perform
		exact comparison by setting the Threshold value to zero.
		\sa CSLFloatProxy::Threshold
		\sa CSLFloatProxy::SetThreshold
	*/
    SI_Bool operator ==(const CSLFloatProxy &in_ToCompare);

	/*! Comparison operator. Compares \p in_ToCompare with the value of the parameter referred by this proxy.
		\param	in_ToCompare	The instance to compare values with
		\return	Whether or not the referred parameter and \p in_ToCompare are equal
		\note Comparison is performed with a threshold value.  You can perform
		exact comparison by setting the Threshold value to zero.
		\sa CSLFloatProxy::Threshold
		\sa CSLFloatProxy::SetThreshold
	*/
    SI_Bool operator ==(const SI_Float &in_ToCompare);

	//! Conversion operator
    operator SI_Float();

	/*! Returns the threshold value
		\return Tolerance value used to determine equality between two floats.
		\sa CSLFloatProxy::SetThreshold
	*/
	SI_Float Threshold();

	/*! Sets the thresold value
		\param in_fThreshold Tolerance value used to determine equality between two floats.
		\b Example
		\code
		// no threshold, the values must be absolutely equal
		CSLFloatProxy l_fProxy( in_pTemplate, in_paramIdx, 0.0 );
		l_fProxy = 0.00501;

		if ( l_fProxy == 0.005F )
		{
			// We get here because abs(0.00501 - 0.005) > 0
		}

		// use a tolerance of 0.0001
		l_fProxy.SetThreshold( 0.0001F );

		if ( l_fProxy == 0.005F )
		{
			// We get here because abs(0.00501 - 0.005) <= 0.0001
		}

		\endcode
		\sa CSLDoubleProxy::Threshold
	*/
	void SetThreshold( SI_Float in_fThreshold );

	/*! Returns the animatable type of this class
		\return CSLAnimatableType::SI_FLOAT_TYPE
	*/
	virtual EElementType Type();

	virtual SI_Float GetFloatValue();
	virtual SI_Void SetFloatValue(SI_Float in_fValue);

private:
	// no copy constructor
	CSLFloatProxy( CSLFloatProxy &in_pBasicType ){}

	SI_Bool Equal( SI_Float in_Float1, SI_Float in_Float2 );

	SI_Float m_fThreshold;
    SI_Float* m_pValue;
};

#endif


text:
const spawn = require('child_process').spawn;

const Switch = function(registry, op, device, callback) {
    if(device == null) callback("no device name provided");

    let err = "";
    console.log(__dirname);
    console.log(registry.dir() );
    const cmd = spawn("sudo", [ "python", __dirname + "/switch.py", op, device ], { cwd: registry.dir() });

    cmd.stdout.pipe(process.stdout);

    cmd.stderr.on("data", function(data) {
        err += data;
    });

    cmd.on("close", function(code) {
        if(callback != null) {
            if(err.length > 0) callback(err);
            else callback(null);
        }
    });
};

module.exports = Switch;

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.ComponentModel;

namespace Azure.ResourceManager.SecurityCenter.Models
{
    /// <summary> The user impact of the assessment. </summary>
    public readonly partial struct SecurityAssessmentUserImpact : IEquatable<SecurityAssessmentUserImpact>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="SecurityAssessmentUserImpact"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public SecurityAssessmentUserImpact(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string LowValue = "Low";
        private const string ModerateValue = "Moderate";
        private const string HighValue = "High";

        /// <summary> Low. </summary>
        public static SecurityAssessmentUserImpact Low { get; } = new SecurityAssessmentUserImpact(LowValue);
        /// <summary> Moderate. </summary>
        public static SecurityAssessmentUserImpact Moderate { get; } = new SecurityAssessmentUserImpact(ModerateValue);
        /// <summary> High. </summary>
        public static SecurityAssessmentUserImpact High { get; } = new SecurityAssessmentUserImpact(HighValue);
        /// <summary> Determines if two <see cref="SecurityAssessmentUserImpact"/> values are the same. </summary>
        public static bool operator ==(SecurityAssessmentUserImpact left, SecurityAssessmentUserImpact right) => left.Equals(right);
        /// <summary> Determines if two <see cref="SecurityAssessmentUserImpact"/> values are not the same. </summary>
        public static bool operator !=(SecurityAssessmentUserImpact left, SecurityAssessmentUserImpact right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="SecurityAssessmentUserImpact"/>. </summary>
        public static implicit operator SecurityAssessmentUserImpact(string value) => new SecurityAssessmentUserImpact(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is SecurityAssessmentUserImpact other && Equals(other);
        /// <inheritdoc />
        public bool Equals(SecurityAssessmentUserImpact other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
'use strict';

module.exports = {
  handlers: ['click-rail', 'drag-scrollbar', 'keyboard', 'wheel', 'touch'],
  maxScrollbarLength: null,
  minScrollbarLength: null,
  pageSpeed: 90,
  scrollXMarginOffset: 0,
  scrollYMarginOffset: 0,
  suppressScrollX: false,
  suppressScrollY: false,
  swipePropagation: true,
  useBothWheelAxes: false,
  wheelPropagation: false,
  wheelSpeed: 1,
  theme: 'default',
  scrollAwareShadows: false
};


text:
using System;
using System.IO;
using System.Text;
using bsn.GoldParser.Grammar;
using bsn.GoldParser.Parser;
using bsn.GoldParser.Semantic;
using GlobalcachingApplication.Plugins.FormulaSolver.FormulaInterpreter;
using GlobalcachingApplication.Plugins.FormulaSolver.FormulaInterpreter.Exception;

[assembly: RuleTrim("<Value> ::= '(' <Expression> ')'", "<Expression>", SemanticTokenType = typeof(GCToken))]

namespace GlobalcachingApplication.Plugins.FormulaSolver.FormulaInterpreter
{
    class FormulaInterpreter
    {
        private CompiledGrammar grammar;
        private SemanticTypeActions<GCToken> actions;

        public FormulaInterpreter(System.IO.BinaryReader reader)
        {
            grammar = CompiledGrammar.Load(reader);
            actions = new SemanticTypeActions<GCToken>(grammar);
            try
            {
                actions.Initialize(true);
            }
            catch (InvalidOperationException ex)
            {
                System.Diagnostics.Debug.Write(ex.Message);
            }
        }

        public object Exec(string input, ExecutionContext ctx)
        {
            var processor = new SemanticProcessor<GCToken>(new StringReader(input), actions);
            ParseMessage parseMessage = processor.ParseAll();

            if (parseMessage == ParseMessage.Accept)
            {
                var statement = processor.CurrentToken as Expression;
                if (statement != null)
                {
                    try
                    {
                        return statement.GetValue(ctx);
                    }
                    catch (FormulaSolverException ex)
                    {
                        return "??" + ex.Message;
                    }
                }
            }
            else
            {
                IToken token = processor.CurrentToken;
                return String.Format("??Syntax error at: {0} [{1}]", token.Position.Index, parseMessage);
            }

            return null;
        }

        private void InsertMissingVariableLines(string input, ExecutionContext ctx)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string name in ctx.GetMissingVariableNames())
            {
                sb.AppendLine(name + "=");
            }
            sb.Append(input);
            input = sb.ToString();
        }
    }
}


text:
<?php

namespace Flarum\Event;

use Flarum\Core\User;
use Flarum\Http\AccessToken;

class UserLoggedIn
{
    public $user;

    public $token;

    public function __construct(User $user, AccessToken $token)
    {
        $this->user = $user;
        $this->token = $token;
    }
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto

package com.google.cloud.compute.v1;

public interface InsertReservationRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.InsertReservationRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Project ID for this request.
   *

   *
   *
   * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
   *
   *
   * @return The project.
   */
  java.lang.String getProject();
  /**
   *
   *
   *

   * Project ID for this request.
   *

   *
   *
   * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
   *
   *
   * @return The bytes for project.
   */
  com.google.protobuf.ByteString getProjectBytes();

  /**
   *
   *
   *

   * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
   *

   *
   * optional string request_id = 37109963;
   *
   * @return Whether the requestId field is set.
   */
  boolean hasRequestId();
  /**
   *
   *
   *

   * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
   *

   *
   * optional string request_id = 37109963;
   *
   * @return The requestId.
   */
  java.lang.String getRequestId();
  /**
   *
   *
   *

   * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
   *

   *
   * optional string request_id = 37109963;
   *
   * @return The bytes for requestId.
   */
  com.google.protobuf.ByteString getRequestIdBytes();

  /**
   *
   *
   *

   * The body resource for this request
   *

   *
   *
   * .google.cloud.compute.v1.Reservation reservation_resource = 285030177 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return Whether the reservationResource field is set.
   */
  boolean hasReservationResource();
  /**
   *
   *
   *

   * The body resource for this request
   *

   *
   *
   * .google.cloud.compute.v1.Reservation reservation_resource = 285030177 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return The reservationResource.
   */
  com.google.cloud.compute.v1.Reservation getReservationResource();
  /**
   *
   *
   *

   * The body resource for this request
   *

   *
   *
   * .google.cloud.compute.v1.Reservation reservation_resource = 285030177 [(.google.api.field_behavior) = REQUIRED];
   *
   */
  com.google.cloud.compute.v1.ReservationOrBuilder getReservationResourceOrBuilder();

  /**
   *
   *
   *

   * Name of the zone for this request.
   *

   *
   *
   * string zone = 3744684 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "zone"];
   *
   *
   * @return The zone.
   */
  java.lang.String getZone();
  /**
   *
   *
   *

   * Name of the zone for this request.
   *

   *
   *
   * string zone = 3744684 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "zone"];
   *
   *
   * @return The bytes for zone.
   */
  com.google.protobuf.ByteString getZoneBytes();
}


text:
var colors = ["red","green","blue"];

for (var i = 0; i < colors.length; i++ ){
	console.log(colors[i]);
}

//arr.forEach(someFunction)

//will print it 3 times;
colors.forEach(function(){
	console.log("forEach color");
})

//

colors.forEach(function(colors){
	console.log(colors);
});


text:
[//]: # (title: PyCharm Plugin Development)

<!-- Copyright 2000-2022 JetBrains s.r.o. and other contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. -->

[PyCharm](https://www.jetbrains.com/pycharm/) is an IntelliJ Platform-based product.
Plugin projects for PyCharm can be developed using IntelliJ IDEA with the [](tools_gradle_intellij_plugin.md).

> Qualifying Open Source projects can [apply for free licenses](https://www.jetbrains.com/community/opensource/) of JetBrains products.
>

## Configuring Plugin Projects Targeting PyCharm
The configuration of PyCharm plugin projects follows the methods described in [Configuring Plugin Projects using a Product-Specific Attribute](dev_alternate_products.md#configuring-plugin-projects-using-a-product-specific-attribute), and [Configuring the plugin.xml File](dev_alternate_products.md#configuring-pluginxml).
The table below summarizes the [](tools_gradle_intellij_plugin.md) attributes to set in the Gradle build script.
Click on an entry in the table's *Attribute* column to go to the documentation about that attribute.

| `gradle-intellij-plugin` Attribute                                                               | Attribute Value                                                                |
|--------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------|
| [`intellij.type`](tools_gradle_intellij_plugin.md#intellij-extension-type)                       | `PY` for PyCharm Professional Edition, or `PC` for PyCharm Community Edition.  |
| [`intellij.version`](tools_gradle_intellij_plugin.md#intellij-extension-version)                 | Set to the targeted `PY` or `PC` version.                                      |
| [`intellij.plugins`](tools_gradle_intellij_plugin.md#intellij-extension-plugins)                 | `Pythonid` for `PY` / `PythonCore` for `PC`.                                   |
| [`intellij.downloadSources`](tools_gradle_intellij_plugin.md#intellij-extension-downloadsources) | `false` is required because no public source code is available.                |
| [`runIde.ideDir`](tools_gradle_intellij_plugin.md#tasks-runide-idedir)                            | Not needed; the Development Instance will automatically match `intellij.type`. |

The dependency on the PyCharm APIs must be declared in the <path>[plugin.xml](plugin_configuration_file.md)</path> file.
As described in [Configuring the plugin.xml File](dev_alternate_products.md#configuring-pluginxml), the [`<depends>`](plugin_configuration_file.md#idea-plugin__depends) tags must declare `com.intellij.modules.python`.

See the SDK code sample [`pycharm_basics`](%gh-sdk-samples%/product_specific/pycharm_basics/) for an example configuration.
Please note that this code sample must be imported into Gradle explicitly, as it is not included in the `_gradleCompositeBuild`.

## Available PyCharm APIs
See [](extension_point_list.md) for PyCharm Community.

The plugin [Python](https://plugins.jetbrains.com/plugin/631-python) (Plugin ID `Pythonid`) defines the APIs for PyCharm Professional.

The plugin [Python Community Edition](https://plugins.jetbrains.com/plugin/7322-python-community-edition) (Plugin ID `PythonCore`) defines the APIs for PyCharm Community.

These plugins include the modules `openapi` and `python-psi-api`.
These are considered stable APIs, but care should be taken to test your plugin with any version of PyCharm you wish to support.

## Additional Articles and Resources
* [Webinar Recording: "Live Development of a PyCharm Plugin" with Joachim Ansorg](https://blog.jetbrains.com/pycharm/2019/01/webinar-recording-live-development-of-a-pycharm-plugin-with-joachim-ansorg/)

## Open Source Plugins for PyCharm
When learning new development configurations, it is helpful to have some representative projects for reference:
* [Flake8 Support](https://github.com/jansorg/pycharm-flake8) Adds support for flake8's # noqa comments in PyCharm.


text:
<?php

namespace PHPExiftool\Driver\Tag\QuickTime;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class CameraID extends AbstractTag
{

    protected $Id = 'cmid';

    protected $Name = 'CameraID';

    protected $FullName = 'QuickTime::UserData';

    protected $GroupName = 'QuickTime';

    protected $g0 = 'QuickTime';

    protected $g1 = 'QuickTime';

    protected $g2 = 'Video';

    protected $Type = 'string';

    protected $Writable = false;

    protected $Description = 'Camera ID';
}


text:
import re
import sys
import argparse

def parse_fasta(fh):
    fa = {}
    current_short_name = None
    # Part 1: compile list of lines per sequence
    for ln in fh:
        if ln[0] == '>':
            # check for bad name
            if ":" in ln:
                print >> sys.stderr, "Error, your fasta records contain a ':' (%s). SALSA requires fasta to not contain this character, please update your fasta and re-try"%(ln[1:].rstrip())
                sys.exit(1)

            # new name line; remember current sequence's short name
            long_name = ln[1:].rstrip()
            current_short_name = long_name.split()[0]
            fa[current_short_name] = []
        else:
            # append nucleotides to current sequence
            fa[current_short_name].append(ln.rstrip())
    # Part 2: join lists into strings
    for short_name, nuc_list in fa.iteritems():
        # join this sequence's lines into one long string
        fa[short_name] = ''.join(nuc_list)
    return fa

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-a","--assembly",help="assembled contigs")
    parser.add_argument("-e","--enzyme",help="restriction enzyme")
    #parser.add_argument("-m","--mapping", help="mapping of read to contigs in bam format")
    #parser.add_argument("-d","--dir",help="output directory for results",default='out')
    args = parser.parse_args()
    f = parse_fasta(open(args.assembly,'r'))

    if args.enzyme == "DNASE":
        for key in f:
            id, seq = key, f[key]
            print id, len(seq)/2, len(seq)/2
        sys.exit(0)

    enzymes_input = args.enzyme.replace(' ','').split(',')
    final_enzymes = []
    for each in enzymes_input:
        if not re.match("^[ACGTN]+$", each):
            print >> sys.stderr, "Error, enzyme should be restriction site sequence (e.g. AACTT) not enzyme name or DNASE, you input %s"%(each)
            sys.exit(1)

        if 'N' in each:
            final_enzymes.append(each.replace('N','G'))
            final_enzymes.append(each.replace('N','A'))
            final_enzymes.append(each.replace('N','T'))
            final_enzymes.append(each.replace('N','C'))
        else:
            final_enzymes.append(each)

    for key in f:

        id,seq = key, f[key]
        left_count = 0
        rigt_count = 0
        for enzyme in final_enzymes:
            pos  = [m.start(0) for m in re.finditer(enzyme,seq)]

            length = len(seq)
            for each in pos:
            	if each < length/2:
            		left_count += 1
            	else:
            		rigt_count += 1

        # pos  = [m.start(0) for m in re.finditer(r"GA[ACTG]TC",seq)]

        # length = len(seq)

        # left_count = 0
        # rigt_count = 0
        # for each in pos:
        #     if each < length/2:
        #         left_count += 1
        #     else:
        #         rigt_count += 1

        print id, left_count, rigt_count

if __name__ == '__main__':
    main()


text:
<?php

namespace Illuminate\Database\Connectors;

use PDO;

class PostgresConnector extends Connector implements ConnectorInterface
{
    /**
     * The default PDO connection options.
     *
     * @var array
     */
    protected $options = [
        PDO::ATTR_CASE => PDO::CASE_NATURAL,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
        PDO::ATTR_STRINGIFY_FETCHES => false,
    ];

    /**
     * Establish a database connection.
     *
     * @param  array  $config
     * @return \PDO
     */
    public function connect(array $config)
    {
        // First we'll create the basic DSN and connection instance connecting to the
        // using the configuration option specified by the developer. We will also
        // set the default character set on the connections to UTF-8 by default.
        $dsn = $this->getDsn($config);

        $options = $this->getOptions($config);

        $connection = $this->createConnection($dsn, $config, $options);

        $charset = $config['charset'];

        $connection->prepare("set names '$charset'")->execute();

        // Next, we will check to see if a timezone has been specified in this config
        // and if it has we will issue a statement to modify the timezone with the
        // database. Setting this DB timezone is an optional configuration item.
        if (isset($config['timezone'])) {
            $timezone = $config['timezone'];

            $connection->prepare("set time zone '$timezone'")->execute();
        }

        // Unlike MySQL, Postgres allows the concept of "schema" and a default schema
        // may have been specified on the connections. If that is the case we will
        // set the default schema search paths to the specified database schema.
        if (isset($config['schema'])) {
            $schema = $this->formatSchema($config['schema']);

            $connection->prepare("set search_path to {$schema}")->execute();
        }

        // Postgres allows an application_name to be set by the user and this name is
        // used to when monitoring the application with pg_stat_activity. So we'll
        // determine if the option has been specified and run a statement if so.
        if (isset($config['application_name'])) {
            $applicationName = $config['application_name'];

            $connection->prepare("set application_name to '$applicationName'")->execute();
        }

        return $connection;
    }

    /**
     * Create a DSN string from a configuration.
     *
     * @param  array   $config
     * @return string
     */
    protected function getDsn(array $config)
    {
        // First we will create the basic DSN setup as well as the port if it is in
        // in the configuration options. This will give us the basic DSN we will
        // need to establish the PDO connections and return them back for use.
        extract($config, EXTR_SKIP);

        $host = isset($host) ? "host={$host};" : '';

        $dsn = "pgsql:{$host}dbname={$database}";

        // If a port was specified, we will add it to this Postgres DSN connections
        // format. Once we have done that we are ready to return this connection
        // string back out for usage, as this has been fully constructed here.
        if (isset($config['port'])) {
            $dsn .= ";port={$port}";
        }

        if (isset($config['sslmode'])) {
            $dsn .= ";sslmode={$sslmode}";
        }

        if (isset($config['sslcert'])) {
            $dsn .= ";sslcert={$sslcert}";
        }

        if (isset($config['sslkey'])) {
            $dsn .= ";sslkey={$sslkey}";
        }

        if (isset($config['sslrootcert'])) {
            $dsn .= ";sslrootcert={$sslrootcert}";
        }

        return $dsn;
    }

    /**
     * Format the schema for the DSN.
     *
     * @param  array|string  $schema
     * @return string
     */
    protected function formatSchema($schema)
    {
        if (is_array($schema)) {
            return '"'.implode('", "', $schema).'"';
        } else {
            return '"'.$schema.'"';
        }
    }
}


text:
class PrefService;

namespace ukm {

// Observer that monitors whether UKM is allowed for all profiles.
//
// For one profile, UKM is allowed iff URL-keyed anonymized data collection is
// enabled.
class UkmConsentStateObserver
    : public syncer::SyncServiceObserver,
      public unified_consent::UrlKeyedDataCollectionConsentHelper::Observer {
 public:
  UkmConsentStateObserver();

  UkmConsentStateObserver(const UkmConsentStateObserver&) = delete;
  UkmConsentStateObserver& operator=(const UkmConsentStateObserver&) = delete;

  ~UkmConsentStateObserver() override;

  // Starts observing whether UKM is allowed for a profile.
  // |pref_service| is the pref service of a profile.
  void StartObserving(syncer::SyncService* sync_service,
                      PrefService* pref_service);

  // Returns true iff all UKM is allowed for all profile states. This means that
  // URL-keyed anonymized data collection is enabled for all profiles.
  virtual bool IsUkmAllowedForAllProfiles();

  // Returns true iff sync is in a state that allows UKM to capture apps.
  // This means that all profiles have APPS data type enabled for syncing.
  virtual bool IsUkmAllowedWithAppsForAllProfiles();

  // Returns true iff sync is in a state that allows UKM to capture extensions.
  // This means that all profiles have EXTENSIONS data type enabled for syncing.
  virtual bool IsUkmAllowedWithExtensionsForAllProfiles();

 protected:
  // Called after UKM consent state changed.
  // If |total_purge| is true, the UKM is not allowed for some profile, and all
  // local data must be purged. Otherwise, more specific consents are checked
  // for individual sync settings, and recorded data may be partially purged if
  // we no longer have the corresponding sync consent.
  virtual void OnUkmAllowedStateChanged(bool total_purge) = 0;

 private:
  // syncer::SyncServiceObserver:
  void OnStateChanged(syncer::SyncService* sync) override;
  void OnSyncShutdown(syncer::SyncService* sync) override;

  // unified_consent::UrlKeyedDataCollectionConsentHelper::Observer:
  void OnUrlKeyedDataCollectionConsentStateChanged(
      unified_consent::UrlKeyedDataCollectionConsentHelper* consent_helper)
      override;

  // Recomputes |ukm_allowed_for_all_profiles_| and other specific consents
  // (e.g. Extension, ChromeOS apps) from |previous_states_|;
  void UpdateUkmAllowedForAllProfiles(bool total_purge);

  // Returns true iff all profile states in |previous_states_| allow UKM.
  // If there are no profiles being observed, this returns false.
  bool CheckPreviousStatesAllowUkm();

  // Returns true iff all profile states in |previous_states_| allow extension
  // UKM. If no profiles are being observed, this returns false.
  bool CheckPreviousStatesAllowExtensionUkm();

  // Returns true iff all profile states in |previous_states_| allow apps
  // UKM. If no profiles are being observed, this returns false.
  bool CheckPreviousStatesAllowAppsUkm();

  // Tracks observed sync services, for cleanup.
  base::ScopedMultiSourceObservation<syncer::SyncService,
                                     syncer::SyncServiceObserver>
      sync_observations_{this};

  // State data about profiles that we need to remember.
  struct ProfileState {
    // Returns true if this state allows UKM (i.e. URL-keyed anonymized
    // data collection is enabled).
    bool AllowsUkm() const;

    // Whether anonymized data collection is enabled.
    bool anonymized_data_collection_enabled = false;

    // Whether the user has extension sync enabled.
    bool extensions_enabled = false;

    // Whether the user has apps sync enabled.
    bool apps_sync_enabled = false;
  };

  // Updates the UKM enabled state for a profile and then triggers an update of
  // the state for all profiles.
  // |sync| and |consent_helper| must not be null.
  void UpdateProfileState(
      syncer::SyncService* sync,
      unified_consent::UrlKeyedDataCollectionConsentHelper* consent_helper);

  // Gets the current state of a profile.
  // |sync| and |consent_helper| must not be null.
  static ProfileState GetProfileState(
      syncer::SyncService* sync,
      unified_consent::UrlKeyedDataCollectionConsentHelper* consent_helper);

  // The state of the profile being observed.
  //
  // Note: UKM consent does not rely on sync but there must be exactly one
  // sync service per profile, so it is safe to key the profile states by the
  // sync service.
  std::map<syncer::SyncService*, ProfileState> previous_states_;

  // The list of URL-keyed anonymized data collection consent helpers.
  //
  // Note: UrlKeyedDataCollectionConsentHelper does not rely on sync but there
  // must be exactly one per Chromium profile. As there is a single sync service
  // per profile, it is safe to key them by sync service instead of introducing
  // an additional map.
  std::map<
      syncer::SyncService*,
      std::unique_ptr<unified_consent::UrlKeyedDataCollectionConsentHelper>>
      consent_helpers_;

  // Tracks if UKM is allowed on all profiles after the last state change.
  bool ukm_allowed_for_all_profiles_ = false;

  // Tracks if apps sync was enabled on all profiles after the last state
  // change.
  bool ukm_allowed_with_apps_for_all_profiles_ = false;

  // Tracks if extension sync was enabled on all profiles after the last state
  // change.
  bool ukm_allowed_with_extensions_for_all_profiles_ = false;
};

}  // namespace ukm

#endif  // COMPONENTS_UKM_OBSERVERS_UKM_CONSENT_STATE_OBSERVER_H_


text:
package me.jcala.blog.controller.admin;

import me.jcala.blog.domain.BlogView;
import me.jcala.blog.service.inter.BlogSer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * 后台管理中博客管理页面
 * 包括对博客的增,删,改
 * 此页面中所有处理请求的前缀为/admin,比如blogAdd方法匹配的url为/admin/blogAdd
 * The type Blog ctrl.
 */
@Controller
@RequestMapping("/admin")
public class BlogCtrl {

    private BlogSer blogSer;

    @Autowired
    public BlogCtrl(BlogSer blogSer) {
        this.blogSer = blogSer;
    }

    /**
     *后台管理中添加博客页面的控制器
     *
     * @return templates下的admin/blog_add.vm页面
     */
    @GetMapping("/blogAdd")
    public String blogAdd() {
        return "admin/blog_add";
    }

    /**
     * 后台管理中修改博客页面的控制器
     * 由于markdown编辑器的问题,使用了正则匹配update地址,而不是/update/{id}的形式
     *
     * @param id    要修改的博客的id
     * @return      templates下的admin/blog_add.vm页面
     */
    @GetMapping("/update{id:\\d+}")
    public String blogModify(@PathVariable int id,Model model){
        BlogView blogView=blogSer.adminGetBlog(id);
        if (blogView==null){
            return "error";
        }else {
            blogView.setVid(id);
            model.addAttribute("blog",blogView);
            return "admin/blog_modify";
        }
    }

    /**
     * 添加博客的表单控制器
     *
     * @param view  表单中提交的博客信息,包括标题,标签,md页面,和md转成的html页面
     * @return      templates下的result页面,用于提示是否保存博客成功
     */
    @PostMapping("/post.action")
    public String postAction(@ModelAttribute("blogForm") BlogView view, Model model){
        blogSer.addBlog(view);
        return "redirect:/admin/blogList/1";
    }

    /**
     * 更新博客的表单控制器
     *
     * @param view 表单中提交的博客信息,包括id,md页面,和md转成的html页面
     * @return     templates下的result页面,用于提示是否保存博客成功
     */
    @PostMapping("/update.action")
    public String update(@ModelAttribute("blogForm") BlogView view,Model model){
        blogSer.updateBlog(view);
        return "redirect:/post/"+view.getVid();
    }

    /**
     * 删除博客的控制器
     *
     * @param id    要删除的博客id
     */
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable int id,Model model){
        blogSer.deleteBlogById(id);
        return "redirect:/admin/blogList/1";
    }

    /**
     * 所有博客列表的显示界面.
     *
     * @param page  显示的为博客的第几页
     * @return      templates下的admin/blog_list.vm页面
     */
    @GetMapping("/blogList/{page}")
    public String blogList(@PathVariable int page, Model model) {
        model.addAttribute("current",page);
        model.addAttribute("pageNum",blogSer.adminGetPageNum());
        model.addAttribute("blogList",blogSer.getBlogPage(page));
        return "admin/blog_list";
    }
}


text:
layout: page
title: Composition Vs. Aggregation - Part 2
---

I'd really like to cover more historical content before making a second post, but I feel I am beginning to understand composition and aggregation much more than I understood these topics a few weeks ago...Especially after harassing a coworker about dependency injection so much.

I feel more comfortable in my absence of knowledge pertaining to these topics simply because I am starting to see the physical (source code) differences between the two. Coupled with my very basic understanding of dependency in general, the overall question of 'Composition Vs Aggregation' starts to make more sense.

> ### *Disclaimer: The following post is probably entirely in the wrong, and this is mostly for my own amusement.*

While I have not come across historical analysis of these two subjects, I am going to go out on a limb, and say that Aggregation is the more modern construct. A few things are making me lean in this direction, here's one of them:

## Striving for loosely coupled designs.

This is an abstract design principle that I can hardly claim to fully comprehend. But if I am understanding my readings correctly, concrete class objects that instantiate other concrete objects within themselves, are *dependent* on that class. That is to say, one object's ability to be instantiated and function as expected, is directly impacted on the availability of that second object. I'll attempt to hack through a C# example of Composition Vs Aggregation concerning this design principle.

#### Composition

{% highlight c# %}
  //An electric guitar that makes no sense without strings/electronics
  public class CompositionGuitar
  {
    private final HumbuckerSet humbuckerSet;
    private final StringSet stringSet;

    public CompositionGuitar(Brand brand){
      humbuckerSet = new HumbuckerSet(brand);
      stringSet = new StringSet(brand);
    }

    public void Shred(){
      stringSet.DoubleTapping();
      humbuckerSet.Transmit();
    }
  }
{% endhighlight %}

In this example, the guitar is used as a whole, and only serves its purpose once *composed* of its parts. Slash did not get drunk and shred on stage missing all his strings and half the electronics.

#### Aggregation
{% highlight c# %}
//An electric guitar a hobbyist has assembled and derived use from at all stages. The strings and electronics exist and have worth outside of the guitar's assembly.

public class AggregationGuitar
{
  private HumbuckerSet humbuckerSet;
  private StringSet stringSet;

  void assemblePieces(HumbuckerSet humbuckerSet, StringSet stringSet)
  {
    this.humbuckerSet = humbuckerSet;
    this.stringSet = stringSet;
    Console.WriteLine("I enjoy assembling this instrument!");
  }

  public void Shred(){
    if (humbuckerSet != null && stringSet != null)
    {
      stringSet.SweepPick();
      humbuckerSet.Transmite();
      Console.WriteLine("This also has value!");
    }
  }
}
{% endhighlight %}

Here, the AggregationGuitar expects an already existing set of humbuckers and set of strings before it can call a method. It is not dependent on its creation, and the code will compile fine...I think.

### My reasoning so far:
Designs that more closely resemble collections of orthogonal objects just seem to be the more advanced topic to me than the alternative. It follows the loosely-coupled principle more closely and I'd be willing to wager that the concept of functional aggregation took time to formalize...

Perhaps I'm just talking out of my ass. I need to read more.


text:
namespace SupermarketsChainDB.Data.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using SupermarketsChainDB.Models;
    using System.Collections.Generic;

    public sealed class Configuration : DbMigrationsConfiguration<SupermarketSystemDbContext>
    {
        public Configuration()
        {
            this.AutomaticMigrationsEnabled = true;
            this.AutomaticMigrationDataLossAllowed = true;
        }

        protected override void Seed(SupermarketSystemDbContext context)
        {
          //  OracleToSqlDb.MigrateToSql();

            /*

            //var measures = new List<Measure>
            //{
            //    new Measure { MeasureName = "liters" },
            //    new Measure { MeasureName = "pieces" },
            //    new Measure { MeasureName = "kg" }
            //};

            //var vendors = new List<Vendor>
            //{
            //    new Vendor { VendorName  = "Nestle Sofia Corp." },
            //    new Vendor { VendorName  = "Zagorka Corp." },
            //    new Vendor { VendorName  = "Targovishte Bottling Company Ltd." }

            //};

            //var products = new List<Product>
            //{
            //    new Product {  ProductName = "Beer "Zagorka"", Price = 0.86M, VendorId = 2, MeasureId = 1, ProductType = ProductType.AlcoholDrinks },
            //    new Product { ProductName = "Vodka "Targovishte"", Price = 7.56M, VendorId = 3, MeasureId = 1, ProductType = ProductType.AlcoholDrinks },
            //    new Product { ProductName = "Beer "Beck's"", Price = 1.03M, VendorId = 2, MeasureId = 1, ProductType = ProductType.AlcoholDrinks },
            //    new Product { ProductName = "Chocolate "Milka"", Price = 2.80M, VendorId = 1, MeasureId = 2, ProductType = ProductType.Confectionery },
            //};

            //foreach (var measure in measures)
            //{
            //    context.Measures.Add(measure);
            //}

            //context.SaveChanges();

            //foreach (var vendor in vendors)
            //{
            //    context.Vendors.Add(vendor);
            //}

            //context.SaveChanges();

            //foreach (var product in products)
            //{
            //    context.Products.Add(product);
            //}

            //context.SaveChanges();

            //base.Seed(context);*/
        }
    }
}


text:
@extends('layouts.masterLayout')

@section('html_title', 'SeAT Settings')

@section('page_content')

SeAT Settings

          {{ Form::open(array('action' => 'SettingsController@postUpdateSetting', 'class' => 'form-horizontal')) }}
            <fieldset>

              <legend>Global Settings</legend>

                Application Name

                  {{ Form::text('app_name', $app_name, array('id' => 'app_name', 'class' => 'form-control'), 'required', 'autofocus') }}
                  The Name of your SeAT Instance.

                Registration Enabled

                    {{ Form::select('registration_enabled', array('true' => 'Yes', 'false' => 'No'), $registration_enabled, array('class' => 'form-control')) }}
                    Are external parties allowed to register to your SeAT instance.

                Required API Mask

                    {{ Form::text('required_mask', $required_mask, array('id' => 'required_mask', 'class' => 'form-control'), 'required') }}
                    What is the minimum required API Key access mask.

                Administrator Contact Email

                    {{ Form::text('administrative_contact', $administrative_contact, array('id' => 'administrative_contact', 'class' => 'form-control'), 'required') }}
                    What is the email address for the SeAT administrator for this installation.

                Color Scheme

                    {{ Form::select('color_scheme', array('black' => 'black', 'blue' => 'blue'), $color_scheme, array('class' => 'form-control')) }}

                Number Format

                    100
                    {{ Form::select('thousand_seperator', array('.' => '.', ',' => ',', ' ' => '(space)'), $thousand_seperator, array('class' => 'form-inline form-control')) }}
                    000
                    {{ Form::select('decimal_seperator', array('.' => '.', ',' => ','), $decimal_seperator, array('class' => 'form-control')) }}
                    00

                  Set the thousand and decimal character, e.g: 100,000.00

              <legend>Seat Notifications Settings</legend>

                Note: These parameters affect the SeAT Notifications system

                Member Inactivity

                    {{ Form::text('seatnotify_member_inactivity_months', $seatnotify_member_inactivity_months, array('class' => 'form-control')) }}
                    After how many months should a character be considered inactive.

                Starbase Fuel Remainder Warning

                    {{ Form::text('seatnotify_fuel_warning_days', $seatnotify_fuel_warning_days, array('class' => 'form-control')) }}
                    How many days in advance should a starbase warn about fuel levels.

              <legend>Seat Queue Settings</legend>

                Note: These parameters affect the SeAT Job Queuing system. Disabling a section here will cease all update work for the affected section.

                Character Updater

                    {{ Form::select('seatscheduled_character', array('true' => 'Yes', 'false' => 'No'), $seatscheduled_character, array('class' => 'form-control')) }}
                    Updates all character related information.

                Corporation Updater

                    {{ Form::select('seatscheduled_corporation', array('true' => 'Yes', 'false' => 'No'), $seatscheduled_corporation, array('class' => 'form-control')) }}
                    Updates all Corporation related information, except for Assets and Wallets.

                Corporation Assets Updater

                    {{ Form::select('seatscheduled_corporation_assets', array('true' => 'Yes', 'false' => 'No'), $seatscheduled_corporation_assets, array('class' => 'form-control')) }}
                    Updates all Corporation Assets related information.

                Corporation Wallets Updater

                    {{ Form::select('seatscheduled_corporation_wallets', array('true' => 'Yes', 'false' => 'No'), $seatscheduled_corporation_wallets, array('class' => 'form-control')) }}
                    Updates all Corporation Wallets related information.

                Eve Updater

                    {{ Form::select('seatscheduled_eve', array('true' => 'Yes', 'false' => 'No'), $seatscheduled_eve, array('class' => 'form-control')) }}
                    Updates all Eve related information.

                Map Updater

                    {{ Form::select('seatscheduled_map', array('true' => 'Yes', 'false' => 'No'), $seatscheduled_map, array('class' => 'form-control')) }}
                    Updates all Map related information.

                Server Updater

                    {{ Form::select('seatscheduled_server', array('true' => 'Yes', 'false' => 'No'), $seatscheduled_server, array('class' => 'form-control')) }}
                    Updates all Server related information.

                Notification Updater

                    {{ Form::select('seatscheduled_notifications', array('true' => 'Yes', 'false' => 'No'), $seatscheduled_notifications, array('class' => 'form-control')) }}
                    Processes all Notifications related information.

                Queue Cleaner

                    {{ Form::select('seatscheduled_queue_cleanup', array('true' => 'Yes', 'false' => 'No'), $seatscheduled_queue_cleanup, array('class' => 'form-control')) }}
                    Cleans the Job Queue of long running jobs.

                  <button id="check-key" name="singlebutton" class="btn btn-success">Update Settings</button>

            </fieldset>
          {{ Form::close() }}

Module Manager

          Not yet, but sooooooooon!

@stop


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__free_wchar_t_declare_82.h
Label Definition File: CWE590_Free_Memory_Not_on_Heap__free.label.xml
Template File: sources-sink-82.tmpl.h
*/
/*
 * @description
 * CWE: 590 Free Memory Not on Heap
 * BadSource: declare Data buffer is declared on the stack
 * GoodSource: Allocate memory on the heap
 *    BadSink : Print then free data
 * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

namespace CWE590_Free_Memory_Not_on_Heap__free_wchar_t_declare_82
{

class CWE590_Free_Memory_Not_on_Heap__free_wchar_t_declare_82_base
{
public:
    /* pure virtual function */
    virtual void action(wchar_t * data) = 0;
};

#ifndef OMITBAD

class CWE590_Free_Memory_Not_on_Heap__free_wchar_t_declare_82_bad : public CWE590_Free_Memory_Not_on_Heap__free_wchar_t_declare_82_base
{
public:
    void action(wchar_t * data);
};

#endif /* OMITBAD */

#ifndef OMITGOOD

class CWE590_Free_Memory_Not_on_Heap__free_wchar_t_declare_82_goodG2B : public CWE590_Free_Memory_Not_on_Heap__free_wchar_t_declare_82_base
{
public:
    void action(wchar_t * data);
};

#endif /* OMITGOOD */

}


text:
from distutils.core import setup
from spreedly import __version__ as version

setup(name='django-spreedly',
      version=version,
      description="Spreedly hook-ins for Django, forked from shelfworthy/django-spreedly",
      author="Jon Smelquist",
      author_email="jon.smelquist@gmail.com",
      url="http://github.com/jsmelquist/django-spreedly",
      packages = ['spreedly','spreedly.pyspreedly']
      )


text:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';

import { LightboxModule } from 'primeng/primeng';// ADDED
import { GalleriaModule } from 'primeng/primeng'; // ADDED

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    LightboxModule,// ADDED
    GalleriaModule// ADDED
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


text:
Purpose:

* Validate the localStorage functionality is available

This usecase covers following methods:

* webapp localStorage setItem and getItem.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Thelephora textilis Spreng.

### Remarks
null


text:
<ion-grid id="canvas-menu">
  <ion-row>
    <ion-col id="view-menu" class="canvas-menu-item" (click)="togglePalette(4)">
      <button ion-button clear color="light" class="canvas-menu-item" >

      </button>
    </ion-col>
    <ion-col id="draw-menu" class="canvas-menu-item active-item" (click)="togglePalette(0)">
      <button ion-button clear color="light" class="canvas-menu-item" >

      </button>
    </ion-col>
    <ion-col id="field-menu" class="canvas-menu-item" (click)="togglePalette(1)">
      <button ion-button clear color="light" class="canvas-menu-item" >

      </button>
    </ion-col>
    <ion-col id="robot-menu" class="canvas-menu-item" (click)="togglePalette(2)">
      <button ion-button clear color="light" class="canvas-menu-item" >

      </button>
    </ion-col>
    <ion-col id="save-menu" class="canvas-menu-item" (click)="togglePalette(3)">
      <button ion-button clear color="light" class="canvas-menu-item" >

      </button>
    </ion-col>
    <ion-col id="open-menu" class="canvas-menu-item" (click)="togglePalette(5)">
      <button ion-button clear color="light" class="canvas-menu-item" >

      </button>
    </ion-col>
  </ion-row>
</ion-grid>

<ion-content id="canvas-scroll" scrollY="true">
  <ion-fab id="undo" right top class="fixed-fab">
    <button ion-fab mini color="light" (click)="undoState()"></button>
  </ion-fab>
  <ion-fab id="clear" right top class="fixed-fab">
    <button ion-fab mini color="light" (click)="confirmClear()"></button>
  </ion-fab>

    <ion-img id="canvas-bg" src="assets/2017-field.jpg"></ion-img>
    <canvas id="actual-canvas">
      Nope.
    </canvas>

</ion-content>

Draw Options

  <ion-list>
    <ion-item>
      <ion-range min="0" max="255" [(ngModel)]="red" color="red" (ionChange)="updateRed()" color="danger">
        <ion-label range-left color="danger">R</ion-label>
        <ion-label range-right color="danger" id="red-val"></ion-label>
      </ion-range>

    </ion-item>
    <ion-item>
      <ion-range min="0" max="255" [(ngModel)]="green" color="green" (ionChange)="updateGreen()" color="secondary">
        <ion-label range-left color="secondary">G</ion-label>
        <ion-label range-right color="secondary" id="green-val"></ion-label>
      </ion-range>

    </ion-item>
    <ion-item>
      <ion-range min="0" max="255" [(ngModel)]="blue" color="blue" (ionChange)="updateBlue()" color="primary">
        <ion-label range-left color="primary">B</ion-label>
        <ion-label range-right color="primary" id="blue-val"></ion-label>
      </ion-range>

    </ion-item>
  </ion-list>
  <ion-grid>
    <ion-row>
      <ion-segment [(ngModel)]="drawingValue" color="primary">
        <ion-segment-button value="pencil" (ionSelect)="changeDrawMode(0)">
          Pencil
        </ion-segment-button>
        <ion-segment-button value="line" (ionSelect)="changeDrawMode(1)">
          Line
        </ion-segment-button>
        <ion-segment-button value="eraser" (ionSelect)="changeDrawMode(2)">
          Eraser
        </ion-segment-button>
      </ion-segment>
    </ion-row>
    <ion-row>
      <ion-col>
        <ion-range min="1" max="10" [(ngModel)]="size" (ionChange)="updateBrushSize()">
          <ion-label range-left color="primary">Size</ion-label>
          <ion-label range-right color="primary" id="size-val"></ion-label>
        </ion-range>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col width-20 center>

          Result:

      </ion-col>
      <ion-col width-80>

      </ion-col>
    </ion-row>
  </ion-grid>

Field Menu

Robot Menu - {{ my_comp.short_name }}

    <ion-grid>
      <ion-row>
        <ion-label>Import from your event</ion-label>
        <ion-select [(ngModel)]="my_match_key" placeholder="Select Your Match" (ionChange)="getMatch()" *ngIf="!my_matches">
          <ion-option *ngFor="let match of my_comp.matches" value="{{ match.key }}">

              {{ matchConverter.convert(match) }}

          </ion-option>
        </ion-select>
        <ion-select [(ngModel)]="my_match_key" placeholder="Select Your Match" (ionChange)="getSortedMatch()" *ngIf="my_matches">
          <ion-option *ngFor="let match of my_matches" value="{{ match.key }}">

              {{ matchConverter.convert(match) }}

          </ion-option>
        </ion-select>
      </ion-row>
    </ion-grid>

        {{ my_match.alliances.red.teams[0].replace("frc", "") }}

        {{ my_match.alliances.red.teams[1].replace("frc", "") }}

        {{ my_match.alliances.red.teams[2].replace("frc", "") }}

        {{ my_match.alliances.blue.teams[0].replace("frc", "") }}

        {{ my_match.alliances.blue.teams[1].replace("frc", "") }}

        {{ my_match.alliances.blue.teams[2].replace("frc", "") }}

    <ion-grid>
      <ion-row>
        <ion-label>Add a robot manually</ion-label>
      </ion-row>
      <ion-row>
        <ion-input [(ngModel)]="robot_team_number" type="number" placeholder="e.g. 3618"></ion-input>
        <ion-select [(ngModel)]="robot_team_alliance" placeholder="Choose Alliance">
          <ion-option value="red-robot">Red Alliance</ion-option>
          <ion-option value="blue-robot">Blue Alliance</ion-option>
        </ion-select>
        <button ion-button icon-only (click)="addRobot()">
          <ion-icon name="add"></ion-icon>
        </button>
      </ion-row>
    </ion-grid>

        {{ robots[0].team_number }}

        {{ robots[1].team_number }}

        {{ robots[2].team_number }}

        {{ robots[3].team_number }}

        {{ robots[4].team_number }}

        {{ robots[5].team_number }}


text:
layout: page
title: House Omega Logistics Seminar
date: 2016-05-24
author: Peter Morse
tags: weekly links, java
status: published
summary: Vestibulum blandit fringilla consectetur. Duis.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 10/18/2019
  endDate: 10/20/2019
  ctyhocn: INDSBHX
  groupCode: HOLS
published: true
---
Curabitur placerat hendrerit dolor vitae laoreet. Quisque nec sem vel risus rhoncus tristique luctus eget elit. Nullam eget magna sem. Phasellus vel lorem elementum orci suscipit condimentum. Ut a nunc neque. Donec tellus urna, tincidunt eget velit eget, rutrum rutrum magna. Ut quis risus erat. Nunc dapibus imperdiet malesuada.
Suspendisse egestas pretium ante non ullamcorper. Phasellus nisi augue, sodales nec eros porta, facilisis imperdiet augue. Etiam purus enim, vulputate vitae vestibulum eu, scelerisque in leo. Aliquam erat volutpat. Cras sem sapien, tristique sit amet condimentum vitae, tristique id lorem. Integer tincidunt, lacus eu tincidunt lobortis, metus risus mattis turpis, vitae rhoncus nisl eros et metus. Nunc nec efficitur elit.

1 Mauris accumsan nibh quis justo pulvinar laoreet
1 In sed metus venenatis, tristique arcu ut, ultricies eros
1 Sed id risus vitae magna pulvinar vehicula
1 Etiam aliquam massa sed nunc sagittis, in consectetur dolor bibendum.

Suspendisse luctus quam non finibus consequat. Aenean molestie arcu porta dui tincidunt faucibus. Integer pretium semper rutrum. Vivamus congue auctor nisi sit amet scelerisque. Duis consequat in mauris id tincidunt. Aenean auctor finibus vestibulum. Pellentesque feugiat, augue nec ultricies dignissim, nulla sapien sodales purus, eget lacinia sem metus ut erat. Fusce placerat sapien vulputate orci convallis, sed fermentum nisl sodales. Fusce efficitur lacus ac iaculis commodo. Nam interdum condimentum massa. Curabitur varius facilisis orci. Praesent lobortis varius felis ac ornare. Praesent fringilla nibh ut sollicitudin consectetur.


text:
package org.onepf.opfpush.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import org.onepf.opfpush.listener.CheckManifestHandler;
import org.onepf.opfutils.OPFChecks;

import java.util.List;
import java.util.Locale;

/**
 * @author Roman Savin
 * @since 22.04.2015
 */
public final class CheckUtils {

    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    private CheckUtils() {
        throw new UnsupportedOperationException();
    }

    /**
     * Checks is a service has been described in the AndroidManifest.xml file.
     *
     * @param context The instance of {@link android.content.Context}.
     * @param service The checked service.
     */
    @SuppressWarnings("PMD.PreserveStackTrace")
    public static void checkService(@NonNull final Context context,
                                    @NonNull final ComponentName service,
                                    @Nullable final CheckManifestHandler checkManifestHandler) {
        final PackageManager packageManager = context.getPackageManager();
        try {
            packageManager.getServiceInfo(service, 0);
        } catch (PackageManager.NameNotFoundException e) {
            final String message = "Service " + service.getClassName()
                    + " hasn't been declared in AndroidManifest.xml";

            if (checkManifestHandler == null) {
                throw new IllegalStateException(message);
            } else {
                checkManifestHandler.onCheckManifestError(message);
            }
        }
    }

    public static void checkPermission(@NonNull final Context context,
                                       @NonNull final String permission,
                                       @Nullable final CheckManifestHandler checkManifestHandler) {

        checkPermission(
                context,
                permission,
                String.format(
                        Locale.US,
                        "You must add %s permission to the AndroidManifest.xml",
                        permission
                ),
                checkManifestHandler
        );
    }

    /**
     * Checks is a permission has been described in the AndroidManifest.xml file.
     *
     * @param context          The instance of {@link android.content.Context}.
     * @param permission       The checked permission.
     * @param exceptionMessage The exception message.
     */
    @SuppressWarnings("PMD.EmptyCatchBlock")
    public static void checkPermission(@NonNull final Context context,
                                       @NonNull final String permission,
                                       @NonNull final String exceptionMessage,
                                       @Nullable final CheckManifestHandler checkManifestHandler) {
        if (TextUtils.isEmpty(permission)) {
            throw new IllegalArgumentException("Permission can't be null or empty.");
        }

        try {
            final PackageInfo info = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
            final String[] requestedPermissions = info.requestedPermissions;
            if (requestedPermissions != null) {
                for (String requestedPermission : requestedPermissions) {
                    if (TextUtils.equals(permission, requestedPermission)) {
                        return;
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException ignore) {
            // ignore
        }

        if (checkManifestHandler == null) {
            throw new SecurityException(exceptionMessage);
        } else {
            checkManifestHandler.onCheckManifestError(exceptionMessage);
        }
    }

    public static void checkReceiver(@NonNull final Context context,
                                     @NonNull final Intent broadcastIntent,
                                     @Nullable final CheckManifestHandler checkManifestHandler) {
        checkReceiver(context, null, broadcastIntent, null, checkManifestHandler);
    }

    public static void checkReceiver(@NonNull final Context context,
                                     @NonNull final String receiverName,
                                     @NonNull final Intent broadcastIntent,
                                     @Nullable final CheckManifestHandler checkManifestHandler) {
        checkReceiver(context, receiverName, broadcastIntent, null, checkManifestHandler);
    }

    public static void checkReceiver(@NonNull final Context context,
                                     @NonNull final Intent broadcastIntent,
                                     @NonNull final String permission,
                                     @Nullable final CheckManifestHandler checkManifestHandler) {
        checkReceiver(context, null, broadcastIntent, permission, checkManifestHandler);
    }

    /**
     * Checks is a receiver has been described in the AndroidManifest.xml file.
     *

     * Uses the following steps for the check:
     *

     *
Checks are there receivers that can handle the {@code broadcastIntent}.

     *
Checks is there receiver with the package name corresponding to the app package name.

     *
If the {@code receiverName} is no {@code null},
     * checks is there receiver belong the founded receivers with the required name.

     *
If the {code permission} is no {@code null}, checks does the founded receiver have this permission.

     *

     *
     * @param context         The instance of {@link android.content.Context}.
     * @param receiverName    The name of the checked receiver.
     * @param broadcastIntent The intent which must be handled by the checked receiver.
     * @param permission      The permission that must be defined for the checked receiver.
     */
    public static void checkReceiver(@NonNull final Context context,
                                     @Nullable final String receiverName,
                                     @NonNull final Intent broadcastIntent,
                                     @Nullable final String permission,
                                     @Nullable final CheckManifestHandler checkManifestHandler) {
        if (checkManifestHandler == null) {
            OPFChecks.checkReceiver(context, receiverName, broadcastIntent, permission);
        } else {
            safeCheckReceiver(context, receiverName, broadcastIntent, permission, checkManifestHandler);
        }
    }

    private static void safeCheckReceiver(@NonNull final Context context,
                                          @Nullable final String receiverName,
                                          @NonNull final Intent broadcastIntent,
                                          @Nullable final String permission,
                                          @NonNull final CheckManifestHandler checkManifestHandler) {
        try {
            OPFChecks.checkReceiver(context, receiverName, broadcastIntent, permission);
        } catch (IllegalStateException e) {
            final String message = prepareCheckReceiverReport(context, e.getMessage(), receiverName, broadcastIntent);
            checkManifestHandler.onCheckManifestError(message);
        }
    }

    @SuppressWarnings({"PMD.ModifiedCyclomaticComplexity", "PMD.StdCyclomaticComplexity", "PMD.ConsecutiveLiteralAppends"})
    @NonNull
    private static String prepareCheckReceiverReport(@NonNull final Context context,
                                                     @Nullable final String exceptionMessage,
                                                     @Nullable final String receiverName,
                                                     @NonNull final Intent broadcastIntent) {
        final String packageName = context.getPackageName();

        final StringBuilder reportBuilder = new StringBuilder("checkReceiver error")
                .append(LINE_SEPARATOR).append("Exception message : ").append(exceptionMessage)
                .append(LINE_SEPARATOR).append("Expected receiverName : ").append(receiverName)
                .append(LINE_SEPARATOR).append("Intent action : ").append(broadcastIntent.getAction());

        final PackageManager packageManager = context.getPackageManager();
        final List<ResolveInfo> receivers = packageManager
                .queryBroadcastReceivers(broadcastIntent, PackageManager.GET_INTENT_FILTERS);
        if (receivers == null) {
            reportBuilder.append(LINE_SEPARATOR).append("queryBroadcastReceivers returns null");
        } else if (receivers.isEmpty()) {
            reportBuilder.append(LINE_SEPARATOR).append("queryBroadcastReceivers returns empty list");
        } else {
            reportBuilder.append(LINE_SEPARATOR)
                    .append("queryBroadcastReceivers returns not empty list. List size : ").append(receivers.size())
                    .append(LINE_SEPARATOR)
                    .append("PackageName : ").append(packageName);

            int emptyPackageNameCounter = 0;
            int emptyReceiverNameCounter = 0;
            for (ResolveInfo receiver : receivers) {
                if (TextUtils.isEmpty(receiver.activityInfo.packageName)) {
                    ++emptyPackageNameCounter;
                } else if (receiver.activityInfo.packageName.equals(packageName)) {
                    reportBuilder.append(LINE_SEPARATOR)
                            .append("Receiver with right package : ")
                            .append(receiver.activityInfo.name);
                }
                if (TextUtils.isEmpty(receiver.activityInfo.name)) {
                    ++emptyReceiverNameCounter;
                } else if (receiver.activityInfo.name.equals(receiverName)) {
                    reportBuilder.append(LINE_SEPARATOR)
                            .append("Receiver with right name has package : ")
                            .append(receiver.activityInfo.packageName);
                }
            }

            reportBuilder.append(LINE_SEPARATOR)
                    .append("Receivers with empty package name : ").append(emptyPackageNameCounter)
                    .append(LINE_SEPARATOR)
                    .append("Receivers with empty name : ").append(emptyReceiverNameCounter);
        }

        reportBuilder.append(LINE_SEPARATOR)
                .append("Available receivers:");

        PackageInfo receiversInfo;
        try {
            receiversInfo = packageManager.getPackageInfo(
                    packageName, PackageManager.GET_RECEIVERS);
        } catch (PackageManager.NameNotFoundException e) {
            reportBuilder.append("Could not get receivers for package ").append(packageName);
            return reportBuilder.toString();
        }
        ActivityInfo[] packageReceivers = receiversInfo.receivers;

        for (ActivityInfo packageReceiver : packageReceivers) {
            reportBuilder.append(LINE_SEPARATOR)
                    .append("Receiver package : ")
                    .append(packageReceiver.packageName)
                    .append(" receiver name : ")
                    .append(packageReceiver.name);
        }

        return reportBuilder.toString();
    }
}


text:
<?php

namespace Magento\Framework\Filesystem\Directory;

use Magento\Framework\Filesystem\DriverPool;
use Magento\TestFramework\Helper\Bootstrap;

/**
 * Class ReadTest
 * Test for Magento\Framework\Filesystem\Directory\Read class
 */
class WriteTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test data to be cleaned
     *
     * @var array
     */
    private $testDirectories = [];

    /**
     * Test instance of Read
     */
    public function testInstance()
    {
        $dir = $this->getDirectoryInstance('newDir1', 0777);
        $this->assertTrue($dir instanceof ReadInterface);
        $this->assertTrue($dir instanceof WriteInterface);
    }

    /**
     * Test for create method
     *
     * @dataProvider createProvider
     * @param string $basePath
     * @param int $permissions
     * @param string $path
     */
    public function testCreate($basePath, $permissions, $path)
    {
        $directory = $this->getDirectoryInstance($basePath, $permissions);
        $this->assertTrue($directory->create($path));
        $this->assertTrue($directory->isExist($path));
    }

    /**
     * Data provider for testCreate
     *
     * @return array
     */
    public function createProvider()
    {
        return [
            ['newDir1', 0777, "newDir1"],
            ['newDir1', 0777, "root_dir1/subdir1/subdir2"],
            ['newDir2', 0777, "root_dir2/subdir"],
            ['newDir1', 0777, "."]
        ];
    }

    /**
     * Test for delete method
     *
     * @dataProvider deleteProvider
     * @param string $path
     */
    public function testDelete($path)
    {
        $directory = $this->getDirectoryInstance('newDir', 0777);
        $directory->create($path);
        $this->assertTrue($directory->isExist($path));
        $directory->delete($path);
        $this->assertFalse($directory->isExist($path));
    }

    /**
     * Data provider for testDelete
     *
     * @return array
     */
    public function deleteProvider()
    {
        return [['subdir'], ['subdir/subsubdir']];
    }

    /**
     * Test for rename method (in scope of one directory instance)
     *
     * @dataProvider renameProvider
     * @param string $basePath
     * @param int $permissions
     * @param string $name
     * @param string $newName
     */
    public function testRename($basePath, $permissions, $name, $newName)
    {
        $directory = $this->getDirectoryInstance($basePath, $permissions);
        $directory->touch($name);
        $created = $directory->read();
        $directory->renameFile($name, $newName);
        $renamed = $directory->read();
        $this->assertTrue(in_array($name, $created));
        $this->assertTrue(in_array($newName, $renamed));
        $this->assertFalse(in_array($name, $renamed));
    }

    /**
     * Data provider for testRename
     *
     * @return array
     */
    public function renameProvider()
    {
        return [['newDir1', 0777, 'first_name.txt', 'second_name.txt']];
    }

    /**
     * Test for rename method (moving to new directory instance)
     *
     * @dataProvider renameTargetDirProvider
     * @param string $firstDir
     * @param string $secondDir
     * @param int $permission
     * @param string $name
     * @param string $newName
     */
    public function testRenameTargetDir($firstDir, $secondDir, $permission, $name, $newName)
    {
        $dir1 = $this->getDirectoryInstance($firstDir, $permission);
        $dir2 = $this->getDirectoryInstance($secondDir, $permission);

        $dir1->touch($name);
        $created = $dir1->read();
        $dir1->renameFile($name, $newName, $dir2);
        $oldPlace = $dir1->read();

        $this->assertTrue(in_array($name, $created));
        $this->assertFalse(in_array($name, $oldPlace));
    }

    /**
     * Data provider for testRenameTargetDir
     *
     * @return array
     */
    public function renameTargetDirProvider()
    {
        return [['dir1', 'dir2', 0777, 'first_name.txt', 'second_name.txt']];
    }

    /**
     * Test for copy method (copy in scope of one directory instance)
     *
     * @dataProvider renameProvider
     * @param string $basePath
     * @param int $permissions
     * @param string $name
     * @param string $newName
     */
    public function testCopy($basePath, $permissions, $name, $newName)
    {
        $directory = $this->getDirectoryInstance($basePath, $permissions);
        $file = $directory->openFile($name, 'w+');
        $file->close();
        $directory->copyFile($name, $newName);
        $this->assertTrue($directory->isExist($name));
        $this->assertTrue($directory->isExist($newName));
    }

    /**
     * Data provider for testCopy
     *
     * @return array
     */
    public function copyProvider()
    {
        return [
            ['newDir1', 0777, 'first_name.txt', 'second_name.txt'],
            ['newDir1', 0777, 'subdir/first_name.txt', 'subdir/second_name.txt']
        ];
    }

    /**
     * Test for copy method (copy to another directory instance)
     *
     * @dataProvider copyTargetDirProvider
     * @param string $firstDir
     * @param string $secondDir
     * @param int $permission
     * @param string $name
     * @param string $newName
     */
    public function testCopyTargetDir($firstDir, $secondDir, $permission, $name, $newName)
    {
        $dir1 = $this->getDirectoryInstance($firstDir, $permission);
        $dir2 = $this->getDirectoryInstance($secondDir, $permission);

        $file = $dir1->openFile($name, 'w+');
        $file->close();
        $dir1->copyFile($name, $newName, $dir2);

        $this->assertTrue($dir1->isExist($name));
        $this->assertTrue($dir2->isExist($newName));
    }

    /**
     * Data provider for testCopyTargetDir
     *
     * @return array
     */
    public function copyTargetDirProvider()
    {
        return [
            ['dir1', 'dir2', 0777, 'first_name.txt', 'second_name.txt'],
            ['dir1', 'dir2', 0777, 'subdir/first_name.txt', 'subdir/second_name.txt']
        ];
    }

    /**
     * Test for changePermissions method
     */
    public function testChangePermissions()
    {
        $directory = $this->getDirectoryInstance('newDir1', 0777);
        $directory->create('test_directory');
        $this->assertTrue($directory->changePermissions('test_directory', 0644));
    }

    /**
     * Test for changePermissionsRecursively method
     */
    public function testChangePermissionsRecursively()
    {
        $directory = $this->getDirectoryInstance('newDir1', 0777);
        $directory->create('test_directory');
        $directory->create('test_directory/subdirectory');
        $directory->writeFile('test_directory/subdirectory/test_file.txt', 'Test Content');

        $this->assertTrue($directory->changePermissionsRecursively('test_directory', 0777, 0644));
    }

    /**
     * Test for touch method
     *
     * @dataProvider touchProvider
     * @param string $basePath
     * @param int $permissions
     * @param string $path
     * @param int $time
     */
    public function testTouch($basePath, $permissions, $path, $time)
    {
        $directory = $this->getDirectoryInstance($basePath, $permissions);
        $directory->openFile($path);
        $this->assertTrue($directory->touch($path, $time));
        $this->assertEquals($time, $directory->stat($path)['mtime']);
    }

    /**
     * Data provider for testTouch
     *
     * @return array
     */
    public function touchProvider()
    {
        return [
            ['test_directory', 0777, 'touch_file.txt', time() - 3600],
            ['test_directory', 0777, 'subdirectory/touch_file.txt', time() - 3600]
        ];
    }

    /**
     * Test isWritable method
     */
    public function testIsWritable()
    {
        $directory = $this->getDirectoryInstance('newDir1', 0777);
        $directory->create('bar');
        $this->assertFalse($directory->isWritable('not_existing_dir'));
        $this->assertTrue($directory->isWritable('bar'));
    }

    /**
     * Test for openFile method
     *
     * @dataProvider openFileProvider
     * @param string $basePath
     * @param int $permissions
     * @param string $path
     * @param string $mode
     */
    public function testOpenFile($basePath, $permissions, $path, $mode)
    {
        $directory = $this->getDirectoryInstance($basePath, $permissions);
        $file = $directory->openFile($path, $mode);
        $this->assertTrue($file instanceof \Magento\Framework\Filesystem\File\WriteInterface);
        $file->close();
    }

    /**
     * Data provider for testOpenFile
     *
     * @return array
     */
    public function openFileProvider()
    {
        return [
            ['newDir1', 0777, 'newFile.txt', 'w+'],
            ['newDir1', 0777, 'subdirectory/newFile.txt', 'w+']
        ];
    }

    /**
     * Test writeFile
     *
     * @dataProvider writeFileProvider
     * @param string $path
     * @param string $content
     * @param string $extraContent
     */
    public function testWriteFile($path, $content, $extraContent)
    {
        $directory = $this->getDirectoryInstance('writeFileDir', 0777);
        $directory->writeFile($path, $content);
        $this->assertEquals($content, $directory->readFile($path));
        $directory->writeFile($path, $extraContent);
        $this->assertEquals($extraContent, $directory->readFile($path));
    }

    /**
     * Test writeFile for append mode
     *
     * @dataProvider writeFileProvider
     * @param string $path
     * @param string $content
     * @param string $extraContent
     */
    public function testWriteFileAppend($path, $content, $extraContent)
    {
        $directory = $this->getDirectoryInstance('writeFileDir', 0777);
        $directory->writeFile($path, $content, 'a+');
        $this->assertEquals($content, $directory->readFile($path));
        $directory->writeFile($path, $extraContent, 'a+');
        $this->assertEquals($content . $extraContent, $directory->readFile($path));
    }

    /**
     * Data provider for testWriteFile and testWriteFileAppend
     *
     * @return array
     */
    public function writeFileProvider()
    {
        return [['file1', '123', '456'], ['folder1/file1', '123', '456']];
    }

    /**
     * Tear down
     */
    public function tearDown()
    {
        /** @var Write $directory */
        foreach ($this->testDirectories as $directory) {
            if ($directory->isExist()) {
                $directory->delete();
            }
        }
    }

    /**
     * Get readable file instance
     * Get full path for files located in _files directory
     *
     * @param string $path
     * @param string $permissions
     * @return Write
     */
    private function getDirectoryInstance($path, $permissions)
    {
        $fullPath = __DIR__ . '/../_files/' . $path;
        $objectManager = Bootstrap::getObjectManager();
        /** @var \Magento\Framework\Filesystem\Directory\WriteFactory $directoryFactory */
        $directoryFactory = $objectManager->create('Magento\Framework\Filesystem\Directory\WriteFactory');
        $directory = $directoryFactory->create($fullPath, DriverPool::FILE, $permissions);
        $this->testDirectories[] = $directory;
        return $directory;
    }
}


text:
[consul.io](https://www.consul.io/) service discovery

[![Size / layers](https://imagelayers.io/badge/travix/consul:0.6.4.svg)](https://imagelayers.io/?images=travix/consul:0.6.4)
[![Stars](https://img.shields.io/docker/stars/travix/consul.svg)](https://hub.docker.com/r/travix/consul/)
[![Pulls](https://img.shields.io/docker/pulls/travix/consul.svg)](https://hub.docker.com/r/travix/consul/)
[![License](https://img.shields.io/github/license/Travix-International/docker-consul.svg)](https://github.com/Travix-International/docker-consul/blob/master/LICENSE)

# Usage

To run this docker container use the following command for the 1st node in a server cluster

```sh
docker run -d \
    travix/consul:latest
```


text:
package presentation.controllers;

import javafx.fxml.FXML;

/**
 * Created by Patrick on 19.06.2015.
 */
public class MainController
{
    /**
     * Initializes the models used by the main view
     */
    public MainController()
    {
    }

    @FXML
    public void initialize()
    {
    }
}


text:
import { DebugElement } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DummyComponent } from 'src/app/mocks/components/dummy.component';

import { AutofocusDirective } from './autofocus.directive';

describe('AutofocusDirective', () => {
  let fixture: ComponentFixture<DummyComponent>;
  let debugElement: DebugElement;
  let directive: AutofocusDirective;

  beforeEach(
    waitForAsync(() => {
      void TestBed.configureTestingModule({
        declarations: [DummyComponent, AutofocusDirective],
      })
        .compileComponents()
        .then(() => {
          fixture = TestBed.createComponent(DummyComponent);
          debugElement = fixture.debugElement.query(By.directive(AutofocusDirective));
          directive = debugElement.injector.get(AutofocusDirective);
        });
    }),
  );

  it('dummy component should compile successfully', () => {
    expect(directive).toBeDefined();
  });

  it('should have variables and methods defined', () => {
    expect(directive?.nativeElement?.autofocus).toBeUndefined();
    expect(directive.autofocusState).toEqual(expect.any(Boolean));
  });

  it('ngOnInit should call directive renderer invokeElementMethod if autofocus condition is met', () => {
    const focusSpy = spyOn(directive.el.nativeElement, 'focus');

    directive.autofocusState = false;
    directive.ngOnInit();
    expect(focusSpy).not.toHaveBeenCalled();

    directive.autofocusState = true;
    directive.ngOnInit();
    expect(focusSpy).toHaveBeenCalled();
  });

  it('autofocus method should set autofocusState property', () => {
    directive.autofocus = true;
    expect(directive.autofocusState).toBeTruthy();
    directive.autofocus = false;
    expect(directive.autofocusState).toBeFalsy();
  });
});


text:
from django.contrib import admin

from anafero.models import Referral, ReferralResponse

admin.site.register(
    Referral,
    list_display=[
        "user",
        "code",
        "label",
        "redirect_to",
        "target_content_type",
        "target_object_id"
    ],
    readonly_fields=["code", "created_at"],
    list_filter=["target_content_type", "created_at"],
    search_fields=["user", "code"]
)

admin.site.register(
    ReferralResponse,
    list_display=[
        "referral",
        "session_key",
        "user",
        "ip_address",
        "action"
    ],
    readonly_fields=["referral", "session_key", "user", "ip_address", "action"],
    list_filter=["action", "created_at"],
    search_fields=["referral__code", "referral__user__username", "ip_address"]
)


text:
/**
 * Copyright (c) 2009 Carnegie Mellon University.
 *     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.
 *
 * For more about this software visit:
 *
 *      http://www.graphlab.ml.cmu.edu
 *
 */

#ifndef GRAPHLAB_DHT_HPP
#define GRAPHLAB_DHT_HPP

#include <boost/functional/hash.hpp>
#include <boost/unordered_map.hpp>
#include <parallel/pthread_tools.hpp>
#include <rpc/dc_dist_object.hpp>

namespace graphlab {

  /**
   * \ingroup rpc
   * Implements a very rudimentary distributed key value store.
   */
  template <typename KeyType, typename ValueType>
  class dht {

  public:
    typedef boost::unordered_map<size_t, ValueType> storage_type;

  private:
    mutable dc_dist_object< dht > rpc;

    boost::hash<KeyType> hasher;
    mutex lock;
    storage_type storage;

  public:
    dht(distributed_control &dc) : rpc(dc, this) { }

    /**
     * Get the owner of the key
     */
    procid_t owner(const KeyType& key) const {
      return hasher(key) % rpc.dc().numprocs();
    }

    /**
     * gets the value associated with a key.
     * Returns (true, Value) if the entry is available.
     * Returns (false, undefined) otherwise.
     */
    std::pair<bool, ValueType> get(const KeyType &key) const {
      // who owns the data?

      const size_t hashvalue = hasher(key);
      const size_t owningmachine = hashvalue % rpc.numprocs();
      std::pair<bool, ValueType> retval;
      // if it is me, we can return it
      if (owningmachine == rpc.dc().procid()) {

        lock.lock();
        typename storage_type::const_iterator iter = storage.find(hashvalue);
        retval.first = iter != storage.end();
        if (retval.first) retval.second = iter->second;
        lock.unlock();
      } else {
        retval = rpc.RPC_CALL(remote_request, dht<KeyType,ValueType>::get)
            (owningmachine, key);
      }
      return retval;
    }

    /**
     * gets the value associated with a key.
     * Returns (true, Value) if the entry is available.
     * Returns (false, undefined) otherwise.
     */
    request_future<std::pair<bool, ValueType> > get_future(const KeyType &key) const {
      // who owns the data?

      const size_t hashvalue = hasher(key);
      const size_t owningmachine = hashvalue % rpc.numprocs();
      std::pair<bool, ValueType> retval;
      // if it is me, we can return it
      if (owningmachine == rpc.dc().procid()) {

        lock.lock();
        typename storage_type::const_iterator iter = storage.find(hashvalue);
        retval.first = iter != storage.end();
        if (retval.first) retval.second = iter->second;
        lock.unlock();
        return retval;
      } else {
        return rpc.RPC_CALL(future_remote_request,dht<KeyType,ValueType>::get)
                             (owningmachine, key);
      }
    }

    /**
     * Sets the newval to be the value associated with the key
     */
    void set(const KeyType &key, const ValueType &newval) {
      // who owns the data?
      const size_t hashvalue = hasher(key);
      const size_t owningmachine = hashvalue % rpc.numprocs();

      // if it is me, set it
      if (owningmachine == rpc.dc().procid()) {
        lock.lock();
        storage[hashvalue] = newval;
        lock.unlock();
      } else {
        rpc.RPC_CALL(remote_call,dht<KeyType,ValueType>::set)
                     (owningmachine, key, newval);
      }
    }

    void print_stats() const {
      std::cerr << rpc.calls_sent() << " calls sent\n";
      std::cerr << rpc.calls_received() << " calls received\n";
    }

    /**
       Must be called by all machines simultaneously
    */
    void clear() {
      rpc.barrier();
      storage.clear();
    }

  };

};
#endif


text:
namespace Org.Apache.REEF.Wake.Examples.P2p
{
    /// <summary>
    /// The pull side of the interface: Clients implement this and register it with
    /// the PullToPush class.
    /// </summary>
    /// <typeparam name="T">The event type</typeparam>
    public interface IEventSource<T>
    {
        /// <summary>
        /// Gets the next event
        /// </summary>
        /// <returns>The next event</returns>
        T GetNext();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/C:/Users/Krirk/AndroidStudioProjects/kitchensink/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.3/res/values-xlarge-land/values.xml -->
    <eat-comment/>
    <dimen name="abc_search_view_text_min_width">256dip</dimen>
</resources>


text:
<?php

/**
 * TOP API: taobao.fenxiao.refund.message.get request
 *
 * @author auto create
 * @since  1.0, 2013-09-13 16:51:03
 */
class Taobao_Request_FenxiaoRefundMessageGetRequest {
	/**
	 * 页码。(大于0的整数。默认为1)
	 **/
	private $pageNo;

	/**
	 * 每页条数。(默认10)
	 **/
	private $pageSize;

	/**
	 * 子采购单id
	 **/
	private $subOrderId;

	private $apiParas = array();

	public function setPageNo($pageNo) {
		$this->pageNo = $pageNo;
		$this->apiParas["page_no"] = $pageNo;
	}

	public function getPageNo() {
		return $this->pageNo;
	}

	public function setPageSize($pageSize) {
		$this->pageSize = $pageSize;
		$this->apiParas["page_size"] = $pageSize;
	}

	public function getPageSize() {
		return $this->pageSize;
	}

	public function setSubOrderId($subOrderId) {
		$this->subOrderId = $subOrderId;
		$this->apiParas["sub_order_id"] = $subOrderId;
	}

	public function getSubOrderId() {
		return $this->subOrderId;
	}

	public function getApiMethodName() {
		return "taobao.fenxiao.refund.message.get";
	}

	public function getApiParas() {
		return $this->apiParas;
	}

	public function check() {

		Taobao_RequestCheckUtil::checkNotNull($this->subOrderId, "subOrderId");
	}

	public function putOtherTextParam($key, $value) {
		$this->apiParas[$key] = $value;
		$this->$key = $value;
	}
}


text:
package foam.dao.index;

import foam.core.FObject;
import foam.dao.Sink;
import foam.mlang.order.Comparator;
import foam.mlang.predicate.Predicate;

/** Have-no-plan Plan. **/
public class NoPlan implements FindPlan, SelectPlan
{
  protected final static NoPlan instance_ = new NoPlan();

  public static NoPlan instance() { return instance_; }

  protected NoPlan() {}

  public long cost() { return Long.MAX_VALUE; }

  public FObject find(Object state, Object key) {
    throw new UnsupportedOperationException();
  }

  public void select(Object state, Sink sink, long skip, long limit, Comparator order, Predicate predicate) {
    //throw new UnsupportedOperationException();
    return;
  }

  @Override
  public String toString() {
    return "no-plan(cost:" + cost() + ")";
  }
}