text:
export const pickerTemplate: string = `

                <input class="form-control" type="text" name="daterangepicker_start">

                <input class="form-control" type="text" name="daterangepicker_end">

            <button class="applyBtn" disabled="disabled" type="button"></button>
            <button class="cancelBtn" type="button"></button>

`;

redpajama_set_name: RedPajamaGithub


text:
let config = {}

window._config = config

export default config


text:
using Humanizer;
using JetBrains.Annotations;

namespace JsonApiDotNetCore.Queries.Internal.QueryableBuilding;

/// <summary>
/// Produces unique names for lambda parameters.
/// </summary>
[PublicAPI]
public sealed class LambdaParameterNameFactory
{
    private readonly HashSet<string> _namesInScope = new();

    public LambdaParameterNameScope Create(string typeName)
    {
        ArgumentGuard.NotNullNorEmpty(typeName);

        string parameterName = typeName.Camelize();
        parameterName = EnsureNameIsUnique(parameterName);

        _namesInScope.Add(parameterName);
        return new LambdaParameterNameScope(parameterName, this);
    }

    private string EnsureNameIsUnique(string name)
    {
        if (!_namesInScope.Contains(name))
        {
            return name;
        }

        int counter = 1;
        string alternativeName;

        do
        {
            counter++;
            alternativeName = name + counter;
        }
        while (_namesInScope.Contains(alternativeName));

        return alternativeName;
    }

    public void Release(string parameterName)
    {
        _namesInScope.Remove(parameterName);
    }
}


text:
package alien4cloud.orchestrator;

import alien4cloud.dao.IGenericSearchDAO;
import alien4cloud.deployment.DeploymentService;
import alien4cloud.model.orchestrators.Orchestrator;
import alien4cloud.model.orchestrators.OrchestratorConfiguration;
import alien4cloud.model.orchestrators.OrchestratorState;
import alien4cloud.orchestrators.locations.services.PluginArchiveIndexer;
import alien4cloud.orchestrators.plugin.IOrchestratorPlugin;
import alien4cloud.orchestrators.plugin.IOrchestratorPluginFactory;
import alien4cloud.orchestrators.services.OrchestratorConfigurationService;
import alien4cloud.orchestrators.services.OrchestratorService;
import alien4cloud.orchestrators.services.OrchestratorStateService;
import alien4cloud.paas.OrchestratorPluginService;
import alien4cloud.paas.exception.PluginConfigurationException;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import org.mockito.Mockito;

public class OrchestratorServiceTest {
    public static final String DEFAULT_CLOUD_CONFIGURATION = "This is the cloud configuration";
    private OrchestratorPluginService orchestratorPluginService;
    private OrchestratorConfigurationService orchestratorConfigurationService;
    private IGenericSearchDAO alienDAO;
    private DeploymentService deploymentService;
    private OrchestratorStateService orchestratorStateService;
    private OrchestratorService orchestratorService;
    private PluginArchiveIndexer archiveIndexer;

    private void setPrivateField(Object target, String fieldName, Object fieldValue) {
        Field field;
        try {
            field = target.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(target, fieldValue);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            throw new RuntimeException("Test failed as we cannot set private field.", e);
        }
    }

    private void initializeMockedOrchestratorService() {
        alienDAO = Mockito.mock(IGenericSearchDAO.class);
        orchestratorConfigurationService = Mockito.mock(OrchestratorConfigurationService.class);
        orchestratorPluginService = Mockito.mock(OrchestratorPluginService.class);
        deploymentService = Mockito.mock(DeploymentService.class);
        orchestratorService = Mockito.mock(OrchestratorService.class);
        archiveIndexer = Mockito.mock(PluginArchiveIndexer.class);
        // initialize orchestrator state service instance with mocks
        orchestratorStateService = new OrchestratorStateService();
        setPrivateField(orchestratorStateService, "alienDAO", alienDAO);
        setPrivateField(orchestratorStateService, "orchestratorConfigurationService", orchestratorConfigurationService);
        setPrivateField(orchestratorStateService, "orchestratorPluginService", orchestratorPluginService);
        setPrivateField(orchestratorStateService, "deploymentService", deploymentService);
        setPrivateField(orchestratorStateService, "orchestratorService", orchestratorService);
        setPrivateField(orchestratorStateService, "archiveIndexer", archiveIndexer);
    }

    @Test
    public void testInitializeNullData() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
        initializeMockedOrchestratorService();

        List<Orchestrator> enabledOrchestrators = Lists.newArrayList();
        initSearch(enabledOrchestrators);

        orchestratorStateService.initialize();
    }

    @Test
    public void testInitializeEmptyData() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
        initializeMockedOrchestratorService();

        List<Orchestrator> enabledOrchestrators = Lists.newArrayList(new Orchestrator[0]);
        initSearch(enabledOrchestrators);

        orchestratorStateService.initialize();
    }

    @SuppressWarnings("unchecked")
    private void initSearch(List<Orchestrator> enabledOrchestrators) {
        Mockito.when(orchestratorService.getAllEnabledOrchestrators()).thenReturn(enabledOrchestrators);
    }

    private List<Orchestrator> searchOrchestrator() {
        Orchestrator cloud = new Orchestrator();
        cloud.setId("id");
        cloud.setName("name");
        cloud.setState(OrchestratorState.CONNECTED);
        cloud.setPluginId("paasPluginId");
        cloud.setPluginBean("paasPluginBean");

        return Lists.newArrayList(cloud);
    }

    private void initializeAndWait() throws ExecutionException, InterruptedException {
        orchestratorStateService.initialize().get();
    }

    @SuppressWarnings("unchecked")
    @Test
    public void testInitializeConfigurableOrchestratorValidConfig() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException,
            SecurityException, PluginConfigurationException, ExecutionException, InterruptedException, IOException {
        initializeMockedOrchestratorService();

        IOrchestratorPluginFactory orchestratorPluginFactory = Mockito.mock(IOrchestratorPluginFactory.class);
        IOrchestratorPlugin orchestratorPlugin = Mockito.mock(IOrchestratorPlugin.class);

        List<Orchestrator> enabledOrchestrators = searchOrchestrator();
        Orchestrator orchestrator = enabledOrchestrators.get(0);
        OrchestratorConfiguration configuration = new OrchestratorConfiguration(orchestrator.getId(), DEFAULT_CLOUD_CONFIGURATION);

        initSearch(enabledOrchestrators);

        Mockito.when(orchestratorService.getPluginFactory(orchestrator)).thenReturn(orchestratorPluginFactory);
        Mockito.when(orchestratorPluginFactory.newInstance(DEFAULT_CLOUD_CONFIGURATION)).thenReturn(orchestratorPlugin);
        Mockito.when(orchestratorPluginFactory.getConfigurationType()).thenReturn(String.class);
        Mockito.when(orchestratorPluginFactory.getDefaultConfiguration()).thenReturn(DEFAULT_CLOUD_CONFIGURATION);
        Mockito.when(orchestratorConfigurationService.configurationAsValidObject(orchestrator.getId(), configuration.getConfiguration()))
                .thenReturn(DEFAULT_CLOUD_CONFIGURATION);
        Mockito.when(orchestratorConfigurationService.getConfigurationOrFail(orchestrator.getId())).thenReturn(configuration);
        initializeAndWait();

        Mockito.verify(orchestratorPlugin, Mockito.times(1)).setConfiguration(orchestrator.getId(), configuration.getConfiguration());
        Mockito.verify(orchestratorPluginService, Mockito.times(1)).register(orchestrator.getId(), orchestratorPlugin);
        IOrchestratorPluginFactory fatory = orchestratorService.getPluginFactory(orchestrator);
        Mockito.verify(archiveIndexer, Mockito.times(1)).indexOrchestratorArchives(fatory, fatory.newInstance(DEFAULT_CLOUD_CONFIGURATION));
        ;
    }

    @SuppressWarnings("unchecked")
    @Test
    public void testInitializeConfigurableOrchstratorInvalidConfig() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException,
            SecurityException, PluginConfigurationException, ExecutionException, InterruptedException, IOException {
        initializeMockedOrchestratorService();

        IOrchestratorPluginFactory orchestratorPluginFactory = Mockito.mock(IOrchestratorPluginFactory.class);
        IOrchestratorPlugin orchestratorPlugin = Mockito.mock(IOrchestratorPlugin.class);

        List<Orchestrator> enabledOrchestrators = searchOrchestrator();
        Orchestrator orchestrator = enabledOrchestrators.get(0);
        OrchestratorConfiguration configuration = new OrchestratorConfiguration(orchestrator.getId(), DEFAULT_CLOUD_CONFIGURATION);

        initSearch(enabledOrchestrators);

        Mockito.when(orchestratorService.getPluginFactory(orchestrator)).thenReturn(orchestratorPluginFactory);
        Mockito.when(orchestratorPluginFactory.newInstance(DEFAULT_CLOUD_CONFIGURATION)).thenReturn(orchestratorPlugin);
        Mockito.when(orchestratorPluginFactory.getConfigurationType()).thenReturn(String.class);
        Mockito.when(orchestratorPluginFactory.getDefaultConfiguration()).thenReturn(DEFAULT_CLOUD_CONFIGURATION);
        Mockito.when(orchestratorConfigurationService.getConfigurationOrFail(orchestrator.getId())).thenReturn(configuration);
        Mockito.when(orchestratorConfigurationService.configurationAsValidObject(orchestrator.getId(), configuration.getConfiguration()))
                .thenReturn(DEFAULT_CLOUD_CONFIGURATION);

        Mockito.doThrow(PluginConfigurationException.class).when(orchestratorPlugin).setConfiguration(orchestrator.getId(), configuration.getConfiguration());

        initializeAndWait();

        Mockito.verify(orchestratorPluginService, Mockito.times(0)).register(orchestrator.getId(), orchestratorPlugin);
        orchestrator = (Orchestrator) searchOrchestrator().get(0);
        orchestrator.setState(OrchestratorState.DISABLED);
        Mockito.verify(alienDAO, Mockito.times(2)).save(Mockito.refEq(orchestrator));
    }
}


text:
using namespace log4cxx;
using namespace log4cxx::helpers;

using orwell::messages::Register;
using orwell::messages::Registered;
using orwell::messages::Welcome;
using orwell::messages::Goodbye;
using orwell::com::RawMessage;

namespace orwell
{
namespace callbacks
{

ProcessRegister::ProcessRegister(
		std::shared_ptr< com::Sender > ioPublisher,
		game::Game & ioGame)
	: InterfaceProcess(ioPublisher, ioGame)
{
}

void ProcessRegister::execute()
{
	ORWELL_LOG_INFO("ProcessRegister::execute");

	orwell::messages::Register const & aRegisterMsg =
		static_cast< orwell::messages::Register const & >(*m_msg);
	std::string const & aClientID = getArgument("RoutingID");

	std::string aTemporaryRobotId = aRegisterMsg.temporary_robot_id();
	std::shared_ptr< orwell::game::Robot > aRobot =
		m_game->getRobotWithoutRealRobot(aTemporaryRobotId);
	Registered aRegistered;
	std::string aRobotId;
	if (aRobot)
	{
		aRobotId = aRobot->getRobotId();
		aRobot->setHasRealRobot(true);
		aRobot->setVideoUrl(aRegisterMsg.video_url());
		aRegistered.set_team(aRobot->getTeam().getName());
	}
	aRegistered.set_robot_id(aRobotId);
	RawMessage aReply(aClientID, "Registered", aRegistered.SerializeAsString());
	m_publisher->send(aReply);
	if (aRobot)
	{
		ORWELL_LOG_INFO("ProcessRegister::execute success");
	}
	else
	{
		ORWELL_LOG_INFO("ProcessRegister::execute failure");
	}
}

}
}


