text:
using System;
using System.Collections.Generic;
using System.Linq;
using d60.Cirqus.Aggregates;
using d60.Cirqus.Events;
using d60.Cirqus.Testing;
using NUnit.Framework;
using TestContext = d60.Cirqus.Testing.TestContext;

namespace d60.Cirqus.Tests.Bugs
{
    [TestFixture]
    public class VerifyThatLoadingAnotherRootMultipleTimesWillYieldTheCorrectVersionEveryTime : FixtureBase
    {
        TestContext _context;

        protected override void DoSetUp()
        {
            _context = RegisterForDisposal(TestContext.Create());
        }

        [Test]
        public void ItWorksInTheSameUnitOfWork()
        {
            using (var uow = _context.BeginUnitOfWork())
            {
                Console.WriteLine("** Creating two aggregate roots **");
                uow.Load<Root>("id1");
                uow.Load<Root>("id2");
                Commit(uow);
            }

            using (var uow = _context.BeginUnitOfWork())
            {
                Console.WriteLine("** Making 1 grab info from 2 **");
                // expected grabbing: "N/A"
                uow.Load<Root>("id1").GrabInformationFrom("id2");
                Commit(uow);
            }

            using (var uow = _context.BeginUnitOfWork())
            {
                Console.WriteLine("** Making 1 grab info from 2 **");
                Console.WriteLine("** Setting name of 2 to 'I now have a NEW name!' **");
                Console.WriteLine("** Making 1 grab info from 2 **");
                // expected grabbing: "I now have a NEW name!"
                uow.Load<Root>("id1").GrabInformationFrom("id2");
                uow.Load<Root>("id2").SetName("I now have a NEW name!");
                uow.Load<Root>("id1").GrabInformationFrom("id2");
                Commit(uow);
            }

            using (var uow = _context.BeginUnitOfWork())
            {
                var rootWithGrabbings = uow.Load<Root>("id1");
                var grabbedNames = rootWithGrabbings.InformationGrabbings.Select(g => g.Item2).ToArray();
                var expectedNames = new[] {"N/A", "N/A", "I now have a NEW name!"};

                Assert(grabbedNames, expectedNames);
            }
        }

        [Test]
        public void ItWorksAcrossUnitsOfWork()
        {
            using (var uow = _context.BeginUnitOfWork())
            {
                Console.WriteLine("** Creating two aggregate roots **");
                uow.Load<Root>("id1");
                uow.Load<Root>("id2");
                Commit(uow);
            }

            using (var uow = _context.BeginUnitOfWork())
            {
                Console.WriteLine("** Making 1 grab info from 2 **");
                // expected grabbing: "N/A"
                uow.Load<Root>("id1").GrabInformationFrom("id2");
                Commit(uow);
            }

            using (var uow = _context.BeginUnitOfWork())
            {
                Console.WriteLine("** Setting name of 2 to 'I now have a name!' **");
                uow.Load<Root>("id2").SetName("I now have a name!");
                Commit(uow);
            }

            using (var uow = _context.BeginUnitOfWork())
            {
                Console.WriteLine("** Making 1 grab info from 2 **");
                // expected grabbing: "I now have a name!"
                uow.Load<Root>("id1").GrabInformationFrom("id2");
                Commit(uow);
            }

            using (var uow = _context.BeginUnitOfWork())
            {
                var rootWithGrabbings = uow.Load<Root>("id1");
                var grabbedNames = rootWithGrabbings.InformationGrabbings.Select(g => g.Item2).ToArray();
                var expectedNames = new[] {"N/A", "I now have a name!"};

                Assert(grabbedNames, expectedNames);
            }
        }

