text:
//
// Calendar.cs
//
// Author:
//       Claudio Rodrigo Pereyra Diaz <claudiorodrigo@pereyradiaz.com.ar>
//
// Copyright (c) 2015 Hamekoz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt;

namespace Samples
{
	public class CalendarSample : VBox
	{
		public CalendarSample ()
		{
			var label = new Label ();
			var calendar = new Calendar () {
				ExpandHorizontal = false,
			};
			var entry = new TextEntry () {
				PlaceholderText = "Enter a date to change calendar",
			};
			var minimumDate = new TextEntry () {
				PlaceholderText = "Enter the minimum date of calendar",
			};
			var maximumDate = new TextEntry () {
				PlaceholderText = "Enter the maximum date of calendar",
			};

			calendar.ValueChanged += delegate {
				label.Text = string.Format ("Selected date: {0}", calendar.Date.ToShortDateString ());
				if (entry.Text != string.Empty)
					entry.Text = calendar.Date.ToShortDateString ();
			};
			label.Text = string.Format ("Selected date: {0}", calendar.Date.ToShortDateString ());

			var button = new Button () {
				Label = "Change values",
			};

			button.Clicked += delegate {
				DateTime dateMin;
				if (DateTime.TryParse (minimumDate.Text, out dateMin))
					calendar.MinimumDate = dateMin.Date;
				DateTime dateMax;
				if (DateTime.TryParse (maximumDate.Text, out dateMax))
					calendar.MaximumDate = dateMax.Date;
				DateTime date;
				if (DateTime.TryParse (entry.Text, out date))
					calendar.Date = date;
			};

			PackStart (calendar);
			PackStart (entry);
			PackStart (minimumDate);
			PackStart (maximumDate);
			PackStart (button);
			PackStart (label);
		}
	}
}


text:
#ifndef _SDD_VALUES_VALUES_TRAITS_HH_
#define _SDD_VALUES_VALUES_TRAITS_HH_

namespace sdd { namespace values {

/*------------------------------------------------------------------------------------------------*/

/// @internal
/// @brief Describe some properties of values.
template <typename Values>
struct values_traits
{
  static constexpr bool stateful = false;
  static constexpr bool fast_iterable = false;
  static constexpr bool has_value_type = true;
};

/*------------------------------------------------------------------------------------------------*/

}} // namespace sdd::values

#endif // _SDD_VALUES_VALUES_TRAITS_HH_

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace tdanielcox\Bluesnap\Models;

/**
 * Class CreditCardInfo
 */
class CreditCardInfo extends Model
{
    public function __construct($data = null)
    {
        parent::__construct($data);
    }

    protected $children = ['creditCard' => self::ITEM, 'billingContactInfo' => self::ITEM];

    /**
     * @var string
     */
    public $pfToken;

    /**
     * @var CreditCard
     */
    public $creditCard;

    /**
     * @var BillingContactInfo
     */
    public $billingContactInfo;
}


text:
Multi-selection checkboxes for forms.