text:
namespace Mosa.DeviceSystem
{
	/// <summary>
	///
	/// </summary>
	public interface IPartitionDevice
	{
		/// <summary>
		/// Gets the starting block number on the disk
		/// </summary>
		uint StartBlock { get; }

		/// <summary>
		/// Gets the block count.
		/// </summary>
		/// <value>The block count.</value>
		uint BlockCount { get; }

		/// <summary>
		/// Gets the size of the block.
		/// </summary>
		/// <value>The size of the block.</value>
		uint BlockSize { get; }

		/// <summary>
		/// Gets a value indicating whether this instance can write.
		/// </summary>
		/// <value><c>true</c> if this instance can write; otherwise, <c>false</c>.</value>
		bool CanWrite { get; }

		/// <summary>
		/// Reads the block.
		/// </summary>
		/// <param name="block">The block.</param>
		/// <param name="count">The count.</param>
		/// <returns></returns>
		byte[] ReadBlock(uint block, uint count);

		/// <summary>
		/// Reads the block.
		/// </summary>
		/// <param name="block">The block.</param>
		/// <param name="count">The count.</param>
		/// <param name="data">The data.</param>
		/// <returns></returns>
		bool ReadBlock(uint block, uint count, byte[] data);

		/// <summary>
		/// Writes the block.
		/// </summary>
		/// <param name="block">The block.</param>
		/// <param name="count">The count.</param>
		/// <param name="data">The data.</param>
		/// <returns></returns>
		bool WriteBlock(uint block, uint count, byte[] data);
	}
}


text:
-uxwrite-in-ul = true
-uxwrite-paragraph-style = p
-uxwrite-shift = true


text: export { FacadeProcess } from './FacadeProcess';


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

<style>
#cover {
  background: url("https://i.giphy.com/l41lYi76UHjfNPofC.gif") no-repeat scroll center center #FFF;
  position: absolute;
  height: 100%;
  width: 100%;
}
</style>


text:
<TITLE>Review for Titanic (1997)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Titanic (1997)

reviewed by
Michael J. Legeros

                               Titanic (1997)

                    A movie review by Michael J. Legeros
                    Copyright 1997 by Michael J. Legeros

(Paramount)
Directed by     James Cameron
Written by      James Cameron
Cast            Leonardo DiCaprio, Kate Winslet, Billy Zane, Kathy
                Bates, Frances Fisher, Gloria Stuart, Bill Paxton,
                Bernard Hill, David Warner
MPAA Rating     "PG-13"
Running Time    184 minutes
Reviewed at     Mission Valley Cinemas, Raleigh, NC (16DEC97)

==

     What to say about James Cameron's TITANIC?  Well, you certainly get
your money's worth.  $200 mil is right there, right up on the damn
screen, with a lavishly, expertly, meticulously recreated and nearly
full-size version of the great lady herself.  However it succeeds (or
fails) as a narrative, by golly Ms. Unsinkable Molly, you *do* get to
take that once-in-a-lifetime time-machine tour.  Up and down and around
we're guided, from stem to stern, in and out of staterooms, ball rooms,
dining halls, cargo holds, and even the boiler room.  (And, geez, will
you ever forget the sight of those massive pistons in the engine room?)
These endlessly fascinating period details are the film's greatest as-
set, guaranteed to hold your interest, no matter how expertly (or poor-
ly) Cameron handles both the characters and the story.  Well, that is,
*both* stories.  Not counting the curiously flat framing device-- a
modern-day deep-sea treasure hunt, starring Bill Paxton and featuring
Cameron's own footage (!) of the wreck itself-- TITANIC is actually
*two* movies in one.

     The first is a breezy but embarrassingly juvenile love story, about
a Third Class boy (Leonardo DiCaprio) and a First Class girl (Kate Win-
slet) and the forces that conspire to keep them apart.  (One of which is
her well-to-do but narrow-minded fiancee, Billy Zane, doing Snidely
Whiplash sans mustache.) JAMES CAMERON'S ROMEO AND JULIET runs about an
hour and a half and, if the teen romance doesn't strike a chord, you're
probably doomed to dwell on some of the worser aspects of the film:
corny dialogue, repetitive shots, weak supporting characters, a cloying
Celtic/New Age score, and, on most of the daylight exteriors, an odd and
presumably special effects-induced "haze." And, yet, even if you can't
believe it and run with it, those ninety or so minutes pass pretty
quickly because there *is* so much atmosphere to take in.  (Cameron
pulls out so many stops and delivers such an embarrassment of riches
that you really have to step back from stepping back to get cranky about
the stuff that sucks.)

     TITANIC-- not *The* Titanic.  Just Titanic-- is also a disaster