        static void Assert(string[] grabbedNames, string[] expectedNames)
        {
            global::NUnit.Framework.Assert.That(grabbedNames, Is.EqualTo(expectedNames), @"
Expected:

    {0}

Got

    {1}

", string.Join(", ", expectedNames), string.Join(", ", grabbedNames));
        }

        void Commit(TestUnitOfWork uow)
        {
            uow.Commit();
            Console.WriteLine(" - committed - ");
            Console.WriteLine();
        }

        public class Root : AggregateRoot, IEmit<RootCreated>, IEmit<InformationGrabbedFrom>, IEmit<RootNamed>
        {
            readonly List<Tuple<string, string>> _informationGrabbings = new List<Tuple<string, string>>();
            string _name;

            public string Name
            {
                get { return _name; }
            }

            public List<Tuple<string, string>> InformationGrabbings
            {
                get { return _informationGrabbings; }
            }

            protected override void Created()
            {
                Emit(new RootCreated());
            }

            public void GrabInformationFrom(string otherRootId)
            {
                Emit(new InformationGrabbedFrom
                {
                    OtherRootId = otherRootId
                });
            }

            public void SetName(string name)
            {
                Emit(new RootNamed { Name = name });
            }

            public void Apply(RootCreated e)
            {
                _name = "N/A";
            }

            public void Apply(InformationGrabbedFrom e)
            {
                var name = Load<Root>(e.OtherRootId).Name;
                Console.WriteLine("This is what I grabbed: {0} ({1})", name, ReplayState);
                _informationGrabbings.Add(Tuple.Create(e.OtherRootId, name));
            }

            public void Apply(RootNamed e)
            {
                _name = e.Name;
            }

            protected internal override void EventEmitted(DomainEvent e)
            {
                if (e is RootNamed)
                {
                    var named = (RootNamed)e;
                    Console.WriteLine("> RootNamed({0})", named.Name);
                    return;
                }

                if (e is InformationGrabbedFrom)
                {
                    var info = (InformationGrabbedFrom) e;
                    Console.WriteLine("> InformationGrabbedFrom({0})", info.OtherRootId);
                    return;
                }
                Console.WriteLine("> {0}", e.GetType().Name);
            }
        }

        public class InformationGrabbedFrom : DomainEvent<Root>
        {
            public string OtherRootId { get; set; }
        }

        public class RootCreated : DomainEvent<Root> { }
        public class RootNamed : DomainEvent<Root>
        {
            public string Name { get; set; }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Mat.Common;

namespace Mat.Sources.Local
{
    public class LocalMediaSource : UpdatingMediaSource, ISelfHostedSource, IDisposable
    {
        private readonly HashSet<String> _extensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
                                                  {
                                                      ".jpeg",
                                                      ".jpg",
                                                      ".png"
                                                  };
        private readonly FileSystemWatcher _watcher = new FileSystemWatcher();

        public LocalMediaSource(ISourceSettings sourceSettings)
        {
            SourceSettings = sourceSettings;
            _watcher.Created += (sender, args) => NewMedia(new LocalMedia(args.FullPath, SourceSettings.Id));
            _watcher.Deleted += (sender, args) => RemoveMedia(new LocalMedia(args.FullPath, SourceSettings.Id));
            _watcher.Renamed += (sender, args) =>
                                    {
                                        RemoveMedia(new LocalMedia(args.OldFullPath, SourceSettings.Id));
                                        NewMedia(new LocalMedia(args.FullPath, SourceSettings.Id));
                                    };
        }

        public override IEnumerable<Media> Media
        {
            get
            {
                if (_sourceSettings.Path == null) return new List<Media>();
                return Directory.EnumerateFiles(_sourceSettings.Path, "*.*", SearchOption.AllDirectories)
                  .Where(path => _extensions.Contains(Path.GetExtension(path)))
                  .Select(f => new LocalMedia(f, SourceSettings.Id));
            }
        }

        private LocalMediaSourceSettings _sourceSettings;
        public override sealed ISourceSettings SourceSettings
        {
            get { return _sourceSettings; }
            set
            {
                if (!(value is LocalMediaSourceSettings)) return;

                _sourceSettings = value as LocalMediaSourceSettings;

                _watcher.EnableRaisingEvents = false;

                if (_sourceSettings == null || _sourceSettings.Path == null) return;

               _watcher.Path = _sourceSettings.Path;
                _watcher.EnableRaisingEvents = true;
            }
        }

        public Stream GetImageStream(string path)
        {
            if (!path.StartsWith(_sourceSettings.Path)) throw new UnauthorizedAccessException();

            return File.Open(path, FileMode.Open, FileAccess.Read);
        }

        public void Dispose()
        {
            _watcher.Dispose();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<template lang="md">

# Curve Line

`BmlCurveLine`

## Instance Properties

|name|type|default|description|
|------|-----|-----|----|
|path|Array[Point]|[]|The key points that makes the curve line.|
|strokeColor|String||Polyline stroke color.|
|strokeWeight|Number||Polyline stroke width.|
|strokeOpacity|Number||Polyline stroke opacity.|
|strokeStyle|String|'solid'|Polyline stroke style. `'solid'` or `'dashed'`.|
|massClear|Boolean|true|Whether remove this overlay or not when `map.clearOverlays` is called.|
|editing|Boolean|false|Enable editing the polyline.|
|clicking|Boolean|true|Whether to respond to a click event.|

## Events

|name|parameter|description|
|------|----|----|
|click|event{type, target, point, pixel}|Triggers when click on the polyline.|
|dblclick|event{type, target, point, pixel}|Triggers when double click on the polyline.|
|mousedown|event{type, target, point, pixel}|Triggers when the mouse is pressed down on the polyline.|
|mouseup|event{type, target, point, pixel}|Triggers when the mouse is released on the polyline.|
|mouseout|event{type, target, point, pixel}|Triggers when the mouse leaves the polyline.|
|mouseover|event{type, target, point, pixel}|Triggers when the mouse enters the polyline.|
|remove|event{type, target}|Triggers when the polyline is removed.|
|lineupdate|event{type, target}|Triggers when the polyline is updated.|

## Examples

### Add an editable polyline on the map

#### Code

```html
<template>
<baidu-map class="map" :center="{lng: 118.454, lat: 32.955}" :zoom="5">
  <bml-curve-line :points="points" :editing="true" @lineupdate="update"></bml-curve-line>
</baidu-map>
</template>

<script>
import {BmlCurveLine} from 'vue-baidu-map'
export default {
  components: {
    BmlCurveLine
  },
  methods: {
    update (e) {
      this.points = e.target.cornerPoints
    }
  },
  data () {
    return {
      points: [
        {lng: 116.432045, lat: 39.910683},
        {lng: 120.129721, lat: 30.314429},
        {lng: 121.491121, lat: 25.127053}
      ]
    }
  }
}
</script>
```

#### Preview

<doc-preview>
  <baidu-map class="map" :center="{lng: 118.454, lat: 32.955}" :zoom="5" :scroll-wheel-zoom="true">
    <bml-curve-line :points="points" :editing="true" @lineupdate="update"></bml-curve-line>
  </baidu-map>
  <md-table>
    <md-table-header>
      <md-table-head>Points</md-table-head>
      <md-table-head>Longitude</md-table-head>
      <md-table-head>Latitude</md-table-head>
    </md-table-header>
    <md-table-body>
      <md-table-row v-for="(point, index) in points" :key="index">
        <md-table-cell>{{`Point-${index + 1}`}}</md-table-cell>
        <md-table-cell>
          <md-input-container>
            <md-input v-model.number="point.lng" md-inline></md-input>
          </md-input-container>
        </md-table-cell>
        <md-table-cell>
          <md-input-container>
            <md-input v-model.number="point.lat" md-inline></md-input>
          </md-input-container>
        </md-table-cell>
      </md-table-row>
    </md-table-body>
  </md-table>
  <md-button @click="addPoint" class="md-raised md-primary">
    Add Point
  </md-button>
</doc-preview>
</template>

<script>
import BmlCurveLine from '../../../components/extra/CurveLine.vue'
export default {
  components: {
    BmlCurveLine
  },
  methods: {
    addPoint () {
      this.points.push({
        lng: 116.404,
        lat: 39.915
      })
    },
    update (e) {
      this.points = e.target.cornerPoints
    }
  },
  data () {
    return {
      points: [
        {lng: 116.432045, lat: 39.910683},
        {lng: 120.129721, lat: 30.314429},
        {lng: 121.491121, lat: 25.127053}
      ]
    }
  }
}
</script>


text:
<!-- Start WOWSlider.com -->
<iframe src="slider.html" style="width:830px;height:360px;max-width:100%;overflow:hidden;border:none;padding:0;margin:0 auto;display:block;" marginheight="0" marginwidth="0"></iframe>
<!-- End WOWSlider.com -->


text:
using System;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using STEP;

namespace IFC
{
    /// <summary>
	/// http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifcareameasure.htm
	/// </summary>
	public class IfcAreaMeasure : BaseIfc
	{
		internal double value;

		public IfcAreaMeasure(double value){ this.value = value; }
		public static implicit operator double(IfcAreaMeasure v){ return v.value; }
		public static implicit operator IfcAreaMeasure(double v){ return new IfcAreaMeasure(v); }
		public static IfcAreaMeasure FromJSON(string json){ return JsonConvert.DeserializeObject<IfcAreaMeasure>(json); }
        public override string ToString(){ return value.ToString(); }
		public override string ToStepValue(bool isSelectOption = false){
			if(isSelectOption){ return $"{GetType().Name.ToUpper()}({value.ToStepValue(isSelectOption)})"; }
			else{ return value.ToStepValue(isSelectOption); }
        }
	}
}


text:
#include "Gwen/Util/ControlFactory.h"
#include "Gwen/Controls.h"

class MenuStrip_Factory : public Gwen::ControlFactory::Base
{
	public:

		GWEN_CONTROL_FACTORY_CONSTRUCTOR( MenuStrip_Factory, Gwen::ControlFactory::Base )
		{

		}

		virtual Gwen::String Name(){ return "MenuStrip"; }
		virtual Gwen::String BaseName(){ return "Base"; }

		virtual Gwen::Controls::Base* CreateInstance( Gwen::Controls::Base* parent )
		{
			Gwen::Controls::MenuStrip* pControl = new Gwen::Controls::MenuStrip( parent );
			return pControl;
		}
};

GWEN_CONTROL_FACTORY( MenuStrip_Factory );


text:
package com.nekogata.backlogger.js_exports.commands.dashboard

import com.nekogata.backlogger.application.command.dashboard.{LoadIssuesCommand, MakeIssueStatusAsProcessingCommand}

import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

@JSExportTopLevel("MakeIssueStatusAsProcessingCommand")
class MakeIssueStatusAsProcessingCommandImpl extends MakeIssueStatusAsProcessingCommand {
  @JSExport
  override var projectId: js.UndefOr[Int] = js.undefined

  @JSExport
  override var issueId: js.UndefOr[Int] = js.undefined

  @JSExport
  override def execute(): Unit = super.execute()
}


text:
template <class TransferableObjectType> class osTransferableObjectCreator;

// Local:
#include <AMDTAPIClasses/Include/Events/apEvent.h>

// ----------------------------------------------------------------------------------
// Class Name:           AP_API apRenderContextCreatedEvent
// General Description:
//   Is thrown when an OpenGL render context is created.
// Author:  AMD Developer Tools Team
// Creation Date:        25/12/2009
// ----------------------------------------------------------------------------------
class AP_API apRenderContextCreatedEvent : public apEvent
{
public:
    apRenderContextCreatedEvent(osThreadId triggeringThreadId, int contextId);
    virtual ~apRenderContextCreatedEvent();

    int contextId() const { return _contextId; };

    // Overrides osTransferableObject:
    virtual osTransferableObjectType type() const;
    virtual bool writeSelfIntoChannel(osChannel& ipcChannel) const;
    virtual bool readSelfFromChannel(osChannel& ipcChannel);

    // Overrides apEvent:
    virtual EventType eventType() const;
    virtual apEvent* clone() const;

private:
    // Only the transferable object creator should be able to call my default constructor:
    friend class osTransferableObjectCreator<apRenderContextCreatedEvent>;
    apRenderContextCreatedEvent();

private:
    // The OpenGL server context id:
    int _contextId;
};

#endif //__APRENDERCONTEXTCREATEDEVENT_H


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.redkale.net.nio;

import java.nio.channels.CompletionHandler;
import java.util.concurrent.*;

/**
 *
 * <p>
 * 详情见: https://redkale.org
 *
 * @author zhangjx
 *
 * @since 2.1.0
 */
public class NioCompletionHandler<A> implements CompletionHandler<Integer, A>, Runnable {

    private final CompletionHandler<Integer, A> handler;

    private A attachment;

    public ScheduledFuture timeoutFuture;

    public NioCompletionHandler(CompletionHandler<Integer, A> handler, A attachment) {
        this.handler = handler;
        this.attachment = attachment;
    }

    public void setAttachment(A attachment) {
        this.attachment = attachment;
    }

    @Override
    public void completed(Integer result, A attach) {
        ScheduledFuture future = this.timeoutFuture;
        if (future != null) {
            this.timeoutFuture = null;
            future.cancel(true);
        }
        handler.completed(result, attachment);
    }

    @Override
    public void failed(Throwable exc, A attach) {
        ScheduledFuture future = this.timeoutFuture;
        if (future != null) {
            this.timeoutFuture = null;
            future.cancel(true);
        }
        handler.failed(exc, attachment);
    }

    @Override
    public void run() {
        handler.failed(new TimeoutException(), attachment);
    }

}


text:
const { Command } = require('discord.js-commando');
const _sdata = require('../../assets/_data/static_data.json');
const { PERMITTED_GROUP } = require('../../assets/_data/settings.json');
const Starboard = require('../../structures/stars/Starboard');

module.exports = class DeleteStarCommand extends Command {
    constructor(client) {
        super(client, {
            name: 'delete-star',
            aliases: ['star-delete', 'star-del', 'del-star'],
            group: 'stars',
            memberName: 'delete',
            description: '`AL: high, perm_group` Add a message to the #starboard!',
            guildOnly: true,

            args: [
                {
                    key: 'message',
                    prompt: 'What message would you like to star?',
                    type: 'message'
                }
            ]
        });
    }

    hasPermission(msg) {
        return msg.member.roles.exists('name', PERMITTED_GROUP)
   || this.client.provider.get(msg.author.id, 'userLevel') >= _sdata.aLevel.high;
    }

    async run(msg, { message }) {
        const starboard = msg.guild.channels.find('name', 'starboard');
        if (!starboard) {
            return msg.embed({
                color: _sdata.colors.blue,
                description: `${msg.author}, you can't delete stars if you don't even have a starboard.`
            });
        }
        const isStarred = await Starboard.isStarred(message.id);
        if (!isStarred) {
            return msg.embed({
                color: _sdata.colors.red,
                description: `${msg.author}, that message is not on the #starboard.`
            });
        }
        await Starboard.removeStar(message, starboard);
        return msg.embed({
            color: _sdata.colors.green,
            description: `${msg.author}, successfully delete the message from the starboard`
        });
    }
};


text:
package org.dspace.app.xmlui.wing.element;

import java.util.ArrayList;

import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.NamespaceSupport;

/**
 * Class representing a set of referenced metadata.
 *
 * @author Scott Phillips
 */

public class ReferenceSet extends AbstractWingElement implements
        StructuralElement
{
    /** The name of the referenceSet element */
    public static final String E_REFERENCE_SET = "referenceSet";

    /** The name of the orderBy attribute */
    public static final String A_ORDER_BY = "orderBy";

    /** The name of the type attribute */
    public static final String A_TYPE = "type";

    /** The possible interactive division methods: get,post, or multipart. */
    public static final String TYPE_SUMMARY_LIST = "summaryList";

    public static final String TYPE_SUMMARY_VIEW = "summaryView";

    public static final String TYPE_DETAIL_LIST = "detailList";

    public static final String TYPE_DETAIL_VIEW = "detailView";

    /** The possible interactive division methods names collected into one array */
    public static final String[] TYPES = { TYPE_SUMMARY_LIST, TYPE_SUMMARY_VIEW, TYPE_DETAIL_LIST, TYPE_DETAIL_VIEW };

    /** The name assigned to this metadata set */
    private String name;

    /** The ordering mechanism to use. */
    private String orderBy;

    /** The reference type, see TYPES defined above */
    private String type;

    /** Special rendering instructions */
    private String rend;

    /** The head label for this referenceset */
    private Head head;

    /** All content of this container, items & lists */
    private java.util.List<AbstractWingElement> contents = new ArrayList<AbstractWingElement>();

    /**
     * Construct a new referenceSet
     *
     * @param context
     *            (Required) The context this element is contained in, such as
     *            where to route SAX events and what i18n catalogue to use.
     * @param childreference
     *            Whether this is a child reference (not requiring a name).
     * @param name
     *            (May be null) a local identifier used to differentiate the
     *            element from its siblings.
     * @param type
     *            (Required) The type of reference set which determines the level
     *            of detail for the metadata rendered. See TYPES for a list of
     *            available types.
     * @param orderBy
     *            (May be null) Determines the ordering of referenced metadata.
     * @param rend
     *            (May be null) a rendering hint used to override the default
     *            display of the element.
     */
    protected ReferenceSet(WingContext context, boolean childreference, String name, String type, String orderBy, String rend)
            throws WingException
    {
        super(context);
        // Names are only required for parent reference sets.
        if (!childreference)
        {
            require(name, "The 'name' parameter is required for reference sets.");
        }
        restrict(
                type,
                TYPES,
                "The 'method' parameter must be one of these values: 'summaryList', 'summaryView', 'detailList', or 'detailView'.");

        this.name = name;
        this.type = type;
        this.orderBy = orderBy;
        this.rend = rend;
    }

    /**
     * Set the head element which is the label associated with this referenceset.
     */
    public Head setHead() throws WingException
    {
        this.head = new Head(context, null);
        return head;

    }

    /**
     * Set the head element which is the label associated with this referenceset.
     *
     * @param characters
     *            (May be null) Unprocessed characters to be referenced
     */
    public void setHead(String characters) throws WingException
    {
        Head head = this.setHead();
        head.addContent(characters);

    }

    /**
     * Set the head element which is the label associated with this referenceset.
     *
     * @param message
     *            (Required) A key into the i18n catalogue for translation into
     *            the user's preferred language.
     */
    public void setHead(Message message) throws WingException
    {
        Head head = this.setHead();
        head.addContent(message);
    }

    /**
     * Add an object reference.
     *
     * @param object
     *            (Required) The referenced object.
     */
    public Reference addReference(Object object)
            throws WingException
    {
        Reference reference = new Reference(context, object);
        contents.add(reference);
        return reference;
    }

    /**
     * Translate this metadata inclusion set to SAX
     *
     * @param contentHandler
     *            (Required) The registered contentHandler where SAX events
     *            should be routed too.
     * @param lexicalHandler
     *            (Required) The registered lexicalHandler where lexical
     *            events (such as CDATA, DTD, etc) should be routed too.
     * @param namespaces
     *            (Required) SAX Helper class to keep track of namespaces able
     *            to determine the correct prefix for a given namespace URI.
     */
    public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler,
            NamespaceSupport namespaces) throws SAXException
    {
        AttributeMap attributes = new AttributeMap();
        if (name != null)
        {
            attributes.put(A_NAME, name);
        }
        if (name != null)
        {
            attributes.put(A_ID, context.generateID(E_REFERENCE_SET, name));
        }

        attributes.put(A_TYPE, type);
        if (orderBy != null)
        {
            attributes.put(A_ORDER_BY, orderBy);
        }
        if (rend != null)
        {
            attributes.put(A_RENDER, rend);
        }

        startElement(contentHandler, namespaces, E_REFERENCE_SET, attributes);

        if (head != null)
        {
            head.toSAX(contentHandler, lexicalHandler, namespaces);
        }

        for (AbstractWingElement content : contents)
        {
            content.toSAX(contentHandler, lexicalHandler, namespaces);
        }

        endElement(contentHandler, namespaces, E_REFERENCE_SET);
    }

    /**
     * dispose
     */
    public void dispose()
    {
        if (contents != null)
        {
            for (AbstractWingElement content : contents)
            {
                content.dispose();
            }
            contents.clear();
        }
        contents = null;
        super.dispose();
    }
}


text:
extern crate libc;

use std::collections::{HashMap, HashSet};
use std::io::{self, Read, Write, Cursor, BufRead};
use std::marker::{Send, Sync};
use std::mem;
use std::net::TcpListener;
use std::rc::Rc;
use std::sync::Arc;
use std::thread;

#[cfg(unix)] use unix::{Transport, Socket};
#[cfg(unix)] mod unix;

#[cfg(windows)] use windows::{Transport, Socket};
#[cfg(windows)] mod windows;

const HEADER_LEN: usize = 8;

#[derive(Debug, Clone, Copy)]
pub enum Role {
    Responder,
    Authorizer,
    Filter,
}

#[derive(Debug)]
enum ProtocolStatus {
    RequestComplete,
    CantMpxConn,
    #[allow(dead_code)] Overloaded,
    UnknownRole,
}

#[derive(Debug)]
enum Record {
    BeginRequest { request_id: u16, role: Result<Role, u16>, keep_conn: bool },
    AbortRequest { request_id: u16 },
    EndRequest { request_id: u16, app_status: i32, protocol_status: ProtocolStatus },
    Params { request_id: u16, content: Vec<u8> },
    Stdin { request_id: u16, content: Vec<u8> },
    Stdout { request_id: u16, content: Vec<u8> },
    Stderr { request_id: u16, content: Vec<u8> },
    Data { request_id: u16, content: Vec<u8> },
    GetValues(Vec<String>),
    GetValuesResult(Vec<(String, String)>),
    UnknownType(u8),
}

fn read_len<R: Read>(mut r: &mut R) -> io::Result<u32> {
    let mut buf: Vec<u8> = Vec::with_capacity(4);
    try!((&mut r).take(1).read_to_end(&mut buf));
    if buf.len() == 1 {
        if buf[0] >> 7 == 1 {
            assert!(try!((&mut r).take(3).read_to_end(&mut buf)) == 3);
            Ok(
                (((buf[0] & 0x7f) as u32) << 24)
                + ((buf[1] as u32) << 16)
                + ((buf[2] as u32) << 8)
                + (buf[3] as u32)
            )
        } else {
            Ok(buf[0] as u32)
        }
    } else {
        Err(io::Error::new(io::ErrorKind::Other, "EOF"))
    }
}

fn read_pair<R: Read>(mut r: &mut R) -> io::Result<(String, String)> {
    let key_len = try!(read_len(r));
    let value_len = try!(read_len(r));
    let mut key = String::with_capacity(key_len as usize);
    assert!(try!((&mut r).take(key_len as u64).read_to_string(&mut key)) == key_len as usize);
    let mut value = String::with_capacity(value_len as usize);
    assert!(try!((&mut r).take(value_len as u64).read_to_string(&mut value)) == value_len as usize);
    Ok((key, value))
}

fn read_pairs<R: Read>(r: &mut R) -> io::Result<Vec<(String, String)>> {
    let mut params = Vec::new();
    match read_pair(r) {
        Ok(param) => {
            params.push(param);
            params.extend(try!(read_pairs(r)).into_iter());
            Ok(params)
        },
        Err(_) => Ok(params),
    }
}

fn write_len<W: Write>(w: &mut W, n: u32) -> io::Result<()> {
    if n < 0x80 {
        try!(w.write_all(&[n as u8]));
    } else {
        assert!(n < 0x80000000);
        let buf = unsafe {
            mem::transmute::<u32, [u8; 4]>((0x80000000 & n).to_be())
        };
        try!(w.write_all(&buf));
    }
    Ok(())
}

fn write_pairs<W: Write>(w: &mut W, pairs: Vec<(String, String)>) -> io::Result<()> {
    for (key, value) in pairs {
        try!(write_len(w, key.len() as u32));
        try!(write_len(w, value.len() as u32));
        try!(write!(w, "{}{}", key, value));
    }
    Ok(())
}

#[inline]
fn write_record<W: Write>(w: &mut W, record_type: u8, request_id: u16, content: &[u8]) -> io::Result<()> {
    assert!(content.len() <= std::u32::MAX as usize);
    let request_id = unsafe {
        mem::transmute::<_, [u8; 2]>(request_id.to_be())
    };
    let content_length = unsafe {
        mem::transmute::<_, [u8; 2]>((content.len() as u16).to_be())
    };
    try!(w.write_all(&[
        1, record_type, request_id[0], request_id[1],
        content_length[0], content_length[1], 0, 0,
    ])); // TODO: Padding
    try!(w.write_all(content));
    Ok(())
}

#[inline]
fn read_record<R: Read>(r: &mut R) -> io::Result<(u8, u16, Vec<u8>)> {
    let mut header: Vec<u8> = Vec::with_capacity(HEADER_LEN);
    assert!(try!(r.take(HEADER_LEN as u64).read_to_end(&mut header)) == HEADER_LEN);
    assert!(header[0] == 1);
    let record_type = header[1];
    let request_id = unsafe { u16::from_be(mem::transmute([header[2], header[3]])) };
    let content_length = unsafe { u16::from_be(mem::transmute([header[4], header[5]])) };
    let padding_length = header[6];
    let mut content: Vec<u8> = Vec::with_capacity(content_length as usize);
    assert!(try!(r.take(content_length as u64).read_to_end(&mut content)) == content_length as usize);
    assert!(try!(r.take(padding_length as u64).read_to_end(&mut Vec::with_capacity(padding_length as usize))) == padding_length as usize);
    Ok((record_type, request_id, content))
}

impl Record {
    fn send<W: Write>(self, w: &mut W) -> io::Result<()> {
        match self {
            Record::EndRequest { request_id, app_status, protocol_status } => {
                let app_status = unsafe {
                    mem::transmute::<_, [u8; 4]>(app_status.to_be())
                };
                let protocol_status = match protocol_status {
                    ProtocolStatus::RequestComplete => 0,
                    ProtocolStatus::CantMpxConn => 1,
                    ProtocolStatus::Overloaded => 2,
                    ProtocolStatus::UnknownRole => 3,
                };
                let content = [
                    app_status[0], app_status[1], app_status[2], app_status[3],
                    protocol_status, 0, 0, 0,
                ];
                try!(write_record(w, 3, request_id, &content));
            },
            Record::Stdout { request_id, content } => {
                try!(write_record(w, 6, request_id, &content));
            },
            Record::Stderr { request_id, content } => {
                try!(write_record(w, 7, request_id, &content));
            },
            Record::GetValuesResult(items) => {
                let mut content = Cursor::new(Vec::new());
                try!(write_pairs(&mut content, items));
                try!(write_record(w, 10, 0, &content.into_inner()));
            },
            Record::UnknownType(record_type) => {
                let content = [record_type, 0, 0, 0, 0, 0, 0, 0];
                try!(write_record(w, 11, 0, &content));
            },
            _ => panic!("Record not sendable"),
        }
        Ok(())
    }

    fn receive<R: Read>(r: &mut R) -> io::Result<Self> {
        let (record_type, request_id, content) = try!(read_record(r));
        let rec = match record_type {
            1 => {
                let role = unsafe {
                    u16::from_be(mem::transmute([content[0], content[1]]))
                };
                let role = match role {
                    1 => Ok(Role::Responder),
                    2 => Ok(Role::Authorizer),
                    3 => Ok(Role::Filter),
                    _ => Err(role),
                };
                let keep_conn = content[2] & 1 == 1;
                Record::BeginRequest {
                    request_id: request_id,
                    role: role,
                    keep_conn: keep_conn
                }
            },
            2 => Record::AbortRequest { request_id: request_id },
            4 => Record::Params { request_id: request_id, content: content },
            5 => Record::Stdin { request_id: request_id, content: content },
            8 => Record::Data { request_id: request_id, content: content },
            9 => {
                let items = try!(read_pairs(&mut Cursor::new(content)));
                Record::GetValues(items.into_iter().map(|(key, _)| key).collect())
            },
            _ if record_type >= 11 => Record::UnknownType(record_type),
            _ => panic!("Record not receivable"),
        };
        Ok(rec)
    }
}

pub struct Stdin<'a> {
    req: &'a mut Request,
}

impl<'a> Stdin<'a> {
    /// Begin reading the second stream of the request, for FastCGI Filter
    /// applications.
    ///
    /// May only be called after all contents of stdin has been read. Panics
    /// if stdin has not reached EOF yet.
    pub fn start_filter_data(&mut self) {
        if !self.req.filter_data {
            assert!(self.req.is_eof);
            self.req.is_eof = false;
            self.req.filter_data = true;
        }
    }
}

impl<'a> BufRead for Stdin<'a> {
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
        if self.req.aborted {
            return Err(io::Error::new(io::ErrorKind::ConnectionAborted, "Request aborted"));
        }
        if self.req.pos == self.req.buf.len() && !self.req.is_eof {
            let mut sock = &*self.req.sock;
            loop {
                match (try!(Record::receive(&mut sock)), self.req.filter_data) {
                    (Record::UnknownType(rec_type), _) => {
                        try!(Record::UnknownType(rec_type).send(&mut sock));
                    },
                    (Record::GetValues(keys), _) => {
                        try!(
                            Record::GetValuesResult(get_values(keys))
                            .send(&mut sock)
                        );
                    },
                    (Record::BeginRequest { request_id, .. }, _) => {
                        try!(Record::EndRequest {
                                request_id: request_id,
                                app_status: 0,
                                protocol_status: ProtocolStatus::CantMpxConn,
                            }
                            .send(&mut sock)
                        );
                    },
                    (Record::AbortRequest { request_id }, _) => {
                        if request_id != self.req.id {
                            continue;
                        }
                        self.req.aborted = true;
                        return Err(io::Error::new(io::ErrorKind::ConnectionAborted, "Request aborted"));
                    }
                    (Record::Stdin { request_id, content }, false)
                    | (Record::Data { request_id, content }, true) => {
                        if request_id != self.req.id {
                            continue;
                        }
                        if content.is_empty() {
                            self.req.is_eof = true;
                        }
                        self.req.buf = content;
                        self.req.pos = 0;
                        break;
                    },
                    _ => (),
                }
            }
        }
        Ok(&self.req.buf[self.req.pos..])
    }

    fn consume(&mut self, amount: usize) {
        self.req.pos = std::cmp::min(self.req.pos + amount, self.req.buf.len());
    }
}

impl<'a> Read for Stdin<'a> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let n = {
            let mut chunk = try!(self.fill_buf());
            try!(chunk.read(buf))
        };
        self.consume(n);
        Ok(n)
    }
}

macro_rules! writer {
    ($Writer:ident) => (
        pub struct $Writer<'a> {
            req: &'a mut Request,
        }

        impl<'a> Write for $Writer<'a> {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                if self.req.aborted {
                    return Err(io::Error::new(io::ErrorKind::ConnectionAborted, "Request aborted"));
                }
                if buf.is_empty() {
                    Ok(0)
                } else {
                    for chunk in buf.chunks(std::u16::MAX as usize) {
                        let rec = Record::$Writer {
                            request_id: self.req.id,
                            content: chunk.to_owned(),
                        };
                        try!(rec.send(&mut &*self.req.sock));
                    }
                    Ok(buf.len())
                }
            }

            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }
    );
}

