text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using ABus.Contracts;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;

namespace ABus.AzureServiceBus
{
    public class AzureBusTransport : IMessageTransport
    {
        public event EventHandler<RawMessage> MessageReceived;

        public event EventHandler<TransportException> ExceptionOccured;

        object topicClientLock = new object();

        public AzureBusTransport()
        {
            this.HostInstances = new Dictionary<string, TransportInstance>();
            this.CreatedTopicClients = new Dictionary<string, TopicClient>();
            this.CreatedSubscriptionClients = new Dictionary<string, SubscriptionClient>();
        }

        Dictionary<string, TransportInstance> HostInstances { get; set; }

        public void ConfigureHost(TransportDefinition transport)
        {
            if (!this.HostInstances.ContainsKey(transport.Uri))
            {
                var hostInstance = new TransportInstance { Uri = transport.Uri, Credentials = transport.Credentials };
                var ns = NamespaceManager.CreateFromConnectionString(hostInstance.ConnectionString);
                hostInstance.Namespace = ns;
                hostInstance.Definition = transport;

                this.HostInstances.Add(transport.Uri, hostInstance);
            }
        }

        public Task DeleteQueueAsync(QueueEndpoint endpoint)
        {
            return this.HostInstances[endpoint.Host].Namespace.DeleteTopicAsync(endpoint.Name);
        }

        public async Task CreateQueueAsync(QueueEndpoint endpoint)
        {
            var host = this.HostInstances[endpoint.Host];
            var topicDescription = new TopicDescription(endpoint.Name);

            // Create the topic
            await host.Namespace.CreateTopicAsync(topicDescription);

            // If an audit enabled create a subscription to forward all mesages to the audit queue
            // Ensure we dont try to audit the audit queue!!
            if (host.EnableAuditing && endpoint.Name != host.AuditQueue)
            {
                var subscriptionConfig = new SubscriptionDescription(endpoint.Name, "Audit")
                {
                    ForwardTo = host.AuditQueue
                };
                await host.Namespace.CreateSubscriptionAsync(subscriptionConfig);
            }
            else
            {
                // When creating the audit queue, a default subscription is needed to hold the messages
                var subscriptionConfig = new SubscriptionDescription(endpoint.Name, "log")
        {
                    LockDuration = TimeSpan.FromSeconds(300), // 5 mins
                    EnableDeadLetteringOnMessageExpiration = true,
                    EnableDeadLetteringOnFilterEvaluationExceptions = true,
                };
                host.Namespace.CreateSubscriptionAsync(subscriptionConfig).Wait();
            }
        }

        public void Publish(QueueEndpoint endpoint, RawMessage message)
        {
            //var client = this.GetTopicClient(endpoint.Name);
        }

        public void Send(QueueEndpoint endpoint, RawMessage message)
        {
            this.SendAsync(endpoint, message).Wait();
        }

        public void Send(QueueEndpoint endpoint, IEnumerable<RawMessage> message)
        {
            this.SendAsync(endpoint, message).Wait();
        }

        public async Task SendAsync(QueueEndpoint endpoint, IEnumerable<RawMessage> messages)
        {
            var client = this.GetTopicClient(endpoint);

            var waitingTasks = new List<Task>();
            foreach(var raw in messages)
                waitingTasks.Add(client.SendAsync(this.ConvertToBrokeredMessage(raw)));

            await Task.WhenAll(waitingTasks.ToArray()).ConfigureAwait(false);
        }

        public async Task SendAsync(QueueEndpoint endpoint, RawMessage message)
        {
            var client = this.GetTopicClient(endpoint);

            var brokeredMessage = this.ConvertToBrokeredMessage(message);
            await client.SendAsync(brokeredMessage).ConfigureAwait(false);
        }

        public async Task SubscribeAsync(QueueEndpoint endpoint, string subscriptionName)
        {
            var client = await this.GetSubscriptionClient(endpoint, subscriptionName);

            // Configure the callback options
            var options = new OnMessageOptions
            {
                AutoComplete = false,
                AutoRenewTimeout = TimeSpan.FromMinutes(1),
                MaxConcurrentCalls = 10,
            };
            client.PrefetchCount = 100;
            client.OnMessageAsync(async message =>
            {
                TransportException transportException = null;
                bool shouldAbandon = false;
                try
                {
                    RawMessage rawMessage = null;
                    // publish the message to the lister
                    if (this.MessageReceived != null)
                    {
                        var source = string.Format("{0}:{1}", endpoint.Name, subscriptionName);
                        rawMessage = this.ConvertFromBrokeredMessage(message);
                        this.MessageReceived(source, rawMessage);
                    }

                    if (rawMessage.MetaData.Contains(StandardMetaData.ShouldDeadLetterMessage))
                    {
                        // Move message to dead letter queue
                        this.UpdateMessageMetaData(message, rawMessage);
                        await message.DeadLetterAsync(message.Properties);
                    }
                    else
                    // Remove message from subscription
                        await message.CompleteAsync();

                }
                catch (Exception ex)
                {
                    // Capture the exception that has occured so that it can be evented out
                    transportException = new TransportException("OnMessage pump", ex);
                    // Indicates a problem, unlock message in subscription
                    shouldAbandon = true;
                }

                if (shouldAbandon)
                {
                    // Abandon the message first
                    await message.AbandonAsync();
                    // Now event the exception
                    if (this.ExceptionOccured != null && transportException != null)
                        this.ExceptionOccured(this, transportException);
                }

            }, options);
        }

        void UpdateMessageMetaData(BrokeredMessage message, RawMessage rawMessage)
        {
            foreach(var m in rawMessage.MetaData)
                if(!message.Properties.ContainsKey(m.Name) && m.Name != StandardMetaData.ShouldDeadLetterMessage)
                    message.Properties.Add(m.Name, m.Value);

        }

        Dictionary<string, TopicClient> CreatedTopicClients { get; set; }
        Dictionary<string, SubscriptionClient> CreatedSubscriptionClients { get; set; }

        /// <summary>
        /// A queue as used with Azure Service Bus is a topic which allows for a pub/sub model on a queue
        /// </summary>
        /// <param name="topic"></param>
        TopicClient GetTopicClient(QueueEndpoint endpoint)
        {
            var host = this.HostInstances[endpoint.Host];
            var ns = host.Namespace;
            var topic = endpoint.Name;

            // As topic clients are not created during startup its possible for
            // multiple threads to request the same topic client while its being obtained.
            // There will be a tempory slow down when a new topic client is requested for the first time.
            // However this should not be noticable for most systems.
            lock (topicClientLock)
            {
                if (!this.CreatedTopicClients.ContainsKey(topic))
                {
                    if (!ns.TopicExists(topic))
                    {
                        try
                        {
                        ns.CreateTopic(topic);
                        }
                        catch (MessagingEntityAlreadyExistsException)
                        {
                            // Case when topic is created by external process
                        }
                    }

                    var topicClient = TopicClient.CreateFromConnectionString(host.ConnectionString, topic);

                    this.CreatedTopicClients.Add(topic, topicClient);
                }
            }
            // return the topic client that has been stored
            return this.CreatedTopicClients[topic];
        }

        async Task<SubscriptionClient> GetSubscriptionClient(QueueEndpoint endpoint, string subscription)
        {
            var host = this.HostInstances[endpoint.Host];
            var ns = host.Namespace;

            var topic = endpoint.Name;

            SubscriptionClient subscriptionClient;
            if (!this.CreatedSubscriptionClients.TryGetValue(subscription, out subscriptionClient))
            {
                if (!ns.TopicExists(topic))
                    throw new ArgumentException(string.Format("Unable to subscribe to topic {0} as it does not exist.", topic));

                // Now check if the subscription already exists if not create it
                if (!ns.SubscriptionExists(topic, subscription))
                {
                    var subscriptionConfig = new SubscriptionDescription(topic, subscription)
                    {
                        DefaultMessageTimeToLive = TimeSpan.FromSeconds(86400), // 24hrs
                        LockDuration = TimeSpan.FromSeconds(300), // 5 mins
                        EnableDeadLetteringOnMessageExpiration = true,
                        EnableDeadLetteringOnFilterEvaluationExceptions = true,
                        //ForwardDeadLetteredMessagesTo = errorQueue,
                    };
                    await ns.CreateSubscriptionAsync(subscriptionConfig).ConfigureAwait(false);
                }

                subscriptionClient = SubscriptionClient.CreateFromConnectionString(host.ConnectionString, topic, subscription, ReceiveMode.PeekLock);

                this.CreatedSubscriptionClients.Add(subscription, subscriptionClient);
            }

            // return the topic client that has been stored
            return subscriptionClient;
        }

        BrokeredMessage ConvertToBrokeredMessage(RawMessage rawMessage)
        {
            var bm = new BrokeredMessage(new MemoryStream(rawMessage.Body), true);
            foreach (var m in rawMessage.MetaData)
            {
                if (m.Name != StandardMetaData.ContentType)
                    bm.Properties.Add(m.Name, m.Value);
            }

            // Transfer system properties
            bm.MessageId = rawMessage.MessageId;
            bm.CorrelationId = rawMessage.CorrelationId;
            bm.ContentType = rawMessage.MetaData[StandardMetaData.ContentType].Value;

            return bm;
        }

        RawMessage ConvertFromBrokeredMessage(BrokeredMessage brokeredMessage)
        {
            var msg = new RawMessage();
            msg.MessageId = brokeredMessage.MessageId;
            msg.CorrelationId = brokeredMessage.CorrelationId;
            if(brokeredMessage.ContentType != null)
                msg.MetaData.Add(new MetaData{Name = StandardMetaData.ContentType, Value = brokeredMessage.ContentType});

            // Transfer meta data
            foreach(var p in brokeredMessage.Properties)
                msg.MetaData.Add(new MetaData{Name = p.Key, Value = p.Value as string});

            using (var stream = brokeredMessage.GetBody<Stream>())
            {
                var buffer = new byte[stream.Length];
                stream.Read(buffer, 0, (int)stream.Length);

                // assign to message
                msg.Body = buffer;
            }

            return msg;
        }

        public Task<bool> QueueExistsAsync(QueueEndpoint endpoint)
        {
            return this.HostInstances[endpoint.Host].Namespace.TopicExistsAsync(endpoint.Name);
        }

        public Task DeferAsync(QueueEndpoint endpoint, RawMessage message, TimeSpan timeToDelay)
        {
            throw new NotImplementedException();
        }
    }
}


text:
extern crate build;
fn main() {
    build::link("shlwapi", true)
}