movie.  Perhaps the granddaddy of all disaster movies.  (Or, at the very
least, the granddaddy of all POSEIDON ADVENTURE remakes.)  Using compu-
ters and models and moving sets, Cameron successfully, believably,
astonishingly recreates *the* great failure of 20th Century technology.
Whatever the liabilities of the script-- and, oh God, there are so many
of them-- the images speak for themselves:  an elderly couple preparing
to drown together in bed, the ass end of a great ship rising higher and
higher into the air, the pained, pale expressions of lifeboat passen-
gers, wincing at the distant screams of the dying.  It's an hour of film
that has to be seen to be believed and, perhaps, be ultimately disap-
pointed by.  (In particular, the death throes are drawn out to an almost
comic extreme.  If you're in a sarcastic mood, comparisons to the for-
ever-and-a-day finale of SPEED 2: CRUISE CONTROL won't be far behind.)
But when we've returned to present day, our tears dried and the pains of
a poor script promptly forgotten, the likely reaction of any paying cus-
tomer will be, well, that they got their money's worth.  And, really,
isn't that the name of the game?

     Grade: B+

--
Mike Legeros - Movie Hell
http://www.nonvirtual.com/hell

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
use strict;
use warnings;

use DBI;
use File::Basename;
use File::Spec;

use CoGe::Accessory::Web;
use CoGe::Core::Storage qw( get_experiment_path );

#open STDERR, '>', File::Spec->devnull() or die "could not open STDERR: $!\n";

my ($db, $user, $conf) = CoGe::Accessory::Web->init();

my $experiment_id = shift;
if ($experiment_id && $experiment_id eq 'c') {
	$experiment_id = shift;
	if ($experiment_id) {
		compress($experiment_id);
	} else {
		my $ids = $db->storage->dbh->selectcol_arrayref('SELECT experiment_id FROM experiment WHERE deleted');
		for (@$ids) {
			compress($_);
		}
	}
} else {
	if ($experiment_id) {
		ls($experiment_id);
	} else {
		my $ids = $db->storage->dbh->selectcol_arrayref('SELECT experiment_id FROM experiment WHERE deleted');
		for (@$ids) {
			ls($_);
		}
	}
}

sub run {
	my $cmd = shift;
	my @results = `$cmd`;
	if (@results) {
		print "\n----- ",$cmd,"\n";
		for (@results) {
			chomp;
			print $_,' ';
		}
	}
}

sub ls {
	my $experiment_id = shift;
	my $path = get_experiment_path($experiment_id);
	if ($path) {
		run "ls $path" if -e $path;
	}
}

sub compress {
	my $experiment_id = shift;
	my $path = get_experiment_path($experiment_id);
	return unless $path && -e $path;
	system('tar czf ' . dirname($path) . '/' . $experiment_id . '.tar.gz --anchored ' . $path);
	system('rm -rf ' . $path);
}


text:
#ifndef control_wm8731_h_
#define control_wm8731_h_

#include "AudioControl.h"

class AudioControlWM8731 : public AudioControl
{
public:
	bool enable(void);
	bool disable(void) { return false; }
	bool volume(float n) { return volumeInteger(n * 80.0 + 47.499); }
	bool inputLevel(float n); // range: 0.0f to 1.0f
	bool inputSelect(int n) { return false; }
protected:
	bool write(unsigned int reg, unsigned int val);
	bool volumeInteger(unsigned int n); // range: 0x2F to 0x7F
};

class AudioControlWM8731master : public AudioControlWM8731
{
public:
	bool enable(void);
};

#endif


text:
using System.Linq;

namespace ManagedShovel
{
    public class SourceDeclarationsDescriptor
    {
        private readonly ManagedShovelConfiguration configuration;

        internal SourceDeclarationsDescriptor(ManagedShovelConfiguration configuration)
        {
            this.configuration = configuration;
        }

        public ToDescriptor To(string broker, params string[] brokers)
        {
            configuration.Destinations = new[] {broker}.Concat(brokers).ToArray();
            return new ToDescriptor(configuration);
        }
    }
}


text:
<?php

$tainted_source_inside_package = $_GET["p"];

function blabla()
{
    echo $_GET["p"];
}

class test_tainted
{
    public function return_tainted_source()
    {
        echo $_GET["p"];
    }
}


text:
BENCHMARK=${BENCHMARK:-"translation"}

docker build --pull -t mlperf-inspur:$BENCHMARK .


text:
local mkstr = ZO_CreateStringId

local SI = Teleporter.SI

mkstr(SI.TELEWELCOMEMSG, Teleporter.var.color.colArtifact .."Luminary" .. Teleporter.var.color.colTeal.." Teleporter loaded")
mkstr(SI.TELEREFRESH, "Refreshing...")
mkstr(SI.TELECLOSE, "Close")

---- Various messages
mkstr(SI.TELE_UNABLE_TO_PORTAL, "Unable to portal to player")
mkstr(SI.TELE_TO_PLAYER, "Porting to player: ")

mkstr(SI.TELE_PLAYER, "Player: ")

mkstr(SI.TELE_ZONE, "Zone: ")
mkstr(SI.TELE_FAST, "Fast Port")
mkstr(SI.TELE_TELE, "Teleporter")

mkstr(SI.TELE_FREQUENCY, "How Fast to Portal (In Seconds)")
mkstr(SI.TELE_PORT_IN_SEC, "Don't Move: Portaling will start in ")

mkstr(SI.TELE_SET_PORTAL_FREQ, "How Fast to Portal (In Seconds)")
mkstr(SI.TELE_SET_PORTAL_FREQ_INFO, "Default is about 45 for slow computers")
mkstr(SI.TELE_PORTAL_ENABLED, "Portaling Enabled! MAKE SURE TO CLICK PORTAL ICON AGAIN TO DISABLE.")
mkstr(SI.TELE_PORTAL_DISABLED, "Portaling Disabled")
mkstr(SI.TELE_PUT_ON_FULL_SET_EXPLOATION_GEAR, "Don't forget to put on a full set of exploration gear")
mkstr(SI.TELE_ERROR, "Error while portaling to player.")
mkstr(SI.TELE_AGAIN_DISABLE, "Tap button again to disable automatic teleporting.")
mkstr(SI.TELE_IN_FIVE_SEC,     "Portal in 5 secs. Don't Move.")


text:
#include <aws/cloudfront/model/KinesisStreamConfig.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Xml;
using namespace Aws::Utils;

namespace Aws
{
namespace CloudFront
{
namespace Model
{

KinesisStreamConfig::KinesisStreamConfig() :
    m_roleARNHasBeenSet(false),
    m_streamARNHasBeenSet(false)
{
}

KinesisStreamConfig::KinesisStreamConfig(const XmlNode& xmlNode) :
    m_roleARNHasBeenSet(false),
    m_streamARNHasBeenSet(false)
{
  *this = xmlNode;
}

KinesisStreamConfig& KinesisStreamConfig::operator =(const XmlNode& xmlNode)
{
  XmlNode resultNode = xmlNode;

  if(!resultNode.IsNull())
  {
    XmlNode roleARNNode = resultNode.FirstChild("RoleARN");
    if(!roleARNNode.IsNull())
    {
      m_roleARN = Aws::Utils::Xml::DecodeEscapedXmlText(roleARNNode.GetText());
      m_roleARNHasBeenSet = true;
    }
    XmlNode streamARNNode = resultNode.FirstChild("StreamARN");
    if(!streamARNNode.IsNull())
    {
      m_streamARN = Aws::Utils::Xml::DecodeEscapedXmlText(streamARNNode.GetText());
      m_streamARNHasBeenSet = true;
    }
  }

  return *this;
}

void KinesisStreamConfig::AddToNode(XmlNode& parentNode) const
{
  Aws::StringStream ss;
  if(m_roleARNHasBeenSet)
  {
   XmlNode roleARNNode = parentNode.CreateChildElement("RoleARN");
   roleARNNode.SetText(m_roleARN);
  }

  if(m_streamARNHasBeenSet)
  {
   XmlNode streamARNNode = parentNode.CreateChildElement("StreamARN");
   streamARNNode.SetText(m_streamARN);
  }

}

} // namespace Model
} // namespace CloudFront
} // namespace Aws


text:
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login, authenticate
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User

from models import UserProfile, individual

from sourcetrans.macro_module import macros, jeeves
import JeevesLib

# "Glue method". Right now you just write a method like `index` below.
# It returns a (faceted) tuple either of the form (template_name, template_ctxt)
# or ("redirect", redirect_url).
#
# SUPER HACKY, obviously. Ideally we would have a full object similar to the django
# HttpResponse that can be faceted. Such an object would need to support Jeeves,
# of course. And the concretized rendering should be moved to a library function
# (like render_to_response).
@jeeves
def add_to_context(context_dict, request, template_name, profile, concretize):
    template_name = concretize(template_name)
    context_dict['concretize'] = concretize

    context_dict['is_admin'] = profile != None and profile.level == "chair"
    context_dict['profile'] = profile

    context_dict['is_logged_in'] = (request.user and
                                    request.user.is_authenticated() and
                                    (not request.user.is_anonymous()))

def request_wrapper(view_fn):
    def real_view_fn(request, *args, **kwargs):
        try:
            profile = UserProfile.objects.get(username=request.user.username)

            ans = view_fn(request, profile, *args, **kwargs)
            template_name = ans[0]
            context_dict = ans[1]

            if template_name == "redirect":
                path = context_dict
                return HttpResponseRedirect(JeevesLib.concretize(profile, path))

            concretizeState = JeevesLib.jeevesState.policyenv.getNewSolverState(profile)
            def concretize(val):
                return concretizeState.concretizeExp(val, JeevesLib.jeevesState.pathenv.getEnv())
            add_to_context(context_dict, request, template_name, profile, concretize)

            return render_to_response(template_name, RequestContext(request, context_dict))

        except Exception:
            import traceback
            traceback.print_exc()
            raise

    real_view_fn.__name__ = view_fn.__name__
    return real_view_fn

@login_required
@request_wrapper
@jeeves
def profile_view(request, user_profile):
    profile = UserProfile.objects.get(username=request.user.username)
    if profile == None:
        profile = UserProfile(username=request.user.username)

    if request.method == 'POST':
        profile.email = request.POST.get('email', '')
        profile.save()

    return ("profile.html", {
        "email": profile.email,
        "which_page": "profile",
    })

# An example of a really simple view.
# The argument `user_profile` is a UserProfile object (defined in models.py).
# Use this instead of `request.user` (which is the ordinary django User model).
# You can access request.POST and request.GET as normal.

@login_required
@request_wrapper
@jeeves
def index(request, user_profile):
    return (   "index.html"
           , { 'name' : user_profile.email } )

@login_required
@request_wrapper
@jeeves
def patients(request, user_profile, patient):
	p=individual.objects.get(pk=patient)
	#dataset={"SSN":p.ssn}
	return (   "patient.html"
		, { 'patient' : p.ssn } )

def register_account(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect("index")

    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.save()

            UserProfile.objects.create(
                username=user.username,
                email=request.POST.get('email', ''),
            )

            user = authenticate(username=request.POST['username'],
                         password=request.POST['password1'])
            login(request, user)
            return HttpResponseRedirect("index")
    else:
        form = UserCreationForm()

    return render_to_response("registration/account.html", RequestContext(request,
        {
            'form' : form,
            'which_page' : "register"
        }))


text:
using Newtonsoft.Json;

namespace LtiLibrary.Core.Lti2
{
    /// <summary>
    /// Contact information for the associated object.
    /// </summary>
    public class Contact
    {
        public Contact(string email)
        {
            Email = email;
        }

        /// <summary>
        /// The email of the primary contact for the associated object.
        /// </summary>
        [JsonProperty("email")]
        public string Email { get; private set; }
    }
}


text:
import * as React from 'react';
import { Feature } from 'toolkit/extension/features/feature';
import { getEmberView } from 'toolkit/extension/utils/ember';
import { addToolkitEmberHook } from 'toolkit/extension/utils/toolkit';
import { componentPrepend } from 'toolkit/extension/utils/react';
import ReactMarkdown from 'react-markdown';

export class MemoAsMarkdown extends Feature {
  injectCSS() {
    return require('./styles.css');
  }

  shouldInvoke() {
    return true;
  }

  applyMarkdown = element => {
    const view = getEmberView(element.getAttribute('id'));
    if (!view) {
      return;
    }

    const toolkitMemoContainer = element.querySelector('.tk-markdown-memo');
    if (toolkitMemoContainer) {
      return;
    }

    const handleClick = event => {
      if (event.target.tagName === 'A') {
        event.stopPropagation();
      }
    };

    const note = view.get('attrs.content.value.memo');
    const originalMemo = element.querySelector('.ynab-grid-cell-memo .user-entered-text');
    if (note && originalMemo) {
      originalMemo.remove();

      componentPrepend(

          <ReactMarkdown
            source={note}
            linkTarget="_blank"
            renderers={{
              link: ({ href, children }) => (

                  {children}

              ),
            }}
          />

,
        element.querySelector('.ynab-grid-cell-memo')
      );
    }
  };

  invoke() {
    addToolkitEmberHook(this, 'register/grid-row', 'didRender', this.applyMarkdown);
  }
}


text:
package org.springframework.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.assertj.core.api.ThrowableTypeAssert;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;

/**
 * Unit tests for {@link UnmodifiableMultiValueMap}.
 *
 * @author Arjen Poutsma
 * @since 6.0
 */
class UnmodifiableMultiValueMapTests {

	@Test
	@SuppressWarnings("unchecked")
	void delegation() {
		MultiValueMap<String, String> mock = mock(MultiValueMap.class);
		UnmodifiableMultiValueMap<String, String> map = new UnmodifiableMultiValueMap<>(mock);

		given(mock.size()).willReturn(1);
		assertThat(map).hasSize(1);

		given(mock.isEmpty()).willReturn(false);
		assertThat(map.isEmpty()).isFalse();

		given(mock.containsKey("foo")).willReturn(true);
		assertThat(map.containsKey("foo")).isTrue();

		given(mock.containsValue(List.of("bar"))).willReturn(true);
		assertThat(map.containsValue(List.of("bar"))).isTrue();

		List<String> list = new ArrayList<>();
		list.add("bar");
		given(mock.get("foo")).willReturn(list);
		List<String> result = map.get("foo");
		assertThat(result).isNotNull().containsExactly("bar");
		assertThatUnsupportedOperationException().isThrownBy(() -> result.add("baz"));

		given(mock.getOrDefault("foo", List.of("bar"))).willReturn(List.of("baz"));
		assertThat(map.getOrDefault("foo", List.of("bar"))).containsExactly("baz");

		given(mock.toSingleValueMap()).willReturn(Map.of("foo", "bar"));
		assertThat(map.toSingleValueMap()).containsExactly(entry("foo", "bar"));
	}

	@Test
	void unsupported() {
		UnmodifiableMultiValueMap<String, String> map = new UnmodifiableMultiValueMap<>(new LinkedMultiValueMap<>());

		assertThatUnsupportedOperationException().isThrownBy(() -> map.put("foo", List.of("bar")));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.putIfAbsent("foo", List.of("bar")));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.putAll(Map.of("foo", List.of("bar"))));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.remove("foo"));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.add("foo", "bar"));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.addAll("foo", List.of("bar")));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.addAll(new LinkedMultiValueMap<>()));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.addIfAbsent("foo", "baz"));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.set("foo", "baz"));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.setAll(Map.of("foo", "baz")));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.replaceAll((s, strings) -> strings));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.remove("foo", List.of("bar")));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.replace("foo", List.of("bar")));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.replace("foo", List.of("bar"), List.of("baz")));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.computeIfAbsent("foo", s -> List.of("bar")));
		assertThatUnsupportedOperationException().isThrownBy(
				() -> map.computeIfPresent("foo", (s1, s2) -> List.of("bar")));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.compute("foo", (s1, s2) -> List.of("bar")));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.merge("foo", List.of("bar"), (s1, s2) -> s1));
		assertThatUnsupportedOperationException().isThrownBy(() -> map.clear());
	}

	@Test
	@SuppressWarnings("unchecked")
	void entrySetDelegation() {
		MultiValueMap<String, String> mockMap = mock(MultiValueMap.class);
		Set<Map.Entry<String, List<String>>> mockSet = mock(Set.class);
		given(mockMap.entrySet()).willReturn(mockSet);
		Set<Map.Entry<String, List<String>>> set = new UnmodifiableMultiValueMap<>(mockMap).entrySet();

		given(mockSet.size()).willReturn(1);
		assertThat(set).hasSize(1);

		given(mockSet.isEmpty()).willReturn(false);
		assertThat(set.isEmpty()).isFalse();

		Map.Entry<String, List<String>> mockedEntry = mock(Map.Entry.class);
		given(mockSet.contains(mockedEntry)).willReturn(true);
		assertThat(set.contains(mockedEntry)).isTrue();

		List<Map.Entry<String, List<String>>> mockEntries = List.of(mock(Map.Entry.class));
		given(mockSet.containsAll(mockEntries)).willReturn(true);
		assertThat(set.containsAll(mockEntries)).isTrue();

		Iterator<Map.Entry<String, List<String>>> mockIterator = mock(Iterator.class);
		given(mockSet.iterator()).willReturn(mockIterator);
		given(mockIterator.hasNext()).willReturn(false);
		assertThat(set.iterator()).isExhausted();
	}

	@Test
	@SuppressWarnings("unchecked")
	void entrySetUnsupported() {
		Set<Map.Entry<String, List<String>>> set = new UnmodifiableMultiValueMap<String, String>(new LinkedMultiValueMap<>()).entrySet();

		assertThatUnsupportedOperationException().isThrownBy(() -> set.add(mock(Map.Entry.class)));
		assertThatUnsupportedOperationException().isThrownBy(() -> set.remove(mock(Map.Entry.class)));
		assertThatUnsupportedOperationException().isThrownBy(() -> set.removeIf(e -> true));
		assertThatUnsupportedOperationException().isThrownBy(() -> set.addAll(mock(List.class)));
		assertThatUnsupportedOperationException().isThrownBy(() -> set.retainAll(mock(List.class)));
		assertThatUnsupportedOperationException().isThrownBy(() -> set.removeAll(mock(List.class)));
		assertThatUnsupportedOperationException().isThrownBy(() -> set.clear());
	}

	@Test
	@SuppressWarnings("unchecked")
	void valuesDelegation() {
		MultiValueMap<String, String> mockMap = mock(MultiValueMap.class);
		Collection<List<String>> mockValues = mock(Collection.class);
		given(mockMap.values()).willReturn(mockValues);
		Collection<List<String>> values = new UnmodifiableMultiValueMap<>(mockMap).values();

		given(mockValues.size()).willReturn(1);
		assertThat(values).hasSize(1);

		given(mockValues.isEmpty()).willReturn(false);
		assertThat(values.isEmpty()).isFalse();

		given(mockValues.contains(List.of("foo"))).willReturn(true);
		assertThat(mockValues.contains(List.of("foo"))).isTrue();

		given(mockValues.containsAll(List.of(List.of("foo")))).willReturn(true);
		assertThat(mockValues.containsAll(List.of(List.of("foo")))).isTrue();

		Iterator<List<String>> mockIterator = mock(Iterator.class);
		given(mockValues.iterator()).willReturn(mockIterator);
		given(mockIterator.hasNext()).willReturn(false);
		assertThat(values.iterator()).isExhausted();
	}

	@Test
	void valuesUnsupported() {
		Collection<List<String>> values =
				new UnmodifiableMultiValueMap<String, String>(new LinkedMultiValueMap<>()).values();

		assertThatUnsupportedOperationException().isThrownBy(() -> values.add(List.of("foo")));
		assertThatUnsupportedOperationException().isThrownBy(() -> values.remove(List.of("foo")));
		assertThatUnsupportedOperationException().isThrownBy(() -> values.addAll(List.of(List.of("foo"))));
		assertThatUnsupportedOperationException().isThrownBy(() -> values.removeAll(List.of(List.of("foo"))));
		assertThatUnsupportedOperationException().isThrownBy(() -> values.retainAll(List.of(List.of("foo"))));
		assertThatUnsupportedOperationException().isThrownBy(() -> values.removeIf(s -> true));
		assertThatUnsupportedOperationException().isThrownBy(() -> values.clear());
	}

	private static ThrowableTypeAssert<UnsupportedOperationException> assertThatUnsupportedOperationException() {
		return assertThatExceptionOfType(UnsupportedOperationException.class);
	}

}