writer!(Stdout);

writer!(Stderr);

/// Request objects are what a FastCGI application will primarily deal with
/// throughout its lifetime.
///
/// The Request API is designed to be an abstraction of the traditional CGI
/// process model. Note that this API is low level. Dealing with things like
/// GET/POST parameters or cookies is outside the scope of this library.
pub struct Request {
    sock: Rc<Socket>,
    id: u16,
    role: Role,
    params: HashMap<String, String>,
    aborted: bool,
    status: i32,
    buf: Vec<u8>,
    pos: usize,
    is_eof: bool,
    filter_data: bool,
}

pub type Params<'a> = Box<Iterator<Item = (String, String)> + 'a>;

fn get_values(keys: Vec<String>) -> Vec<(String, String)> {
    keys.into_iter().filter_map(|key|
        match key.as_ref() {
            "FCGI_MAX_CONNS" => Some((key, "1".to_owned())),
            "FCGI_MAX_REQS" => Some((key, "1".to_owned())),
            "FCGI_MPXS_CONNS" => Some((key, "0".to_owned())),
            _ => None,
        }
    ).collect()
}

impl Request {
    fn begin(mut sock: &Socket) -> io::Result<(u16, Role, bool)> {
        loop {
            match try!(Record::receive(&mut sock)) {
                Record::UnknownType(rec_type) => {
                    try!(Record::UnknownType(rec_type).send(&mut sock));
                },
                Record::GetValues(keys) => {
                    try!(Record::GetValuesResult(get_values(keys)).send(&mut sock));
                },
                Record::BeginRequest { request_id, role: Ok(role), keep_conn } => {
                    return Ok((request_id, role, keep_conn));
                },
                Record::BeginRequest { request_id, role: Err(_), .. } => {
                    try!(Record::EndRequest {
                        request_id: request_id,
                        app_status: 0,
                        protocol_status: ProtocolStatus::UnknownRole
                    }.send(&mut sock));
                },
                _ => (),
            }
        }
    }