redpajama_set_name: RedPajamaGithub


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__int_zero_divide_45.c
Label Definition File: CWE369_Divide_by_Zero__int.label.xml
Template File: sources-sinks-45.tmpl.c
*/
/*
 * @description
 * CWE: 369 Divide by Zero
 * BadSource: zero Fixed value of zero
 * GoodSource: Non-zero
 * Sinks: divide
 *    GoodSink: Check for zero before dividing
 *    BadSink : Divide a constant by data
 * Flow Variant: 45 Data flow: data passed as a static global variable from one function to another in the same source file
 *
 * */

#include "std_testcase.h"

static int CWE369_Divide_by_Zero__int_zero_divide_45_badData;
static int CWE369_Divide_by_Zero__int_zero_divide_45_goodG2BData;
static int CWE369_Divide_by_Zero__int_zero_divide_45_goodB2GData;

#ifndef OMITBAD

static void badSink()
{
    int data = CWE369_Divide_by_Zero__int_zero_divide_45_badData;
    /* POTENTIAL FLAW: Possibly divide by zero */
    printIntLine(100 / data);
}

void CWE369_Divide_by_Zero__int_zero_divide_45_bad()
{
    int data;
    /* Initialize data */
    data = -1;
    /* POTENTIAL FLAW: Set data to zero */
    data = 0;
    CWE369_Divide_by_Zero__int_zero_divide_45_badData = data;
    badSink();
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2BSink()
{
    int data = CWE369_Divide_by_Zero__int_zero_divide_45_goodG2BData;
    /* POTENTIAL FLAW: Possibly divide by zero */
    printIntLine(100 / data);
}

static void goodG2B()
{
    int data;
    /* Initialize data */
    data = -1;
    /* FIX: Use a value not equal to zero */
    data = 7;
    CWE369_Divide_by_Zero__int_zero_divide_45_goodG2BData = data;
    goodG2BSink();
}

/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2GSink()
{
    int data = CWE369_Divide_by_Zero__int_zero_divide_45_goodB2GData;
    /* FIX: test for a zero denominator */
    if( data != 0 )
    {
        printIntLine(100 / data);
    }
    else
    {
        printLine("This would result in a divide by zero");
    }
}

static void goodB2G()
{
    int data;
    /* Initialize data */
    data = -1;
    /* POTENTIAL FLAW: Set data to zero */
    data = 0;
    CWE369_Divide_by_Zero__int_zero_divide_45_goodB2GData = data;
    goodB2GSink();
}

void CWE369_Divide_by_Zero__int_zero_divide_45_good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE369_Divide_by_Zero__int_zero_divide_45_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE369_Divide_by_Zero__int_zero_divide_45_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using EnvDTE;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell.Interop;
using Moq;
using Xunit;

namespace Clide
{
	public class ServiceLocatorExtensionsSpec
	{
		[Fact]
		public void when_getting_typed_export_then_succeeds ()
		{
			var container = new CompositionContainer(new TypeCatalog(typeof(Foo)));
			var locator = new ServiceLocatorImpl(Mock.Of<IServiceProvider>(), new Lazy<ExportProvider>(() => container));

			var foo = locator.GetExport<Foo>();

			Assert.NotNull (foo);
		}

		[Fact]
		public void when_getting_typed_export_with_metadata_then_succeeds ()
		{
			var container = new CompositionContainer(new TypeCatalog(typeof(Foo)));
			var locator = new ServiceLocatorImpl(Mock.Of<IServiceProvider>(), new Lazy<ExportProvider>(() => container));

			var foo = locator.GetExport<Foo, IFooMetadata>();

			Assert.NotNull (foo);
			Assert.Equal ("asdf", foo.Metadata.Id);
		}

		[Fact]
		public void when_getting_typed_export_with_metadata_dictionary_then_succeeds ()
		{
			var container = new CompositionContainer(new TypeCatalog(typeof(Foo)));
			var locator = new ServiceLocatorImpl(Mock.Of<IServiceProvider>(), new Lazy<ExportProvider>(() => container));

			var foo = locator.GetExport<Foo, IDictionary<string, object>>();

			Assert.NotNull (foo);
			Assert.Equal ("asdf", foo.Metadata["Id"]);
		}

		[Fact]
		public void when_getting_typed_exports_then_succeeds ()
		{
			var container = new CompositionContainer(new TypeCatalog(typeof(Foo)));
			var locator = new ServiceLocatorImpl(Mock.Of<IServiceProvider>(), new Lazy<ExportProvider>(() => container));

			var foo = locator.GetExports<Foo>().FirstOrDefault();

			Assert.NotNull (foo);
		}

		[Fact]
		public void when_getting_typed_exports_with_metadata_then_succeeds ()
		{
			var container = new CompositionContainer(new TypeCatalog(typeof(Foo)));
			var locator = new ServiceLocatorImpl(Mock.Of<IServiceProvider>(), new Lazy<ExportProvider>(() => container));

			var foo = locator.GetExports<Foo, IFooMetadata>().FirstOrDefault();

			Assert.NotNull (foo);
			Assert.Equal ("asdf", foo.Metadata.Id);
		}

		[Fact]
		public void when_getting_typed_exports_with_metadata_dictionary_then_succeeds ()
		{
			var container = new CompositionContainer(new TypeCatalog(typeof(Foo)));
			var locator = new ServiceLocatorImpl(Mock.Of<IServiceProvider>(), new Lazy<ExportProvider>(() => container));

			var foo = locator.GetExports<Foo, IDictionary<string, object>>().FirstOrDefault();

			Assert.NotNull (foo);
			Assert.Equal ("asdf", foo.Metadata["Id"]);
		}

		[Fact]
		public void when_retrieving_service_then_invokes_service_provider ()
		{
			var locator = new ServiceLocatorImpl (
				Mock.Of<IServiceProvider>(x => x.GetService(typeof(Foo)) == new Foo()),
				new Lazy<ExportProvider>(() => Mock.Of<ExportProvider>()));

			var foo = locator.GetService(typeof(Foo));

			Assert.NotNull (foo);
		}

		[Fact]
		public void when_getting_locator_from_service_provider_then_retrieves_from_provider_component ()
		{
			var services = Mock.Of<IServiceProvider>(s => s.GetService(typeof(SComponentModel)) ==
				Mock.Of<IComponentModel>(c => c.GetService<IServiceLocatorProvider>() ==
					new Mock<IServiceLocatorProvider> { DefaultValue = DefaultValue.Mock }.Object));

			var locator = services.GetServiceLocator();

			Assert.NotNull (locator);
		}

		[Fact]
		public void when_getting_locator_from_null_service_provider_then_throws ()
		{
			Assert.Throws<ArgumentNullException> (() => ((IServiceProvider)null).GetServiceLocator ());
		}

		[Fact]
		public void when_getting_locator_from_null_dte_then_throws ()
		{
			Assert.Throws<ArgumentNullException> (() => ((DTE)null).GetServiceLocator ());
		}

		[Fact]
		public void when_getting_locator_from_null_project_then_throws ()
		{
			Assert.Throws<ArgumentNullException> (() => ((Project)null).GetServiceLocator ());
		}

		[Fact]
		public void when_getting_locator_from_null_vsproject_then_throws ()
		{
			Assert.Throws<ArgumentNullException> (() => ((IVsProject)null).GetServiceLocator ());
		}

		[Fact]
		public void when_getting_locator_from_null_vshierarchy_then_throws ()
		{
			Assert.Throws<ArgumentNullException> (() => ((IVsHierarchy)null).GetServiceLocator ());
		}
	}
}


text:
package org.optaplanner.examples.coachshuttlegathering.domain;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamInclude;
import org.optaplanner.examples.coachshuttlegathering.domain.location.RoadLocation;
import org.optaplanner.examples.common.domain.AbstractPersistable;

@XStreamAlias("CsgBus")
@XStreamInclude({
        Coach.class,
        Shuttle.class
})
public abstract class Bus extends AbstractPersistable implements BusOrStop {

    protected String name;
    protected RoadLocation departureLocation;
    protected int capacity;
    protected int mileageCost;

    // Shadow variables
    protected BusStop nextStop;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public RoadLocation getDepartureLocation() {
        return departureLocation;
    }

    public void setDepartureLocation(RoadLocation departureLocation) {
        this.departureLocation = departureLocation;
    }

    public int getCapacity() {
        return capacity;
    }

    public void setCapacity(int capacity) {
        this.capacity = capacity;
    }

    public int getMileageCost() {
        return mileageCost;
    }

    public void setMileageCost(int mileageCost) {
        this.mileageCost = mileageCost;
    }

    @Override
    public BusStop getNextStop() {
        return nextStop;
    }

    @Override
    public void setNextStop(BusStop nextStop) {
        this.nextStop = nextStop;
    }

    // ************************************************************************
    // Complex methods
    // ************************************************************************

    public abstract int getSetupCost();

    @Override
    public RoadLocation getLocation() {
        return departureLocation;
    }

    @Override
    public Bus getBus() {
        return this;
    }

    public abstract int getDistanceFromTo(RoadLocation sourceLocation, RoadLocation targetLocation);

    public abstract int getDurationFromTo(RoadLocation sourceLocation, RoadLocation targetLocation);

    public abstract StopOrHub getDestination();

    @Override
    public String toString() {
        return name;
    }

}


text:
/*
htop - ColumnsPanel.c
(C) 2004-2015 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/

#include "MainPanel.h"
#include "Process.h"
#include "Platform.h"
#include "CRT.h"

#include <stdlib.h>

/*{
#include "Panel.h"
#include "Action.h"
#include "Settings.h"

typedef struct MainPanel_ {
   Panel super;
   State* state;
   IncSet* inc;
   Htop_Action *keys;
   pid_t pidSearch;
} MainPanel;

typedef bool(*MainPanel_ForeachProcessFn)(Process*, size_t);

#define MainPanel_getFunctionBar(this_) (((Panel*)(this_))->defaultBar)

}*/

static const char* MainFunctions[]  = {"Help  ", "Setup ", "Search", "Filter", "Tree  ", "SortBy", "Nice -", "Nice +", "Kill  ", "Quit  ", NULL};

void MainPanel_updateTreeFunctions(MainPanel* this, bool mode) {
   FunctionBar* bar = MainPanel_getFunctionBar(this);
   if (mode) {
      FunctionBar_setLabel(bar, KEY_F(5), "Sorted");
      FunctionBar_setLabel(bar, KEY_F(6), "Collap");
   } else {
      FunctionBar_setLabel(bar, KEY_F(5), "Tree  ");
      FunctionBar_setLabel(bar, KEY_F(6), "SortBy");
   }
}

void MainPanel_pidSearch(MainPanel* this, int ch) {
   Panel* super = (Panel*) this;
   pid_t pid = ch-48 + this->pidSearch;
   for (int i = 0; i < Panel_size(super); i++) {
      Process* p = (Process*) Panel_get(super, i);
      if (p && p->pid == pid) {
         Panel_setSelected(super, i);
         break;
      }
   }
   this->pidSearch = pid * 10;
   if (this->pidSearch > 10000000) {
      this->pidSearch = 0;
   }
}

static HandlerResult MainPanel_eventHandler(Panel* super, int ch) {
   MainPanel* this = (MainPanel*) super;

   HandlerResult result = IGNORED;

   Htop_Reaction reaction = HTOP_OK;

   if (EVENT_IS_HEADER_CLICK(ch)) {
      int x = EVENT_HEADER_CLICK_GET_X(ch);
      ProcessList* pl = this->state->pl;
      Settings* settings = this->state->settings;
      int hx = super->scrollH + x + 1;
      ProcessField field = ProcessList_keyAt(pl, hx);
      if (field == settings->sortKey) {
         Settings_invertSortOrder(settings);
         settings->treeView = false;
      } else {
         reaction |= Action_setSortKey(settings, field);
      }
      reaction |= HTOP_RECALCULATE | HTOP_REDRAW_BAR | HTOP_SAVE_SETTINGS;
      result = HANDLED;
   } else if (ch != ERR && this->inc->active) {
      bool filterChanged = IncSet_handleKey(this->inc, ch, super, (IncMode_GetPanelValue) MainPanel_getValue, NULL);
      if (this->inc->found) {
         reaction |= Action_follow(this->state);
      }
      if (filterChanged) {
         this->state->pl->incFilter = IncSet_filter(this->inc);
         reaction = HTOP_REFRESH | HTOP_REDRAW_BAR;
      }
      reaction |= HTOP_KEEP_FOLLOWING;
      result = HANDLED;
   } else if (ch == 27) {
      return HANDLED;
   } else if (ch != ERR && ch > 0 && ch < KEY_MAX && this->keys[ch]) {
      reaction |= (this->keys[ch])(this->state);
      result = HANDLED;
   } else if (isdigit(ch)) {
      MainPanel_pidSearch(this, ch);
   } else {
      if (ch != ERR) {
         this->pidSearch = 0;
      } else {
         reaction |= HTOP_KEEP_FOLLOWING;
      }
   }

   if (reaction & HTOP_REDRAW_BAR) {
      MainPanel_updateTreeFunctions(this, this->state->settings->treeView);
      IncSet_drawBar(this->inc);
   }
   if (reaction & HTOP_UPDATE_PANELHDR) {
      ProcessList_printHeader(this->state->pl, Panel_getHeader(super));
   }
   if (reaction & HTOP_REFRESH) {
      result |= REDRAW;
   }
   if (reaction & HTOP_RECALCULATE) {
      result |= RESCAN;
   }
   if (reaction & HTOP_SAVE_SETTINGS) {
      this->state->settings->changed = true;
   }
   if (reaction & HTOP_QUIT) {
      return BREAK_LOOP;
   }
   if (!(reaction & HTOP_KEEP_FOLLOWING)) {
      this->state->pl->following = -1;
      Panel_setSelectionColor(super, CRT_colors[PANEL_SELECTION_FOCUS]);
   }
   return result;
}

int MainPanel_selectedPid(MainPanel* this) {
   Process* p = (Process*) Panel_getSelected((Panel*)this);
   if (p) {
      return p->pid;
   }
   return -1;
}

const char* MainPanel_getValue(MainPanel* this, int i) {
   Process* p = (Process*) Panel_get((Panel*)this, i);
   if (p)
      return p->comm;
   return "";
}

bool MainPanel_foreachProcess(MainPanel* this, MainPanel_ForeachProcessFn fn, size_t arg, bool* wasAnyTagged) {
   Panel* super = (Panel*) this;
   bool ok = true;
   bool anyTagged = false;
   for (int i = 0; i < Panel_size(super); i++) {
      Process* p = (Process*) Panel_get(super, i);
      if (p->tag) {
         ok = fn(p, arg) && ok;
         anyTagged = true;
      }
   }
   if (!anyTagged) {
      Process* p = (Process*) Panel_getSelected(super);
      if (p) ok = fn(p, arg) && ok;
   }
   if (wasAnyTagged)
      *wasAnyTagged = anyTagged;
   return ok;
}

PanelClass MainPanel_class = {
   .super = {
      .extends = Class(Panel),
      .delete = MainPanel_delete
   },
   .eventHandler = MainPanel_eventHandler
};

MainPanel* MainPanel_new() {
   MainPanel* this = AllocThis(MainPanel);
   Panel_init((Panel*) this, 1, 1, 1, 1, Class(Process), false, FunctionBar_new(MainFunctions, NULL, NULL));
   this->keys = xCalloc(KEY_MAX, sizeof(Htop_Action));
   this->inc = IncSet_new(MainPanel_getFunctionBar(this));

   Action_setBindings(this->keys);
   Platform_setBindings(this->keys);

   return this;
}

void MainPanel_setState(MainPanel* this, State* state) {
   this->state = state;
}

void MainPanel_delete(Object* object) {
   Panel* super = (Panel*) object;
   MainPanel* this = (MainPanel*) object;
   Panel_done(super);
   IncSet_delete(this->inc);
   free(this->keys);
   free(this);
}


text:
/**
 * Expose the enumerateDevices function.
 */
module.exports = enumerateDevices;

/**
 * Dependencies.
 */
var
	debug = require('debug')('iosrtc:enumerateDevices'),
	exec = require('cordova/exec'),
	MediaDeviceInfo = require('./MediaDeviceInfo'),
	Errors = require('./Errors');

function enumerateDevices() {

	// Detect callback usage to assist 5.0.1 to 5.0.2 migration
	// TODO remove on 6.0.0
	Errors.detectDeprecatedCallbaksUsage('cordova.plugins.iosrtc.enumerateDevices', arguments);

	return new Promise(function (resolve) {
		function onResultOK(data) {
			debug('enumerateDevices() | success');
			resolve(getMediaDeviceInfos(data.devices));
		}

		exec(onResultOK, null, 'iosrtcPlugin', 'enumerateDevices', []);
	});
}

/**
 * Private API.
 */

function getMediaDeviceInfos(devices) {
	debug('getMediaDeviceInfos() | [devices:%o]', devices);

	var id,
		mediaDeviceInfos = [];

	for (id in devices) {
		if (devices.hasOwnProperty(id)) {
			mediaDeviceInfos.push(new MediaDeviceInfo(devices[id]));
		}
	}

	return mediaDeviceInfos;
}


text:
package com.facebook.buck.zip;

import com.facebook.buck.io.MoreFiles;
import com.facebook.buck.io.MorePosixFilePermissions;
import com.facebook.buck.io.ProjectFilesystem;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Enumeration;
import java.util.Set;

public class Unzip {

  /** Utility class: do not instantiate. */
  private Unzip() {}

  public enum ExistingFileMode {
    OVERWRITE,
    OVERWRITE_AND_CLEAN_DIRECTORIES,
  }

  /**
   * Unzips a file to a destination and returns the paths of the written files.
   */
  public static ImmutableList<Path> extractZipFile(
      Path zipFile,
      ProjectFilesystem filesystem,
      ExistingFileMode existingFileMode) throws IOException {

    ImmutableList.Builder<Path> filesWritten = ImmutableList.builder();
    try (ZipFile zip = new ZipFile(zipFile.toFile())) {
      Enumeration<ZipArchiveEntry> entries = zip.getEntries();
      while (entries.hasMoreElements()) {
        ZipArchiveEntry entry = entries.nextElement();
        String fileName = entry.getName();
        Path target = Paths.get(fileName);
        if (filesystem.exists(target)) {
          switch (existingFileMode) {
            case OVERWRITE:
              // Unpack the file or directory as usual, overwriting the file.
              break;
            case OVERWRITE_AND_CLEAN_DIRECTORIES:
              // Delete the file or directory before unpacking it.
              filesystem.deleteRecursivelyIfExists(target);
              break;
          }
        }

        // TODO(mbolin): Keep track of which directories have already been written to avoid
        // making unnecessary Files.createDirectories() calls. In practice, a single zip file will
        // have many entries in the same directory.

        if (entry.isDirectory()) {
          // Create the directory and all its parent directories
          filesystem.mkdirs(target);
        } else {
          // Create parent folder
          filesystem.createParentDirs(target);

          filesWritten.add(filesystem.resolve(target));
          // Write file
          try (OutputStream out = filesystem.newFileOutputStream(target)) {
            ByteStreams.copy(zip.getInputStream(entry), out);
          }

          // TODO(simons): Implement what the comment below says we should do.
          //
          // Sets the file permissions of the output file given the information in {@code entry}'s
          // extra data field. According to the docs at
          // http://www.opensource.apple.com/source/zip/zip-6/unzip/unzip/proginfo/extra.fld there
          // are two extensions that might support file permissions: Acorn and ASi UNIX. We shall
          // assume that inputs are not from an Acorn SparkFS. The relevant section from the docs:
          //
          //

          //    The following is the layout of the ASi extra block for Unix.  The
          //    local-header and central-header versions are identical.
          //    (Last Revision 19960916)
          //
          //    Value         Size        Description
          //    -----         ----        -----------
          //   (Unix3) 0x756e        Short       tag for this extra block type ("nu")
          //   TSize         Short       total data size for this block
          //   CRC           Long        CRC-32 of the remaining data
          //   Mode          Short       file permissions
          //   SizDev        Long        symlink'd size OR major/minor dev num
          //   UID           Short       user ID
          //   GID           Short       group ID
          //   (var.)        variable    symbolic link filename
          //
          //   Mode is the standard Unix st_mode field from struct stat, containing
          //   user/group/other permissions, setuid/setgid and symlink info, etc.
          //

          //
          // From the stat man page, we see that the following mask values are defined for the file
          // permissions component of the st_mode field:
          //
          //

          //   S_ISUID   0004000   set-user-ID bit
          //   S_ISGID   0002000   set-group-ID bit (see below)
          //   S_ISVTX   0001000   sticky bit (see below)
          //
          //   S_IRWXU     00700   mask for file owner permissions
          //
          //   S_IRUSR     00400   owner has read permission
          //   S_IWUSR     00200   owner has write permission
          //   S_IXUSR     00100   owner has execute permission
          //
          //   S_IRWXG     00070   mask for group permissions
          //   S_IRGRP     00040   group has read permission
          //   S_IWGRP     00020   group has write permission
          //   S_IXGRP     00010   group has execute permission
          //
          //   S_IRWXO     00007   mask for permissions for others
          //   (not in group)
          //   S_IROTH     00004   others have read permission
          //   S_IWOTH     00002   others have write permission
          //   S_IXOTH     00001   others have execute permission
          //

          //
          // For the sake of our own sanity, we're going to assume that no-one is using symlinks,
          // but we'll check and throw if they are.
          //
          // Before we do anything, we should check the header ID. Pfft!
          //
          // Having jumped through all these hoops, it turns out that InfoZIP's "unzip" store the
          // values in the external file attributes of a zip entry (found in the zip's central
          // directory) assuming that the OS creating the zip was one of an enormous list that
          // includes UNIX but not Windows, it first searches for the extra fields, and if not found
          // falls through to a code path that supports MS-DOS and which stores the UNIX file
          // attributes in the upper 16 bits of the external attributes field.
          //
          // We'll support neither approach fully, but we encode whether this file was executable
          // via storing 0100 in the fields that are typically used by zip implementations to store
          // POSIX permissions. If we find it was executable, use the platform independent java
          // interface to make this unpacked file executable.

          Set<PosixFilePermission> permissions =
              MorePosixFilePermissions.fromMode(entry.getExternalAttributes() >> 16);
          if (permissions.contains(PosixFilePermission.OWNER_EXECUTE)) {
            MoreFiles.makeExecutable(filesystem.resolve(target).toFile());
          }

        }
      }
    }
    return filesWritten.build();
  }

  public static ImmutableList<Path> extractZipFile(
      Path zipFile,
      Path destination,
      ExistingFileMode existingFileMode) throws IOException {
    // Create output directory if it does not exist
    Files.createDirectories(destination);
    return extractZipFile(zipFile, new ProjectFilesystem(destination), existingFileMode);
  }

}


text:
copyright:
  years: 2016, 2017
lastupdated: "2017-02-07"

---

{:new_window: target="_blank"}
{:codeblock: .codeblock}

# Utilisation de Dynatrace
{: #using_dynatrace}

Dynatrace est un service tiers qui offre une fonction de surveillance pour votre appli.

Pour plus d'informations sur les fonctions offertes par le service Dynatrace, voir [Dynatrace Application Monitoring](http://www.dynatrace.com/en/products/application-monitoring.html).

Si votre application est configurée pour utiliser Dynatrace, par défaut, l'environnement d'exécution Liberty acquiert un fichier JAR d'agent Dynatrace à partir d'un site Dynatrace et exécute l'agent Dynatrace avec votre application. Avec ce comportement par défaut, la configuration minimale nécessaire pour utiliser Dynatrace consiste à créer un service fourni par l'utilisateur qui pointe vers votre collecteur Dynatrace.

## Création d'un service fourni par l'utilisateur qui pointe vers votre collecteur Dynatrace

Tout d'abord, vous devez configurez un collecteur Dynatrace.  Ensuite, vous devez créer un service fourni par l'utilisateur afin de transmettre des informations qui permettront à l'agent Dynatrace de se connecter au collecteur Dynatrace. Pour mieux comprendre la relation entre les composants Dynatrace, voir [Dynatrace Architecture](https://community.dynatrace.com/community/display/DOCDT63/Architecture).

1. Configurez un collecteur Dynatrace.
  * Pour obtenir les instructions relatives au téléchargement et à la configuration du collecteur Dynatrace, voir le [site Web Dynatrace](https://community.dynatrace.com/community/display/EVAL/Step+3+-+Connect+Agent+to+Dynatrace).
  * Vérifiez que le collecteur est configuré dans un emplacement accessible pour l'agent Dynatrace qui s'exécute avec votre appli dans Bluemix.
2. Créez un service fourni par l'utilisateur qui pointe vers le collecteur Dynatrace en cours d'exécution. **REMARQUE** Le nom du service fourni par l'utilisateur doit contenir la chaîne **dynatrace**.
Peu importe la casse des caractères. Par exemple, utilisez la commande suivante, dans laquelle **my-dynatrace-collector** contient **dynatrace** :

        $ cf cups my-dynatrace-collector -p '{"server":"DynatraceCollectorIPaddress","profile":"Monitoring"}'
        {: codeblock}

    Dans cet exemple, my-dynatrace-collector est le nom donné au service, DynatraceCollectorIPaddress est l'adresse IP du collecteur Dynatrace que vous avez configuré et le paramètre profile fait référence au nom de profil Dynatrace facultatif associé à cette application surveillée.
La valeur par défaut de profile est Monitoring. Vous pouvez spécifier des paramètres optionnels, comme dans l'exemple suivant :

        $ cf cups my-dynatrace-collector -p '{"server":"DynatraceCollectorIPaddress","profile":"Monitoring",
                                              "options" : {"param-dynatrace-1": "valeur",
                                                           "param-dynatrace-2": "valeur"}}'
        {: codeblock}

    Pour plus d'informations sur les options disponibles, voir [Agent Setting section of Agent Configuration](https://community.dynatrace.com/community/display/DOCDT62/Agent+Configuration) sur le site Web de la communauté Dynatrace. Par exemple, vous pouvez utiliser l'option exclude pour exclure des classes de la surveillance par Dynatrace. Pour plus d'informations sur la configuration du service fourni par l'utilisateur, voir [DynaTrace Agent Framework](https://github.com/cloudfoundry/ibm-websphere-liberty-buildpack/blob/master/docs/framework-dynatrace-agent.md).

3. Après avoir envoyé par commande push votre appli à Bluemix, associez le service fourni par l'utilisateur que vous avez créé à cette appli. Utilisez par exemple la commande suivante :

        $ cf bs myApp my-dynatrace-collector
        {: codeblock}

    **Remarque** : Vous devez reconstituer votre application après avoir associé le service.

## Configuration facultative
{: #optional_configuration}

Vous pouvez choisir d'acquérir et d'héberger vous-même le fichier JAR d'agent Dynatrace.  Dans ce cas, les étapes de configuration supplémentaires suivantes sont nécessaires.
1. Procurez-vous et hébergez le fichier JAR d'agent Dynatrace de sorte que le pack de construction Liberty puisse le télécharger.
2. Configurez votre application Liberty de sorte qu'elle puisse télécharger l'agent Dynatrace.

### Hébergement de l'agent Dynatrace
{: #hosting_dynatrace_agent}
L'agent Dynatrace doit être hébergé sur un serveur Web, et le pack de construction liberty doit pouvoir télécharger le fichier JAR d'agent à partir de ce serveur. Le serveur doit être configuré avec un fichier `index.yml` qui indique les détails concernant le fichier JAR d'agent. Pour configurer l'agent Dynatrace, procédez comme suit :
  1. Téléchargez le fichier JAR de l'agent Dynatrace. Pour obtenir les instructions relatives au téléchargement du fichier JAR de l'agent Dynatrace, voir [Dynatrace Server Platform Installers](https://community.dynatrace.com/community/display/EVAL/Step+1+-+Download+and+install+Dynatrace) sur le site Web de la communauté Dynatrace. Le fichier JAR d'agent approprié pour une exécution sur Bluemix est **dynatrace-agent-unix.jar**, version **6.+**.
  2. Hébergez le fichier JAR d'agent dans un emplacement à partir duquel le pack de construction Liberty peut le télécharger. Vous pouvez l'héberger directement sur Bluemix à l'aide des fonctions disponibles sur le serveur, ou vous pouvez l'héberger sur un emplacement disponible publiquement.
     * Prenez soin de fournir un fichier `index.yml` à l'emplacement d'hébergement. Le fichier `index.yml` doit contenir une entrée composée de l'ID de version du fichier JAR d'agent suivi d'un signe deux-points et de l'URL complète de l'emplacement de ce fichier JAR d'agent. Par exemple :

            ---
               6.3.0: https://my-dynatrace-agent.mybluemix.net/dynatrace-agent-6.3.0-unix.jar
            {: codeblock}

     * Le fichier **dynatrace-agent-6.3.0-unix.jar** doit être disponible à l'emplacement spécifié dans le fichier `index.yml`. L'emplacement du fichier JAR et celui du fichier `index.yml` peuvent être le même répertoire.

### Configuration de l'appli Liberty
{: #configuring_liberty_app}

L'appli Liberty que vous souhaitez surveiller doit être configurée pour localiser le serveur qui héberge le fichier JAR d'agent que vous avez précédemment configuré.
Vous pouvez configurer l'appli avec la variable d'environnement **JBP_CONFIG_DYNATRACEAPPMONAGENT**. La variable d'environnement **JBP_CONFIG_DYNATRACEAPPMONAGENT** indique au pack de construction l'emplacement à partir duquel il doit télécharger l'agent Dynatrace. Pour définir la variable d'environnement, procédez comme suit :

1. Affectez à la variable **JBP_CONFIG_DYNATRACEAPPMONAGENT** la valeur *"repository_root: URL_of_server_hosting_index.yml"*. Par exemple, après avoir envoyé par commande push votre application, exécutez la commande suivante :

        $ cf se myApp JBP_CONFIG_DYNATRACEAPPMONAGENT 'repository_root: https://my-dynatrace-agent-host.mybluemix.net'
        {: codeblock}

    Dans cet exemple, *my-dynatrace-agent-host.mybluemix.net* est l'URL du fichier `index.yml` hébergé par le serveur que vous avez précédemment configuré.

2. Après avoir défini la variable d'environnement, reconstituez votre application. Consultez le fichier journal de préproduction (staging). Il doit contenir
un message indiquant le bon déroulement du téléchargement de l'agent Dynatrace à partir du serveur sur lequel il est hébergé. Par exemple :
```
    Downloading dynatrace-agent-6.3.0-unix.jar 6.3.0 from https://my-dynatrace-agent-host.mybluemix.net/dynatrace-agent-6.3.0-unix.jar (17.8s)
```
{: codeblock}

# rellinks
{: #rellinks notoc}
## general
{: #general notoc}
* [Environnement d'exécution Liberty](index.html)
* [Présentation de Liberty Profile](http://www-01.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.wlp.nd.doc/ae/cwlp_about.html)


text:
<?php

namespace Box\Mod\Servicedomain\Api;

/**
 * Domain order management
 */
class Admin extends \Api_Abstract
{
    /**
     * Update domain service.
     * Does not send actions to domain registar. Used to sync domain details
     * on BoxBilling
     *
     * @param int $order_id - domain order id
     *
     * @optional string $ns1 - 1 Nameserver hostname, ie: ns1.mydomain.com
     * @optional string $ns2 - 2 Nameserver hostname, ie: ns2.mydomain.com
     * @optional string $ns3 - 3 Nameserver hostname, ie: ns3.mydomain.com
     * @optional string $ns4 - 4 Nameserver hostname, ie: ns4.mydomain.com
     * @optional int $period - domain registration years
     * @optional bool $privacy - flag to define if domain privacy protection is enabled/disabled
     * @optional bool $locked - flag to define if domain is locked or not
     * @optional string $transfer_code - domain EPP code
     *
     * @return boolean
     */
    public function update($data)
    {
        $s = $this->_getService($data);

        return $this->getService()->updateDomain($s, $data);
    }

    /**
     * Update domain nameservers
     *
     * @param int $order_id - domain order id
     * @param string $ns1 - 1 Nameserver hostname, ie: ns1.mydomain.com
     * @param string $ns2 - 2 Nameserver hostname, ie: ns2.mydomain.com
     *
     * @optional string $ns3 - 3 Nameserver hostname, ie: ns3.mydomain.com
     * @optional string $ns4 - 4 Nameserver hostname, ie: ns4.mydomain.com
     *
     * @return boolean
     */
    public function update_nameservers($data)
    {
        $s = $this->_getService($data);

        return $this->getService()->updateNameservers($s, $data);
    }

    /**
     * Update domain contact details
     *
     * @param int $order_id - domain order id
     * @param array $contact - Contact array must contain these fields: first_name, last_name, email, company, address1, address2, country, city, state, postcode, phone_cc, phone
     *
     * @return boolean
     */
    public function update_contacts($data)
    {
        $s = $this->_getService($data);

        return $this->getService()->updateContacts($s, $data);
    }

    /**
     * Enable domain privacy protection
     *
     * @param int $order_id - domain order id
     *
     * @return boolean
     */
    public function enable_privacy_protection($data)
    {
        $s = $this->_getService($data);

        return $this->getService()->enablePrivacyProtection($s);
    }

    /**
     * Disable domain privacy protection
     *
     * @param int $order_id - domain order id
     *
     * @return boolean
     */
    public function disable_privacy_protection($data)
    {
        $s = $this->_getService($data);

        return $this->getService()->disablePrivacyProtection($s);
    }

    /**
     * Get domain transfer code
     *
     * @param int $order_id - domain order id
     *
     * @return boolean
     */
    public function get_transfer_code($data)
    {
        $s = $this->_getService($data);

        return $this->getService()->getTransferCode($s);
    }

    /**
     * Lock domain
     *
     * @param int $order_id - domain order id
     *
     * @return boolean
     */
    public function lock($data)
    {
        $s = $this->_getService($data);

        return $this->getService()->lock($s);;
    }

    /**
     * Unlock domain
     *
     * @param int $order_id - domain order id
     *
     * @return boolean
     */
    public function unlock($data)
    {
        $s = $this->_getService($data);

        return $this->getService()->unlock($s);;
    }

    /**
     * Get paginated top level domains list
     * @return array
     */
    public function tld_get_list($data)
    {
        list($sql, $params) = $this->getService()->tldGetSearchQuery($data);
        $per_page = isset($data['per_page']) ? $data['per_page'] : $this->di['pager']->getPer_page();
        $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page);
        foreach($pager['list'] as $key => $tldArr){
            $tld = $this->di['db']->getExistingModelById('Tld', $tldArr['id'], sprintf('Tld #%s not found', $tldArr['id']));
            $pager['list'][$key] = $this->getService()->tldToApiArray($tld);
        }

        return $pager;
    }

    /**
     * Get top level domain details
     *
     * @param string $tld - top level domain, ie: .com
     *
     * @return array
     * @throws Box_Exception
     */
    public function tld_get($data)
    {
        if (!isset($data['tld'])) {
            throw new \Box_Exception('TLD is missing');
        }

        $tld = $data['tld'];
        if ($tld[0] != '.') {
            $tld = '.' . $tld;
        }

        $model = $this->getService()->tldFindOneByTld($tld);
        if (!$model instanceof \Model_Tld) {
            throw new \Box_Exception('TLD not found');
        }

        return $this->getService()->tldToApiArray($model);
    }

    /**
     * Delete top level domain
     *
     * @param string $tld - top level domain, ie: .com
     *
     * @return bool
     * @throws Box_Exception
     */
    public function tld_delete($data)
    {
        if (!isset($data['tld'])) {
            throw new \Box_Exception('TLD is missing');
        }

        $model = $this->getService()->tldFindOneByTld($data['tld']);

        if (!$model instanceof \Model_Tld) {
            throw new \Box_Exception('TLD not found');
        }

        return $this->getService()->tldRm($model);
    }

    /**
     * Add new top level domain
     *
     * @param string $tld - top level domain, ie: .com
     * @param int $tld_registrar_id - domain registrar id
     * @param float $price_registration - registration price
     * @param float $price_renew - renewal price
     * @param float $price_transfer - transfer price
     *
     * @return bool
     * @throws Box_Exception
     */
    public function tld_create($data)
    {
        if (!isset($data['tld'])) {
            throw new \Box_Exception('TLD is missing');
        }

        if ($this->getService()->tldAlreadyRegistered($data['tld'])) {
            throw new \Box_Exception('Tld already registered');
        }

        if (!isset($data['tld_registrar_id'])) {
            throw new \Box_Exception('TLD registrar id is missing');
        }

        if (!isset($data['price_registration'])) {
            throw new \Box_Exception('Registration price is missing');
        }

        if (!isset($data['price_renew'])) {
            throw new \Box_Exception('Renewal price is missing');
        }

        if (!isset($data['price_transfer'])) {
            throw new \Box_Exception('Transfer price is missing');
        }

        return $this->getService()->tldCreate($data);
    }

    /**
     * Update top level domain
     *
     * @param string $tld - top level domain, ie: .com
     *
     * @optional int $tld_registrar_id - domain registrar id
     * @optional float $price_registration - registration price
     * @optional float $price_renew - renewal price
     * @optional float $price_transfer - transfer price
     *
     * @return bool
     * @throws Box_Exception
     */
    public function tld_update($data)
    {
        if (!isset($data['tld'])) {
            throw new \Box_Exception('TLD is missing');
        }

        $model = $this->getService()->tldFindOneByTld($data['tld']);
        if (!$model instanceof \Model_Tld) {
            throw new \Box_Exception('TLD not found');
        }

        return $this->getService()->tldUpdate($model, $data);
    }

    /**
     * Get paginated registars list
     *
     * @return array
     */
    public function registrar_get_list($data)
    {
        list($sql, $params) = $this->getService()->registrarGetSearchQuery($data);
        $per_page = isset($data['per_page']) ? $data['per_page'] : $this->di['pager']->getPer_page();
        $pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page);

        $registrars = $this->di['db']->find('TldRegistrar', 'ORDER By name ASC');

        $registrarsArr = array();
        foreach ($registrars as $registrar) {
            $registrarsArr[] = $this->getService()->registrarToApiArray($registrar);
        }

        $pager['list'] = $registrarsArr;

        return $pager;
    }

    /**
     * Get registrars pairs
     *
     * @return array
     */
    public function registrar_get_pairs($data)
    {
        return $this->getService()->registrarGetPairs();
    }

    /**
     * Get available registars for install
     *
     * @return type
     */
    public function registrar_get_available($data)
    {
        return $this->getService()->registrarGetAvailable();
    }

    /**
     * Install domain registrar
     *
     * @param string $code - registar code
     *
     * @return bool
     */
    public function registrar_install($data)
    {
        if (!isset($data['code'])) {
            throw new \Box_Exception('Registrar code not passed');
        }

        $code = $data['code'];
        if (!in_array($code, $this->getService()->registrarGetAvailable())) {
            throw new \Box_Exception('Registrar is not available for installation.');
        }

        return $this->getService()->registrarCreate($data['code']);
    }

    /**
     * Uninstall domain registrar
     *
     * @param int $id - registar id
     *
     * @return bool
     */
    public function registrar_delete($data)
    {
        if (!isset($data['id'])) {
            throw new \Box_Exception('Registrar id not passed');
        }

        $model = $this->di['db']->load('TldRegistrar', $data['id']);
        if (!$model instanceof \Model_TldRegistrar) {
            throw new \Box_Exception('Registrar not found');
        }

        return $this->getService()->registrarRm($model);
    }

    /**
     * Copy domain registrar
     *
     * @param int $id - registar id
     *
     * @return bool
     */
    public function registrar_copy($data)
    {
        if (!isset($data['id'])) {
            throw new \Box_Exception('Registrar id not passed');
        }

        $model = $this->di['db']->load('TldRegistrar', $data['id']);

        if (!$model instanceof \Model_TldRegistrar) {
            throw new \Box_Exception('Registrar not found');
        }

        return $this->getService()->registrarCopy($model);
    }

    /**
     * Get domain registrar details
     *
     * @param int $id - registar id
     *
     * @return array
     */
    public function registrar_get($data)
    {
        if (!isset($data['id'])) {
            throw new \Box_Exception('Registrar id is missing');
        }

        $registrar = $this->di['db']->load('TldRegistrar', $data['id']);

        if (!$registrar instanceof \Model_TldRegistrar) {
            throw new \Box_Exception('Registrar not found');
        }

        return $this->getService()->registrarToApiArray($registrar);
    }

    /**
     * Sync domain expiration dates with registrars.
     * This action is run once a month
     * @return bool
     */
    public function batch_sync_expiration_dates($data)
    {
        return $this->getService()->batchSyncExpirationDates();
    }

    /**
     * Update domain registrar
     *
     * @param int $id - registar id
     *
     * @optional string $title - registar title
     * @optional array $config - registar configuration array
     *
     * @return bool
     */
    public function registrar_update($data)
    {
        if (!isset($data['id'])) {
            throw new \Box_Exception('Registrar id is missing');
        }

        $model = $this->di['db']->load('TldRegistrar', $data['id']);

        if (!$model instanceof \Model_TldRegistrar) {
            throw new \Box_Exception('Registrar not found');
        }

        return $this->getService()->registrarUpdate($model, $data);
    }

    protected function _getService($data)
    {
        if (!isset($data['order_id'])){
            throw new \Box_Exception('Order id is missing');
        }

        $orderId = $data['order_id'];

        $order = $this->di['db']->load('ClientOrder', $orderId);
        if (!$order instanceof \Model_ClientOrder) {
            throw new \Box_Exception('Order not found');
        }

        $orderService = $this->di['mod_service']('order');
        $s            = $orderService->getOrderService($order);

        if (!$s instanceof \Model_ServiceDomain) {
            throw new \Box_Exception('Domain order is not activated');
        }

        return $s;
    }
}


text:
import afk.bot.london.TankRobot;
import afk.bot.london.VisibleRobot;
import java.util.List;

/**
 * Sample class of what coded bot will look like
 *
 * @author Jessica
 *
 */
public class AimBot extends TankRobot
{

    public AimBot()
    {
        super();
    }

    @Override
    public void init()
    {
        super.init();
        setName("Sitting Duck");
    }

    @Override
    public void gotHit()
    {
        System.out.println("I got hit!");
    }

    @Override
    public void didHit()
    {
        System.out.println("I hit someone!");
    }

    @Override
    public void start()
    {
    }

    @Override
    public void hitObject()
    {
    }

    @Override
    public void sonarWarning(float[] distance)
    {
    }

    @Override
    public void robotVisible(List<VisibleRobot> visibleBots)
    {
        VisibleRobot visible = visibleBots.get(0);
        System.out.println("elevation: " + visible.elevation);
        System.out.println("barrel: " + events.barrel);
        target(visible, 0.6f);
    }

    @Override
    public void idle()
    {
    }
}


text:
#pragma once
#ifndef DB3DPROFILE_H
#define DB3DPROFILE_H

#include "dbsurf.h"
#include "AcDbGeomRef.h"

class AcDb3dProfileData;

#pragma pack(push, 8)

/// <summary> <para>
/// This class is used to represent a 3d profile that can be used as input to
/// functions such as createExtrudedSurface(), createRevolvedSurface(), and
/// createSweptSurface().  An object of this class can represent an entity
/// such as a curve or a region, or it can represent an edge or a set of edges
/// that form a connected chain.
/// </para> </summary>
///
class ACDB_PORT AcDb3dProfile : public AcRxObject
{
public:

    ACRX_DECLARE_MEMBERS(AcDb3dProfile);

    /// <summary>
    /// Default constructor.
    /// </summary>
    AcDb3dProfile ();

    /// <summary>
    /// Constructor for a profile that is an entity such as a curve or region.
    /// </summary>
    /// <param name="pEntity">
    /// Pointer to an AcDbEntity that is to be used as a profile to create
    /// a surface such as an extrusion or loft.
    /// </param>
    AcDb3dProfile ( AcDbEntity *pEntity );

    /// <summary>
    /// Constructor for a profile that is a face.  The profile will consist of
    /// the outer edges of the face.
    /// </summary>
    /// <param name="faceSubentPath">
    /// Subent path of the face.
    /// </param>
    AcDb3dProfile ( const AcDbFullSubentPath& faceSubentPath );

    /// <summary>
    /// Constructor for a profile that is a path.
    /// </summary>
    /// <param name="pathRef">
    /// reference to the path
    /// </param>
    AcDb3dProfile ( const AcDbPathRef & pathRef);

    /// <summary>
    /// Constructor for a profile that is a vertex
    /// </summary>
    /// <param name="vertexRef">
    /// reference to the vertex
    /// </param>
    AcDb3dProfile ( const AcDbVertexRef & vertexRef);

    /// <summary>
    /// Copy constructor.
    /// </summary>
    /// <param name="src">
    /// Source object to be copied.
    /// </param>
    AcDb3dProfile ( const AcDb3dProfile& src );

    /// <summary>
    /// Destructor.
    /// </summary>
    virtual ~AcDb3dProfile();

    /// <summary>
    /// Copies the contents of input object into this object.
    /// </summary>
    /// <param name="src">
    /// Source object to be copied.
    /// </param>
    /// <returns>
    /// eOk if successful.
    /// </returns>
    virtual Acad::ErrorStatus copyFrom ( const AcRxObject *src ) override;

    /// <summary>
    /// Returns the profile entity.  If the profile is for an edge or set of
    /// edges then the returned entity will be an AcDbCurve of the edge or edges.
    /// The caller should not delete this pointer or post it to the database.
    /// </summary>
    /// <returns>
    /// Profile entity. The caller should not delete this pointer.
    /// </returns>
    AcDbEntity*  entity () const;

    /// <summary>
    /// Returns the path reference of the edge if the profile is an edge or
    /// set of edges.  If the profile is not an edge or set of edges, pathRef will be
    /// empty and eInvalidInput will be returned
    /// </summary>
    /// <param name="pathRef">
    /// path reference of the edge(s)
    /// </param>
    /// <returns>
    /// Acad::ErrorStatus
    /// </returns>
    Acad::ErrorStatus getPathRef( AcDbPathRef &pathRef ) const;

    /// <summary>
    /// Returns the vertex reference of the vertex if the profile is a vertex.
    /// If the profile is not an edge or set of edges, vertexRef will be
    /// empty and eInvalidInput will be returned
    /// </summary>
    /// <param name="vertexRef">
    /// vertex reference
    /// </param>
    /// <returns>
    /// Acad::ErrorStatus
    /// </returns>
    Acad::ErrorStatus getVertexRef( AcDbVertexRef &vertexRef ) const;

    /// <summary>
    /// Converts profile into new profiles that are of a type that can be used for
    /// extrude, revolve, sweep, or loft operations.  The converted profiles are returned in
    /// the output array.  If this profile is of type AcDbTrace, AcDbSolid, or AcDbFace then
    /// the converted profile will be for a region.  If this profile is of type
    /// AcDb3dPolyline and the profile is linear or whose 'Fit' property is quadratic or
    /// cubic then the converted profile will be a line or a spline.
    /// </summary>
    /// <param name="explodeMultiFaceRegions">
    /// If this profile is of type AcDbSurface or AcDbRegion and has more than one face,
    /// then we explode to get multiple surface or region profiles that each have only
    /// one face.
    /// </param>
    /// <param name="convertSurfaceToEdges">
    /// If this profile is a face or is of type AcDbSurface, AcDbRegion, AcDbTrace,
    /// AcDbSolid, or AcDbFace then we convert to an edge profile that is defined by
    /// the surface or region edges.
    /// </param>
    /// <param name="nonPlanarOnly">
    /// This parameter is only relevant when convertSurfaceToEdges is set to true.
    /// If this parameter is true then only non-planar surfaces will be converted to
    /// edge profiles.  Regions and planar surfaces will not be converted.
    /// </param>
    /// <param name="outerLoopOnly">
    /// This parameter is only relevant when convertSurfaceToEdges is set to true.
    /// If this parameter is true then only the outer loop of the surface or region
    /// will be converted to an edge profile.
    /// </param>
    /// <param name="convertedProfileArr">
    /// Output list of converted profiles.  The caller is responsible for
    /// deleting the objects in this list.
    /// </param>
    /// <returns>
    /// eOk if successful.  Even when this function returns eOk, it is possible for
    /// the output list to be empty depending on the profile type and the values of
    /// the other parameters.
    /// </returns>
    Acad::ErrorStatus  convertProfile ( bool explodeMultiFaceRegions, bool convertSurfaceToEdges,
                                        bool nonPlanarOnly, bool outerLoopOnly,
                                        AcArray<AcDb3dProfile*>& convertedProfileArr ) const;

    static AcDb3dProfile* convertProfile(const AcArray<AcDbPathRef>&);
    /// <summary>
    /// Set the profile to a path.
    /// </summary>
    /// <param name="pathRef">
    /// reference to the path
    /// </param>
    /// <returns>
    /// eOk if successful.
    /// </returns>
    Acad::ErrorStatus set ( const AcDbPathRef &pathRef );

    /// <summary>
    /// Set the profile to a vertex.
    /// </summary>
    /// <param name="vertexRef">
    /// reference to the vertex
    /// </param>
    /// <returns>
    /// eOk if successful.
    /// </returns>
    Acad::ErrorStatus set ( const AcDbVertexRef &vertexRef );

    /// <summary>
    /// Set the profile to an entity such as a curve or region.
    /// </summary>
    /// <param name="pEntity">
    /// Pointer to an AcDbEntity that is to be used as a profile to create
    /// a surface such as an extrusion or loft.
    /// </param>
    /// <returns>
    /// eOk if successful.
    /// </returns>
    Acad::ErrorStatus set ( AcDbEntity *pEntity );

    /// <summary>
    /// Return whether the profile forms a closed loop.
    /// </summary>
    /// <returns>
    /// True if profile is closed, false otherwise.
    /// </returns>
    bool  isClosed () const;

    /// <summary>
    /// Return whether the profile is planar.
    /// </summary>
    /// <returns>
    /// True if profile is planar, false otherwise.
    /// </returns>
    bool  isPlanar () const;

    /// <summary>
    /// Return whether the profile is an edge or face.
    /// </summary>
    /// <returns>
    /// True if profile is an edge or face, false otherwise.
    /// </returns>
    bool  isSubent () const;

    /// <summary>
    /// Return whether the profile is a face.
    /// </summary>
    /// <returns>
    /// True if profile is a face, false otherwise.
    /// </returns>
    bool  isFace () const;

    /// <summary>
    /// Return whether the profile is an edge.
    /// </summary>
    /// <returns>
    /// True if profile is an edge, false otherwise.
    /// </returns>
    bool  isEdge () const;

    /// <summary>
    /// Return whether the profile is valid and may be used to
    /// create a surface.
    /// </summary>
    /// <returns>
    /// True if profile is a valid entity, edge, or face.
    /// </returns>
    bool  isValid () const;

    /// <summary>
    /// Merge connected sets of profiles into one or more profiles.
    /// </summary>
    /// <param name="profileArr">
    /// Input array of profiles that are to be merged.
    /// </param>
    /// <param name="mergeEdges">
    /// If this parameter is false then any edge profiles in the input array will
    /// not be merged and will be copied directly to the ouput array.
    /// </param>
    /// <param name="mergeCurves">
    /// If this parameter is false then any curve profiles in the input array will
    /// not be merged and will be copied directly to the ouput array.
    /// </param>
    /// <param name="mergedProfileArr">
    /// Output array of merged profiles.  The caller is responsible for deleting all
    /// objects that are returned in this array.
    /// </param>
    /// <returns>
    /// eOk if successful.
    /// </returns>
    static Acad::ErrorStatus mergeProfiles ( const AcArray<AcDb3dProfile*>& profileArr,
                                             bool mergeEdges, bool mergeCurves,
                                             AcArray<AcDb3dProfile*>& mergedProfileArr );

    /// <summary>
    /// Assignment operator.
    /// </summary>
    /// <param name="src">
    /// Source object to be copied.
    /// </param>
    /// <returns>
    /// Reference to this object.
    /// </returns>
    AcDb3dProfile& operator = ( const AcDb3dProfile& src );

private:
    friend class AcDb3dProfileData;
    friend class AcDbLoftProfile;

    AcDb3dProfileData *mProfileData;
};

/// <summary> <para>
/// This class is used to represent a profile that can be used as input to
/// createLoftedSurface().  An object of this class can represent an entity
/// such as a curve or a region, or it can represent an edge or a set of edges
/// that form a connected chain.  This class also maintains continuity data
/// if the profile is for an edge or point and the profile is the first or
/// last profile of the loft.
/// </para> </summary>
///
class ACDB_PORT AcDbLoftProfile : public AcDb3dProfile
{
public:

    ACRX_DECLARE_MEMBERS(AcDbLoftProfile);

    /// <summary>
    /// Default constructor.
    /// </summary>
    AcDbLoftProfile ();

    /// <summary>
    /// Constructor for a profile that is an entity such as a curve or region.
    /// </summary>
    /// <param name="pEntity">
    /// Pointer to an AcDbEntity that is to be used as a profile to create
    /// a surface such as an extrusion or loft.
    /// </param>
    AcDbLoftProfile ( AcDbEntity *pEntity );

    /// <summary>
    /// Constructor for a profile that is an edge or a sequence of connected
    /// edges.
    /// </summary>
    /// <param name="pathRef">
    /// Subent paths of the edges that make up the profile.
    /// </param>
    AcDbLoftProfile ( const AcDbPathRef & pathRef);

    /// <summary>
    /// Constructor for a profile that is a point.
    /// </summary>
    /// <param name="pnt">
    /// An AcGePoint3d that is to be used as a profile to create
    /// a surface such as an extrusion or loft.
    /// </param>
    AcDbLoftProfile ( const AcGePoint3d& pnt );

    /// <summary>
    /// Copy constructor.
    /// </summary>
    /// <param name="src">
    /// Source object to be copied.
    /// </param>
    AcDbLoftProfile ( const AcDbLoftProfile& src );

    /// <summary>
    /// Copies the contents of input object into this object.
    /// </summary>
    /// <param name="src">
    /// Source object to be copied.
    /// </param>
    /// <returns>
    /// eOk if successful.
    /// </returns>
    virtual Acad::ErrorStatus copyFrom ( const AcRxObject *src ) override;

    /// <summary>
    /// Return the continuity for the profile: 0, 1, or 2, which
    /// corresponds to a continuity of G0, G1, or G2.  By default, the
    /// continuity is 1 unless it has been explicitly set to another
    /// value.
    /// </summary>
    /// <returns>
    /// Continuity for the profile: 0, 1, or 2, which
    /// corresponds to a continuity of G0, G1, or G2.
    /// </returns>
    Adesk::Int16  continuity () const;

    /// <summary>
    /// Set the continuity for the profile.
    /// </summary>
    /// <param name="value">
    /// Must be 0, 1, or 2, which corresponds to a continuity of
    /// G0, G1, or G2.
    /// </param>
    void          setContinuity ( Adesk::Int16 value );

    /// <summary>
    /// Return the magnitude of the takeoff vector if the continuity is
    /// 1 or 2.  By default, this value is 0.5 unless it has been
    /// explicitly set to another value.
    /// </summary>
    /// <returns>
    /// Magnitude of the takeoff vector.
    /// </returns>
    double        magnitude () const;

    /// <summary>
    /// Set the magnitude of the takeoff vector for the profile if
    /// the continuity is 1 or 2.
    /// </summary>
    /// <param name="value">
    /// Magnitude of takeoff vector.
    /// </param>
    void          setMagnitude ( double value );

    /// <summary>
    /// Assignment operator.
    /// </summary>
    /// <param name="src">
    /// Source object to be copied.
    /// </param>
    /// <returns>
    /// Reference to this object.
    /// </returns>
    AcDbLoftProfile& operator = ( const AcDbLoftProfile& src );

    /// <summary>
    /// Assignment operator.  Copies the entity and edge data from the
    /// input object, but does not change the continuity or magnitude.
    /// </summary>
    /// <param name="src">
    /// Source object to be copied.
    /// </param>
    /// <returns>
    /// Reference to this object.
    /// </returns>
    AcDbLoftProfile& operator = ( const AcDb3dProfile& src );
};

#pragma pack(pop)
#endif // DB3DPROFILE_H


text:
using Semver;
using Simple301.Core.Models;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Web.Routing;
using System.Linq;
using Umbraco.Core.Persistence.Migrations;
using System;
using System.Web;
using Umbraco.Core.Services;

namespace Simple301.Core
{
    public class MyApplication : ApplicationEventHandler
    {
        private SemVersion _targetVersion = new SemVersion(1, 0, 1);
        private const string REDIRECTS_TABLE_NAME = "Redirects";
        /// <summary>
        /// On application starting we inject the Redirect Content Finder into the very
        /// first slot of Umbraco's Content Resolver pipeline
        /// </summary>
        protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            if (!ContentFinderResolver.Current.ContainsType(typeof(RedirectContentFinder)))
            {
                ContentFinderResolver.Current.InsertType<RedirectContentFinder>(0);
            }
        }

        /// <summary>
        /// On Application Started we need to ensure that the Redirects table exists. If not, create it
        /// </summary>
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            //Grab the Umbraco database context and spin up a new DatabaseSchemaHelper
            var db = applicationContext.DatabaseContext.Database;
            var migrationService = ApplicationContext.Current.Services.MigrationEntryService;
            var creator = new DatabaseSchemaHelper(db, LoggerResolver.Current.Logger, SqlSyntaxContext.SqlSyntaxProvider);

            //Ensure the Redirects table exists. If not, create it
            if (!creator.TableExist(REDIRECTS_TABLE_NAME))
            {
                creator.CreateTable<Redirect>(false);
                this.AddTargetVersionMigrationEntry(migrationService);
            }
            else if(!MigrationVersionCheck(migrationService) && !ValidateTableRead(db, migrationService))
            {
                HandleMigrations(db, migrationService);
            }
        }

        /// <summary>
        /// Check if we have an entry for the latest version
        /// </summary>
        /// <param name="migrationService">Migration service</param>
        /// <returns>True if we have an entry</returns>
        private bool MigrationVersionCheck(IMigrationEntryService migrationService)
        {
            return migrationService.FindEntry(REDIRECTS_TABLE_NAME, this._targetVersion) != null;
        }

        /// <summary>
        /// Helper method called to update the migration entries with an entry that matches the
        /// latest target version
        /// </summary>
        /// <param name="migrationService"></param>
        private void AddTargetVersionMigrationEntry(IMigrationEntryService migrationService)
        {
            var match = migrationService.FindEntry(REDIRECTS_TABLE_NAME, this._targetVersion);
            if (match == null)
                migrationService.CreateEntry(REDIRECTS_TABLE_NAME, this._targetVersion);
        }

        /// <summary>
        /// Hack to support legacy version checking. This supports the state that exists before
        /// we implemented migration version entry on database create, which will exist moving forward.
        /// This only supports legacy installs
        /// </summary>
        /// <param name="db">Database</param>
        /// <param name="migrationService">Migration service</param>
        /// <returns>True if success</returns>
        private bool ValidateTableRead(UmbracoDatabase db, IMigrationEntryService migrationService)
        {
            try
            {
                // run through creating and deleting a redirect.
                var redirect = RedirectRepository.AddRedirect(true, "old", "new", "notes");
                RedirectRepository.DeleteRedirect(redirect.Id);
                this.AddTargetVersionMigrationEntry(migrationService);
                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }

        /// <summary>
        /// Handles checking and running migrations
        /// </summary>
        /// <param name="db">Database context</param>
        /// <param name="migrationService">Migration service</param>
        private void HandleMigrations(UmbracoDatabase db, IMigrationEntryService migrationService)
        {
            var latestMigrationVersion = new SemVersion(0, 0, 0);

            // get all migrations for "Redirects" already executed
            var migrations = migrationService.GetAll(REDIRECTS_TABLE_NAME);

            // get the latest migration for "Redirects" executed
            var latestMigration = migrations.OrderByDescending(x => x.Version).FirstOrDefault();

            if (latestMigration != null)
                latestMigrationVersion = latestMigration.Version;

            if (this._targetVersion == latestMigrationVersion)
                return;

            var migrationsRunner = new MigrationRunner(
              migrationService,
              ApplicationContext.Current.ProfilingLogger.Logger,
              latestMigrationVersion,
              this._targetVersion,
              REDIRECTS_TABLE_NAME);

            try
            {
                migrationsRunner.Execute(db);
            }
            catch (HttpException e){}
            catch (Exception e)
            {
                LogHelper.Error<MigrationRunner>("Error running Redirects migration", e);
            }
        }
    }
}


text:
import json
import logging
import sys

from pyflink.table import (EnvironmentSettings, TableEnvironment, DataTypes, TableDescriptor,
                           Schema)
from pyflink.table.expressions import col
from pyflink.table.udf import udf

def process_json_data_with_udf():
    t_env = TableEnvironment.create(EnvironmentSettings.in_streaming_mode())

    # define the source
    table = t_env.from_elements(
        elements=[
            (1, '{"name": "Flink", "tel": 123, "addr": {"country": "Germany", "city": "Berlin"}}'),
            (2, '{"name": "hello", "tel": 135, "addr": {"country": "China", "city": "Shanghai"}}'),
            (3, '{"name": "world", "tel": 124, "addr": {"country": "USA", "city": "NewYork"}}'),
            (4, '{"name": "PyFlink", "tel": 32, "addr": {"country": "China", "city": "Hangzhou"}}')
        ],
        schema=['id', 'data'])

    # define the sink
    t_env.create_temporary_table(
        'sink',
        TableDescriptor.for_connector('print')
                       .schema(Schema.new_builder()
                               .column('id', DataTypes.BIGINT())
                               .column('data', DataTypes.STRING())
                               .build())
                       .build())

    # update json columns
    @udf(result_type=DataTypes.STRING())
    def update_tel(data):
        json_data = json.loads(data)
        json_data['tel'] += 1
        return json.dumps(json_data)

    table = table.select(col('id'), update_tel(col('data')))

    # execute
    table.execute_insert('sink') \
         .wait()
    # remove .wait if submitting to a remote cluster, refer to
    # https://nightlies.apache.org/flink/flink-docs-stable/docs/dev/python/faq/#wait-for-jobs-to-finish-when-executing-jobs-in-mini-cluster
    # for more details

if __name__ == '__main__':
    logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")

    process_json_data_with_udf()


text:
package com.sinotrans.transport.service;

import com.sinotrans.transport.dto.*;
import com.sinotrans.transport.dto.common.CommonListResponse;
import com.sinotrans.transport.dto.common.CommonNoPageListResponse;

/**
 * Created by emi on 2016/5/13.
 */
public interface OrderExportService {

    CommonListResponse search(Long userId, OrderExportSearchRequest searchRequest);

    OrderExportAlterResponse create(Long userId, OrderExportAlterRequest request);

    OrderExportAlterResponse alter(Long userId, Long orderId, OrderExportAlterRequest request);

    CommonNoPageListResponse searchContainer(Long userId, Long orderId);

    CommonNoPageListResponse modifyContainer(Long userId, ContainerExportAlterRequest alterRequest);

    CommonNoPageListResponse searchAddress(Long userId, Long containerId);

    CommonNoPageListResponse modifyAddress(Long userId, AddressExportAlterRequest alterRequest);

    OrderExportAllResponse searchAll(Long userId, Long orderId);

    ContainerDropResponse dropContainers(Long userId, DomainsDropRequest dropRequest);

    CommonNoPageListResponse dropAddresses(Long userId, DomainsDropRequest dropRequest);

    OrderExportAllResponse sendOrder(Long userId, Long orderId);
}


text:
namespace MassTransit.Azure.ServiceBus.Core.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using MessageData;
    using NUnit.Framework;

    [TestFixture]
    public class Sending_a_message_with_data :
        AzureServiceBusTestFixture
    {
        [Test]
        public async Task Should_store_and_retrieve_the_message_data_from_blob_storage()
        {
            var data = NewId.NextGuid().ToString();

            var message = new DataMessage
            {
                CorrelationId = InVar.CorrelationId,
                Data = await _repository.PutString(data)
            };

            await InputQueueSendEndpoint.Send(message);

            ConsumeContext<DataMessage> consumeContext = await _handler;

            Assert.That(consumeContext.Message.Data.HasValue, Is.True);

            Assert.That(_data, Is.EqualTo(data));
        }

        Task<ConsumeContext<DataMessage>> _handler;
        string _data;
        IMessageDataRepository _repository;

        protected override void ConfigureServiceBusBus(IServiceBusBusFactoryConfigurator configurator)
        {
            _repository = configurator.UseMessageData(x => x.AzureStorage(Configuration.StorageAccount));
        }

        protected override void ConfigureServiceBusReceiveEndpoint(IServiceBusReceiveEndpointConfigurator configurator)
        {
            _handler = Handler<DataMessage>(configurator, async context =>
            {
                _data = await context.Message.Data.Value;
            });
        }

        public class DataMessage
        {
            public Guid CorrelationId { get; set; }
            public MessageData<string> Data { get; set; }
        }
    }

    [TestFixture]
    public class Sending_a_message_with_object_data :
        AzureServiceBusTestFixture
    {
        [Test]
        public async Task Should_store_and_retrieve_the_message_data_from_blob_storage()
        {
            var dataDictionary = new DataDictionary()
            {
                Values = new Dictionary<string, string>()
                {
                    { "First", "1st" },
                    { "Second", "2nd" }
                }
            };

            await InputQueueSendEndpoint.Send<DataMessage>(new
            {
                InVar.CorrelationId,
                Dictionary = dataDictionary
            });

            ConsumeContext<DataMessage> consumeContext = await _handler;

            Assert.That(consumeContext.Message.Dictionary.HasValue, Is.True);
            Assert.That(_data.Values, Is.EqualTo(dataDictionary.Values));
        }

        Task<ConsumeContext<DataMessage>> _handler;
        DataDictionary _data;
        IMessageDataRepository _repository;

        protected override void ConfigureServiceBusBus(IServiceBusBusFactoryConfigurator configurator)
        {
            _repository = configurator.UseMessageData(x => x.AzureStorage(Configuration.StorageAccount));
        }

        protected override void ConfigureServiceBusReceiveEndpoint(IServiceBusReceiveEndpointConfigurator configurator)
        {
            _handler = Handler<DataMessage>(configurator, async context =>
            {
                _data = await context.Message.Dictionary.Value;
            });
        }

        public class DataMessage
        {
            public Guid CorrelationId { get; set; }
            public MessageData<DataDictionary> Dictionary { get; set; }
        }

        public class DataDictionary
        {
            public Dictionary<string, string> Values { get; set; }
        }
    }

    [TestFixture]
    public class Sending_a_message_with_huge_object_data :
        AzureServiceBusTestFixture
    {
        [Test]
        public async Task Should_store_and_retrieve_the_message_data_from_blob_storage()
        {
            var dataDictionary = new DataDictionary() { Values = new Dictionary<string, string>() };

            for (int i = 0; i < 10000; i++)
            {
                dataDictionary.Values.Add(i.ToString(), $"Value {i}");
            }

            await InputQueueSendEndpoint.Send<DataMessage>(new
            {
                InVar.CorrelationId,
                Dictionary = dataDictionary
            });

            ConsumeContext<DataMessage> consumeContext = await _handler;

            Assert.That(consumeContext.Message.Dictionary.HasValue, Is.True);
            Assert.That(_data.Values, Is.EqualTo(dataDictionary.Values));
        }

        Task<ConsumeContext<DataMessage>> _handler;
        DataDictionary _data;
        IMessageDataRepository _repository;

        protected override void ConfigureServiceBusBus(IServiceBusBusFactoryConfigurator configurator)
        {
            _repository = configurator.UseMessageData(x => x.AzureStorage(Configuration.StorageAccount));
        }

        protected override void ConfigureServiceBusReceiveEndpoint(IServiceBusReceiveEndpointConfigurator configurator)
        {
            _handler = Handler<DataMessage>(configurator, async context =>
            {
                _data = await context.Message.Dictionary.Value;
            });
        }

        public class DataMessage
        {
            public Guid CorrelationId { get; set; }
            public MessageData<DataDictionary> Dictionary { get; set; }
        }

        public class DataDictionary
        {
            public Dictionary<string, string> Values { get; set; }
        }
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE617_Reachable_Assertion__fscanf_84a.cpp
Label Definition File: CWE617_Reachable_Assertion.label.xml
Template File: sources-sink-84a.tmpl.cpp
*/
/*
 * @description
 * CWE: 617 Reachable Assertion
 * BadSource: fscanf Read data from the console using fscanf()
 * GoodSource: Number greater than ASSERT_VALUE
 * Sinks:
 *    BadSink : Assert if n is less than or equal to ASSERT_VALUE
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */

#include "std_testcase.h"
#include "CWE617_Reachable_Assertion__fscanf_84.h"

namespace CWE617_Reachable_Assertion__fscanf_84
{

#ifndef OMITBAD

void bad()
{
    int data;
    /* Initialize data */
    data = -1;
    CWE617_Reachable_Assertion__fscanf_84_bad * badObject = new CWE617_Reachable_Assertion__fscanf_84_bad(data);
    delete badObject;
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
    int data;
    /* Initialize data */
    data = -1;
    CWE617_Reachable_Assertion__fscanf_84_goodG2B * goodG2BObject =  new CWE617_Reachable_Assertion__fscanf_84_goodG2B(data);
    delete goodG2BObject;
}

void good()
{
    goodG2B();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

using namespace CWE617_Reachable_Assertion__fscanf_84; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
using System.Numerics;

namespace HoloLens.DevicePortal.Models
{
    public class Frustum
    {
        public Vector4 Bottom { get; set; }
        public Vector4 Far { get; set; }
        public Vector4 Left { get; set; }
        public Vector4 Near { get; set; }
        public Vector4 Right { get; set; }
        public Vector4 Top { get; set; }
    }
}


text:
package rocks.xmpp.extensions.messagecorrect.model;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Objects;

/**
 * The implementation of the {@code <replace/>} element in the {@code urn:xmpp:message-correct:0} namespace.
 *
Usage

 *
Advertising Support for Message Correction

 *

 * xmppClient.enableFeature(Replace.NAMESPACE);
 *

 *
Checking if a Message Should be Corrected

 *

 * Replace replace = message.getExtension(Replace.class);
 * if (replace != null) {
 *     String oldMessageId = replace.getId();
 *     // Replace old message with message...
 * }
 *

 *
Correcting a Message

 *

 * Message correctedMessage = new Message(jid, Message.Type.CHAT, "This is the corrected text");
 * correctedMessage.addExtension(new Replace(id));
 * xmppClient.send(correctedMessage);
 *

 *

 * This class is immutable.
 *
 * @author Christian Schudt
 * @see XEP-0308: Last Message Correction
 * @see XML Schema
 */
@XmlRootElement
public final class Replace {

    /**
     * urn:xmpp:message-correct:0
     */
    public static final String NAMESPACE = "urn:xmpp:message-correct:0";

    @XmlAttribute
    private final String id;

    private Replace() {
        this.id = null;
    }

    /**
     * @param id The id of the message which shall be corrected.
     */
    public Replace(String id) {
        this.id = Objects.requireNonNull(id);
    }

    /**
     * Gets the id of the message which shall be corrected.
     *
     * @return The message id.
     */
    public final String getId() {
        return id;
    }

    @Override
    public final String toString() {
        return "Replacement for message with id: " + id;
    }
}


text:
import Ember from 'ember';
import layout from '../templates/components/md-btn-dropdown';
import computed from 'ember-new-computed';
import MaterializeButton from './md-btn';

export default MaterializeButton.extend({
  layout: layout,
  tagName: 'a',
  classNames: ['dropdown-button'],
  icon: "mdi-navigation-expand-more",
  iconPosition: 'right',
  attributeBindings: [
    'inDuration', 'outDuration', 'constrainWidth', 'hover', 'gutter', 'belowOrigin'
  ],
  didInsertElement() {
    this._super(...arguments);
    Ember.run.scheduleOnce('afterRender', this, this._setupDropdown);
  },
  _setupDropdown() {
    // needed until the Materialize.dropdown plugin is replaced
    this.$().attr('data-activates', this.get('_dropdownContentId'));

    var that = this;
    this.$().dropdown({
      hover: this.getWithDefault('hover', false) === 'true',
      constrainWidth: this.getWithDefault('constrainWidth', true) === 'true',
      inDuration: this.getWithDefault('inDuration', that.get('_mdSettings.dropdownInDuration')),
      outDuration: this.getWithDefault('outDuration', that.get('_mdSettings.dropdownOutDuration')),
      gutter: this.getWithDefault('gutter', 0),
      belowOrigin: this.getWithDefault('belowOrigin', false) === 'true'
    });
  },
  _dropdownContentId: computed({
    get() {
      return `${this.get('element.id')}-dropdown-content`;
    }
  })
});


text:
<?php namespace Cviebrock\LaravelElasticsearch;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

/**
 * Class ServiceProvider
 *
 * @package Cviebrock\LaravelElasticsearch
 */
class ServiceProvider extends BaseServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = false;

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot() {

		$app = $this->app;

		if (version_compare($app::VERSION, '5.0') >= 0) {
			// Laravel 5
			$configPath = realpath(__DIR__ . '/../config/elasticsearch.php');
			$this->publishes([
				$configPath => config_path('elasticsearch.php')
			]);
		}
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register() {

		$this->app->bindShared('elasticsearch.factory', function ($app) {
			return new Factory();
		});

		$this->app->bindShared('elasticsearch', function ($app) {
			return new Manager($app, $app['elasticsearch.factory']);
		});
	}
}