text:
namespace content {
class BrowserContext;
}

namespace chromeos {

// Launches web dialog during OOBE/Login with specified URL and title.
class LoginWebDialog : public ui::WebDialogDelegate {
 public:
  // Delegate class to get notifications from the dialog.
  class Delegate {
   public:
    // Called when dialog has been closed.
    virtual void OnDialogClosed();

   protected:
    virtual ~Delegate() {}
  };

  // If |parent_window| is null then the dialog is placed in the modal dialog
  // container on the primary display.
  LoginWebDialog(content::BrowserContext* browser_context,
                 Delegate* delegate,
                 gfx::NativeWindow parent_window,
                 const base::string16& title,
                 const GURL& url);
  ~LoginWebDialog() override;

  void Show();

  // Overrides dialog title.
  void SetDialogTitle(const base::string16& title);

  static content::WebContents* GetCurrentWebContents();

  // Returns |dialog_window_| instance for test, can be NULL if dialog is not
  // shown or closed.
  gfx::NativeWindow get_dialog_window_for_test() const {
    return dialog_window_;
  }

 protected:
  // ui::WebDialogDelegate implementation.
  ui::ModalType GetDialogModalType() const override;
  base::string16 GetDialogTitle() const override;
  GURL GetDialogContentURL() const override;
  void GetWebUIMessageHandlers(
      std::vector<content::WebUIMessageHandler*>* handlers) const override;
  void GetDialogSize(gfx::Size* size) const override;
  void GetMinimumDialogSize(gfx::Size* size) const override;
  std::string GetDialogArgs() const override;
  void OnDialogShown(content::WebUI* webui) override;
  // NOTE: This function deletes this object at the end.
  void OnDialogClosed(const std::string& json_retval) override;
  void OnCloseContents(content::WebContents* source,
                       bool* out_close_dialog) override;
  bool ShouldShowDialogTitle() const override;
  bool HandleContextMenu(content::RenderFrameHost* render_frame_host,
                         const content::ContextMenuParams& params) override;
  bool HandleOpenURLFromTab(content::WebContents* source,
                            const content::OpenURLParams& params,
                            content::WebContents** out_new_contents) override;
  bool HandleShouldOverrideWebContentsCreation() override;
  std::vector<ui::Accelerator> GetAccelerators() override;
  bool AcceleratorPressed(const ui::Accelerator& accelerator) override;

 private:
  content::BrowserContext* const browser_context_;
  gfx::NativeWindow parent_window_;
  gfx::NativeWindow dialog_window_;
  // Notifications receiver.
  Delegate* const delegate_;

  base::string16 title_;
  const GURL url_;

  DISALLOW_COPY_AND_ASSIGN(LoginWebDialog);
};

}  // namespace chromeos

#endif  // CHROME_BROWSER_CHROMEOS_LOGIN_UI_LOGIN_WEB_DIALOG_H_


text:
from google.cloud import speech_v1

async def sample_recognize():
    # Create a client
    client = speech_v1.SpeechAsyncClient()

    # Initialize request argument(s)
    config = speech_v1.RecognitionConfig()
    config.language_code = "language_code_value"

    audio = speech_v1.RecognitionAudio()
    audio.content = b'content_blob'

    request = speech_v1.RecognizeRequest(
        config=config,
        audio=audio,
    )

    # Make the request
    response = await client.recognize(request=request)

    # Handle the response
    print(response)

# [END speech_v1_generated_Speech_Recognize_async]


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

<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ask="http://schemas.android.com/apk/res-auto"
    android:keyWidth="10%p">

    <Row android:keyWidth="10%p">
        <Key android:codes="113" android:keyLabel="q" android:popupCharacters="\@" android:keyEdgeFlags="left" />
        <Key android:codes="119" android:keyLabel="w" android:popupCharacters=""/>
        <Key android:codes="101" android:keyLabel="e" android:popupCharacters="€"/>
        <Key android:codes="114" android:keyLabel="r" android:popupCharacters=""/>
        <Key android:codes="116" android:keyLabel="t" android:popupCharacters=""/>
        <Key android:codes="121" android:keyLabel="y" android:popupCharacters=""/>
        <Key android:codes="117" android:keyLabel="u" android:popupCharacters="ü"/>
        <Key android:codes="105" android:keyLabel="i" android:popupCharacters=""/>
        <Key android:codes="111" android:keyLabel="o" android:popupCharacters="ö"/>
        <Key android:codes="112" android:keyLabel="p" android:popupCharacters="" android:keyEdgeFlags="right"/>
    </Row>

    <Row android:keyWidth="11.111%p">
        <Key android:codes="97" android:keyLabel="a" android:popupCharacters="ä" android:keyEdgeFlags="left"/>
        <Key android:codes="115" android:keyLabel="s" android:popupCharacters="ßẞ§ſ"/>
        <Key android:codes="100" android:keyLabel="d" android:popupCharacters=""/>
        <Key android:codes="102" android:keyLabel="f" android:popupCharacters=""/>
        <Key android:codes="103" android:keyLabel="g" android:popupCharacters=""/>
        <Key android:codes="104" android:keyLabel="h" android:popupCharacters=""/>
        <Key android:codes="106" android:keyLabel="j" android:popupCharacters=""/>
        <Key android:codes="107" android:keyLabel="k" android:popupCharacters=""/>
        <Key android:codes="108" android:keyLabel="l" android:popupCharacters="" android:keyEdgeFlags="right"/>
    </Row>

    <Row android:keyWidth="10.625%p">
        <Key android:codes="-1" android:keyWidth="15%p" android:isModifier="true" android:isSticky="true" android:keyEdgeFlags="left"/>
        <Key android:codes="122" android:keyLabel="z" android:popupCharacters=""/>
        <Key android:codes="120" android:keyLabel="x" android:popupCharacters=""/>
        <Key android:codes="99" android:keyLabel="c" android:popupCharacters=""/>
        <Key android:codes="118" android:keyLabel="v" android:popupCharacters=""/>
        <Key android:codes="98" android:keyLabel="b" android:popupCharacters=""/>
        <Key android:codes="110" android:keyLabel="n" android:popupCharacters=""/>
        <Key android:codes="109" android:keyLabel="m" android:popupCharacters=""/>
        <Key android:codes="-5" android:isRepeatable="true" android:keyEdgeFlags="right"/>
    </Row>
</Keyboard>


text:
package hu.interconnect.hr.backend.api.dto;

import java.util.Date;
import java.util.List;

import hu.interconnect.hr.backend.api.enumeration.KivetelnapTipus;

public class KivetelnapokResponseDTO {

	public List<KivetelnapDTO> kivetelnapok;

	public KivetelnapokResponseDTO(List<KivetelnapDTO> kivetelnapok) {
		this.kivetelnapok = kivetelnapok;
	}

	public static class KivetelnapDTO {

		public int id;

		public Date datum;

		public KivetelnapTipus tipus;

		public KivetelnapDTO(int id, Date datum, KivetelnapTipus tipus) {
			this.id = id;
			this.datum = datum;
			this.tipus = tipus;
		}
	}
}


text:
<?php

namespace PhlyRestfully\View;

use PhlyRestfully\ApiProblem;
use PhlyRestfully\HalCollection;
use PhlyRestfully\HalResource;
use PhlyRestfully\Link;
use PhlyRestfully\LinkCollection;
use PhlyRestfully\Plugin\HalLinks;
use Zend\Paginator\Paginator;
use Zend\Stdlib\Hydrator\HydratorInterface;
use Zend\View\HelperPluginManager;
use Zend\View\Renderer\JsonRenderer;

/**
 * Handles rendering of the following:
 *
 * - API-Problem
 * - HAL collections
 * - HAL resources
 */
class RestfulJsonRenderer extends JsonRenderer
{
    /**
     * @var ApiProblem
     */
    protected $apiProblem;

    /**
     * Whether or not to render exception stack traces in API-Problem payloads
     *
     * @var bool
     */
    protected $displayExceptions = false;

    /**
     * @var HelperPluginManager
     */
    protected $helpers;

    /**
     * Set helper plugin manager instance.
     *
     * Also ensures that the 'HalLinks' helper is present.
     *
     * @param  HelperPluginManager $helpers
     */
    public function setHelperPluginManager(HelperPluginManager $helpers)
    {
        if (!$helpers->has('HalLinks')) {
            $this->injectHalLinksHelper($helpers);
        }
        $this->helpers = $helpers;
    }

    /**
     * Lazy-loads a helper plugin manager if none available.
     *
     * @return HelperPluginManager
     */
    public function getHelperPluginManager()
    {
        if (!$this->helpers instanceof HelperPluginManager) {
            $this->setHelperPluginManager(new HelperPluginManager());
        }
        return $this->helpers;
    }

    /**
     * Set display_exceptions flag
     *
     * @param  bool $flag
     * @return RestfulJsonRenderer
     */
    public function setDisplayExceptions($flag)
    {
        $this->displayExceptions = (bool) $flag;
        return $this;
    }