    fn new(sock: Rc<Socket>, id: u16, role: Role) -> io::Result<Self> {
        let mut buf = Vec::new();
        let mut params = HashMap::new();
        let mut aborted = false;
        loop {
            match try!(Record::receive(&mut &*sock)) {
                Record::UnknownType(rec_type) => {
                    try!(Record::UnknownType(rec_type).send(&mut &*sock));
                },
                Record::GetValues(keys) => {
                    try!(
                        Record::GetValuesResult(get_values(keys))
                        .send(&mut &*sock)
                    );
                },
                Record::BeginRequest { request_id, .. } => {
                    try!(Record::EndRequest {
                            request_id: request_id,
                            app_status: 0,
                            protocol_status: ProtocolStatus::CantMpxConn,
                        }
                        .send(&mut &*sock)
                    );
                }
                Record::AbortRequest { request_id } => {
                    if id != request_id {
                        continue;
                    }
                    aborted = true;
                    break;
                }
                Record::Params { request_id, content } => {
                    if id != request_id {
                        continue;
                    }
                    if content.is_empty() {
                        params.extend(try!(read_pairs(&mut Cursor::new(&buf))));
                        break;
                    } else {
                        buf.extend(content);
                    }
                },
                _ => (),
            }
        }
        Ok(Request {
            sock: sock,
            id: id,
            role: role,
            params: params,
            aborted: aborted,
            status: 0,
            buf: Vec::new(),
            pos: 0,
            is_eof: false,
            filter_data: false,
        })
    }

    pub fn role(&self) -> Role {
        self.role
    }

    /// Retrieves the value of the given parameter name.
    pub fn param(&self, key: &str) -> Option<String> {
        self.params.get(key).map(|s| s.clone())
    }