[Example](https://jsfiddle.net/5typ998v/5/)


text:
title: Lauren Manoogian
date: 2017-04-21 10:36:00 Z
tags:
- shopify
- e-commerce
- design
- inspiration
- fashion
- apparel
- clothing
- womens
image: "/uploads/267-laurenmanoogian@2x.jpg"
store-link: https://laurenmanoogian.com
credit: Lemonade
credit-link: http://lemonadeny.com
---


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Npgsql;
using RohBot.Packets;
using RohBot.Rooms;
using SuperWebSocket;

namespace RohBot
{
    public class Connection : WebSocketSession<Connection>
    {
        public string Address { get; private set; }
        public bool IsMobile { get; private set; }
        public Session Session { get; set; }

        public void SendJoinRoom(Room room)
        {
            Send(new Chat
            {
                Method = "join",
                Name = room.RoomInfo.Name,
                ShortName = room.RoomInfo.ShortName
            });

            room.SendHistory(this);
        }

        public void SendLeaveRoom(Room room)
        {
            Send(new Chat
            {
                Method = "leave",
                Name = room.RoomInfo.Name,
                ShortName = room.RoomInfo.ShortName
            });
        }

        public void Login(string username, string password, List<string> tokens)
        {
            Account account = null;
            string message;

            do
            {
                if (Session != null)
                {
                    message = "You are already logged in.";
                    break;
                }

                if (!Util.IsValidUsername(username))
                {
                    message = Util.InvalidUsernameMessage;
                    break;
                }

                var existingTokens = LoginToken.FindAll(username).ToList();

                if (String.IsNullOrEmpty(password))
                {
                    if (tokens.Count == 0)
                    {
                        message = "Missing password.";
                        break;
                    }

                    if (!existingTokens.Any(t => t.Address == Address && tokens.Contains(t.Token)))
                    {
                        message = "Automatic login failed. Login with your username and password.";
                        break;
                    }

                    account = Account.Get(username);
                    tokens = existingTokens.Select(t => t.Token).ToList();
                    message = String.Format("Logged in as {0}.", account.Name);
                }
                else
                {
                    if (!Util.IsValidPassword(password))
                    {
                        message = Util.InvalidPasswordMessage;
                        break;
                    }

                    account = Account.Get(username);
                    if (account == null)
                    {
                        message = "Invalid username or password.";
                        break;
                    }

                    var givenPassword = Convert.ToBase64String(Util.HashPassword(password, Convert.FromBase64String(account.Salt)));
                    if (givenPassword != account.Password)
                    {
                        account = null;
                        message = "Invalid username or password.";
                        break;
                    }

                    LoginToken newToken = existingTokens.FirstOrDefault(t => t.Address == Address);
                    if (newToken == null)
                    {
                        newToken = new LoginToken
                        {
                            Name = account.Name.ToLower(),
                            Address = Address,
                            Token = Util.GenerateLoginToken(),
                            Created = Util.GetCurrentTimestamp()
                        };

                        newToken.Insert();
                        existingTokens.Add(newToken);
                    }

                    tokens = existingTokens.Select(t => t.Token).ToList();
                    message = String.Format("Logged in as {0}.", account.Name);
                }
            } while (false);

            if (account != null)
            {
                Send(new AuthenticateResponse
                {
                    Name = account.Name,
                    Tokens = string.Join(",", tokens),
                    Success = true
                });

                var session = Program.SessionManager.GetOrCreate(account);
                session.Add(this);
            }

            SendSysMessage(message);
        }

        public void Register(string username, string password)
        {
            string message;

            username = username.Trim();

            do
            {
                if (Session != null)
                {
                    message = "You can not register while logged in.";
                    break;
                }

                if (!Util.IsValidUsername(username))
                {
                    message = Util.InvalidUsernameMessage;
                    break;
                }

                if (!Util.IsValidPassword(password))
                {
                    message = Util.InvalidPasswordMessage;
                    break;
                }

                var accountsFromAddress = Account.FindWithAddress(Address).Count();
                if (accountsFromAddress >= 3)
                {
                    message = "Too many accounts were created from this location.";
                    break;
                }

                var salt = Util.GenerateSalt();
                var account = new Account
                {
                    Address = Address,
                    Name = username,
                    Password = Convert.ToBase64String(Util.HashPassword(password, salt)),
                    Salt = Convert.ToBase64String(salt),
                    EnabledStyle = "",
                    Rooms = new string[0]
                };

                try
                {
                    account.Insert();
                }
                catch (NpgsqlException)
                {
                    message = "An account with that name already exists.";
                    break;
                }

                message = "Account created. You can now login.";
            } while (false);

            SendSysMessage(message);
        }

        public void SendSysMessage(string message)
        {
            Send(new SysMessage { Content = Util.HtmlEncode(message), Date = Util.GetCurrentTimestamp() });
        }

        public void Send(Packet packet)
        {
            Send(Packet.WriteToMessage(packet));
        }

        private static readonly Regex MobileUserAgent = new Regex(@"Android|iPhone|iPad|iPod|Windows Phone", RegexOptions.Compiled);

        protected override void OnSessionStarted()
        {
            Session = null;

            try
            {
                var isLocal = RemoteEndPoint.Address.ToString() == "127.0.0.1";
                Address = isLocal ? Items["X-Real-IP"].ToString() : RemoteEndPoint.Address.ToString();
            }
            catch
            {
                Address = "127.0.0.1";
            }

            try
            {
                IsMobile = MobileUserAgent.IsMatch(Items["User-Agent"].ToString());
            }
            catch
            {
                IsMobile = false;
            }
        }
    }
}


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Automatically generated strings for Moodle installer
 *
 * Do not edit this file manually! It contains just a subset of strings
 * needed during the very first steps of installation. This file was
 * generated automatically by export-installer.php (which is part of AMOS
 * {@link http://docs.moodle.org/dev/Languages/AMOS}) using the
 * list of strings defined in /install/stringnames.txt.
 *
 * @package   installer
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

defined('MOODLE_INTERNAL') || die();

$string['clianswerno'] = 'n';
$string['cliansweryes'] = 'i';
$string['cliincorrectvalueerror'] = 'Gwall, gwerth anghywir "{$a->value}" ar gyfer "{$a->option}"';
$string['cliincorrectvalueretry'] = 'Gwerth anghywir, rhowch gynnig arall arni';
$string['clitypevalue'] = 'math o werth';
$string['clitypevaluedefault'] = 'math o werth, pwyswch Enter i ddefnyddio\'r gwerth diofyn ({$a})';
$string['cliunknowoption'] = 'Dewisiadau dieithr:
  {$a}
Defnyddiwch y dewis --help.';
$string['cliyesnoprompt'] = 'mae teipio i (yn golygu iawn) neu n (yn golygu na)';
$string['environmentrequireinstall'] = 'angen ei osod/ei alluogi.';
$string['environmentrequireversion'] = 'Mae angen fersiwn {$a->needed} ac rydych yn defnyddio {$a->current}';


text:
<?php

declare(strict_types=1);

namespace LIN3S\SharedKernel\Domain\Model\Email;

use LIN3S\SharedKernel\Exception\Exception;

/**
 * @author Beñat Espiña <benatespina@gmail.com>
 */
class EmailInvalidException extends Exception
{
}


text:
import java.util.ArrayList;
import java.util.Collection;

public class SingularCollection<T> {
	private Collection rawTypes;
	private Collection<Integer> integers;
	private Collection<T> generics;
	private Collection<? extends Number> extendsGenerics;

	public static void main(String[] args) {
	}

	@java.lang.SuppressWarnings("all")
	public static abstract class SingularCollectionBuilder<T, C extends SingularCollection<T>, B extends SingularCollection.SingularCollectionBuilder<T, C, B>> {
		@java.lang.SuppressWarnings("all")
		private java.util.ArrayList<java.lang.Object> rawTypes;
		@java.lang.SuppressWarnings("all")
		private java.util.ArrayList<Integer> integers;
		@java.lang.SuppressWarnings("all")
		private java.util.ArrayList<T> generics;
		@java.lang.SuppressWarnings("all")
		private java.util.ArrayList<Number> extendsGenerics;

		@java.lang.SuppressWarnings("all")
		protected abstract B self();

		@java.lang.SuppressWarnings("all")
		public abstract C build();

		@java.lang.SuppressWarnings("all")
		public B rawType(final java.lang.Object rawType) {
			if (this.rawTypes == null) this.rawTypes = new java.util.ArrayList<java.lang.Object>();
			this.rawTypes.add(rawType);
			return self();
		}

		@java.lang.SuppressWarnings("all")
		public B rawTypes(final java.util.Collection<?> rawTypes) {
			if (rawTypes == null) {
				throw new java.lang.NullPointerException("rawTypes cannot be null");
			}
			if (this.rawTypes == null) this.rawTypes = new java.util.ArrayList<java.lang.Object>();
			this.rawTypes.addAll(rawTypes);
			return self();
		}

		@java.lang.SuppressWarnings("all")
		public B clearRawTypes() {
			if (this.rawTypes != null) this.rawTypes.clear();
			return self();
		}

		@java.lang.SuppressWarnings("all")
		public B integer(final Integer integer) {
			if (this.integers == null) this.integers = new java.util.ArrayList<Integer>();
			this.integers.add(integer);
			return self();
		}

		@java.lang.SuppressWarnings("all")
		public B integers(final java.util.Collection<? extends Integer> integers) {
			if (integers == null) {
				throw new java.lang.NullPointerException("integers cannot be null");
			}
			if (this.integers == null) this.integers = new java.util.ArrayList<Integer>();
			this.integers.addAll(integers);
			return self();
		}

		@java.lang.SuppressWarnings("all")
		public B clearIntegers() {
			if (this.integers != null) this.integers.clear();
			return self();
		}

		@java.lang.SuppressWarnings("all")
		public B generic(final T generic) {
			if (this.generics == null) this.generics = new java.util.ArrayList<T>();
			this.generics.add(generic);
			return self();
		}

		@java.lang.SuppressWarnings("all")
		public B generics(final java.util.Collection<? extends T> generics) {
			if (generics == null) {
				throw new java.lang.NullPointerException("generics cannot be null");
			}
			if (this.generics == null) this.generics = new java.util.ArrayList<T>();
			this.generics.addAll(generics);
			return self();
		}

		@java.lang.SuppressWarnings("all")
		public B clearGenerics() {
			if (this.generics != null) this.generics.clear();
			return self();
		}

		@java.lang.SuppressWarnings("all")
		public B extendsGeneric(final Number extendsGeneric) {
			if (this.extendsGenerics == null) this.extendsGenerics = new java.util.ArrayList<Number>();
			this.extendsGenerics.add(extendsGeneric);
			return self();
		}

		@java.lang.SuppressWarnings("all")
		public B extendsGenerics(final java.util.Collection<? extends Number> extendsGenerics) {
			if (extendsGenerics == null) {
				throw new java.lang.NullPointerException("extendsGenerics cannot be null");
			}
			if (this.extendsGenerics == null) this.extendsGenerics = new java.util.ArrayList<Number>();
			this.extendsGenerics.addAll(extendsGenerics);
			return self();
		}

		@java.lang.SuppressWarnings("all")
		public B clearExtendsGenerics() {
			if (this.extendsGenerics != null) this.extendsGenerics.clear();
			return self();
		}

		@java.lang.Override
		@java.lang.SuppressWarnings("all")
		public java.lang.String toString() {
			return "SingularCollection.SingularCollectionBuilder(rawTypes=" + this.rawTypes + ", integers=" + this.integers + ", generics=" + this.generics + ", extendsGenerics=" + this.extendsGenerics + ")";
		}
	}

	@java.lang.SuppressWarnings("all")
	private static final class SingularCollectionBuilderImpl<T> extends SingularCollection.SingularCollectionBuilder<T, SingularCollection<T>, SingularCollection.SingularCollectionBuilderImpl<T>> {
		@java.lang.SuppressWarnings("all")
		private SingularCollectionBuilderImpl() {
		}

		@java.lang.Override
		@java.lang.SuppressWarnings("all")
		protected SingularCollection.SingularCollectionBuilderImpl<T> self() {
			return this;
		}

		@java.lang.Override
		@java.lang.SuppressWarnings("all")
		public SingularCollection<T> build() {
			return new SingularCollection<T>(this);
		}
	}

	@java.lang.SuppressWarnings("all")
	protected SingularCollection(final SingularCollection.SingularCollectionBuilder<T, ?, ?> b) {
		java.util.Collection<java.lang.Object> rawTypes;
		switch (b.rawTypes == null ? 0 : b.rawTypes.size()) {
		case 0:
			rawTypes = java.util.Collections.emptyList();
			break;
		case 1:
			rawTypes = java.util.Collections.singletonList(b.rawTypes.get(0));
			break;
		default:
			rawTypes = java.util.Collections.unmodifiableList(new java.util.ArrayList<java.lang.Object>(b.rawTypes));
		}
		this.rawTypes = rawTypes;
		java.util.Collection<Integer> integers;
		switch (b.integers == null ? 0 : b.integers.size()) {
		case 0:
			integers = java.util.Collections.emptyList();
			break;
		case 1:
			integers = java.util.Collections.singletonList(b.integers.get(0));
			break;
		default:
			integers = java.util.Collections.unmodifiableList(new java.util.ArrayList<Integer>(b.integers));
		}
		this.integers = integers;
		java.util.Collection<T> generics;
		switch (b.generics == null ? 0 : b.generics.size()) {
		case 0:
			generics = java.util.Collections.emptyList();
			break;
		case 1:
			generics = java.util.Collections.singletonList(b.generics.get(0));
			break;
		default:
			generics = java.util.Collections.unmodifiableList(new java.util.ArrayList<T>(b.generics));
		}
		this.generics = generics;
		java.util.Collection<Number> extendsGenerics;
		switch (b.extendsGenerics == null ? 0 : b.extendsGenerics.size()) {
		case 0:
			extendsGenerics = java.util.Collections.emptyList();
			break;
		case 1:
			extendsGenerics = java.util.Collections.singletonList(b.extendsGenerics.get(0));
			break;
		default:
			extendsGenerics = java.util.Collections.unmodifiableList(new java.util.ArrayList<Number>(b.extendsGenerics));
		}
		this.extendsGenerics = extendsGenerics;
	}

	@java.lang.SuppressWarnings("all")
	public static <T> SingularCollection.SingularCollectionBuilder<T, ?, ?> builder() {
		return new SingularCollection.SingularCollectionBuilderImpl<T>();
	}
}


text:
package com.github.javarch.support.config;

import java.util.Properties;

import javax.inject.Inject;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

/**
 *
 * @author Lucas Oliveira
 *
 */
@Configuration
@ComponentScan(basePackages={"com.github.javarch.support"})
@PropertySource("classpath:email.properties")
@Profile("email") // enable email
public class EMailConfig {

	@Inject
	private Environment env;

	@Bean
	@Scope(value=BeanDefinition.SCOPE_PROTOTYPE)
	public SimpleMailMessage templateMessage(){
		SimpleMailMessage simpleMessage = new SimpleMailMessage();
		simpleMessage.setFrom( env.getRequiredProperty("mail.username") );

		return simpleMessage;
	}

	/**
	 * http://support.google.com/mail/bin/answer.py?hl=en&answer=13287
	 * @return
	 */
	@Bean
	public MailSender mailSender(){
		JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
		mailSender.setDefaultEncoding("UTF-8");
		mailSender.setHost( env.getRequiredProperty("mail.host") );
		mailSender.setPassword( env.getRequiredProperty("mail.password") );
		mailSender.setUsername(env.getRequiredProperty("mail.username"));
		mailSender.setPort( env.getProperty("mail.port", Integer.class, 25) );
		mailSender.setProtocol( env.getRequiredProperty("mail.transport.protocol"));

		mailSender.setJavaMailProperties( mailProperties() );

		return mailSender;
	}

	protected Properties mailProperties() {
		Properties javaMailProperties = new Properties();

		javaMailProperties.put("mail.smtp.auth", env.getProperty("mail.smtp.auth", Boolean.class, false));
		javaMailProperties.put("mail.smtp.starttls.enable", env.getProperty("mail.smtp.starttls.enable", Boolean.class, false));

		return javaMailProperties;
	}

}


text:
package timely.balancer.netty.ws;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.Session;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.ScheduledFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import timely.api.response.TimelyException;
import timely.auth.util.ProxiedEntityUtils;
import timely.client.websocket.ClientHandler;
import timely.netty.http.auth.TimelyAuthenticationToken;

public class WsClientHandler extends ClientHandler {

    private static final Logger LOG = LoggerFactory.getLogger(WsClientHandler.class);
    private final ChannelHandlerContext ctx;
    private final TimelyAuthenticationToken token;
    private ScheduledFuture<?> ping;

    public WsClientHandler(ChannelHandlerContext ctx, TimelyAuthenticationToken token, int pingRate) {
        this.ctx = ctx;
        this.token = token;
        this.ping = this.ctx.executor().scheduleAtFixedRate(() -> {
            LOG.trace("Sending ping on channel {}", ctx.channel());
            ctx.writeAndFlush(new PingWebSocketFrame());
        }, pingRate, pingRate, TimeUnit.SECONDS);
    }

    @Override
    public void beforeRequest(Map<String, List<String>> headers) {
        if (token.getClientCert() != null) {
            Multimap<String, String> proxyRequestHeaders = HashMultimap.create();
            ProxiedEntityUtils.addProxyHeaders(proxyRequestHeaders, token.getClientCert());
            for (String s : proxyRequestHeaders.keySet()) {
                headers.put(s, new ArrayList<>(proxyRequestHeaders.get(s)));
            }
        }

        Multimap<String, String> originalRequestHeaders = token.getHttpHeaders();
        for (String s : originalRequestHeaders.keySet()) {
            if (!headers.containsKey(s)) {
                // add pre-existing values if key does not exist in proxyRequest
                headers.put(s, new ArrayList<>(originalRequestHeaders.get(s)));
            }
        }
    }

    @Override
    public void onOpen(Session session, EndpointConfig config) {
        session.addMessageHandler(String.class, message -> {
            ctx.writeAndFlush(new TextWebSocketFrame(message));
            LOG.debug("Message received on Websocket session {}: {}", session.getId(), message);
        });
    }

    @Override
    public void onClose(Session session, CloseReason reason) {
        super.onClose(session, reason);
        if (!reason.getCloseCode().equals(CloseReason.CloseCodes.NORMAL_CLOSURE)) {
            LOG.error("Abnormal close: " + reason.getReasonPhrase());
            Exception e = new TimelyException(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(), reason.getReasonPhrase(),
                    "");
            WsRelayHandler.sendErrorResponse(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, e);
        }
        if (!ping.isCancelled()) {
            ping.cancel(false);
        }
    }

    @Override
    public void onError(Session session, Throwable t) {
        super.onError(session, t);
        LOG.error(t.getMessage(), t);
        Exception e = new TimelyException(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(), t.getMessage(), "");
        WsRelayHandler.sendErrorResponse(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, e);
        if (!ping.isCancelled()) {
            ping.cancel(false);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2008-2017 Qualogy Solutions B.V.

    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.

-->
<binding  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="binding.xsd">
	<include path="app-mapping-core-binding.xml"/>

	<mapping name="applications" class="com.qualogy.qafe.bind.core.application.ApplicationStack" post-set="postset">
		<namespace uri="http://qafe.com/schema"  default="elements"/>
		<structure usage="optional" field="globalConfiguration" type="com.qualogy.qafe.bind.core.application.Configuration" post-set="postset">
			<collection field="configurationItems" factory="org.jibx.runtime.Utility.arrayListFactory" type="java.util.List" usage="optional" item-type="com.qualogy.qafe.bind.core.application.KeyValue"/>
		</structure>
		<collection field="applications" factory="org.jibx.runtime.Utility.arrayListFactory" type="java.util.List" item-type="com.qualogy.qafe.bind.core.application.ApplicationContext"/>
	</mapping>

	<mapping name="application" ordered="false" class="com.qualogy.qafe.bind.core.application.ApplicationContext" post-set="postset">
	 	<namespace uri="http://qafe.com/schema"  default="elements"/>
	 	<structure usage="required" field="id" type="com.qualogy.qafe.bind.core.application.ApplicationIdentifier">
			<value name="id" style="attribute" field="id"  usage="required"/>
		</structure>

		<value name="root" style="attribute" field="root"  usage="optional"/>
		<value name="name" style="attribute" field="name"  usage="optional"/>
		<value name="order" style="attribute" field="order"  usage="optional"/>
		<value name="root-menu" style="attribute" field="rootMenu"  usage="optional"/>

		<value name="auto-scan" style="attribute" field="autoScanRoot" usage="optional"/>
		<value name="recurse-scan" style="attribute" field="recursiveScan" usage="optional"/>

		<structure usage="optional" field="applicationConfiguration" type="com.qualogy.qafe.bind.core.application.Configuration" post-set="postset">
			<collection field="configurationItems" factory="org.jibx.runtime.Utility.arrayListFactory" type="java.util.List" usage="optional" item-type="com.qualogy.qafe.bind.core.application.KeyValue"/>
		</structure>

		<structure field="globalTransactions" name="transaction" usage="optional" type="com.qualogy.qafe.bind.business.transaction.GlobalTransactions" post-set="postset">
			<collection field="defaultBusinessActionTransactionBehaviours" factory="org.jibx.runtime.Utility.arrayListFactory" type="java.util.List" usage="required">
				<structure name="business-action" usage="optional" type="com.qualogy.qafe.bind.business.transaction.DefaultBusinessActionTransactionBehaviour">
					<value name="managed" field="management" usage="optional" style="attribute" default="global"/>
					<value name="isolation" field="isolation" usage="optional" style="attribute" default="default"/>
					<value name="propagation" field="propagation" usage="optional" style="attribute" default="required"/>
					<value name="timeout" field="timeout" usage="optional" style="attribute" default="-1"/>
					<structure field="idpattern" usage="optional" type="com.qualogy.qafe.bind.core.pattern.ActionIdPattern">
						<structure field="idpattern" usage="optional" type="com.qualogy.qafe.bind.core.pattern.WildCardPattern">
							<value name="id" style="attribute" field="pattern"  usage="required"/>
						</structure>
					</structure>
				</structure>
			</collection>
		</structure>

		<collection field="mappingFileLocations" factory="org.jibx.runtime.Utility.arrayListFactory" type="java.util.List" usage="optional">
			<structure name="application-mapping-file" usage="optional" type="com.qualogy.qafe.bind.io.FileLocation"  post-set="postset">
				<value name="location" field="location" usage="required" style="attribute"/>
			</structure>
		</collection>
		<collection field="concreteApplicationMappings" factory="org.jibx.runtime.Utility.arrayListFactory" type="java.util.List" usage="optional" item-type="com.qualogy.qafe.bind.domain.ApplicationMapping"/>

		<structure usage="optional" field="messages" type="com.qualogy.qafe.bind.core.messages.Messages" post-set="postset"/>

	</mapping>

	<mapping class="com.qualogy.qafe.bind.core.application.KeyValue" name="configuration">
		<namespace uri="http://qafe.com/schema"  default="elements"/>
		<value name="name" field="key" usage="required" style="attribute"/>
		<value name="value" field="value" usage="required" style="attribute"/>
   </mapping>

	<mapping name="messages" class="com.qualogy.qafe.bind.core.messages.Messages" post-set="postset">
		<namespace uri="http://qafe.com/schema"  default="elements"/>
		<collection field="bindBundles" factory="org.jibx.runtime.Utility.arrayListFactory" type="java.util.List" usage="optional" item-type="com.qualogy.qafe.bind.core.messages.Bundle"/>
		<collection field="bundleFileLocations" factory="org.jibx.runtime.Utility.arrayListFactory" type="java.util.List" usage="optional">
			<structure name="bundle-file" usage="optional" type="com.qualogy.qafe.bind.io.FileLocation"  post-set="postset">
				<value name="location" field="location" usage="required" style="attribute"/>
			</structure>
		</collection>
	</mapping>

	<mapping class="com.qualogy.qafe.bind.core.messages.Bundle" name="bundle" post-set="postset">
  	<namespace uri="http://qafe.com/schema"  default="elements"/>
  	<value name="id" field="id" usage="optional" style="attribute"/>
	<value name="desc" field="description" usage="optional" style="attribute"/>
	<collection field="bindmessages" factory="org.jibx.runtime.Utility.arrayListFactory" type="java.util.List" usage="optional">
		<structure type="com.qualogy.qafe.bind.core.messages.Message" name="message" post-set="postset">
  		<value name="key" field="key" usage="required" style="attribute"/>
			<collection field="messageValues" factory="org.jibx.runtime.Utility.arrayListFactory" type="java.util.List" usage="optional">
				<structure type="com.qualogy.qafe.bind.core.messages.MessageValue" name="text">
			  	<value name="locale" field="locale" usage="optional" style="attribute"/>
					<value field="value" usage="optional" style="text"/>
			  </structure>
			</collection>
  		</structure>
	</collection>
  </mapping>
</binding>


text:
import requests as r
import urllib
import json
import sys
import os

# export FLICKR_API_KEY="<api-key>" in .bashrc

flick_rest_url = "https://api.flickr.com/services/rest/"
PER_PAGE = 5
sort_options= ["interestingness-desc", "interestingness-asc", "relevance"] # date-posted-asc/desc, date-taken-asc/desc

args                 = dict() # parameters to pass to flickr rest api
args['method']       = 'flickr.photos.search'
args['sort']         = sort_options[0]
args['safe_search']  = 1
args['content_type'] = 7
args['media']        = 'photos'
args['extras']       = 'url_n'
args['per_page']     = PER_PAGE
args['page']         = 1
args['format']       ='json'
args['jsoncallback'] = 1
args['tag_mode']     = 'all' # any for OR, all for AND

if len(sys.argv) > 1:
    query = sys.argv[1]
    query = query.replace(' ',',')
else:
    query="nile,river"
print "query = '{}'".format(query)
args['tags']         = query
args['api_key']      = os.environ['FLICKR_API_KEY']

o = r.get(flick_rest_url, args)
print "ok = {}, status_code = {}".format(o.ok, o.status_code)

text = o.text[2:-1] # remove round bracket for json parsing
j = json.loads(text)
print json.dumps(j, indent=4, sort_keys=True)

image_urls = [ j['photos']['photo'][i]['url_n'] for i in range(len(j['photos']['photo'])) ]
print "\n".join(image_urls)


text:
using namespace std;

PotentialHardWall::PotentialHardWall(string potential_name)
                        : PotentialExternal(potential_name) {
  ReadParameters();

}

void PotentialHardWall::ReadParameters() {
  cout << setw(35) << "[eP] External potential type: " << "Hard wall"
       << endl;

  string flag;
  string symbol;
  double radius;

  while (true) {
    cin >> flag >> symbol;
    if (symbol == "end") {
      break;
    }
    else {
      cin >> flag >> radius;
      radii[symbol] = radius;
      cout << setw(35) << "[eP] Radius for bead type   : " << symbol << " - "
           << radius << endl;
    }
  }

}

double PotentialHardWall::BeadEnergy(Bead& bead, double box_l[]) {
  double energy = 0;
  // Get the z coordinate from the trial coordinate array.
  double z = bead.GetCrd(1, 2);
  // If the bead falls outside of the box in the z-direction.
  if (z <= radii[bead.Symbol()] || z+radii[bead.Symbol()] >= box_l[2]) {
    energy = kVeryLargeEnergy;
  }

  return energy;

}

double PotentialHardWall::BeadForceOnWall(Bead& bead, double box_l[]) {
  // 0 force since this is a hard wall.
  return 0;

}


text:
using Microsoft.Xna.Framework.Media;
using OxyEngine.Audio;
using OxyEngine.Dependency;
using OxyEngine.Ecs.Behaviours;

namespace OxyEngine.Ecs.Components
{
  /// <summary>
  ///   Component for playing songs (ambient, long audio files)
  /// </summary>
  public class SongComponent : GameComponent, ILoadable
  {
    /// <summary>
    ///   Song to play
    /// </summary>
    public Song Song { get; set; }

    /// <summary>
    ///   If song must be looped
    /// </summary>
    public bool Loop { get; set; }

    private AudioManager _audioManager;

    public void Load()
    {
      _audioManager = Container.Instance.ResolveByName<AudioManager>(InstanceName.AudioManager);
    }

    /// <summary>
    ///   Start playing of a song
    /// </summary>
    public void Play()
    {
      _audioManager.PlaySong(Song);
    }

    /// <summary>
    ///   Pause song
    /// </summary>
    public void Pause()
    {
      _audioManager.PauseSong();
    }

    /// <summary>
    ///   Stop song
    /// </summary>
    public void Stop()
    {
      _audioManager.StopSong();
    }
  }
}


text:
processing-hash-highlighting
=====================================

First year free time project. Program for highlighting syntax based on a hash function.

![An example showing a recursive factorial function being highlighted by the program](./example.png)


text:
package dhcp6

import (
	"encoding/binary"
	"io"
	"net"
	"time"
)

// IAPrefix represents an Identity Association Prefix, as defined in RFC 3633,
// Section 10.
//
// Routers may use identity assocation prefixes (IAPrefixes) to request IPv6
// prefixes to assign individual address to IPv6 clients, using the lifetimes
// specified in the preferred lifetime and valid lifetime fields.  Multiple
// IAPrefixes may be present in a single DHCP request, but only enscapsulated
// within an IAPD's options.
type IAPrefix struct {
	// PreferredLifetime specifies the preferred lifetime of an IPv6 prefix.
	// When the preferred lifetime of a prefix expires, the prefix becomes
	// deprecated, and addresses from the prefix should not be used in new
	// communications.
	//
	// The preferred lifetime of a prefix must not be greater than its valid
	// lifetime.
	PreferredLifetime time.Duration

	// ValidLifetime specifies the valid lifetime of an IPv6 prefix.  When the
	// valid lifetime of a prefix expires, addresses from the prefix the address
	// should not be used for any further communication.
	//
	// The valid lifetime of a prefix must be greater than its preferred
	// lifetime.
	ValidLifetime time.Duration

	// PrefixLength specifies the length in bits of an IPv6 address prefix, such
	// as 32, 64, etc.
	PrefixLength uint8

	// Prefix specifies the IPv6 address prefix from which IPv6 addresses can
	// be allocated.
	Prefix net.IP

	// Options specifies a map of DHCP options specific to this IAPrefix.
	// Its methods can be used to retrieve data from an incoming IAPrefix, or
	// send data with an outgoing IAPrefix.
	Options Options
}

// NewIAPrefix creates a new IAPrefix from preferred and valid lifetime
// durations, an IPv6 prefix length, an IPv6 prefix, and an optional Options
// map.
//
// The preferred lifetime duration must be less than the valid lifetime
// duration.  The IPv6 prefix must be exactly 16 bytes, the correct length
// for an IPv6 address.  Failure to meet either of these conditions will result
// in an error.  If an Options map is not specified, a new one will be
// allocated.
func NewIAPrefix(preferred time.Duration, valid time.Duration, prefixLength uint8, prefix net.IP, options Options) (*IAPrefix, error) {
	// Preferred lifetime must always be less than valid lifetime.
	if preferred > valid {
		return nil, ErrInvalidLifetimes
	}

	// From documentation: If ip is not an IPv4 address, To4 returns nil.
	if prefix.To4() != nil {
		return nil, ErrInvalidIP
	}

	// If no options set, make empty map
	if options == nil {
		options = make(Options)
	}

	return &IAPrefix{
		PreferredLifetime: preferred,
		ValidLifetime:     valid,
		PrefixLength:      prefixLength,
		Prefix:            prefix,
		Options:           options,
	}, nil
}

// MarshalBinary allocates a byte slice containing the data from a IAPrefix.
func (i *IAPrefix) MarshalBinary() ([]byte, error) {
	//  4 bytes: preferred lifetime
	//  4 bytes: valid lifetime
	//  1 byte : prefix length
	// 16 bytes: IPv6 prefix
	//  N bytes: options
	opts := i.Options.enumerate()
	b := make([]byte, 25+opts.count())

	binary.BigEndian.PutUint32(b[0:4], uint32(i.PreferredLifetime/time.Second))
	binary.BigEndian.PutUint32(b[4:8], uint32(i.ValidLifetime/time.Second))
	b[8] = i.PrefixLength
	copy(b[9:25], i.Prefix)
	opts.write(b[25:])

	return b, nil
}

// UnmarshalBinary unmarshals a raw byte slice into a IAPrefix.
//
// If the byte slice does not contain enough data to form a valid IAPrefix,
// io.ErrUnexpectedEOF is returned.  If the preferred lifetime value in the
// byte slice is less than the valid lifetime, ErrInvalidLifetimes is
// returned.
func (i *IAPrefix) UnmarshalBinary(b []byte) error {
	// IAPrefix must at least contain lifetimes, prefix length, and prefix
	if len(b) < 25 {
		return io.ErrUnexpectedEOF
	}

	i.PreferredLifetime = time.Duration(binary.BigEndian.Uint32(b[0:4])) * time.Second
	i.ValidLifetime = time.Duration(binary.BigEndian.Uint32(b[4:8])) * time.Second

	// Preferred lifetime must always be less than valid lifetime.
	if i.PreferredLifetime > i.ValidLifetime {
		return ErrInvalidLifetimes
	}

	i.PrefixLength = b[8]

	prefix := make(net.IP, 16)
	copy(prefix, b[9:25])
	i.Prefix = prefix

	options, err := parseOptions(b[25:])
	if err != nil {
		return err
	}
	i.Options = options

	return nil
}


text:
Scala2JsonAPI
=============

scala to Json api.


text:
package io.sunflower.jaxrs.filter;

import io.sunflower.util.Duration;

import javax.ws.rs.container.*;
import javax.ws.rs.ext.Provider;
import java.util.Locale;
import java.util.function.Supplier;

/**
 * This class adds an "X-Runtime" HTTP response header that includes the time
 * taken to execute the request, in seconds (based on the implementation from
 * Ruby on Rails).
 *
 * @see Rack::Runtime
 */
@Provider
@PreMatching
public class RuntimeFilter implements ContainerRequestFilter, ContainerResponseFilter {

    private static final float NANOS_IN_SECOND = Duration.seconds(1).toNanoseconds();
    private static final String RUNTIME_HEADER = "X-Runtime";
    private static final String RUNTIME_PROPERTY = "io.sunflower.jaxrs.filter.runtime";

    private Supplier<Long> currentTimeProvider = System::nanoTime;

    void setCurrentTimeProvider(Supplier<Long> currentTimeProvider) {
        this.currentTimeProvider = currentTimeProvider;
    }

    @Override
    public void filter(final ContainerRequestContext request) {
        request.setProperty(RUNTIME_PROPERTY, currentTimeProvider.get());
    }

    @Override
    public void filter(final ContainerRequestContext request,
            final ContainerResponseContext response) {

        final Long startTime = (Long) request.getProperty(RUNTIME_PROPERTY);
        if (startTime != null) {
            final float seconds = (currentTimeProvider.get() - startTime) / NANOS_IN_SECOND;
            response.getHeaders().putSingle(RUNTIME_HEADER, String.format(Locale.ROOT, "%.6f", seconds));
        }
    }
}


text:
package edu.uci.ics.asterix.transaction.management.opcallbacks;

import edu.uci.ics.asterix.common.transactions.AbstractOperationCallback;
import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
import edu.uci.ics.hyracks.dataflow.common.data.accessors.ITupleReference;
import edu.uci.ics.hyracks.storage.am.common.api.ISearchOperationCallback;

/**
 * Secondary index searches perform no locking at all.
 */
public class SecondaryIndexSearchOperationCallback extends AbstractOperationCallback implements
        ISearchOperationCallback {

    public SecondaryIndexSearchOperationCallback() {
        super(-1, null, null, null);
    }

    @Override
    public boolean proceed(ITupleReference tuple) throws HyracksDataException {
        return true;
    }

    @Override
    public void reconcile(ITupleReference tuple) throws HyracksDataException {
        // Do nothing.
    }

    @Override
    public void cancel(ITupleReference tuple) throws HyracksDataException {
        // Do nothing.
    }

    @Override
    public void complete(ITupleReference tuple) throws HyracksDataException {
        // Do nothing.
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Thrift Javascript Bindings: Unit Test</title>

  <link rel="stylesheet" href="build/js/lib/qunit.css" type="text/css" media="screen" />

Thrift Javascript Bindings: Unit Test (ThriftTest.thrift)


text:
package wshttpserver;

import java.io.File;
import java.util.HashMap;

/**
 * Mime types of common open formats.
 *
 * @author Joris
 */
public class HttpMime
{
        private static final HashMap<String, String> mime = new HashMap<>();

        static
        {
                // Archives
                mime.put("7z", "application/x-7z-compressed");
                mime.put("jar", "application/java-archive");
                mime.put("zip", "application/zip");

                // Images
                mime.put("bmp", "image/x-ms-bmp");
                mime.put("gif", "image/gif");
                mime.put("jpe", "image/jpeg");
                mime.put("jpeg", "image/jpeg");
                mime.put("jpg", "image/jpeg");
                mime.put("png", "image/png");
                mime.put("svg", "image/svg+xml");
                mime.put("svgz", "image/svg+xml");
                mime.put("tif", "image/tiff");
                mime.put("tiff", "image/tiff");

                // Source code
                mime.put("css", "text/css; charset=UTF-8");
                mime.put("htc", "text/x-component; charset=UTF-8");
                mime.put("htm", "text/html; charset=UTF-8");
                mime.put("html", "text/html; charset=UTF-8");
                mime.put("java", "text/x-java; charset=UTF-8");
                mime.put("js", "application/javascript; charset=UTF-8");
                mime.put("mml", "text/mathml; charset=UTF-8");
                mime.put("rdf", "application/rdf+xml; charset=UTF-8");
                mime.put("rss", "application/rss+xml; charset=UTF-8");
                mime.put("shtml", "text/html; charset=UTF-8");
                mime.put("xht", "application/xhtml+xml; charset=UTF-8");
                mime.put("xhtml", "application/xhtml+xml; charset=UTF-8");
                mime.put("xml", "application/xml; charset=UTF-8");
                mime.put("xsd", "application/xml; charset=UTF-8");
                mime.put("xsd", "application/xml; charset=UTF-8");
                mime.put("xsl", "application/xml-dtd; charset=UTF-8");
                mime.put("xspf", "application/xspf+xml; charset=UTF-8");
                mime.put("xul", "application/vnd.mozilla.xul+xml; charset=UTF-8");

                // Plain text & Config
                mime.put("cfg", "text/plain; charset=UTF-8");
                mime.put("conf", "text/plain; charset=UTF-8");
                mime.put("csv", "text/csv; charset=UTF-8");
                mime.put("ini", "text/plain; charset=UTF-8");
                mime.put("set", "text/plain; charset=UTF-8");
                mime.put("text", "text/plain; charset=UTF-8");
                mime.put("txt", "text/plain; charset=UTF-8");
                mime.put("yaml", "text/x-yaml; charset=UTF-8");

                // Java
                mime.put("class", "application/java-vm");
                mime.put("ser", "application/java-serialized-object");

                // Fonts
                mime.put("woff", "application/x-font-woff");
                mime.put("ttf", "application/x-font-ttf");

                // Audio
                mime.put("flac", "audio/flac");
                mime.put("kar", "audio/midi");
                mime.put("mid", "audio/midi");
                mime.put("midi", "audio/midi");
                mime.put("oga", "audio/ogg");
                mime.put("ogg", "audio/ogg");
                mime.put("spx", "audio/ogg");
                mime.put("wav", "audio/x-wav");

                // Video
                mime.put("ogv", "video/ogg");
                mime.put("mng", "video/x-mng");

                // Torrent
                mime.put("torrent", "application/x-bittorrent");

                // LibreOffice
                mime.put("odb", "application/vnd.oasis.opendocument.database");
                mime.put("odf", "application/vnd.oasis.opendocument.formula");
                mime.put("odg", "application/vnd.oasis.opendocument.graphics");
                mime.put("odi", "application/vnd.oasis.opendocument.image");
                mime.put("odm", "application/vnd.oasis.opendocument.text-master");
                mime.put("odp", "application/vnd.oasis.opendocument.presentation");
                mime.put("ods", "application/vnd.oasis.opendocument.spreadsheet");
                mime.put("odt", "application/vnd.oasis.opendocument.text");
                mime.put("otg", "application/vnd.oasis.opendocument.graphics-template");
                mime.put("oth", "application/vnd.oasis.opendocument.text-web");
                mime.put("otp", "application/vnd.oasis.opendocument.presentation-template");
                mime.put("ots", "application/vnd.oasis.opendocument.spreadsheet-template");
                mime.put("ott", "application/vnd.oasis.opendocument.text-template");
                mime.put("odc", "application/vnd.oasis.opendocument.chart");

                // Adobe crap
                mime.put("pdf", "application/pdf");
        }

        /** Gets a mimetype string by file extension.
         * @param extension A file extension without a dot. for example "html"
         * @return A mime type string, for example "text/html; charset=UTF-8"
         */
        @ThreadSafe // The HashMap can not be modified after static initialization and is thus thread safe (http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html)
        public static String getMime(String extension)
        {
                String m = mime.get(extension);
                if (m == null)
                {
                        return "application/octet-stream";
                }
                return m;
        }

        /** Gets a mimetype string by file name.
         * @param file
         * @return A mime type string, for example "text/html; charset=UTF-8"
         */
        @ThreadSafe
        public static String getMime(File file)
        {
                String path = file.getPath();
                int i = path.lastIndexOf('.');
                if (i < 0)
                {
                        return "application/octet-stream";
                }

                return getMime(path.substring(i + 1));
        }
}


text:
'use strict';

/**
 * @ngdoc service
 * @name paracosmApp.CurrentUserService
 * @description
 * # CurrentUserService
 * Service in the paracosmApp.
 */
angular.module('paracosmApp')
  .service('CurrentUserService', function (Auth, Ref, $firebaseObject) {
    // AngularJS will instantiate a singleton by calling 'new' on this function
    var service = {};
    var cachedUser;
    service.getCurrentUser = function getCurrentUser() {

    	cachedUser = {
    		auth: Auth.$getAuth(),
            profile: {
                name: ''
            }
    	};

    	if (cachedUser.auth && cachedUser.auth.uid) {
    		cachedUser.profile = $firebaseObject(Ref.child('users/'+cachedUser.auth.uid));
    	}

    	return cachedUser;
    };

    service.getName = function () {
        var user = cachedUser || service.getCurrentUser();

        if (user.profile && user.profile.name) {
            return user.profile.name;
        } else {

            if (user.auth.provider === 'password') {
                return user.auth.password.email;
            } else if (user.auth.provider === 'google') {
                return user.auth.google.displayName;
            }
        }

    };

    return service;
  });


text:
(function() {
var _;

var loaded = {
  underscore: false,
  jQuery: false,
  moment: false,
  ddp: false,
  cal: false,
  template1: false,
  template2: false
};

var loading = {
  underscore: false,
  jQuery: false,
  moment: false,
  ddp: false,
  cal: false,
  template1: false,
  template2: false
};

function depHandler(){
  if( !loading.underscore && !loading.jQuery ){
    loading.jQuery = true;
    loadJQuery();
    loading.underscore = true;
    loadUnderscore();
  }else if( loaded.underscore && loaded.jQuery && !loading.moment){
    loading.moment = true;
    loadMoment();
    loading.ddp = true;
    loadDdp();
    loading.template1 = true;
    loadCalTemp1();
    loading.template2 = true;
    loadCalTemp2();
    loadCss();
  }else if( loaded.moment && loaded.ddp && !loading.cal ){
    loading.cal = true;
    loadCal();
  }else if( loaded.cal && loaded.ddp && loaded.template1 && loaded.template2){
    main(jQuery );
  };
};

function jQueryLoadHandler( ) {
  loaded.jQuery = true;
  depHandler();
};
function underscoreLoadHandler( ) {
  loaded.underscore = true;
  _ = window._;
  depHandler();
};
function momentLoadHandler( ) {
  loaded.moment = true;
  depHandler();
};
function calLoadHandler( ) {
  loaded.cal = true;
  depHandler();
};
function ddpLoadHandler( ) {
  loaded.ddp = true;
  depHandler();
};

function loadLib( url, callback ){
  var script_tag = document.createElement('script');
  script_tag.setAttribute("type","text/javascript");
  script_tag.setAttribute("src", url );
  if (script_tag.readyState) {
    script_tag.onreadystatechange = function () { // For old versions of IE
        if (this.readyState == 'complete' || this.readyState == 'loaded') {
          callback();
        }
    };
  } else { // Other browsers
    script_tag.onload = callback;
  }
  // Try to find the head, otherwise default to the documentElement
  (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
};

function loadUnderscore(){
  if (window._ === undefined ) {
    loadLib( "https://s3.amazonaws.com/tidefish-widget/underscore.min.js", underscoreLoadHandler );
  } else {
    underscoreLoadHandler();
  }
};

function loadJQuery(){
  if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.11.1') {
    loadLib( "https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js", jQueryLoadHandler );
  } else {
    jqueryLoadHandler();
  }
};

function loadMoment(){
  if (window.moment === undefined ) {
    loadLib( "https://s3.amazonaws.com/tidefish-widget/moment.min.js", momentLoadHandler );
  } else {
    momentLoadHandler();
  }
};

function loadDdp(){
  loadLib(  "https://s3.amazonaws.com/tidefish-widget/meteor-ddp.min.js", ddpLoadHandler );
  loaded.ddp = true;
};

function loadCal(){
  loadLib( "https://s3.amazonaws.com/tidefish-widget/cal.min.js", calLoadHandler );
  loaded.cal = true;
};

function loadCss(){
  $('head').append( '<link rel="stylesheet" href="https://s3.amazonaws.com/tidefish-widget/style.min.css">' );
};

var scheduleTempText;
function loadCalTemp1(){
  $.get("https://s3.amazonaws.com/tidefish-widget/widget-schedule-template.html", function(text){
    scheduleTempText = text;
    loaded.template1 = true;
    depHandler();
  });
};

var calTempText;
function loadCalTemp2(){
  $.get( "https://s3.amazonaws.com/tidefish-widget/widget-cal-template.html", function(text){
    calTempText = text;
    loaded.template2 = true;
    depHandler();
  });
};

depHandler();

/******** Library startup helpers ******/

/*
 * Create calendar object and helpers
 */
function SetupCalendar( events ){
  var cal = jQuery('#tideFishCalendar').clndr({
    template: calTempText,
    onRender: function(){
      var self = this;
      $('#jumpToDateSubmit').click(function(e){
        var date = moment($('#jumpToDateInput').val());
        if( date.isValid() ){
          self.setSelected( date, false );
          self.applyChange( date );
        }
        $('#jumpToDateInput').val('');
      });
    },
    lengthOfTime: {
      intervalUnit: 'days',
      interval: 14,
      startDate: moment()
    },
    extraDateData: function(day){
      return {
        avaliable: isAvaliable( day, events )
      };
    }
  });

  return cal;
};

/*
 * Setup prototcol to fetch data from Tide.Fish Servers
 */
function DDP( id, events, callback, ws ){
  this.id = id;
  if( ws ){
    this.ddp = new MeteorDdp(ws);
  }else{
    this.ddp = new MeteorDdp('wss://tide.fish/websocket');
  }
  this.callback = callback;
  this.events = events;
  this.subscribedTo = {};
  this.connected = false;
  this._startupQueue = [];
  var self = this;

  self.watch();
  self.ddp.connect().done(function(){
    self.subscribe(moment());
    self.connected = true;
    _.each(self._startupQueue, function( sub ){
      self.subscribe( sub );
    });
  });
  window.onbeforeunload = function() { self.ddp.close(); }
};

/*
 * Subscribes to week passed in.
 * It converts the moment object passed in to start if ISO week before sending subscription
 */
DDP.prototype.subscribe = function(week){
  var startOfWeek = week.startOf('isoWeek');
  var key = startOfWeek.format("WWYYYY");
  if( this.subscribedTo[ key ]){ return; }
  if( !this.connected ){ this._startupQueue.push(startOfWeek.clone()); return; };
  var id = this.id;
  this.subscribedTo[key] = this.ddp.subscribe('PublicSchedule',[
      id,
      startOfWeek.isoWeek(),
      startOfWeek.isoWeekday(6).year()
  ]);
}

DDP.prototype.watch = function() {
  var callback = this.changeCallback;
  var self = this;

  self.ddp.watch("Schedule", function(changedDoc, message){
    if( message === "added" ){
      if( !self.events[ dateKey( moment( changedDoc.date.$date ) ) ] ){
        self.events[ dateKey( moment( changedDoc.date.$date ) ) ] = {};
      }
      self.events[ dateKey( moment(changedDoc.date.$date) ) ][changedDoc.boatId] = changedDoc;
    }else if( message === "changed" ){
      self.events[ dateKey( moment( changedDoc.date.$date)) ][changedDoc.boatId] = changedDoc;
    }else if( message === "removed" ){
      delete events[ dateKey( moment(changedDoc.date.$date)) ][changedDoc.boatId];
    }
    self.callback();
  });
};

/*
 * Object representing the events section of the widget
 */
function EventsDisplay(events){
  this.date = moment();
  this.events = events;
  this.template = _.template( scheduleTempText );

  this.render();

  return this;
};

EventsDisplay.prototype.render = function(){
  var data = {
    events: this.events[ dateKey(this.date) ],
    date: this.date
  };
  $('#tideFishEvents').html( this.template( data ) );
};

EventsDisplay.prototype.setDate = function( date ){
  this.date = date;
  this.render();
};

/*
 * Helper functions for widget
 */
function dateKey( date ){
  return date.format("MM/DD/YYYY");
};

function isAvaliable( day, events ){
  var avaliable = false;
  _.each( events[dateKey(day)], function( e ){
    if( e.avaliable.length > 0 ){
      avaliable = true;
    }
  });
  return avaliable;
};

/******** Our main function ********/
function main($) {

    $(document).ready(function($) {
        var id = jQuery('#tideFishSchedule').attr('data-accountId');
        if( !id ){
          console.error( "data-accountId not defined on #tideFishSchedule" )
        }else{
          jQuery('#tideFishSchedule').append('

');

          var events = {};

          var eventsDisplay = new EventsDisplay(events);

          // Setup Calendar and attach data callbacks
          var cal = SetupCalendar(events);
          cal.options.onSelect = function(day){
            eventsDisplay.setDate( day );
          }

          var ws = jQuery('#tideFishSchedule').attr('data-ws');
          var ddp = new DDP( id , events, function(){
            cal.render();
            eventsDisplay.render();
          }, ws);

          // When the interval changes on the calendar we may need more data
          cal.options.clickEvents.onIntervalChange = function(start, end){
            var endBound = end.clone().add(5,'days');
            for( var date = start.clone(); !date.isAfter(endBound,'isoWeek'); date.add(1,'week') ){
              ddp.subscribe( date.clone() );
            }
          }

          // since intervalChange hook was set after cal init, we need to trigger first time
          cal.options.clickEvents.onIntervalChange( cal.intervalStart, cal.intervalEnd );
        }
    });
}

})(); // We call our anonymous function immediately


text:
require File.expand_path('../../../../spec_helper', __FILE__)
require File.expand_path('../../shared/constants', __FILE__)
require 'openssl'

describe "OpenSSL::HMAC.hexdigest" do
  it "returns an SHA1 hex digest" do
    cur_digest = OpenSSL::Digest::Digest.new('SHA1')
    cur_digest.hexdigest.should == HMACConstants::BlankSHA1HexDigest
    hexdigest = OpenSSL::HMAC.hexdigest(cur_digest,
                                        HMACConstants::Key,
                                        HMACConstants::Contents)
    hexdigest.should == HMACConstants::SHA1Hexdigest
  end
end

# Should add in similar specs for MD5, RIPEMD160, and SHA256


text:
// Copyright 2019 Google LLC
//
// 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
//
//     https://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.

using System;
using System.Collections.Generic;
using Xunit;

namespace Google.Cloud.Tools.VersionCompat.Tests.ClassMethod
{
    namespace MethodAdded.A { public class C { } }
    namespace MethodAdded.B { public class C { public void A() { } } }

    namespace MethodRemoved.A { public class C { public void A() { } } }
    namespace MethodRemoved.B { public class C { } }

    namespace MethodMadeExported.A { public class C { private void A() { } } }
    namespace MethodMadeExported.B { public class C { protected internal void A() { } } }

    namespace MethodMadeNotExported.A { public class C { protected internal void A() { } } }
    namespace MethodMadeNotExported.B { public class C { private void A() { } } }

    namespace ReturnTypeChanged1.A { public class C { public void A() { } } }
    namespace ReturnTypeChanged1.B { public class C { public int A() => 0; } }

    namespace ReturnTypeChanged2.A { public class C { public IEnumerable<int> A() => null; } }
    namespace ReturnTypeChanged2.B { public class C { public IEnumerable<long> A() => null; } }

    namespace ParamNameChanged.A { public class C { public void A(int i) { } } }
    namespace ParamNameChanged.B { public class C { public void A(int j) { } } }

    namespace ParamInOutChanged1.A { public class C { public void A(in string s) { } } }
    namespace ParamInOutChanged1.B { public class C { public void A(ref string s) { } } }

    namespace ParamInOutChanged2.A { public class C { public void A(ref string s) { } } }
    namespace ParamInOutChanged2.B { public class C { public void A(out string s) => s = ""; } }

    namespace ToStatic.A { public class C { public void A() { } } }
    namespace ToStatic.B { public class C { public static void A() { } } }

    namespace FromStatic.A { public class C { public static void A() { } } }
    namespace FromStatic.B { public class C { public void A() { } } }

    namespace GenericConstraintAdded1.A { public class C { public void A<T>() { } } }
    namespace GenericConstraintAdded1.B { public class C { public void A<T>() where T : new() { } } }

    namespace GenericConstraintAdded2.A { public class C { public void A<T>() { } } }
    namespace GenericConstraintAdded2.B { public class C { public void A<T>() where T : class { } } }

    namespace GenericConstraintAdded3.A { public class C { public void A<T>() { } } }
    namespace GenericConstraintAdded3.B { public class C { public void A<T>() where T : struct { } } }

    namespace GenericConstraintAdded4.A { public class C { public void A<T>() { } } }
    namespace GenericConstraintAdded4.B { public class C { public void A<T>() where T : IList<T> { } } }

    namespace GenericConstraintRemoved1.A { public class C { public void A<T>() where T : new() { } } }
    namespace GenericConstraintRemoved1.B { public class C { public void A<T>() { } } }

    namespace GenericConstraintRemoved2.A { public class C { public void A<T>() where T : class { } } }
    namespace GenericConstraintRemoved2.B { public class C { public void A<T>() { } } }

    namespace GenericConstraintRemoved3.A { public class C { public void A<T>() where T : struct { } } }
    namespace GenericConstraintRemoved3.B { public class C { public void A<T>() { } } }

    namespace GenericConstraintRemoved4.A { public class C { public void A<T>() where T : IList<T> { } } }
    namespace GenericConstraintRemoved4.B { public class C { public void A<T>() { } } }

    namespace GenericConstraintChanged1.A { public class C { public void A<T>() where T : IList<T> { } } }
    namespace GenericConstraintChanged1.B { public class C { public void A<T>() where T : IEquatable<T> { } } }

    namespace GenericConstraintChanged2.A { public class C { public void A<T, U>() where T : IList<T> { } } }
    namespace GenericConstraintChanged2.B { public class C { public void A<T, U>() where T : IList<U> { } } }

    namespace GenericConstraintChanged3.A { public class C { public void A<T, U>() where T : IList<T> where U : IList<T> { } } }
    namespace GenericConstraintChanged3.B { public class C { public void A<T, U>() where T : IList<U> where U : IList<T> { } } }

#nullable enable
    namespace GenericConstraintChanged4.A { public class C { public void A<T>() where T : notnull, IList<T> { } } }
    namespace GenericConstraintChanged4.B { public class C { public void A<T>() where T : IList<T> { } } }
#nullable restore

    namespace MethodModiferChanged1.A { public abstract class C { public virtual int A() => 0; } }
    namespace MethodModiferChanged1.B { public abstract class C { public int A() => 0; } }

    namespace MethodModiferChanged2.A { public abstract class C { public virtual int A() => 0; } }
    namespace MethodModiferChanged2.B { public abstract class C { public abstract int A(); } }

    public abstract class Base { public abstract int A(); }

    namespace MethodModiferChanged3.A { public abstract class C : Base { public override int A() => 0; } }
    namespace MethodModiferChanged3.B { public abstract class C : Base { public sealed override int A() => 0; } }

    namespace MethodModiferChanged4.A { public abstract class C { public int A() => 0; } }
    namespace MethodModiferChanged4.B { public abstract class C { public virtual int A() => 0; } }

    namespace MethodModiferChanged5.A { public abstract class C { public abstract int A(); } }
    namespace MethodModiferChanged5.B { public abstract class C { public virtual int A() => 0; } }

    namespace MethodModiferChanged6.A { public abstract class C : Base { public sealed override int A() => 0; } }
    namespace MethodModiferChanged6.B { public abstract class C : Base { public override int A() => 0; } }

    namespace MethodAccessModifierChanged1.A { public class C { public void A() { } } }
    namespace MethodAccessModifierChanged1.B { public class C { protected void A() { } } }

    namespace MethodAccessModifierChanged2.A { public class C { protected void A() { } } }
    namespace MethodAccessModifierChanged2.B { public class C { public void A() { } } }

    public class ClassMethodTest : TestBase
    {
        [Fact] public void MethodAdded() => TestMinor(Cause.MethodAdded);
        [Fact] public void MethodRemoved() => TestMajor(Cause.MethodRemoved);
        [Fact] public void MethodMadeExported() => TestMinor(Cause.MethodMadeExported);
        [Fact] public void MethodMadeNotExported() => TestMajor(Cause.MethodMadeNotExported);
        [Fact] public void ReturnTypeChanged1() => TestMajor(Cause.MethodReturnTypeChanged);
        [Fact] public void ReturnTypeChanged2() => TestMajor(Cause.MethodReturnTypeChanged);
        [Fact] public void ParamNameChanged() => TestMajor(Cause.MethodParameterNameChanged);
        [Fact] public void ParamInOutChanged1() => TestMajor(Cause.MethodParameterInOutChanged);
        [Fact] public void ParamInOutChanged2() => TestMajor(Cause.MethodParameterInOutChanged);
        [Fact] public void ToStatic() => TestMajor(Cause.MethodMadeStatic);
        [Fact] public void FromStatic() => TestMajor(Cause.MethodMadeNonStatic);
        [Fact] public void GenericConstraintAdded1() => TestMajor(Cause.MethodGenericConstraintChanged);
        [Fact] public void GenericConstraintAdded2() => TestMajor(Cause.MethodGenericConstraintChanged);
        [Fact] public void GenericConstraintAdded3() => TestMajor(Cause.MethodGenericConstraintChanged);
        [Fact] public void GenericConstraintAdded4() => TestMajor(Cause.MethodGenericConstraintChanged);
        [Fact] public void GenericConstraintRemoved1() => TestMinor(Cause.MethodGenericConstraintChanged);
        [Fact] public void GenericConstraintRemoved2() => TestMinor(Cause.MethodGenericConstraintChanged);
        [Fact] public void GenericConstraintRemoved3() => TestMinor(Cause.MethodGenericConstraintChanged);
        [Fact] public void GenericConstraintRemoved4() => TestMinor(Cause.MethodGenericConstraintChanged);
        [Fact] public void GenericConstraintChanged1() => Test()
            ((Level.Major, Cause.MethodGenericConstraintChanged), (Level.Minor, Cause.MethodGenericConstraintChanged));
        [Fact] public void GenericConstraintChanged2() => Test()
            ((Level.Major, Cause.MethodGenericConstraintChanged), (Level.Minor, Cause.MethodGenericConstraintChanged));
        [Fact] public void GenericConstraintChanged3() => Test()
            ((Level.Major, Cause.MethodGenericConstraintChanged), (Level.Minor, Cause.MethodGenericConstraintChanged));
        [Fact]
        public void GenericConstraintChanged4() => Test()
            ((Level.Major, Cause.MethodGenericConstraintChanged), (Level.Minor, Cause.MethodGenericConstraintChanged));
        [Fact] public void MethodModiferChanged1() => TestMajor(Cause.MethodModifierChanged);
        [Fact] public void MethodModiferChanged2() => TestMajor(Cause.MethodModifierChanged);
        [Fact] public void MethodModiferChanged3() => TestMajor(Cause.MethodModifierChanged);
        [Fact] public void MethodModiferChanged4() => TestMinor(Cause.MethodModifierChanged);
        [Fact] public void MethodModiferChanged5() => TestMinor(Cause.MethodModifierChanged);
        [Fact] public void MethodModiferChanged6() => TestMinor(Cause.MethodModifierChanged);
        [Fact] public void MethodAccessModifierChanged1() => TestMajor(Cause.MethodAccessModifierChanged);
        [Fact] public void MethodAccessModifierChanged2() => TestMinor(Cause.MethodAccessModifierChanged);
    }
}


text:
 #include <QtGui>
#include <QWidget>

 #include <omni/ui/flowlayout.hpp>

 FlowLayout::FlowLayout(QWidget *parent, int margin, int hSpacing, int vSpacing)
     : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing)
 {
     setContentsMargins(margin, margin, margin, margin);
 }

 FlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing)
     : m_hSpace(hSpacing), m_vSpace(vSpacing)
 {
     setContentsMargins(margin, margin, margin, margin);
 }

 FlowLayout::~FlowLayout()
 {
     QLayoutItem *item;
     while ((item = takeAt(0)))
         delete item;
 }

 void FlowLayout::addItem(QLayoutItem *item)
 {
     itemList.append(item);
 }

 int FlowLayout::horizontalSpacing() const
 {
     if (m_hSpace >= 0) {
         return m_hSpace;
     } else {
         return smartSpacing(QStyle::PM_LayoutHorizontalSpacing);
     }
 }

 int FlowLayout::verticalSpacing() const
 {
     if (m_vSpace >= 0) {
         return m_vSpace;
     } else {
         return smartSpacing(QStyle::PM_LayoutVerticalSpacing);
     }
 }

 int FlowLayout::count() const
 {
     return itemList.size();
 }

 QLayoutItem *FlowLayout::itemAt(int index) const
 {
     return itemList.value(index);
 }

 QLayoutItem *FlowLayout::takeAt(int index)
 {
     if (index >= 0 && index < itemList.size())
         return itemList.takeAt(index);
     else
         return 0;
 }

 Qt::Orientations FlowLayout::expandingDirections() const
 {
     return 0;
 }

 bool FlowLayout::hasHeightForWidth() const
 {
     return true;
 }

 int FlowLayout::heightForWidth(int width) const
 {
     int height = doLayout(QRect(0, 0, width, 0), true);
     return height;
 }

 void FlowLayout::setGeometry(const QRect &rect)
 {
     QLayout::setGeometry(rect);
     doLayout(rect, false);
 }

 QSize FlowLayout::sizeHint() const
 {
     return minimumSize();
 }

 QSize FlowLayout::minimumSize() const
 {
     QSize size;
     QLayoutItem *item;
     foreach (item, itemList)
         size = size.expandedTo(item->minimumSize());

     size += QSize(2*margin(), 2*margin());
     return size;
 }

 int FlowLayout::doLayout(const QRect &rect, bool testOnly) const
 {
     int left, top, right, bottom;
     getContentsMargins(&left, &top, &right, &bottom);
     QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom);
     int x = effectiveRect.x();
     int y = effectiveRect.y();
     int lineHeight = 0;

     QLayoutItem *item;
     foreach (item, itemList) {
         QWidget *wid = item->widget();
         int spaceX = horizontalSpacing();
         if (spaceX == -1)
             spaceX = wid->style()->layoutSpacing(
                 QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal);
         int spaceY = verticalSpacing();
         if (spaceY == -1)
             spaceY = wid->style()->layoutSpacing(
                 QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Vertical);
         int nextX = x + item->sizeHint().width() + spaceX;
         if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) {
             x = effectiveRect.x();
             y = y + lineHeight + spaceY;
             nextX = x + item->sizeHint().width() + spaceX;
             lineHeight = 0;
         }

         if (!testOnly)
             item->setGeometry(QRect(QPoint(x, y), item->sizeHint()));

         x = nextX;
         lineHeight = qMax(lineHeight, item->sizeHint().height());
     }
     return y + lineHeight - rect.y() + bottom;
 }
 int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const
 {
     QObject *parent = this->parent();
     if (!parent) {
         return -1;
     } else if (parent->isWidgetType()) {
         QWidget *pw = static_cast<QWidget *>(parent);
         return pw->style()->pixelMetric(pm, 0, pw);
     } else {
         return static_cast<QLayout *>(parent)->spacing();
     }
 }


text:
package org.rythmengine.internal;

import org.rythmengine.RythmEngine;
import org.rythmengine.template.ITemplate;
import org.rythmengine.utils.I18N;

import java.util.Locale;

/**
 * Created with IntelliJ IDEA.
 * User: luog
 * Date: 10/03/13
 * Time: 7:10 AM
 * To change this template use File | Settings | File Templates.
 */
public class CacheKey {
    public static String i18nMsg(ITemplate template, String key, boolean useFormat) {
        return i18nMsg(template, key, useFormat, null);
    }

    public static String i18nMsg(ITemplate template, Object key, boolean useFormat, Locale locale) {
        if (null == template) return "";
        if (null == locale) {
            locale = I18N.locale();
        }
        return String.format("%s-i18nM-%s-%s-%s", key, locale, useFormat, template.__engine());
    }

    public static String i18nBundle(RythmEngine engine, Locale locale) {
        return String.format("i18nB-%s-%s", locale, engine);
    }
}


text:
using Tests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using FluentAssertions;
using Core.Operations.Projects;
using Core.Operations.Projects.Extras;
using Voodoo.TestData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Cache;
using System.Text;
using System.Threading.Tasks;
using Voodoo;
using Voodoo.Messages;

namespace Tests.Operations.Projects
{
    [TestClass]
    public class ProjectUpdateCommandTests
    {
        [TestMethod]
        public async Task ProjectUpdateCommand_ValidRequest_IsOk()
        {
            var request = await ProjectTestHelper.GetExistingProject();
            var command = new ProjectSaveCommand(request);
            var response = await command.ExecuteAsync();
            response.Details.Should().BeEmpty();
            response.Message.Should().Be(ProjectMessages.UpdateOk);
            response.IsOk.Should().BeTrue();
        }

    }
}


text:
'use strict';

var expect = require('expect.js');
var concat = require('concat-stream');
var fs = require('fs');
var path = require('path');
var folderify = require('../lib/folderify');
var browserify = require('browserify');

function rf (file) {
  return fs.readFileSync(path.join(__dirname, file), 'utf8');
}

function checkTransform (sourcefile, expectedfile, done) {
  var source = rf(sourcefile);
  var expected = rf(expectedfile);
  var result = concat(function (data) {
    expect(data).to.be.equal(expected);
    done();
  });
  var stream = folderify(sourcefile);
  stream.pipe(result);
  stream.write(source);
  stream.end();
}

describe('folderify', function () {
  it('is defined', function () {
    expect(folderify).to.be.an('function');
  });

  it('return a through stream', function () {
    expect(folderify().constructor.name).to.be.equal('Stream');
  });

  this.timeout(3000);

  it('un-requires include-folder', function (done) {
    checkTransform(
      'fixtures/source/unrequire-include-folder.js',
      'fixtures/expected/unrequire-include-folder.js',
      done
    );
  });

  it('replaces includeFolder call with `files` array', function (done) {
    checkTransform(
      'fixtures/source/include-folder-default.js',
      'fixtures/expected/include-folder-default.js',
      done
    );
  });

  it('respects includeFolder pattern-match arguments', function (done) {
    checkTransform(
      'fixtures/source/include-folder-regex.js',
      'fixtures/expected/include-folder-regex.js',
      done
    );
  });

  it('preserves filenames when option is set', function (done) {
    checkTransform(
      'fixtures/source/include-folder-filenames.js',
      'fixtures/expected/include-folder-filenames.js',
      done
    );
  });

  describe('as a browserify transform', function () {
    var expectedBundle = rf('fixtures/expected/bundle.js');
    var expectedBundleWithJson = rf('fixtures/expected/bundle-with-json.js');

    it('doesn\'t require brfs', function (done) {
      var b = browserify(path.join(__dirname, 'fixtures/source/bundle.js'));
      b.transform(folderify);

      b
        .bundle()
        .on('error', done)
        .pipe(concat(function (data) {
          expect(data.toString('utf8')).to.be.equal(expectedBundle);
          done();
        }));
    });

    it('supports brfs running after folderify', function (done) {
      var b = browserify(path.join(__dirname, 'fixtures/source/bundle.js'));
      b.transform(folderify);
      b.transform('brfs');

      b
        .bundle()
        .on('error', done)
        .pipe(concat(function (data) {
          expect(data.toString('utf8')).to.be.equal(expectedBundle);
          done();
        }));
    });

    it('support brfs running before folderify', function (done) {
      var b = browserify(__dirname + '/fixtures/source/bundle.js');
      b.transform('brfs');
      b.transform(folderify);

      b
        .bundle()
        .on('error', done)
        .pipe(concat(function (data) {
          expect(data.toString('utf8')).to.be.equal(expectedBundle);
          done();
        }));
    });

    it('support bundles with non JavaScript files', function (done) {
      var b = browserify(__dirname + '/fixtures/source/bundle-with-json.js');
      b.transform('brfs');
      b.transform(folderify);

      b
        .bundle()
        .on('error', done)
        .pipe(concat(function (data) {
          expect(data.toString('utf8')).to.be.equal(expectedBundleWithJson);
          done();
        }));
    });
  });

  describe('Custom extensions', function () {
    it('expose validExtensions', function () {
      expect(folderify.validExtensions).to.be.an('array');
    });

    it('can modify validExtensions for allowing custom extensions', function (done) {
      var origin = folderify.validExtensions;
      folderify.validExtensions = ['.custom-js'];
      checkTransform(
        'fixtures/source/include-folder-default.custom-js',
        'fixtures/expected/include-folder-default.custom-js',
        function (err) {
          folderify.validExtensions = origin;
          done(err);
        }
      );
    });
  });
});


text:
import * as ts from 'typescript';
import {AbsoluteFsPath} from '../../../src/ngtsc/file_system';
import {NgccReflectionHost, SwitchableVariableDeclaration} from '../host/ngcc_host';
import {isWithinPackage} from './util';

export interface SwitchMarkerAnalysis {
  sourceFile: ts.SourceFile;
  declarations: SwitchableVariableDeclaration[];
}

export type SwitchMarkerAnalyses = Map<ts.SourceFile, SwitchMarkerAnalysis>;
export const SwitchMarkerAnalyses = Map;

/**
 * This Analyzer will analyse the files that have an R3 switch marker in them
 * that will be replaced.
 */
export class SwitchMarkerAnalyzer {
  constructor(private host: NgccReflectionHost, private packagePath: AbsoluteFsPath) {}
  /**
   * Analyze the files in the program to identify declarations that contain R3
   * switch markers.
   * @param program The program to analyze.
   * @return A map of source files to analysis objects. The map will contain only the
   * source files that had switch markers, and the analysis will contain an array of
   * the declarations in that source file that contain the marker.
   */
  analyzeProgram(program: ts.Program): SwitchMarkerAnalyses {
    const analyzedFiles = new SwitchMarkerAnalyses();
    program.getSourceFiles()
        .filter(sourceFile => isWithinPackage(this.packagePath, sourceFile))
        .forEach(sourceFile => {
          const declarations = this.host.getSwitchableDeclarations(sourceFile);
          if (declarations.length) {
            analyzedFiles.set(sourceFile, {sourceFile, declarations});
          }
        });
    return analyzedFiles;
  }
}


text:
require File.expand_path('../application', __FILE__)

# Initialize the rails application
Oreidig::Application.initialize!


text:
action :something do
  log 'message'
end


text:
#include <time.h>
#include <iostream>
#include <fstream>
#include <sstream>

int main(int argc, char* args[]){
	if(argc <= 1){return 0;}
	fstream file;
	file.open(args[1]);
	if(!file.is_open()){
		file.close(); return 0;
	}
	stringstream fileContents;
	fileContents << file.rdbuf();
	string program = fileContents.str();

	bfcpu cpu = bfcpu();

	cpu.readStringToOptomizedProgram_operatorCollapse(program);
	cpu.runOptimizedProgram_operatorCollapseMicrocode();

	return 0;
}


text:
package core

import (
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common"
)

// ComputeImageCapabilitySchemaSummary Summary information for a compute image capability schema
type ComputeImageCapabilitySchemaSummary struct {

	// The compute image capability schema OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm).
	Id *string `mandatory:"true" json:"id"`

	// The name of the compute global image capability schema version
	ComputeGlobalImageCapabilitySchemaVersionName *string `mandatory:"true" json:"computeGlobalImageCapabilitySchemaVersionName"`

	// The OCID of the image associated with this compute image capability schema
	ImageId *string `mandatory:"true" json:"imageId"`

	// A user-friendly name for the compute image capability schema.
	DisplayName *string `mandatory:"true" json:"displayName"`

	// The date and time the compute image capability schema was created, in the format defined by RFC3339 (https://tools.ietf.org/html/rfc3339).
	// Example: `2016-08-25T21:10:29.600Z`
	TimeCreated *common.SDKTime `mandatory:"true" json:"timeCreated"`

	// The OCID of the compartment containing the compute global image capability schema
	CompartmentId *string `mandatory:"false" json:"compartmentId"`

	// Defined tags for this resource. Each key is predefined and scoped to a
	// namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
	// Example: `{"Operations": {"CostCenter": "42"}}`
	DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`

	// Free-form tags for this resource. Each tag is a simple key-value pair with no
	// predefined name, type, or namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
	// Example: `{"Department": "Finance"}`
	FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`
}

func (m ComputeImageCapabilitySchemaSummary) String() string {
	return common.PointerString(m)
}


text:
title: "Peter Kokot"
---

# Peter Kokot

## Project title:

{{ site.github.project_title }}

[GitHub Profile](https://github.com/petk)

```php
<?php

echo "Hello World";
```


text:
<?xml version="1.0" ?>
<doc>
	<str name="Patent Number">
		US7575683
	</str>
	<str name="Application Number">
		US11698628
	</str>
	<str name="Kind Code">
		B2
	</str>
	<str name="Title">
		Portable wetlands
	</str>
	<str name="Abstract">
		The present invention includes a portable Sub-Surface Flow Constructed Wetlands system for removing pollutants from a body of water. The portable wetlands system includes a sealed container having pipes for the inflow and outlet of the water. The system also includes a high surface area substrate located in a lower portion of the container and a heavier substrate and at least one emergent aquatic plant located in an upper portion of the container. The container of the system may be mounted on a trailer and the entire system may be light enough to be capable of being towed by a normal mid-sized pickup truck. The present invention also contemplates a method for removing pollutants from water using such a portable wetlands system. The water to be treated is flowed through the portable wetlands system in order to remove pollutants. The present invention further contemplates a method for constructing such a portable wetlands system.
	</str>
	<str name="Document Types">
		US | USB | DOCDB
	</str>
	<str name="Application Date">
		2007-01-26
	</str>
	<str name="Application Year">
		2007
	</str>
	<str name="Application(Year/Month)">
		2007-01
	</str>
	<str name="Publication Date">
		2009-08-18
	</str>
	<str name="Publication Year">
		2009
	</str>
	<str name="Publication(Year/Month)">
		2009-08
	</str>
	<str name="All IPC">
		C02F3/04 | C02F3/32
	</str>
	<str name="IPC Primary">
		C02F3/04
	</str>
	<str name="IPC Section">
		C
	</str>
	<str name="IPC Class">
		C02
	</str>
	<str name="IPC Subclass">
		C02F
	</str>
	<str name="IPC Group">
		C02F3
	</str>
	<str name="All UPC">
		210/150 | 210/602 | 210/617
	</str>
	<str name="UPC Primary">
		210/150
	</str>
	<str name="UPC Class">
		210
	</str>
	<str name="Family Members">
		US20080179240A1 | US7575683
	</str>
	<str name="Family Member Count">
		2
	</str>
	<str name="Family Members Cited By Count">
		0
	</str>
	<str name="Other References Count">
		0
	</str>
	<str name="Cited By Count">
		0
	</str>
	<str name="Cites">
		US6126827 | US5876484 | US4169050 | US5486291 | US6200469 | JP2006051434 | JP2001198593
	</str>
	<str name="Cites Count">
		7
	</str>
	<str name="Priority Country">
		US
	</str>
	<str name="Priority Number">
		69862807
	</str>
	<str name="Priority Date">
		2007-01-26
	</str>
	<str name="Inventor(s)">
		KAUPPI, FREDERICK, J. | WELSH, JAMES, H. | LYON, STEPHEN, R.
	</str>
	<str name="1st Inventor">
		KAUPPI, FREDERICK, J.
	</str>
	<str name="Number of Inventors">
		3
	</str>
	<str name="1st Inventor Address">
		Newport, Beach, CA
	</str>
	<str name="Inventor(s) Address">
		Newport, Beach, CA | Santa, Ana, CA | Long, Beach, CA
	</str>
	<str name="Agent/Attorney">
		STETINA BRUNDA GARRED & BRUCKER
	</str>
	<str name="Primary Examiner">
		PRINCE, FRED
	</str>
	<str name="cited by within 3 years">
		0
	</str>
	<str name="cited by within 5 years">
		0
	</str>
</doc>