    /**
     * Whether or not what was rendered represents an API problem
     *
     * @return bool
     */
    public function isApiProblem()
    {
        return (null !== $this->apiProblem);
    }

    /**
     * @return null|ApiProblem
     */
    public function getApiProblem()
    {
        return $this->apiProblem;
    }

    /**
     * Render a view model
     *
     * If the view model is a RestfulJsonRenderer, determines if it represents
     * an ApiProblem, HalCollection, or HalResource, and, if so, creates a custom
     * representation appropriate to the type.
     *
     * If not, it passes control to the parent to render.
     *
     * @param  mixed $nameOrModel
     * @param  mixed $values
     * @return string
     */
    public function render($nameOrModel, $values = null)
    {
        $this->apiProblem = null;

        if (!$nameOrModel instanceof RestfulJsonModel) {
            return parent::render($nameOrModel, $values);
        }

        if ($nameOrModel->isApiProblem()) {
            return $this->renderApiProblem($nameOrModel->getPayload());
        }

        if ($nameOrModel->isHalResource()) {
            $helper  = $this->helpers->get('HalLinks');
            $payload = $helper->renderResource($nameOrModel->getPayload());
            return parent::render($payload);
        }

        if ($nameOrModel->isHalCollection()) {
            $helper  = $this->helpers->get('HalLinks');
            $payload = $helper->renderCollection($nameOrModel->getPayload());
            if ($payload instanceof ApiProblem) {
                return $this->renderApiProblem($payload);
            }
            return parent::render($payload);
        }

        return parent::render($nameOrModel, $values);
    }

    /**
     * Render an API Problem representation
     *
     * Also sets the $apiProblem member to the passed object.
     *
     * @param  ApiProblem $apiProblem
     * @return string
     */
    protected function renderApiProblem(ApiProblem $apiProblem)
    {
        $this->apiProblem   = $apiProblem;
        if ($this->displayExceptions) {
            $apiProblem->setDetailIncludesStackTrace(true);
        }
        return parent::render($apiProblem->toArray());
    }

    /**
     * Inject the helper manager with the HalLinks helper
     *
     * @param  HelperPluginManager $helpers
     */
    protected function injectHalLinksHelper(HelperPluginManager $helpers)
    {
        $helper = new HalLinks();
        $helper->setView($this);
        $helper->setServerUrlHelper($helpers->get('ServerUrl'));
        $helper->setUrlHelper($helpers->get('Url'));
        $helpers->setService('HalLinks', $helper);
    }
}


text:
using Hotcakes.Modules.Core.Admin.AppCode;

namespace Hotcakes.Modules.Core.Admin.Parts.GiftCardGateways.Hotcakes
{
    partial class Edit : HccGiftCardGatewayPart
    {
        public override void LoadData()
        {
        }

        public override void SaveData()
        {
        }
    }
}


text:
package org.hisp.dhis.security.oauth2;

import org.hisp.dhis.DhisSpringTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
public class OAuth2ClientServiceTest
    extends DhisSpringTest
{
    @Autowired
    private OAuth2ClientService oAuth2ClientService;

    private OAuth2Client clientA;

    private OAuth2Client clientB;

    private OAuth2Client clientC;

    @Override
    public void setUpTest()
    {
        clientA = new OAuth2Client();
        clientA.setName( "clientA" );
        clientA.setCid( "clientA" );

        clientB = new OAuth2Client();
        clientB.setName( "clientB" );
        clientB.setCid( "clientB" );

        clientC = new OAuth2Client();
        clientC.setName( "clientC" );
        clientC.setCid( "clientC" );
    }

    @Test
    public void testGetAll()
    {
        oAuth2ClientService.saveOAuth2Client( clientA );
        oAuth2ClientService.saveOAuth2Client( clientB );
        oAuth2ClientService.saveOAuth2Client( clientC );

        Collection<OAuth2Client> all = oAuth2ClientService.getOAuth2Clients();

        assertEquals( 3, all.size() );
    }

    @Test
    public void testGetByClientID()
    {
        oAuth2ClientService.saveOAuth2Client( clientA );
        oAuth2ClientService.saveOAuth2Client( clientB );
        oAuth2ClientService.saveOAuth2Client( clientC );

        assertNotNull( oAuth2ClientService.getOAuth2ClientByClientId( "clientA" ) );
        assertNotNull( oAuth2ClientService.getOAuth2ClientByClientId( "clientB" ) );
        assertNotNull( oAuth2ClientService.getOAuth2ClientByClientId( "clientC" ) );
    }
}


text:
<container>
</container>


text:
package device

import (
	"errors"
	"fmt"
	"github.com/kunaldawn/goandroid/adbutility"
	"strings"
	"time"
)

const (
	PROP_BOOT_STATUS = "sys.boot_completed" // Property that represents devices boot status
)

// Device struct represents adb capable android device, its serial number and
// associated adb endpoint. Device timeout represents all device specific adb operation timeouts.
type Device struct {
	Serial      string                 // Device serial number
	Timeout     int                    // Timeout in seconds for all adb and shell operations
	AdbEndpoint adbutility.AdbEndpoint // Adb endpoint for this device
}

// NewDevice method creates a new Device based on given serial number, adb operation timeout and
// connecting adb enpoint for this device.
func NewDevice(serial string, timeout int, endPoint adbutility.AdbEndpoint) Device {
	return Device{Serial: serial, Timeout: timeout, AdbEndpoint: endPoint}
}

// IsAvailable method checkes availability of the device in the adb endpoint. It returns
// boolean value indicating availibility status of the device and error in case of
// something went wrong while doing adb operations.
func (dev Device) IsAvailable() (bool, error) {
	devices, err := dev.AdbEndpoint.GetAttachedDevices(dev.Timeout)
	if err != nil {
		return false, err
	}
	for index := range devices {
		if dev.Serial == devices[index] {
			return true, nil
		}
	}
	return false, nil
}

// Adb method allows to execute adb command on this device instance. It takes a adb command
// and optional list of arguments. It returns outout of the adb command and error in case
// of something went wrong. Please note that adb will timeout within default adb operation
// timeout.
func (dev Device) Adb(command string, args ...string) (string, error) {
	return dev.AdbEndpoint.Adb(dev.Timeout, append([]string{"-s", dev.Serial, command}, args...)...)
}

// Shell method allows to execute adb shell commands on associated device instance. It takes
// a shell comand and a list of opetional command arguments. It returns adb shell command output
// and stderr output combiled as string and error in case of adb operation failure or timeout.
func (dev Device) Shell(command string, args ...string) (string, error) {
	return dev.Adb("shell", append([]string{command}, args...)...)
}

// GetProperty method is used to extract a device property value based on the specified
// key. It returns string representation of the property value and error in case of
// adb operation failure or specified key is not located.
func (dev Device) GetProperty(key string) (string, error) {
	prop, err := dev.GetAllProperties()
	if err != nil {
		return "", err
	}
	val, ok := prop[key]
	if !ok {
		return "", errors.New(fmt.Sprintf("Key [%s] is not found in device properties", key))
	}
	return val, nil
}

// GetAllProperties method returns a map of [key: value] pairs of all device
// properties. It also returns error in case of adb operation failure.
func (dev Device) GetAllProperties() (map[string]string, error) {
	prop_map := make(map[string]string)
	prop, err := dev.Shell("getprop")
	if err != nil {
		return prop_map, err
	}
	lines := strings.Split(prop, "\n")
	for index := range lines {
		parts := strings.Split(lines[index], ":")
		if len(parts) == 2 {
			key := strings.TrimSpace(strings.Replace(strings.Replace(parts[0], "[", "", -1), "]", "", -1))
			value := strings.TrimSpace(strings.Replace(strings.Replace(parts[1], "[", "", -1), "]", "", -1))
			prop_map[key] = value
		}
	}
	return prop_map, nil
}

// Pull method pulls a file or directory from specified source path to specified
// destination path. Specified path must exist on device and specified destination path
// must exist on local machine. It returns command output and error in case of adb operation
// failed.
func (dev Device) Pull(src string, dst string) (string, error) {
	return dev.Adb("pull", src, dst)
}

// Push method pushes a file or directory from local machine from specified source
// path to device in specified destination path. Specified source path mast exist on
// local machine and destinaltion path mast exist on device. It returns command output
// and error in case of adb operation failed.
func (dev Device) Push(src string, dst string) (string, error) {
	return dev.Adb("push", src, dst)
}

// WaitForAvailability method waits for associatred device to be available or
// attached to the adb endpoint within specified timeout period. It returns
// error in case of adb operation failure or timeout.
func (dev Device) WaitForAvailability(timeout int) error {
	_, err := dev.AdbEndpoint.Adb(timeout, "-s", dev.Serial, "wait-for-device")
	return err
}

// Root method gains root access to the device, for this the device must be rooted.
// It returns error in case of root failed or adb operation failed.
func (dev Device) Root() error {
	out, err := dev.Adb("root")
	if err != nil {
		return err
	}
	if !strings.Contains(out, "restarting adbd as root") && !strings.Contains(out, "adbd is already running as root") {
		return errors.New("Unable to gain root access to device")
	}
	return dev.WaitForAvailability(dev.Timeout)
}

// Reboot method reboots associated device. It waits for the device to become
// available again within specified restart timeout and the device to complete
// its boot sequence within specified boot timeout. It returns error in case
// of adb operation failure or timeout has been reached.
func (dev Device) Reboot(restartTimeout int, bootTimeout int) error {
	_, err := dev.Adb("reboot")
	if err != nil {
		return err
	}
	err = dev.WaitForAvailability(restartTimeout)
	if err != nil {
		return err
	}
	return dev.WaitForBootToComplete(bootTimeout)
}

// WaitForBootToComplete method waits for the device to complete its boot sequence
// within specified ammount of timeout. It returns error in case of adb operation failure
// or timeout has been reached.
func (dev Device) WaitForBootToComplete(bootTimeout int) error {
	startTime := time.Now()
	for {
		currentTime := time.Now()
		delta := currentTime.Sub(startTime)
		if delta.Seconds() >= float64(bootTimeout) {
			break
		}
		val, err := dev.GetProperty(PROP_BOOT_STATUS)
		if err != nil {
			return err
		}
		if val == "1" {
			return nil
		}
	}
	return errors.New("Device not completed boot sequence in timeout")
}


text:
using System;
using System.Windows;
using System.Windows.Media;

namespace Omnius.Wpf
{
    public static class UIElementExtensions
    {
        public static TAncestor FindAncestor<TAncestor>(this UIElement element)
            where TAncestor : UIElement
        {
            var temp = element;

            while ((temp != null) && !(temp is TAncestor))
            {
                temp = VisualTreeHelper.GetParent(temp) as UIElement;
            }

            return temp as TAncestor;
        }