    /// Iterates over the FastCGI parameters.
    pub fn params(&self) -> Params {
        Box::new(self.params.iter().map(|(k, v)| (k.clone(), v.clone())))
    }

    /// Standard input stream of the request.
    pub fn stdin(&mut self) -> Stdin {
        Stdin { req: self }
    }

    /// Standard output stream of the request.
    pub fn stdout(&mut self) -> Stdout {
        Stdout { req: self }
    }

    /// Standard error stream of the request.
    pub fn stderr(&mut self) -> Stderr {
        Stderr { req: self }
    }

    /// Checks if the client has closed the connection prematurely.
    ///
    /// The reliability of this method depends on whether the web server
    /// notifies such event (by sending the `FCGI_REQUEST_ABORTED` record) to
    /// the FastCGI application. This value is updated synchronously; the
    /// update may only be triggered by reading from stdin.
    pub fn is_aborted(&self) -> bool {
        self.aborted
    }

    /// Reports the specified exit code to the web server.
    ///
    /// This will consume the Request object. If you finish processing the
    /// Request object without calling `exit`, it is assumed that the exit code
    /// is 0.
    pub fn exit(mut self, code: i32) {
        self.status = code;
    }
}

impl Drop for Request {
    fn drop(&mut self) {
        Record::Stdout {
            request_id: self.id,
            content: Vec::new(),
        }.send(&mut &*self.sock).unwrap_or(());
        Record::Stderr {
            request_id: self.id,
            content: Vec::new()
        }.send(&mut &*self.sock).unwrap_or(());
        Record::EndRequest {
            request_id: self.id,
            app_status: self.status,
            protocol_status: ProtocolStatus::RequestComplete,
        }.send(&mut &*self.sock).unwrap_or(());
    }
}

fn run_transport<F>(handler: F, transport: &mut Transport) where
        F: Fn(Request) + Send + Sync + 'static {
    let addrs: Option<HashSet<String>> = match std::env::var("FCGI_WEB_SERVER_ADDRS") {
        Ok(value) => Some(value.split(',').map(|s| s.to_owned()).collect()),
        Err(std::env::VarError::NotPresent) => None,
        Err(e) => Err(e).unwrap(),
    };
    let handler = Arc::new(handler);
    loop {
        let sock = match transport.accept() {
            Ok(sock) => sock,
            Err(e) => panic!(e.to_string()),
        };
        let allow = match addrs {
            Some(ref addrs) => match sock.peer() {
                Ok(ref addr) => addrs.contains(addr),
                Err(_) => false,
            },
            None => true,
        };
        if allow {
            let handler = handler.clone();
            thread::spawn(move || {
                let sock = Rc::new(sock);
                loop {
                    let (request_id, role, keep_conn) = Request::begin(&sock).unwrap();
                    handler(Request::new(sock.clone(), request_id, role).unwrap());
                    if !keep_conn { break; }
                }
            });
        }
    }
}

#[cfg(unix)]
/// Runs as a FastCGI process with the given handler.
///
/// Available under Unix only. If you are using Windows, use `run_tcp` instead.
pub fn run<F>(handler: F) where F: Fn(Request) + Send + Sync + 'static {
    run_transport(handler, &mut Transport::new())
}

#[cfg(unix)]
/// Accepts requests from a user-supplied raw file descriptor. IPv4, IPv6, and
/// Unix domain sockets are supported.
///
/// Available under Unix only.
pub fn run_raw<F>(handler: F, raw_fd: std::os::unix::io::RawFd) where
        F: Fn(Request) + Send + Sync + 'static {
    run_transport(handler, &mut Transport::from_raw_fd(raw_fd))
}

#[cfg(unix)]
/// Accepts requests from a user-supplied TCP listener.
pub fn run_tcp<F>(handler: F, listener: &TcpListener) where
        F: Fn(Request) + Send + Sync + 'static {
    use std::os::unix::io::AsRawFd;
    run_transport(handler, &mut Transport::from_raw_fd(listener.as_raw_fd()))
}

#[cfg(windows)]
/// Accepts requests from a user-supplied TCP listener.
pub fn run_tcp<F>(handler: F, listener: &TcpListener) where
        F: Fn(Request) + Send + Sync + 'static {
    run_transport(handler, &mut Transport::from_tcp(&listener))
}

#[cfg(unix)]
/// Check if the program is running as FastCGI. This check is not necessary if
/// you use `run_tcp`.
pub fn is_fastcgi() -> bool {
    Transport::new().is_fastcgi()
}


text:
import { Column, ValueTransformer, Entity, PrimaryGeneratedColumn } from "../../../../../src";
import { lowercase, encrypt } from "./User";

const trim: ValueTransformer = {
    to: (entityValue: string) => {
        return entityValue.trim();
    },
    from: (databaseValue: string) => {
        return databaseValue;
    }
};

@Entity()
export class Category {
    @PrimaryGeneratedColumn("uuid")
    id: string;

    @Column({transformer: [lowercase, trim, encrypt]})
    description: string;
}


text:
package com.nodeta.scalandra

/**
 * Interface to determine sort order when doind range queries.
 */
trait Order {
  def toBoolean : Boolean
}

/**
 * Ascending sort order
 */
case object Ascending extends Order {
  implicit def toBoolean() : Boolean = false
}

/**
 * Descending sort order
 */
case object Descending extends Order {
  implicit def toBoolean() : Boolean = true
}


text:
'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
	errorHandler = require('../errors'),
	passport = require('passport'),
	fs = require('fs');

var Activation = require('../../models/activation');
var User = require('../../models/user');
var Log = require('../../models/log');
var Comment = require('../../models/comment');

/**
 * Update user details
 */
exports.update = function(req, res) {
	// Init Variables
	var user = req.user;
	var message = null;

	// For security measurement we remove the roles from the req.body object
	delete req.body.roles;

	if (user) {
		// Merge existing user
		user = _.extend(user, req.body);
		user.updated = Date.now();
		user.displayName = user.firstName + ' ' + user.lastName;

		user.save(function(err) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			} else {
				req.login(user, function(err) {
					if (err) {
						res.status(400).send(err);
					} else {
						res.json(user);
					}
				});
			}
		});
	} else {
		res.status(400).send({
			message: 'User is not signed in'
		});
	}
};

/**
 * Send User
 */
exports.me = function(req, res) {
	res.json(req.user || null);
};

exports.adminListUser = function(req,res){
	var page = req.param("page")-1;
	var _limit = req.param("limit");
	var activeCode = (req.param("code")!= undefined) ? req.param("code") : "";
	if(activeCode){
		Activation.findOne({name: activeCode},function (err, data) {
			if(err) console.log(err);
			if(data){
				if(data.userId){
					res.jsonp({
						error:true,
						msg:"This key has been active"
					});
				}else{
					User.count({ type: { $ne: 'admin' } }, function (err, count) {
						if (err) {
							return res.status(400).send({ message: errorHandler.getErrorMessage(err) });
						} else {
							User.find({ type: { $ne: 'admin' } },'_id username displayName provider email created publishedVideo', { skip: page*_limit, limit: _limit, sort:{ _id: -1 }},function (err1, users) {
								if (err1) {
									return res.status(400).send({ message: errorHandler.getErrorMessage(err1) });
								} else {
									res.jsonp({
										error:false,
										data: users,
										total: count
									});
								}
							});
						}
					});
				}
			}else{
				res.jsonp({
					error:true,
					msg:"Invalid active code"
				});
				return;
			}

		});
	}else{
		User.count({ type: { $ne: 'admin' } }, function (err, count) {
			if (err) {
				return res.status(400).send({ message: errorHandler.getErrorMessage(err) });
			} else {
				User.find({ type: { $ne: 'admin' } },'_id username displayName provider email created publishedVideo', { skip: page*_limit, limit: _limit, sort:{ _id: -1 }},function (err1, users) {
					if (err1) {
						return res.status(400).send({ message: errorHandler.getErrorMessage(err1) });
					} else {
						res.jsonp({
							error:false,
							data: users,
							total: count
						});
					}
				});
			}
		});
	}
}

exports.adminDeleteUser = function(req,res){

	/*Image.find({userId: req.param("id")}, function(err, data){
		if(err)
			return res.status(400).send({message: errorHandler.getErrorMessage(err)});
		for(var i=0; i< data.length; i++){

			var curItem = data[i];
			var imageUrl = "./public/upload/"+curItem.name+"."+curItem.extension;
			var videoUrl = "./public/upload/video/"+curItem.name+".webm";
			if (fs.existsSync(imageUrl))
				fs.unlinkSync(imageUrl);
			if (fs.existsSync(videoUrl))
				fs.unlinkSync(videoUrl);
			Comment.remove({ videoId: curItem._id }, function(err1){
				if(err1)
					return res.status(400).send({message: errorHandler.getErrorMessage(err1)});
			});
			Image.remove({ _id: curItem._id }, function(err2){
				if(err2)
					return res.status(400).send({message: errorHandler.getErrorMessage(err2)});
			});

		}
		User.remove({_id: req.param('id')}, function(err3){
			if(err3)
				return res.status(400).send({message: errorHandler.getErrorMessage(err3)});
			res.jsonp({
				message: "delete user success"
			});
		})
	});*/

}


text:
"use strict";

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

var _index = _interopRequireDefault(require("./_lib/formatDistance/index.js"));

var _index2 = _interopRequireDefault(require("./_lib/formatLong/index.js"));

var _index3 = _interopRequireDefault(require("./_lib/formatRelative/index.js"));

var _index4 = _interopRequireDefault(require("./_lib/localize/index.js"));