        public static TAncestor FindAncestor<TAncestor>(this UIElement element, Predicate<TAncestor> match)
            where TAncestor : UIElement
        {
            var temp = element;

            while ((temp != null) && (!(temp is TAncestor) || !match.Invoke((TAncestor)temp)))
            {
                temp = VisualTreeHelper.GetParent(temp) as UIElement;
            }

            return temp as TAncestor;
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Google\Cloud\Samples\Functions\TipsInfiniteRetries\Test;

use Google\Cloud\Logging\LoggingClient;
use Google\Cloud\TestUtils\CloudFunctionDeploymentTrait;
use Google\Cloud\PubSub\PubSubClient;
use PHPUnit\Framework\TestCase;

/**
 * Class DeployTest.
 *
 * This test is not run by the CI system.
 *
 * To skip deployment of a new function, run with "GOOGLE_SKIP_DEPLOYMENT=true".
 * To skip deletion of the tested function, run with "GOOGLE_KEEP_DEPLOYMENT=true".
 * @group deploy
 */
class DeployTest extends TestCase
{
    use CloudFunctionDeploymentTrait;

    private static $entryPoint = 'avoidInfiniteRetries';

    /* var string */
    private static $projectId;

    /* var string */
    private static $topicName;

    /** @var LoggingClient */
    private static $loggingClient;

    public function testTipsRetry(): void
    {
        // Send Pub/Sub message.
        $this->publishMessage();

        $fiveMinAgo = date(\DateTime::RFC3339, strtotime('-5 minutes'));
        $this->processFunctionLogs($fiveMinAgo, function (\Iterator $logs) {
            // Concatenate all relevant log messages.
            $actual = '';
            foreach ($logs as $log) {
                $info = $log->info();
                $actual .= $info['textPayload'];
            }

            // Check that multiple invocations of the function have occurred.
            $retryCount = substr_count($actual, 'retrying...');
            $this->assertGreaterThan(1, $retryCount);

            // Check that the function has stopped retrying
            $this->assertStringContainsString('Dropping event', $actual);
        }, 3, 30);
    }

    private function publishMessage(): void
    {
        // Construct Pub/Sub message
        $message = json_encode(['retry' => true]);

        // Publish a message to the function.
        $pubsub = new PubSubClient([
            'projectId' => self::$projectId,
        ]);
        $topic = $pubsub->topic(self::$topicName);
        $topic->publish(['data' => $message]);
    }

    /**
     * Deploy the Cloud Function, called from DeploymentTrait::deployApp().
     *
     * Overrides CloudFunctionDeploymentTrait::doDeploy().
     */
    private static function doDeploy()
    {
        self::$projectId = self::requireEnv('GOOGLE_PROJECT_ID');
        self::$topicName = self::requireEnv('FUNCTIONS_TOPIC');
        return self::$fn->deploy(['--retry' => ''], '--trigger-topic=' . self::$topicName);
    }
}


text:
package org.cloudfoundry.operations;

import org.cloudfoundry.AbstractIntegrationTest;
import org.cloudfoundry.operations.spaces.CreateSpaceRequest;
import org.cloudfoundry.operations.spaces.GetSpaceRequest;
import org.cloudfoundry.operations.spaces.SpaceDetail;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import reactor.test.StepVerifier;

import java.time.Duration;

import static org.assertj.core.api.Assertions.assertThat;

public final class SpacesTest extends AbstractIntegrationTest {

    @Autowired
    private CloudFoundryOperations cloudFoundryOperations;

    @Autowired
    private String organizationName;

    @Test
    public void create() {
        String spaceName = this.nameFactory.getSpaceName();

        this.cloudFoundryOperations.spaces()
            .create(CreateSpaceRequest.builder()
                .name(spaceName)
                .organization(this.organizationName)
                .build())
            .thenMany(this.cloudFoundryOperations.spaces()
                .list())
            .filter(spaceSummary -> spaceName.equals(spaceSummary.getName()))
            .as(StepVerifier::create)
            .expectNextCount(1)
            .expectComplete()
            .verify(Duration.ofMinutes(5));
    }

    @Test
    public void getWithURLReservedCharacterInName() {
        String spaceName = this.nameFactory.getSpaceName() + "+test";

        this.cloudFoundryOperations.spaces()
            .create(CreateSpaceRequest.builder()
                .name(spaceName)
                .organization(this.organizationName)
                .build())
            .then(this.cloudFoundryOperations.spaces()
                .get(GetSpaceRequest.builder()
                    .name(spaceName)
                    .build()))
            .map(SpaceDetail::getName)
            .as(StepVerifier::create)
            .expectNext(spaceName)
            .expectComplete()
            .verify(Duration.ofMinutes(5));
    }

    @Test
    public void list() {
        this.cloudFoundryOperations.spaces()
            .list()
            .count()
            .as(StepVerifier::create)
            .consumeNextWith(count -> assertThat(count).isGreaterThan(0))
            .expectComplete()
            .verify(Duration.ofMinutes(5));
    }

}


text:
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace Burrows.Testing
{
    using System;
    using Context;

    public interface IReceivedMessage
    {
        IReceiveContext Context { get; }
        Exception Exception { get; }
    }

    public interface IReceivedMessage<T> :
        IReceivedMessage
    {
        T Message { get; }
    }

    public class ReceivedMessage :
		IReceivedMessage
	{
		readonly IReceiveContext _context;
		Exception _exception;

		public ReceivedMessage(IReceiveContext context)
		{
			_context = context;
		}

		public Exception Exception
		{
			get { return _exception; }
		}

		public IReceiveContext Context
		{
			get { return _context; }
		}

		public void SetException(Exception exception)
		{
			_exception = exception;
		}
	}

	public class ReceivedMessage<T> :
		IReceivedMessage<T>
		where T : class
	{
		readonly IConsumeContext<T> _context;
		Exception _exception;

		public ReceivedMessage(IConsumeContext<T> context)
		{
			_context = context;
		}

		public Exception Exception
		{
			get { return _exception; }
		}

		public IReceiveContext Context
		{
			get { return _context.BaseContext; }
		}

		public T Message
		{
			get { return _context.Message; }
		}

		public void SetException(Exception exception)
		{
			_exception = exception;
		}
	}
}


text:
from IECore import *

class LsHeaderOp( Op ) :

	def __init__( self ) :

		Op.__init__( self, "Lists the contents of Cortex file headers.",
			Parameter(
				name = "result",
				description = "A list of meta-data contained in the file header.",
				defaultValue = StringVectorData()
			)
		)

		self.parameters().addParameters(

			[
				FileNameParameter(
					name = "file",
					description = "The file to list the header from.",
					defaultValue = "",
					check = FileNameParameter.CheckType.MustExist,
					extensions = " ".join( Reader.supportedExtensions() ),
					allowEmptyString = False,
				),

				StringParameter(
					name = "resultType",
					description = "The format of the result",
					defaultValue = "string",
					presets = (
						( "string", "string" ),
						( "stringVector", "stringVector" ),
					),
					presetsOnly = True,
				)
			]
		)

		self.userData()["UI"] = CompoundObject(
									{
										"showResult": BoolData( True ),
										"closeAfterExecution": BoolData( True ),
									}
								)

	def doOperation( self, operands ) :

		try:
			reader = Reader.create( operands["file"].value )
			headers = reader.readHeader()
		except:
			debugException( "Error reading header" )
			headers = None

		if headers is None:
			raise Exception, ("Could not get header from file " + operands["file"].value)

		def formatCompound( compound, lines, level = 0 ):
			levelStr = "";
			i = 0
			while( i < level ):
				levelStr += "     "
				i += 1

			for key in compound.keys():
				value = compound[ key ]
				if isinstance( value, CompoundObject ) or isinstance( value, CompoundData ):
					lines.append( levelStr + key + ": " )
					formatCompound( value, lines, level + 1 )
				elif isSimpleDataType( value ):
					lines.append( levelStr + key + ": " + str(value.value) )
				elif isSequenceDataType( value ):
					lines.append( levelStr + key + ": " + ", ".join( map( str, value ) ) )
				else:
					lines.append( levelStr + key + ": " + str(value) )

		headerLines = []
		formatCompound( headers, headerLines )

		if operands.resultType.value == "string" :
			return StringData( "\n".join( headerLines ) )
		else :
			return StringVectorData( headerLines )

registerRunTimeTyped( LsHeaderOp )


text:
int writeLogFile (char* metric,int code, char* operation,double value);

// Log the analyzer and its behaviour
// Metric --> filename
// code --> Code for logging
// operation --> string that describe the operation
// value to write (if present)
// parameter to write (if present)
int writeLogFileAnalyzer (char* metric,int code, char* operation,double value,char* parameter);
char* setFileName(char* metric, char* dirlog);
char* setFileNameResults (char *metric);


text:
[![Version](https://img.shields.io/cocoapods/v/DHLoadingIndicatorView.svg?style=flat)](http://cocoadocs.org/docsets/DHLoadingIndicatorView)
[![License](https://img.shields.io/cocoapods/l/DHLoadingIndicatorView.svg?style=flat)](http://cocoadocs.org/docsets/DHLoadingIndicatorView)
[![Platform](https://img.shields.io/cocoapods/p/DHLoadingIndicatorView.svg?style=flat)](http://cocoadocs.org/docsets/DHLoadingIndicatorView)

## Usage

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

iOS 7

## Installation

DHLoadingIndicatorView is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

    pod "DHLoadingIndicatorView"

## Description

To use this view, just create it as any other UIView. The default look of the view is an activity
indicator and the label 'Loading...' next to it. The view can be configured by one of the basic
properties, or by accessing the subviews. Check out the header file for documentation on the
available proporties that can be used to customize the view.

Examples:

![Basic](https://raw.githubusercontent.com/davidahouse/DHLoadingIndicatorView/master/IndicatorViewExample_Basic.png)

![Changed Font](https://raw.githubusercontent.com/davidahouse/DHLoadingIndicatorView/master/IndicatorViewExample_Font.png)

![Frame](https://raw.githubusercontent.com/davidahouse/DHLoadingIndicatorView/master/IndicatorViewExample_Frame.png)

## Author

David House, davidahouse@gmail.com

## License

DHLoadingIndicatorView is available under the MIT license. See the LICENSE file for more info.


text:
module Motion; module Pixate; module Observer
  def startObserving
    @netServiceBrowser = NSNetServiceBrowser.alloc.init
    @netServiceBrowser.delegate = self
    @netServiceBrowser.searchForServicesOfType("_pixate-observer._tcp", inDomain: "")
  end

  def netServiceBrowser(netServiceBrowser,
                        didFindService: service,
                        moreComing: moreComing)
    @netServiceBrowser.stop

    @netService = NSNetService.alloc.initWithDomain(service.domain, type: service.type, name: service.name)
    @netService.delegate = self
    @netService.resolveWithTimeout(0.0)
  end

  def netServiceDidResolveAddress(service)
    @netService.stop

    @socket = Socket.alloc.initWithHost(service.hostName, Port: service.port)
    @socket.delegate = self
    @socket.startReceivingData
  end

  def socketDidReceive(string)
    NSLog(string)
    style(string)
  end
end; end; end


text:
<?php

namespace Magento\Sales\Controller\Adminhtml\Order;

use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
use Magento\Backend\Model\View\Result\ForwardFactory;

/**
 * Adminhtml sales orders creation process controller
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 * @SuppressWarnings(PHPMD.NumberOfChildren)
 */
abstract class Create extends \Magento\Backend\App\Action
{
    /**
     * @var \Magento\Framework\Escaper
     */
    protected $escaper;

    /**
     * @var PageFactory
     */
    protected $resultPageFactory;

    /**
     * @var \Magento\Backend\Model\View\Result\ForwardFactory
     */
    protected $resultForwardFactory;

    /**
     * @param Action\Context $context
     * @param \Magento\Catalog\Helper\Product $productHelper
     * @param \Magento\Framework\Escaper $escaper
     * @param PageFactory $resultPageFactory
     * @param ForwardFactory $resultForwardFactory
     */
    public function __construct(
        Action\Context $context,
        \Magento\Catalog\Helper\Product $productHelper,
        \Magento\Framework\Escaper $escaper,
        PageFactory $resultPageFactory,
        ForwardFactory $resultForwardFactory
    ) {
        parent::__construct($context);
        $productHelper->setSkipSaleableCheck(true);
        $this->escaper = $escaper;
        $this->resultPageFactory = $resultPageFactory;
        $this->resultForwardFactory = $resultForwardFactory;
    }

    /**
     * Retrieve session object
     *
     * @return \Magento\Backend\Model\Session\Quote
     */
    protected function _getSession()
    {
        return $this->_objectManager->get('Magento\Backend\Model\Session\Quote');
    }

    /**
     * Retrieve quote object
     *
     * @return \Magento\Quote\Model\Quote
     */
    protected function _getQuote()
    {
        return $this->_getSession()->getQuote();
    }

    /**
     * Retrieve order create model
     *
     * @return \Magento\Sales\Model\AdminOrder\Create
     */
    protected function _getOrderCreateModel()
    {
        return $this->_objectManager->get('Magento\Sales\Model\AdminOrder\Create');
    }

    /**
     * Retrieve gift message save model
     *
     * @return \Magento\GiftMessage\Model\Save
     */
    protected function _getGiftmessageSaveModel()
    {
        return $this->_objectManager->get('Magento\GiftMessage\Model\Save');
    }

    /**
     * Initialize order creation session data
     *
     * @return $this
     */
    protected function _initSession()
    {
        /**
         * Identify customer
         */
        if ($customerId = $this->getRequest()->getParam('customer_id')) {
            $this->_getSession()->setCustomerId((int)$customerId);
        }

        /**
         * Identify store
         */
        if ($storeId = $this->getRequest()->getParam('store_id')) {
            $this->_getSession()->setStoreId((int)$storeId);
        }

        /**
         * Identify currency
         */
        if ($currencyId = $this->getRequest()->getParam('currency_id')) {
            $this->_getSession()->setCurrencyId((string)$currencyId);
            $this->_getOrderCreateModel()->setRecollect(true);
        }
        return $this;
    }

    /**
     * Processing request data
     *
     * @return $this
     */
    protected function _processData()
    {
        return $this->_processActionData();
    }

    /**
     * Process request data with additional logic for saving quote and creating order
     *
     * @param string $action
     * @return $this
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    protected function _processActionData($action = null)
    {
        $eventData = [
            'order_create_model' => $this->_getOrderCreateModel(),
            'request_model' => $this->getRequest(),
            'session' => $this->_getSession(),
        ];

        $this->_eventManager->dispatch('adminhtml_sales_order_create_process_data_before', $eventData);

        /**
         * Saving order data
         */
        if ($data = $this->getRequest()->getPost('order')) {
            $this->_getOrderCreateModel()->importPostData($data);
        }

        /**
         * Initialize catalog rule data
         */
        $this->_getOrderCreateModel()->initRuleData();

        /**
         * init first billing address, need for virtual products
         */
        $this->_getOrderCreateModel()->getBillingAddress();

        /**
         * Flag for using billing address for shipping
         */
        if (!$this->_getOrderCreateModel()->getQuote()->isVirtual()) {
            $syncFlag = $this->getRequest()->getPost('shipping_as_billing');
            $shippingMethod = $this->_getOrderCreateModel()->getShippingAddress()->getShippingMethod();
            if ($syncFlag === null
            && $this->_getOrderCreateModel()->getShippingAddress()->getSameAsBilling() && empty($shippingMethod)
            ) {
                $this->_getOrderCreateModel()->setShippingAsBilling(1);
            } else {
                $this->_getOrderCreateModel()->setShippingAsBilling((int)$syncFlag);
            }
        }

        /**
         * Change shipping address flag
         */
        if (!$this->_getOrderCreateModel()->getQuote()->isVirtual() && $this->getRequest()->getPost('reset_shipping')
        ) {
            $this->_getOrderCreateModel()->resetShippingMethod(true);
        }

        /**
         * Collecting shipping rates
         */
        if (!$this->_getOrderCreateModel()->getQuote()->isVirtual() && $this->getRequest()->getPost(
            'collect_shipping_rates'
        )
        ) {
            $this->_getOrderCreateModel()->collectShippingRates();
        }

        /**
         * Apply mass changes from sidebar
         */
        if ($data = $this->getRequest()->getPost('sidebar')) {
            $this->_getOrderCreateModel()->applySidebarData($data);
        }

        /**
         * Adding product to quote from shopping cart, wishlist etc.
         */
        if ($productId = (int)$this->getRequest()->getPost('add_product')) {
            $this->_getOrderCreateModel()->addProduct($productId, $this->getRequest()->getPostValue());
        }

        /**
         * Adding products to quote from special grid
         */
        if ($this->getRequest()->has('item') && !$this->getRequest()->getPost('update_items') && !($action == 'save')
        ) {
            $items = $this->getRequest()->getPost('item');
            $items = $this->_processFiles($items);
            $this->_getOrderCreateModel()->addProducts($items);
        }

        /**
         * Update quote items
         */
        if ($this->getRequest()->getPost('update_items')) {
            $items = $this->getRequest()->getPost('item', []);
            $items = $this->_processFiles($items);
            $this->_getOrderCreateModel()->updateQuoteItems($items);
        }

        /**
         * Remove quote item
         */
        $removeItemId = (int)$this->getRequest()->getPost('remove_item');
        $removeFrom = (string)$this->getRequest()->getPost('from');
        if ($removeItemId && $removeFrom) {
            $this->_getOrderCreateModel()->removeItem($removeItemId, $removeFrom);
        }

        /**
         * Move quote item
         */
        $moveItemId = (int)$this->getRequest()->getPost('move_item');
        $moveTo = (string)$this->getRequest()->getPost('to');
        $moveQty = (int)$this->getRequest()->getPost('qty');
        if ($moveItemId && $moveTo) {
            $this->_getOrderCreateModel()->moveQuoteItem($moveItemId, $moveTo, $moveQty);
        }

        if ($paymentData = $this->getRequest()->getPost('payment')) {
            $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($paymentData);
        }

        $eventData = [
            'order_create_model' => $this->_getOrderCreateModel(),
            'request' => $this->getRequest()->getPostValue(),
        ];

        $this->_eventManager->dispatch('adminhtml_sales_order_create_process_data', $eventData);

        $this->_getOrderCreateModel()->saveQuote();

        if ($paymentData = $this->getRequest()->getPost('payment')) {
            $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($paymentData);
        }

        /**
         * Saving of giftmessages
         */
        $giftmessages = $this->getRequest()->getPost('giftmessage');
        if ($giftmessages) {
            $this->_getGiftmessageSaveModel()->setGiftmessages($giftmessages)->saveAllInQuote();
        }

        /**
         * Importing gift message allow items from specific product grid
         */
        if ($data = $this->getRequest()->getPost('add_products')) {
            $this->_getGiftmessageSaveModel()->importAllowQuoteItemsFromProducts(
                $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonDecode($data)
            );
        }

        /**
         * Importing gift message allow items on update quote items
         */
        if ($this->getRequest()->getPost('update_items')) {
            $items = $this->getRequest()->getPost('item', []);
            $this->_getGiftmessageSaveModel()->importAllowQuoteItemsFromItems($items);
        }

        $data = $this->getRequest()->getPost('order');
        $couponCode = '';
        if (isset($data) && isset($data['coupon']['code'])) {
            $couponCode = trim($data['coupon']['code']);
        }

        if (!empty($couponCode)) {
            $isApplyDiscount = false;
            foreach ($this->_getQuote()->getAllItems() as $item) {
                if (!$item->getNoDiscount()) {
                    $isApplyDiscount = true;
                    break;
                }
            }
            if (!$isApplyDiscount) {
                $this->messageManager->addError(
                    __(
                        '"%1" coupon code was not applied. Do not apply discount is selected for item(s)',
                        $this->escaper->escapeHtml($couponCode)
                    )
                );
            } else {
                if ($this->_getQuote()->getCouponCode() !== $couponCode) {
                    $this->messageManager->addError(
                        __(
                            '"%1" coupon code is not valid.',
                            $this->escaper->escapeHtml($couponCode)
                        )
                    );
                } else {
                    $this->messageManager->addSuccess(__('The coupon code has been accepted.'));
                }
            }
        }

        return $this;
    }

    /**
     * Process buyRequest file options of items
     *
     * @param array $items
     * @return array
     */
    protected function _processFiles($items)
    {
        /* @var $productHelper \Magento\Catalog\Helper\Product */
        $productHelper = $this->_objectManager->get('Magento\Catalog\Helper\Product');
        foreach ($items as $id => $item) {
            $buyRequest = new \Magento\Framework\DataObject($item);
            $params = ['files_prefix' => 'item_' . $id . '_'];
            $buyRequest = $productHelper->addParamsToBuyRequest($buyRequest, $params);
            if ($buyRequest->hasData()) {
                $items[$id] = $buyRequest->toArray();
            }
        }
        return $items;
    }

    /**
     * @return $this
     */
    protected function _reloadQuote()
    {
        $id = $this->_getQuote()->getId();
        $this->_getQuote()->load($id);
        return $this;
    }

    /**
     * Acl check for admin
     *
     * @return bool
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed($this->_getAclResource());
    }

    /**
     * Get acl resource
     *
     * @return string
     */
    protected function _getAclResource()
    {
        $action = strtolower($this->getRequest()->getActionName());
        if (in_array($action, ['index', 'save', 'cancel']) && $this->_getSession()->getReordered()) {
            $action = 'reorder';
        }
        switch ($action) {
            case 'index':
            case 'save':
                $aclResource = 'Magento_Sales::create';
                break;
            case 'reorder':
                $aclResource = 'Magento_Sales::reorder';
                break;
            case 'cancel':
                $aclResource = 'Magento_Sales::cancel';
                break;
            default:
                $aclResource = 'Magento_Sales::actions';
                break;
        }
        return $aclResource;
    }
}


text:
package picklesjar.pickles.ut.runtime.routine.lock;

import picklesjar.pickles.ut.recipes.sequence.ShouldBeAfter;
import picklesjar.pickles.ut.recipes.sequence.ShouldBeBefore;
import picklesjar.pickles.ut.runtime.UnitTestRuntimeFoundation;
import picklesjar.pickles.ut.runtime.routine.Routine;
import picklesjar.pickles.ut.runtime.routine.config.ConfigureRoutine;

public interface LockRoutine
	extends Routine {

	@ShouldBeAfter( ConfigureRoutine.class )
	public static String lock() {

		return UnitTestRuntimeFoundation.lock();
	}

	@ShouldBeBefore( ConfigureRoutine.class )
	public static void unlock( String key ) {

		UnitTestRuntimeFoundation.unlock( key );
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="@dimen/custom_profile_image"
    android:layout_height="@dimen/custom_profile_image"
    android:padding="2dp">

    <ImageView
        android:id="@+id/image"
        android:layout_width="@dimen/custom_profile_image"
        android:layout_height="@dimen/custom_profile_image"
        android:contentDescription="@null" />

</FrameLayout>


text:
import * as React from 'react';
import { Button } from 'react-bootstrap';

type FooterProps = {
    canGoForward: boolean;
    canGoBack: boolean;
    goForward: () => void;
    goBack: () => void;
};
export default function Footer(props: FooterProps) {
    return (

            <Button
                bsStyle="primary"
                className={props.canGoBack ? 'navbar-link' : 'navbar-link disabled'}
                onClick={() => props.goBack()}
            >

                Previous
            </Button>
            <Button
                bsStyle="primary"
                className={props.canGoForward ? 'navbar-link' : 'navbar-link disabled'}
                onClick={() => props.goForward()}
            >
                Next

            </Button>

    );
}


text:
angular
=======

Repositorio dedicado a  AngularJS


text:
<?php

namespace Cake\Validation;

/**
 * A Proxy class used to remove any extra arguments when the user intended to call
 * a method in another class that is not aware of validation providers signature
 */
class RulesProvider {

/**
 * The class to proxy, defaults to \Cake\Validation\Validation in construction
 *
 * @var object
 */
	protected $_class;

/**
 * Constructor, sets the default class to use for calling methods
 *
 * @param string $class the default class to proxy
 */
	public function __construct($class = '\Cake\Validation\Validation') {
		$this->_class = $class;
	}

/**
 * Proxies validation method calls to the Validation class, it slices
 * the arguments array to avoid passing more arguments than required to
 * the validation methods.
 *
 * @param string $method the validation method to call
 * @param array $arguments the list of arguments to pass to the method
 * @return bool whether or not the validation rule passed
 */
	public function __call($method, $arguments) {
		$arguments = array_slice($arguments, 0, -1);
		return call_user_func_array([$this->_class, $method], $arguments);
	}

}


text:
package org.apache.sshd.client.auth;

import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.auth.AbstractUserAuthMethodFactory;

/**
 * @author Apache MINA SSHD Project
 */
public abstract class AbstractUserAuthFactory
        extends AbstractUserAuthMethodFactory<ClientSession, UserAuth>
        implements UserAuthFactory {
    protected AbstractUserAuthFactory(String name) {
        super(name);
    }
}


text:
- - -

**_This project is not actively maintained. Proceed at your own risk!_**

- - -

The Instagram Ruby Gem
====================
A Ruby wrapper for the Instagram REST and Search APIs

Installation
------------
	gem install instagram

Instagram REST and Search APIs
------------------------------
Our [developer site](http://instagram.com/developer) documents all the Instagram REST and Search APIs.

Blog
----------------------------
The [Developer Blog] features news and important announcements about the Instagram Platform. You will also find tutorials and best practices to help you build great platform integrations. Make sure to subscribe to the RSS feed not to miss out on new posts: [http://developers.instagram.com](http://developers.instagram.com).

Community
----------------------
The [Stack Overflow community](http://stackoverflow.com/questions/tagged/instagram/) is a great place to ask API related questions or if you need help with your code. Make sure to tag your questions with the Instagram tag to get fast answers from other fellow developers and members of the Instagram team.

Does your project or organization use this gem?
-----------------------------------------------
Add it to the [apps](http://github.com/Instagram/instagram-ruby-gem/wiki/apps) wiki!

Sample Application
------------------

```ruby
require "sinatra"
require "instagram"

enable :sessions

CALLBACK_URL = "http://localhost:4567/oauth/callback"

Instagram.configure do |config|
  config.client_id = "YOUR_CLIENT_ID"
  config.client_secret = "YOUR_CLIENT_SECRET"
  # For secured endpoints only
  #config.client_ips = '<Comma separated list of IPs>'
end

get "/" do
  '<a href="/oauth/connect">Connect with Instagram</a>'
end

get "/oauth/connect" do
  redirect Instagram.authorize_url(:redirect_uri => CALLBACK_URL)
end

get "/oauth/callback" do
  response = Instagram.get_access_token(params[:code], :redirect_uri => CALLBACK_URL)
  session[:access_token] = response.access_token
  redirect "/nav"
end

get "/nav" do
  html =
  """
    <h1>Ruby Instagram Gem Sample Application</h1>
    <ol>
      <li><a href='/user_recent_media'>User Recent Media</a> Calls user_recent_media - Get a list of a user's most recent media</li>
      <li><a href='/user_media_feed'>User Media Feed</a> Calls user_media_feed - Get the currently authenticated user's media feed uses pagination</li>
      <li><a href='/location_recent_media'>Location Recent Media</a> Calls location_recent_media - Get a list of recent media at a given location, in this case, the Instagram office</li>
      <li><a href='/media_search'>Media Search</a> Calls media_search - Get a list of media close to a given latitude and longitude</li>
      <li><a href='/media_popular'>Popular Media</a> Calls media_popular - Get a list of the overall most popular media items</li>
      <li><a href='/user_search'>User Search</a> Calls user_search - Search for users on instagram, by name or username</li>
      <li><a href='/location_search'>Location Search</a> Calls location_search - Search for a location by lat/lng</li>
      <li><a href='/location_search_4square'>Location Search - 4Square</a> Calls location_search - Search for a location by Fousquare ID (v2)</li>
      <li><a href='/tags'>Tags</a>Search for tags, view tag info and get media by tag</li>
      <li><a href='/limits'>View Rate Limit and Remaining API calls</a>View remaining and ratelimit info.</li>
    </ol>
  """
  html
end

get "/user_recent_media" do
  client = Instagram.client(:access_token => session[:access_token])
  user = client.user
  html = "<h1>#{user.username}'s recent media</h1>"
  for media_item in client.user_recent_media
    html << "<div style='float:left;'><img src='#{media_item.images.thumbnail.url}'><br/> <a href='/media_like/#{media_item.id}'>Like</a>  <a href='/media_unlike/#{media_item.id}'>Un-Like</a>  <br/>LikesCount=#{media_item.likes[:count]}</div>"
  end
  html
end

get '/media_like/:id' do
  client = Instagram.client(:access_token => session[:access_token])
  client.like_media("#{params[:id]}")
  redirect "/user_recent_media"
end

get '/media_unlike/:id' do
  client = Instagram.client(:access_token => session[:access_token])
  client.unlike_media("#{params[:id]}")
  redirect "/user_recent_media"
end

get "/user_media_feed" do
  client = Instagram.client(:access_token => session[:access_token])
  user = client.user
  html = "<h1>#{user.username}'s media feed</h1>"

  page_1 = client.user_media_feed(777)
  page_2_max_id = page_1.pagination.next_max_id
  page_2 = client.user_recent_media(777, :max_id => page_2_max_id ) unless page_2_max_id.nil?
  html << "<h2>Page 1</h2><br/>"
  for media_item in page_1
    html << "<img src='#{media_item.images.thumbnail.url}'>"
  end
  html << "<h2>Page 2</h2><br/>"
  for media_item in page_2
    html << "<img src='#{media_item.images.thumbnail.url}'>"
  end
  html
end

get "/location_recent_media" do
  client = Instagram.client(:access_token => session[:access_token])
  html = "<h1>Media from the Instagram Office</h1>"
  for media_item in client.location_recent_media(514276)
    html << "<img src='#{media_item.images.thumbnail.url}'>"
  end
  html
end

get "/media_search" do
  client = Instagram.client(:access_token => session[:access_token])
  html = "<h1>Get a list of media close to a given latitude and longitude</h1>"
  for media_item in client.media_search("37.7808851","-122.3948632")
    html << "<img src='#{media_item.images.thumbnail.url}'>"
  end
  html
end

get "/media_popular" do
  client = Instagram.client(:access_token => session[:access_token])
  html = "<h1>Get a list of the overall most popular media items</h1>"
  for media_item in client.media_popular
    html << "<img src='#{media_item.images.thumbnail.url}'>"
  end
  html
end

get "/user_search" do
  client = Instagram.client(:access_token => session[:access_token])
  html = "<h1>Search for users on instagram, by name or usernames</h1>"
  for user in client.user_search("instagram")
    html << "<li> <img src='#{user.profile_picture}'> #{user.username} #{user.full_name}</li>"
  end
  html
end

get "/location_search" do
  client = Instagram.client(:access_token => session[:access_token])
  html = "<h1>Search for a location by lat/lng with a radius of 5000m</h1>"
  for location in client.location_search("48.858844","2.294351","5000")
    html << "<li> #{location.name} <a href='https://www.google.com/maps/preview/@#{location.latitude},#{location.longitude},19z'>Map</a></li>"
  end
  html
end

get "/location_search_4square" do
  client = Instagram.client(:access_token => session[:access_token])
  html = "<h1>Search for a location by Fousquare ID (v2)</h1>"
  for location in client.location_search("3fd66200f964a520c5f11ee3")
    html << "<li> #{location.name} <a href='https://www.google.com/maps/preview/@#{location.latitude},#{location.longitude},19z'>Map</a></li>"
  end
  html
end

get "/tags" do
  client = Instagram.client(:access_token => session[:access_token])
  html = "<h1>Search for tags, get tag info and get media by tag</h1>"
  tags = client.tag_search('cat')
  html << "<h2>Tag Name = #{tags[0].name}. Media Count =  #{tags[0].media_count}. </h2><br/><br/>"
  for media_item in client.tag_recent_media(tags[0].name)
    html << "<img src='#{media_item.images.thumbnail.url}'>"
  end
  html
end

get "/limits" do
  client = Instagram.client(:access_token => session[:access_token])
  html = "<h1/>View API Rate Limit and calls remaining</h1>"
  response = client.utils_raw_response
  html << "Rate Limit = #{response.headers[:x_ratelimit_limit]}.  <br/>Calls Remaining = #{response.headers[:x_ratelimit_remaining]}"

  html
end
```

Contributing
------------
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.

Here are some ways *you* can contribute:

* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](http://github.com/Instagram/instagram-ruby-gem/issues)
* by reviewing patches

Submitting an Issue
-------------------
We use the [GitHub issue tracker](http://github.com/Instagram/instagram-ruby-gem/issues) to track bugs and
features. Before submitting a bug report or feature request, check to make sure it hasn't already
been submitted. You can indicate support for an existing issue by voting it up. When submitting a
bug report, please include a [Gist](http://gist.github.com/) that includes a stack trace and any
details that may be necessary to reproduce the bug, including your gem version, Ruby version, and
operating system. Ideally, a bug report should include a pull request with failing specs.

Submitting a Pull Request
-------------------------
1. Fork the project.
2. Create a topic branch.
3. Implement your feature or bug fix.
4. Add documentation for your feature or bug fix.
5. Run <tt>rake doc:yard</tt>. If your changes are not 100% documented, go back to step 4.
6. Add specs for your feature or bug fix.
7. Run <tt>rake spec</tt>. If your changes are not 100% covered, go back to step 6.
8. Commit and push your changes.
9. Submit a pull request. Please do not include changes to the gemspec, version, or history file. (If you want to create your own version for some reason, please do so in a separate commit.)
10. If you haven't already, complete the Contributor License Agreement ("CLA").

Contributor License Agreement ("CLA")
_____________________________________
In order to accept your pull request, we need you to submit a CLA. You only need
to do this once to work on any of Instagram's or Facebook's open source projects.

Complete your CLA here: [https://code.facebook.com/cla](https://code.facebook.com/cla)

Copyright
---------
Copyright (c) 2014, Facebook, Inc. All rights reserved.
By contributing to Instagram Ruby Gem, you agree that your contributions will be licensed under its BSD license.
See [LICENSE](https://github.com/Instagram/instagram-ruby-gem/blob/master/LICENSE.md) for details.


text:
<!DOCTYPE html>
<html>
<head>
    <title>Example Scala.js application</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body style="margin: 0">

<div id="main">
    <form id="start-session">
        <button>Start Session</button>
    </form>
</div>

<script type="text/javascript" src="../pairing-buddy-frontend-fastopt.js"></script>
<script type="text/javascript" src="/workbench.js"></script>
<script>
    pb.frontend.PairingBuddyApp().main(document.getElementById('main'));
</script>
</body>
</html>