var _index5 = _interopRequireDefault(require("./_lib/match/index.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * @type {Locale}
 * @category Locales
 * @summary Japanese (Hiragana) locale.
 * @language Japanese (Hiragana)
 * @iso-639-2 jpn
 * @author Eri Hiramatsu [@Eritutteo]{@link https://github.com/Eritutteo}
 */
var locale = {
  code: 'ja-Hira',
  formatDistance: _index.default,
  formatLong: _index2.default,
  formatRelative: _index3.default,
  localize: _index4.default,
  match: _index5.default,
  options: {
    weekStartsOn: 0
    /* Sunday */
    ,
    firstWeekContainsDate: 1
  }
};
var _default = locale;
exports.default = _default;
module.exports = exports.default;


text:
Is a Pure Javascript Canvas Implementation of Matrix Grid ( Primary Application was to Generate Github Like Random Avatar using minBlock.js or Pixel Pattern)

#Check Out Demo
http://flouthoc.github.io/minBlock.js/

#Usage
Getting Started
```html
<script type="text/javascript" src="https://raw.githubusercontent.com/flouthoc/minBlock.js/master/index.js"></script>
```

#Usage

####Regular
```js
  init({
        divId          : canvasID,
        time           : timefortransition,
        randomColor    : true,
        colorPrimary   : PrimaryColor,
        colorSecondary : SecondaryColor'
      });
  //here "time" defines the Delay between two transitions
````

####Fixed Color
```js
  init({
        divId          : canvasID,
        time           : timefortransition,
        randomColor    : false,
        colorPrimary   : PrimaryColor,
        colorSecondary : SecondaryColor'
      });

```

####Pause ( This'll make sure that Matrix Does Not Changes In a Loop )
```js
   init({
          divId          : CanvasId,
          time           : 300,
          randomColor    : true,
          colorPrimary   : primaryColor,
          colorSecondary : secondaryColor,
          pause: true
        });

  ```

#Not Yet Implemented
1. Making it Sensitive for nxn Matrix
2. ~~Simplifying Arguments To JSON format~~ [by @alvaropinot](https://github.com/alvaropinot)


text:
module Mongo
  class Cluster
    module Topology

      # Defines behaviour for when a cluster is in an unknown state.
      #
      # @since 2.0.0
      class Unknown
        include Loggable

        # The display name for the topology.
        #
        # @since 2.0.0
        NAME = 'Unknown'.freeze

        # @return [ Hash ] options The options.
        attr_reader :options

        # Get the display name.
        #
        # @example Get the display name.
        #   Unknown.display_name
        #
        # @return [ String ] The display name.
        #
        # @since 2.0.0
        def display_name
          NAME
        end

        # Elect a primary server within this topology.
        #
        # @example Elect a primary server.
        #   topology.elect_primary(description, servers)
        #
        # @param [ Server::Description ] description The description of the
        #   elected primary.
        # @param [ Array<Server> ] servers The list of known servers to the
        #   cluster.
        #
        # @return [ Sharded, ReplicaSet ] The new topology.
        def elect_primary(description, servers)
          if description.mongos?
            log_debug([ "Mongos #{description.address.to_s} discovered." ])
            Sharded.new(options)
          else
            initialize_replica_set(description, servers)
          end
        end

        # Initialize the topology with the options.
        #
        # @example Initialize the topology.
        #   Unknown.new(options)
        #
        # @param [ Hash ] options The options.
        #
        # @since 2.0.0
        def initialize(options)
          @options = options
        end

        # An unknown topology is not a replica set.
        #
        # @example Is the topology a replica set?
        #   Unknown.replica_set?
        #
        # @return [ false ] Always false.
        #
        # @since 2.0.0
        def replica_set?; false; end

        # Unknown topologies have no replica set name.
        #
        # @example Get the replica set name.
        #   unknown.replica_set_name
        #
        # @return [ nil ] Always nil.
        #
        # @since 2.0.0
        def replica_set_name; nil; end

        # Select appropriate servers for this topology.
        #
        # @example Select the servers.
        #   Unknown.servers(servers)
        #
        # @param [ Array<Server> ] servers The known servers.
        #
        # @raise [ Unknown ] Cannot select servers when the topology is
        #   unknown.
        #
        # @since 2.0.0
        def servers(servers)
        end

        # An unknown topology is not sharded.
        #
        # @example Is the topology sharded?
        #   Unknown.sharded?
        #
        # @return [ false ] Always false.
        #
        # @since 2.0.0
        def sharded?; false; end

        # An unknown topology is not single.
        #
        # @example Is the topology single?
        #   Unknown.single?
        #
        # @return [ true ] Always false.
        #
        # @since 2.0.0
        def single?; false; end

        # An unknown topology is unknown.
        #
        # @example Is the topology unknown?
        #   Unknown.unknown?
        #
        # @return [ true ] Always true.
        #
        # @since 2.0.0
        def unknown?; true; end

        private

        def initialize_replica_set(description, servers)
          log_debug([ "Server #{description.address.to_s} discovered as primary." ])
          servers.each do |server|
            if server.standalone? && server.address != description.address
              server.description.unknown!
            end
          end
          ReplicaSet.new(options.merge(:replica_set => description.replica_set_name))
        end
      end
    end
  end
end


text:
@interface EGViewController ()

@end

@implementation EGViewController
@synthesize myWebView;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    NSString *path = [[NSBundle mainBundle] pathForResource:@"index"
                                                     ofType:@"html"];
    [myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath: path
                                                                   isDirectory:NO]]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
var express = require("express");
var mongoose = require("mongoose");
var moment = require("moment");
var app = express();
var feedGen = require("./feedGen.js");
var youtube = require("./youtube.js");

var Schema = mongoose.Schema;

// detect link
if(process.env.MONGO_PORT) {
    mongoose.connect('mongodb://mongo/ytrss');
} else {
    mongoose.connect('mongodb://localhost/ytrss');
}

var db = mongoose.connection;

db.on('error', function (err) {
    console.log('Can not access DB.', err);
    process.exit(1);
});

db.once('open', function () {
    console.log('Connected to mongo');
});

var feedSchema = new Schema({
    id: { type: String, unique: true},
    title: String,
    image: String,
    updated: { type: Date, default: Date.now },
    feed: { }
});

var Feed = mongoose.model('Feed', feedSchema);

app.get('/', function(req, res) {
    res.send('To get an RSS feed to an YouTube Playlist, call http://' +
            req.headers.host +
            '/feed/PLAYLISTID

 GitHub: https://github.com/DirkHeinke/youtube2rss'
    );
});

app.put('/feed/:id', function (req, res) {
    var id = req.params.id;

    collectFeed(id, function (err) {
        console.log(err);
        // only log, no user notification ;)
    });

    res.send('OK');
});

app.get('/feed/:id', function (req, res) {
    var id = req.params.id;
    console.log('Request for', id);

    sendFeed(id, res);
});

function sendFeed(id, res) {
    Feed.find({id: id}, function (err, feeds) {
        if(err) {
            res.status(404).end();
        } else {
            if(feeds.length == 1) {
                console.log('Cached', id);
                res.header("Content-Type", "text/xml");
                res.send(feeds[0].feed);
            } else {
                console.log('New feed', id);
                collectFeed(id, function (err) {
                    if(!err) {
                        sendFeed(id, res);
                    } else {
                        res.status(404).end();
                    }
                });
            }
        }
    });
}

function collectFeed(id, cb) {
    youtube.getFeedMeta(id, function (err, data) {
        if(err) {
            cb(err)
        } else {
            var items;

            for (var i = 0; i < data.items.length; i++) {
                if (data.items[i].id == id) {
                    items = data.items[i];
                    break;
                }
            }

            var channelTitle = items.snippet.channelTitle;
            var title = items.snippet.localized.title;
            var image = items.snippet.thumbnails.high.url;

            youtube.getFeedItems(id, function (err, data) {
                if(err) {
                    cb(err)
                } else {
                    var feed = feedGen.genFeed(
                        id,
                        channelTitle + ": " + title,
                        'Feed of the YouTube Playlist: ' + title,
                        'feedUrl',
                        'https://www.youtube.com/playlist?list=' + id,
                        image,
                        Date.now(),
                        60 * 30,
                        data.items);

                    var f = {
                        id: id,
                        title: channelTitle,
                        image: image,
                        feed: feed,
                        updated: Date.now()
                    };

                    Feed.findOneAndUpdate(
                        {'id': id},
                        f,
                        {upsert: true},
                        function (err) {
                            if (err) {
                                console.log("Error while saving to DB", err);
                            }
                            cb();
                        }
                    );
                }
            });
        }
    });
}

app.get('/update', function (req, res) {
    console.log('Updating manual');
    res.send('Okay');
    updateFeeds()
});

function updateFeeds() {
    var past = moment().subtract(1, 'h');

    Feed.find({
        updated: {
            $lt: past
        }
    }, function (err, feeds) {
        for(var i=0; i < feeds.length; i++) {
            collectFeed(feeds[i].id, function (err) {
                if(err) {
                    console.log(err);
                }
            });
        }
    })
}

setInterval(function () {
    updateFeeds();
}, 60000);

var server = app.listen(8080, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('App listening at http://%s:%s', host, port);
});


text:
/* jshint asi: true */
/* global define: false */
define(function(require) {
    var app = require("app")
    var github = app.github;

    var blogContent = $("#blog-content")

    function render(list) {
        if (!$.isArray(list)) {
            return
        }

        blogContent.children("h3").remove()

        list.forEach(function(issue) {
            if (issue.user.login !== "jamesfancy") {
                return
            }

            $("<div>").addClass("topic-link").append(
                $("<span>").addClass("comments").text("评论"),
                $("<span>").addClass("value").text(issue.comments || 0),
                $("<a>").attr("href", "../blog/#" + issue.number)
                    .text(issue.title)
            ).appendTo(blogContent)
        })
    }

    function show(page) {
        github.getIssues(page || 1, function(error, json) {
            if (error) {
                console.error(error)
                return
            }

            render(json)
        })
    }

    return {
        show: function() {
            show()
        }
    }
})


text:
ola microservice using Spring Boot

The detailed instructions to run *Red Hat Helloworld MSA* demo, can be found at the following repository: <https://github.com/redhat-helloworld-msa/helloworld-msa>

Build and Deploy ola locally
----------------------------

1. Open a command prompt and navigate to the root directory of this microservice.
2. Type this command to build and execute the microservice:

        mvn clean compile spring-boot:run

3. The application will be running at the following URL: <http://localhost:8080/api/ola>

Deploy the application in OpenShift
-----------------------------------

1. Make sure to be connected to the Docker Daemon
2. Execute

		mvn clean package docker:build fabric8:json fabric8:apply


text:
package org.olat.ldap;

public class LDAPConstants {

	/**
	 * SECURITY_GROUP_LDAP predfined groups length restricted to 16 chars!
	 */
	public static final String SECURITY_GROUP_LDAP = "ldap";

	public static final String LDAP_USER_IDENTIFYER = "userID";

	public static final String LDAP_USER_PASSWORD = "userPassword";

}


text:
.apiref-row {
    padding-bottom: 1em;
    display: block;
    float: none;
}

.apiref-spec {
    display: inline;
    font-family: monospace;
    font-weight: bold;
}

.apiref-lambda {
    display: inline;
    font-family: monospace;
    font-weight: bold;
    font-style: italic;
}

.apiref-result {
    display: block;
    font-family: monospace;
    font-style: italic;
    margin-left: 20px;
}

.apiref-doc {
    display: block;
    float: none;
    margin-left: 30px;
}

.codeblock {
    display: block;
    background: lightgrey;
    border: 1px solid black;
    padding: 10px;
    margin: 20px 5px 20px 5px;
    white-space:pre;
}

/* From coloring-css.lisp in colorize */
.symbol { color : #770055; background-color : transparent; border: 0px; margin: 0px;}
a.symbol:link { color : #229955; background-color : transparent; text-decoration: none; border: 0px; margin: 0px; }
a.symbol:active { color : #229955; background-color : transparent; text-decoration: none; border: 0px; margin: 0px; }
a.symbol:visited { color : #229955; background-color : transparent; text-decoration: none; border: 0px; margin: 0px; }
a.symbol:hover { color : #229955; background-color : transparent; text-decoration: none; border: 0px; margin: 0px; }
.special { color : #FF5000; background-color : inherit; }
.keyword { color : #770000; background-color : inherit; }
.comment { color : #007777; background-color : inherit; }
.string { color : #777777; background-color : inherit; }
.character { color : #0055AA; background-color : inherit; }
.syntaxerror { color : #FF0000; background-color : inherit; }
span.paren1:hover { color : inherit; background-color : #BAFFFF; }
span.paren2:hover { color : inherit; background-color : #FFCACA; }
span.paren3:hover { color : inherit; background-color : #FFFFBA; }
span.paren4:hover { color : inherit; background-color : #CACAFF; }
span.paren5:hover { color : inherit; background-color : #CAFFCA; }
span.paren6:hover { color : inherit; background-color : #FFBAFF; }


text:
all: parsers run

parsers:
	pegjs ini-pegjs.pegjs
	jison ini-jison.jison

watch:
	ls $(WATCH_FILES) | entr -c make parsers run

run:
	node test.js

.PHONY: parser watch run


text:
{% load i18n cms_admin admin_urls %}

{# INFO: columns are defined in base.html options #}
{% spaceless %}
<li class="cms-tree-node {{ css_class }}
    {% if follow_descendants %}{% if descendants %} jstree-open{% elif node.is_branch %} jstree-closed{% endif %}{% endif %}
    {% if page.reverse_id == 'page_types' %} cms-tree-node-pagetype{% endif %}
    {% if node.depth == 0 %} cms-tree-node-top{% endif %}
    {% if filtered %} cms-tree-node-filtered{% endif %}
    {% if has_add_permission %} cms-tree-node-root-allow-children{% endif %}
    {% block extra_class %}
        {% if is_shared_page %}
            cms-tree-node-shared-true
        {% else %}
            cms-tree-node-shared-false
        {% endif %}
    {% endblock %}
    "
    {% if is_popup %}onclick="opener.dismissRelatedLookupPopup(window, {{ page.id }}); return false;"{% endif %}
    data-id="{{ page.pk }}"
    data-node-id="{{ node.pk }}"
    data-slug="{{ page.get_slug }}"
    data-is-home="{{ page.is_home|yesno:"true,false" }}"
    data-move-permission="{{ has_move_page_permission|yesno:"true,false" }}"
    data-add-permission="{{ has_add_page_permission|yesno:"true,false" }}"
    {% block extra_data %}
        {% if is_shared_page %}
            data-shared-page="-true"
        {% else %}
            data-shared-page="-false"
        {% endif %}
    {% endblock %}
    data-colview='

                {% block row_icon %}
                    {% if page.is_home %}

                    {% endif %}
                    {% if page.soft_root %}

                    {% endif %}
                    {% if page.application_urls %}

                    {% endif %}
                {% endblock %}

    '
    data-colpreview='

                        {% autoescape on %}{% trans "View on site" %}{% endautoescape %}

    '
    {% for lang in site_languages %}
    data-col{{ lang|lower|cut:'-' }}='

                    {% if has_publish_permission %}

                            {# INFO: renders  #}
                            {% tree_publish_row page lang %}

                                        {% autoescape on %}{% trans "Preview" %}{% endautoescape %}

                                {# hide if page is empty #}
                                {% if lang in page_languages %}
                                    {% if ancestors|nodes_are_published:lang %}
                                        {% if page|is_dirty:lang or not page|is_published:lang %}

                                                    {% autoescape on %}{% trans "Publish" %}{% endautoescape %}

                                        {% endif %}
                                        {% if page|is_published:lang %}

                                                    {% autoescape on %}{% trans "Unpublish" %}{% endautoescape %}

                                        {% endif %}
                                    {% endif %}
                                {% else %}

                                            {% autoescape on %}{% trans "Configure" %}{% endautoescape %}

                                {% endif %}

                    {% else %}

                            {% tree_publish_row page lang %}

                    {% endif %}

    '
    {% endfor %}
    data-colmenu='

                    {% if has_change_permission %}

                    {% endif %}
                        {% if page.in_navigation %}

                        {% else %}

                        {% endif %}
                    {% if has_change_permission %}

                    {% endif %}

    '
    data-coloptions='

                        {% if has_change_permission or has_change_advanced_settings_permission %}

                        {% else %}

                        {% endif %}
                            {% autoescape on %}{% trans "Page settings (SHIFT click for advanced settings)" %}{% endautoescape %}
                        {% if has_change_permission or has_change_advanced_settings_permission %}

                        {% endif %}

                        {% if has_add_page_permission %}

                        {% else %}

                        {% endif %}
                                {% autoescape on %}{% trans 'New sub page' %}{% endautoescape %}
                        {% if has_add_page_permission %}

                        {% else %}

                        {% endif %}

                        {% autoescape on %}{% trans "Options" %}{% endautoescape %}

                        {# dummy structure #}

                                    {% autoescape on %}{% trans 'Copy' %}{% endautoescape %}

                                    {% autoescape on %}{% trans 'Cut' %}{% endautoescape %}

                                    {% autoescape on %}{% trans "Paste" %}{% endautoescape %}

                                    {% autoescape on %}{% trans 'Delete' %}...{% endautoescape %}

                                    {% autoescape on %}{% trans "Advanced settings" %}{% endautoescape %}

                            {% if CMS_PERMISSION %}

                                        {% autoescape on %}{% trans "Permissions" %}{% endautoescape %}

                            {% endif %}

    '
    {% block extra_cols %}{% endblock %}
    >

    {% language LANGUAGE_CODE %}
        {{ page.get_admin_tree_title }}
    {% endlanguage %}

    {# INFO render children #}
    {% if descendants %}

            {% show_admin_menu_for_pages descendants depth=node.depth|add:1 %}

    {% endif %}

{% endspaceless %}


text:
package main

import (
	"log"
	"os"
	"path/filepath"
	"time"
)

import (
	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
)

type Directory struct {
	name     string
	parent   *Directory
	children []*Directory
}

func NewDirectory(name string, parent *Directory) *Directory {
	return &Directory{name: name, parent: parent}
}

var _ walk.TreeItem = new(Directory)

func (d *Directory) Text() string {
	return d.name
}

func (d *Directory) Parent() walk.TreeItem {
	if d.parent == nil {
		// We can't simply return d.parent in this case, because the interface
		// value then would not be nil.
		return nil
	}

	return d.parent
}

func (d *Directory) ChildCount() int {
	if d.children == nil {
		// It seems this is the first time our child count is checked, so we
		// use the opportunity to populate our direct children.
		if err := d.ResetChildren(); err != nil {
			log.Print(err)
		}
	}

	return len(d.children)
}

func (d *Directory) ChildAt(index int) walk.TreeItem {
	return d.children[index]
}

func (d *Directory) Image() interface{} {
	return d.Path()
}

func (d *Directory) ResetChildren() error {
	d.children = nil

	dirPath := d.Path()

	if err := filepath.Walk(d.Path(), func(path string, info os.FileInfo, err error) error {
		if err != nil {
			if info == nil {
				return filepath.SkipDir
			}
		}

		name := info.Name()

		if !info.IsDir() || path == dirPath || shouldExclude(name) {
			return nil
		}

		d.children = append(d.children, NewDirectory(name, d))

		return filepath.SkipDir
	}); err != nil {
		return err
	}

	return nil
}

func (d *Directory) Path() string {
	elems := []string{d.name}

	dir, _ := d.Parent().(*Directory)

	for dir != nil {
		elems = append([]string{dir.name}, elems...)
		dir, _ = dir.Parent().(*Directory)
	}

	return filepath.Join(elems...)
}

type DirectoryTreeModel struct {
	walk.TreeModelBase
	roots []*Directory
}

var _ walk.TreeModel = new(DirectoryTreeModel)

func NewDirectoryTreeModel() (*DirectoryTreeModel, error) {
	model := new(DirectoryTreeModel)

	drives, err := walk.DriveNames()
	if err != nil {
		return nil, err
	}

	for _, drive := range drives {
		switch drive {
		case "A:\\", "B:\\":
			continue
		}

		model.roots = append(model.roots, NewDirectory(drive, nil))
	}

	return model, nil
}

func (*DirectoryTreeModel) LazyPopulation() bool {
	// We don't want to eagerly populate our tree view with the whole file system.
	return true
}

func (m *DirectoryTreeModel) RootCount() int {
	return len(m.roots)
}

func (m *DirectoryTreeModel) RootAt(index int) walk.TreeItem {
	return m.roots[index]
}

type FileInfo struct {
	Name     string
	Size     int64
	Modified time.Time
}

type FileInfoModel struct {
	walk.SortedReflectTableModelBase
	dirPath string
	items   []*FileInfo
}

var _ walk.ReflectTableModel = new(FileInfoModel)

func NewFileInfoModel() *FileInfoModel {
	return new(FileInfoModel)
}

func (m *FileInfoModel) Items() interface{} {
	return m.items
}

func (m *FileInfoModel) SetDirPath(dirPath string) error {
	m.dirPath = dirPath
	m.items = nil

	if err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			if info == nil {
				return filepath.SkipDir
			}
		}

		name := info.Name()

		if path == dirPath || shouldExclude(name) {
			return nil
		}

		item := &FileInfo{
			Name:     name,
			Size:     info.Size(),
			Modified: info.ModTime(),
		}

		m.items = append(m.items, item)

		if info.IsDir() {
			return filepath.SkipDir
		}

		return nil
	}); err != nil {
		return err
	}

	m.PublishRowsReset()

	return nil
}

func (m *FileInfoModel) Image(row int) interface{} {
	return filepath.Join(m.dirPath, m.items[row].Name)
}

func shouldExclude(name string) bool {
	switch name {
	case "System Volume Information", "pagefile.sys", "swapfile.sys":
		return true
	}

	return false
}

func main() {
	var mainWindow *walk.MainWindow
	var splitter *walk.Splitter
	var treeView *walk.TreeView
	var tableView *walk.TableView
	var webView *walk.WebView

	treeModel, err := NewDirectoryTreeModel()
	if err != nil {
		log.Fatal(err)
	}
	tableModel := NewFileInfoModel()

	if err := (MainWindow{
		AssignTo: &mainWindow,
		Title:    "Walk File Browser Example",
		MinSize:  Size{600, 400},
		Size:     Size{1024, 640},
		Layout:   HBox{MarginsZero: true},
		Children: []Widget{
			HSplitter{
				AssignTo: &splitter,
				Children: []Widget{
					TreeView{
						AssignTo: &treeView,
						Model:    treeModel,
						OnCurrentItemChanged: func() {
							dir := treeView.CurrentItem().(*Directory)
							if err := tableModel.SetDirPath(dir.Path()); err != nil {
								walk.MsgBox(
									mainWindow,
									"Error",
									err.Error(),
									walk.MsgBoxOK|walk.MsgBoxIconError)
							}
						},
					},
					TableView{
						AssignTo:      &tableView,
						StretchFactor: 2,
						Columns: []TableViewColumn{
							TableViewColumn{
								DataMember: "Name",
								Width:      192,
							},
							TableViewColumn{
								DataMember: "Size",
								Format:     "%d",
								Alignment:  AlignFar,
								Width:      64,
							},
							TableViewColumn{
								DataMember: "Modified",
								Format:     "2006-01-02 15:04:05",
								Width:      120,
							},
						},
						Model: tableModel,
						OnCurrentIndexChanged: func() {
							var url string
							if index := tableView.CurrentIndex(); index > -1 {
								name := tableModel.items[index].Name
								dir := treeView.CurrentItem().(*Directory)
								url = filepath.Join(dir.Path(), name)
							}

							webView.SetURL(url)
						},
					},
					WebView{
						AssignTo:      &webView,
						StretchFactor: 2,
					},
				},
			},
		},
	}.Create()); err != nil {
		log.Fatal(err)
	}

	splitter.SetFixed(treeView, true)
	splitter.SetFixed(tableView, true)

	mainWindow.Run()
}


text:
[![Build Status][build-status-image]][build-status]

[build-status-image]: https://travis-ci.org/kaazing/version-properties-maven-plugin.svg?branch=develop
[build-status]: https://travis-ci.org/kaazing/version-properties-maven-plugin


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/a2zcms-ci.iml" filepath="$PROJECT_DIR$/.idea/a2zcms-ci.iml" />
    </modules>
  </component>
</project>


text:
Gun
===

Gun is an asynchronous SPDY, HTTP and Websocket client.

Goals
-----

Gun aims to provide an **easy to use** client compatible with
HTTP, SPDY and Websocket.

Gun is **always connected**. It will maintain a permanent
connection to the server, reopening it as soon as the server
closes it, saving time for the requests that come in.

All connections are **supervised** automatically, allowing
the developer to focus on writing his code without worrying.

Sponsors
--------

The development of the Gun project is sponsored
by [LeoFS Cloud Storage](http://www.leofs.org).

Support
-------

 *  Official IRC Channel: #ninenines on irc.freenode.net
 *  [Mailing Lists](http://lists.ninenines.eu)
 *  [Commercial Support](http://ninenines.eu/support)


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "categories".
 *
 * @property integer $id
 * @property string $type
 * @property string $name
 */
class Categories extends \yii\db\ActiveRecord
{

    public $indicator;

    public $indicators_available;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'categories';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['type', 'name'], 'required'],
            [['type'], 'string', 'max' => 45],
            [['name'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'type' => 'Typ',
            'name' => 'Kategoria',
        ];
    }

    public function getIndicators()
    {
        return $this->hasMany(IndicatorNames::className(), ['id' => 'id_indicator_names'])
            ->viaTable('categories_indicators', ['id_categories' => 'id']);
    }
}


text:
package org.globsframework.functional.impl;

import org.globsframework.functional.FunctionalKey;
import org.globsframework.functional.FunctionalKeyBuilder;
import org.globsframework.functional.MutableFunctionalKey;
import org.globsframework.metamodel.Field;
import org.globsframework.metamodel.fields.FieldValueVisitor;
import org.globsframework.model.FieldValue;
import org.globsframework.utils.exceptions.ItemNotFound;

public class TwoFieldsMutableKey extends AbstractFieldValue<MutableFunctionalKey>
    implements MutableFunctionalKey, FunctionalKey {
    private final TwoFunctionalKeyBuilder functionalKeyBuilder;
    private Object value1;
    private Object value2;

    TwoFieldsMutableKey(TwoFunctionalKeyBuilder functionalKeyBuilder) {
        this.functionalKeyBuilder = functionalKeyBuilder;
    }

    TwoFieldsMutableKey(TwoFunctionalKeyBuilder functionalKeyBuilder, Object value1, Object value2) {
        this.functionalKeyBuilder = functionalKeyBuilder;
        this.value1 = value1;
        this.value2 = value2;
    }

    protected MutableFunctionalKey doSet(Field field, Object o) {
        if (functionalKeyBuilder.field1 == field) {
            value1 = o;
        }
        else {
            value2 = o;
        }
        return this;
    }

    protected Object doGet(Field field) {
        return field == functionalKeyBuilder.field1 ? value1 : value2;
    }

    public FunctionalKey getShared() {
        return this;
    }

    public FunctionalKey create() {
        return new TwoFieldsMutableKey(functionalKeyBuilder,
                                       value1, value2);
    }

    public boolean contains(Field field) {
        return field == functionalKeyBuilder.field1 ||
               field == functionalKeyBuilder.field2;
    }

    public int size() {
        return 2;
    }

    public <T extends FieldValueVisitor> T accept(T functor) throws Exception {
        functionalKeyBuilder.field1.visit(functor, value1);
        functionalKeyBuilder.field2.visit(functor, value2);
        return functor;
    }

    public <T extends Functor> T apply(T functor) throws Exception {
        functor.process(functionalKeyBuilder.field1, value1);
        functor.process(functionalKeyBuilder.field2, value2);
        return functor;
    }

    public FieldValue[] toArray() {
        return new FieldValue[]{FieldValue.value(functionalKeyBuilder.field1, value1),
                                FieldValue.value(functionalKeyBuilder.field2, value2)};
    }

    public FunctionalKeyBuilder getBuilder() {
        return functionalKeyBuilder;
    }

    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        TwoFieldsMutableKey that = (TwoFieldsMutableKey)o;

        if (!functionalKeyBuilder.equals(that.functionalKeyBuilder)) {
            return false;
        }
        if (value1 != null ? !value1.equals(that.value1) : that.value1 != null) {
            return false;
        }
        return value2 != null ? value2.equals(that.value2) : that.value2 == null;
    }

    public int hashCode() {
        int result = functionalKeyBuilder.hashCode();
        result = 31 * result + (value1 != null ? value1.hashCode() : 0);
        result = 31 * result + (value2 != null ? value2.hashCode() : 0);
        return result;
    }

    public boolean isSet(Field field) throws ItemNotFound {
        return true;
    }

    public String toString() {
        return "TwoFieldsMutableKey{" +
              "functionalKeyBuilder=" + functionalKeyBuilder +
              ", value1=" + value1 +
              ", value2=" + value2 +
              '}';
    }
}