text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.machinelearning.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import java.util.List;

/**
 * Image Object Detection. Object detection is used to identify objects in an image and locate each object with a
 * bounding box e.g. locate all dogs and cats in an image and draw a bounding box around each.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "taskType")
@JsonTypeName("ImageObjectDetection")
@Fluent
public final class ImageObjectDetection extends AutoMLVertical {
    /*
     * Primary metric to optimize for this task.
     */
    @JsonProperty(value = "primaryMetric")
    private ObjectDetectionPrimaryMetrics primaryMetric;

    /*
     * Settings used for training the model.
     */
    @JsonProperty(value = "modelSettings")
    private ImageModelSettingsObjectDetection modelSettings;

    /*
     * Search space for sampling different combinations of models and their hyperparameters.
     */
    @JsonProperty(value = "searchSpace")
    private List<ImageModelDistributionSettingsObjectDetection> searchSpace;

    /*
     * [Required] Limit settings for the AutoML job.
     */
    @JsonProperty(value = "limitSettings", required = true)
    private ImageLimitSettings limitSettings;

    /*
     * Model sweeping and hyperparameter sweeping related settings.
     */
    @JsonProperty(value = "sweepSettings")
    private ImageSweepSettings sweepSettings;

    /*
     * Validation data inputs.
     */
    @JsonProperty(value = "validationData")
    private MLTableJobInput validationData;

    /*
     * The fraction of training dataset that needs to be set aside for validation purpose.
     * Values between (0.0 , 1.0)
     * Applied when validation dataset is not provided.
     */
    @JsonProperty(value = "validationDataSize")
    private Double validationDataSize;

    /** Creates an instance of ImageObjectDetection class. */
    public ImageObjectDetection() {
    }

    /**
     * Get the primaryMetric property: Primary metric to optimize for this task.
     *
     * @return the primaryMetric value.
     */
    public ObjectDetectionPrimaryMetrics primaryMetric() {
        return this.primaryMetric;
    }

    /**
     * Set the primaryMetric property: Primary metric to optimize for this task.
     *
     * @param primaryMetric the primaryMetric value to set.
     * @return the ImageObjectDetection object itself.
     */
    public ImageObjectDetection withPrimaryMetric(ObjectDetectionPrimaryMetrics primaryMetric) {
        this.primaryMetric = primaryMetric;
        return this;
    }

    /**
     * Get the modelSettings property: Settings used for training the model.
     *
     * @return the modelSettings value.
     */
    public ImageModelSettingsObjectDetection modelSettings() {
        return this.modelSettings;
    }

    /**
     * Set the modelSettings property: Settings used for training the model.
     *
     * @param modelSettings the modelSettings value to set.
     * @return the ImageObjectDetection object itself.
     */
    public ImageObjectDetection withModelSettings(ImageModelSettingsObjectDetection modelSettings) {
        this.modelSettings = modelSettings;
        return this;
    }

    /**
     * Get the searchSpace property: Search space for sampling different combinations of models and their
     * hyperparameters.
     *
     * @return the searchSpace value.
     */
    public List<ImageModelDistributionSettingsObjectDetection> searchSpace() {
        return this.searchSpace;
    }

    /**
     * Set the searchSpace property: Search space for sampling different combinations of models and their
     * hyperparameters.
     *
     * @param searchSpace the searchSpace value to set.
     * @return the ImageObjectDetection object itself.
     */
    public ImageObjectDetection withSearchSpace(List<ImageModelDistributionSettingsObjectDetection> searchSpace) {
        this.searchSpace = searchSpace;
        return this;
    }

    /**
     * Get the limitSettings property: [Required] Limit settings for the AutoML job.
     *
     * @return the limitSettings value.
     */
    public ImageLimitSettings limitSettings() {
        return this.limitSettings;
    }

    /**
     * Set the limitSettings property: [Required] Limit settings for the AutoML job.
     *
     * @param limitSettings the limitSettings value to set.
     * @return the ImageObjectDetection object itself.
     */
    public ImageObjectDetection withLimitSettings(ImageLimitSettings limitSettings) {
        this.limitSettings = limitSettings;
        return this;
    }

    /**
     * Get the sweepSettings property: Model sweeping and hyperparameter sweeping related settings.
     *
     * @return the sweepSettings value.
     */
    public ImageSweepSettings sweepSettings() {
        return this.sweepSettings;
    }

    /**
     * Set the sweepSettings property: Model sweeping and hyperparameter sweeping related settings.
     *
     * @param sweepSettings the sweepSettings value to set.
     * @return the ImageObjectDetection object itself.
     */
    public ImageObjectDetection withSweepSettings(ImageSweepSettings sweepSettings) {
        this.sweepSettings = sweepSettings;
        return this;
    }

    /**
     * Get the validationData property: Validation data inputs.
     *
     * @return the validationData value.
     */
    public MLTableJobInput validationData() {
        return this.validationData;
    }

    /**
     * Set the validationData property: Validation data inputs.
     *
     * @param validationData the validationData value to set.
     * @return the ImageObjectDetection object itself.
     */
    public ImageObjectDetection withValidationData(MLTableJobInput validationData) {
        this.validationData = validationData;
        return this;
    }

    /**
     * Get the validationDataSize property: The fraction of training dataset that needs to be set aside for validation
     * purpose. Values between (0.0 , 1.0) Applied when validation dataset is not provided.
     *
     * @return the validationDataSize value.
     */
    public Double validationDataSize() {
        return this.validationDataSize;
    }

    /**
     * Set the validationDataSize property: The fraction of training dataset that needs to be set aside for validation
     * purpose. Values between (0.0 , 1.0) Applied when validation dataset is not provided.
     *
     * @param validationDataSize the validationDataSize value to set.
     * @return the ImageObjectDetection object itself.
     */
    public ImageObjectDetection withValidationDataSize(Double validationDataSize) {
        this.validationDataSize = validationDataSize;
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public ImageObjectDetection withLogVerbosity(LogVerbosity logVerbosity) {
        super.withLogVerbosity(logVerbosity);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public ImageObjectDetection withTargetColumnName(String targetColumnName) {
        super.withTargetColumnName(targetColumnName);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public ImageObjectDetection withTrainingData(MLTableJobInput trainingData) {
        super.withTrainingData(trainingData);
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    @Override
    public void validate() {
        super.validate();
        if (modelSettings() != null) {
            modelSettings().validate();
        }
        if (searchSpace() != null) {
            searchSpace().forEach(e -> e.validate());
        }
        if (limitSettings() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property limitSettings in model ImageObjectDetection"));
        } else {
            limitSettings().validate();
        }
        if (sweepSettings() != null) {
            sweepSettings().validate();
        }
        if (validationData() != null) {
            validationData().validate();
        }
    }

    private static final ClientLogger LOGGER = new ClientLogger(ImageObjectDetection.class);
}


text:
package com.dev.blogs;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.dev.blogs.config.AppConfig;
import com.dev.blogs.dao.ItemDao;
import com.dev.blogs.model.Item;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=AppConfig.class, loader=AnnotationConfigContextLoader.class)
public class TestItem {
	@Autowired
	private ItemDao itemDao;

	@Test
	public void testInsertFind() {
		// Создать тестовый объект
		Item item = new Item();
		item.setName("zheka");
		item.setWarehouseId(1l);

		// Сохранить тестовый объект в базе данных
		Long id = itemDao.insert(item);
		// Вытащить тестовый объект из базы данных
		Item itemFromDb = itemDao.findById(id);

		// Сравнить вытащенный объект из базы данных с тестовым объектом
		assertEquals(item, itemFromDb);

		// Удалить тестовый объект из базы данных
		itemDao.delete(itemFromDb);
	}

	@Test
	public void testInsertFindUpdate() {
		// Создать тестовый объект
		Item item = new Item();
		item.setName("zheka");
		item.setWarehouseId(1l);

		// Сохранить тестовый объект в базе данных
		Long id = itemDao.insert(item);

		// Вытащить тестовый объект из базы данных
		Item itemFromDb = itemDao.findById(id);

		// Обновить в вытащенном объекте поле name
		itemFromDb.setName("vasya");
		// Записать обновленый тестовый объект в базу данных
		itemDao.update(itemFromDb);
		// После обновления повторно вытащить тестовый объект из базы данных
		Item updatedItemFromDb = itemDao.findById(itemFromDb.getId());

		// Сравнить тестовый обновленный объект с повторно вытащенным
		assertEquals(itemFromDb, updatedItemFromDb);

		// Удалить тестовый объект из базы данных
		itemDao.delete(updatedItemFromDb);
	}

	@Test
	public void testDelete() {
		// Создать тестовый объект
		Item item = new Item();
		item.setName("test message");
		item.setWarehouseId(1l);

		// Сохранить тестовый объект в базе данных
		Long id = itemDao.insert(item);
		// Вытащить тестовый объект из базы данных
		Item itemToDelete = itemDao.findById(id);
		// Удалить тестовый объект из базы данных
		itemDao.delete(itemToDelete);
		// Найти удаленный объект в базе данных
		Item itemAfterDeleting = itemDao.findById(id);

		// Сравнить вытащенный объект после удаления из базы данных на null
		assertNull(itemAfterDeleting);
	}
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Aurora.Settings.Layers
{
    /// <summary>
    /// Interaction logic for Control_SolidFillLayer.xaml
    /// </summary>
    public partial class Control_SolidFillLayer : UserControl
    {
        private bool settingsset = false;

        public Control_SolidFillLayer()
        {
            InitializeComponent();
        }

        public Control_SolidFillLayer(SolidFillLayerHandler datacontext)
        {
            InitializeComponent();

            this.DataContext = datacontext;
        }

        public void SetSettings()
        {
            if(this.DataContext is SolidFillLayerHandler && !settingsset)
            {
                this.ColorPicker_primaryColor.SelectedColor = Utils.ColorUtils.DrawingColorToMediaColor((this.DataContext as SolidFillLayerHandler).Properties._PrimaryColor ?? System.Drawing.Color.Empty);

                settingsset = true;
            }
        }

        private void ColorPicker_primaryColor_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color?> e)
        {
            if (IsLoaded && settingsset && this.DataContext is SolidFillLayerHandler && sender is Xceed.Wpf.Toolkit.ColorPicker && (sender as Xceed.Wpf.Toolkit.ColorPicker).SelectedColor.HasValue)
            {
                (this.DataContext as SolidFillLayerHandler).Properties._PrimaryColor = Utils.ColorUtils.MediaColorToDrawingColor((sender as Xceed.Wpf.Toolkit.ColorPicker).SelectedColor.Value);
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            SetSettings();

            this.Loaded -= UserControl_Loaded;
        }
    }
}


text:
package br.ufc.mdcc.mpos.net.rpc.util;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import br.ufc.mdcc.mpos.net.rpc.deploy.model.DependencePath;

/**
 * Class loader for jar files.
 *
 * @author Philipp B. Costa
 */
public final class JarClassLoader {
	private ClassLoader classLoader;
	private Map<String, Class<?>> cache = new HashMap<String, Class<?>>();

	public JarClassLoader(ClassLoader thread, List<DependencePath> dependences) throws ClassLoaderException {
		URL urlJars[] = new URL[dependences.size()];
		int count = 0;
		for (DependencePath app : dependences) {
			try {
				urlJars[count++] = new File(app.getPath()).toURI().toURL();
			} catch (Exception e) {
				throw new ClassLoaderException("Error for loading jarPaths");
			}
		}
		classLoader = URLClassLoader.newInstance(urlJars, thread);
	}

	public synchronized Object newInstance(String clsName) throws InstantiationException, IllegalAccessException {
		Class<?> cls = getClassFromClassLoader(clsName);
		if (cls != null) {
			return cls.newInstance();
		}
		return null;
	}

	public synchronized Class<?> resolveClass(String clsName) {
		return getClassFromClassLoader(clsName);
	}

	private Class<?> getClassFromClassLoader(String clsName) {
		Class<?> cls = cache.get(clsName);
		if (cls != null) {
			return cls;
		}

		try {
			cls = Class.forName(clsName, true, classLoader);
			cache.put(clsName, cls);
			return cls;
		} catch (ClassNotFoundException e) {
		}

		return null;
	}
}


text:
#include <stdio.h>
#include <hxMath.h>
//#include <hxMacros.h>
#include <cpp/CppInt32__.h>
#include <map>

#ifdef SYS_CONSOLE

#elif defined(_WIN32)

#include <windows.h>
// Stoopid windows ...
#ifdef RegisterClass
#undef RegisterClass
#endif
#ifdef abs
#undef abs
#endif

#else

#include <wchar.h>
#ifndef EMSCRIPTEN
typedef  int64_t  __int64;
#endif

#endif

#ifdef HXCPP_SCRIPTABLE
#include <hx/Scriptable.h>
#endif

// --- hxObject -----------------------------------------

namespace hx
{

String sNone[] = { String(null()) };

Dynamic Object::__IField(int inFieldID)
{
   return __Field( __hxcpp_field_from_id(inFieldID), HX_PROP_DYNAMIC );
}

double Object::__INumField(int inFieldID)
{
   return __IField(inFieldID);
}

Dynamic *Object::__GetFieldMap() { return 0; }

int Object::__Compare(const Object *inRHS) const
{
   hx::Object *real = const_cast<Object *>(this)->__GetRealObject();
   return real < inRHS ? -1 : real==inRHS ? 0 : 1;
}

hx::Val Object::__Field(const String &inString, hx::PropertyAccess inCallProp)
{
   #if 0
   // Will be true for 'Implements dynamic'
   if (inCallProp && __GetFieldMap())
   {
      Dynamic resolve = __Field(HX_CSTRING("resolve"), false);
      if (resolve.mPtr)
         return resolve(inString);
   }
   #endif
   return null();
}

bool Object::__HasField(const String &inString)
{
   return false;
}
Dynamic Object::__Run(const Array<Dynamic> &inArgs) { return 0; }
Dynamic Object::__GetItem(int inIndex) const { return null(); }
Dynamic Object::__SetItem(int inIndex,Dynamic) { return null();  }

void Object::__SetThis(Dynamic inThis) { }

bool Object::__Is(Dynamic inClass ) const { return __Is(inClass.GetPtr()); }

hx::Class Object__mClass;

bool AlwaysCast(Object *inPtr) { return inPtr!=0; }

#if (HXCPP_API_LEVEL < 330)
DynamicArray Object::__EnumParams() { return DynamicArray(); }
String Object::__Tag() const { return HX_CSTRING("<not enum>"); }
int Object::__Index() const { return -1; }
#endif

#if (HXCPP_API_LEVEL >= 330) && !defined(HXCPP_SCRIPTABLE)
// Other implementation is in Cppia.cpp
void *hx::Object::_hx_getInterface(int inId)
{
   return 0;
}
#endif

#ifdef HXCPP_SCRIPTABLE

class Object__scriptable : public hx::Object {
   typedef Object__scriptable __ME;
   void __construct() { }
   typedef hx::Object super;
   typedef hx::Object __superString;
   HX_DEFINE_SCRIPTABLE(HX_ARR_LIST0);
   HX_DEFINE_SCRIPTABLE_DYNAMIC;
};

hx::ScriptFunction Object::__script_construct;

static void __s_toString(hx::CppiaCtx *ctx) {
   ctx->returnString((ctx->getThis())->toString());
}
static hx::ScriptNamedFunction __scriptableFunctions[] = {
  hx::ScriptNamedFunction("toString",__s_toString,"s"),
  hx::ScriptNamedFunction(0,0,0) };

#endif

void Object::__boot()
{
   Static(Object__mClass) = hx::_hx_RegisterClass(HX_CSTRING("Dynamic"),AlwaysCast,sNone,sNone,0,0, 0, 0 );

   #ifdef HXCPP_SCRIPTABLE
   hx::ScriptableRegisterClass( HX_CSTRING("hx.Object"), (int)sizeof(hx::Object__scriptable), __scriptableFunctions, Object__scriptable::__script_create, Object::__script_construct );
   #endif
}

hx::Class &Object::__SGetClass() { return Object__mClass; }

hx::Class Object::__GetClass() const { return Object__mClass; }

hx::FieldRef Object::__FieldRef(const String &inString) { return hx::FieldRef(this,inString); }

String Object::__ToString() const { return HX_CSTRING("Object"); }

const char * Object::__CStr() const { return __ToString().__CStr(); }

hx::Val Object::__SetField(const String &inField,const hx::Val &inValue, hx::PropertyAccess inCallProp)
{
   hx::Throw( HX_CSTRING("Invalid field:") + inField );
   return null();
}

Dynamic Object::__run()
{
   return __Run(Array_obj<Dynamic>::__new());
}

Dynamic Object::__run(D a)
{
   return __Run( Array_obj<Dynamic>::__new(0,1) << a );
}

Dynamic Object::__run(D a,D b)
{
   return __Run( Array_obj<Dynamic>::__new(0,2) << a << b );
}

Dynamic Object::__run(D a,D b,D c)
{
   return __Run( Array_obj<Dynamic>::__new(0,3) << a << b << c);
}
Dynamic Object::__run(D a,D b,D c,D d)
{
   return __Run( Array_obj<Dynamic>::__new(0,4) << a << b << c << d);
}
Dynamic Object::__run(D a,D b,D c,D d,D e)
{
   return __Run( Array_obj<Dynamic>::__new(0,5) << a << b << c << d << e);
}

void Object::__GetFields(Array<String> &outFields)
{
}

String Object::toString()
{
   Dynamic *m = __GetFieldMap();
   if (m)
   {
      Dynamic func;
      if (FieldMapGet(m,HX_CSTRING("toString"),func))
         return func();
   }
   return __ToString();
}

} // end namespace hx


text:
package com.bmwcarit.barefoot.tracker;

import java.util.Properties;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicReference;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zeromq.ZMQ;

import com.bmwcarit.barefoot.matcher.Matcher;
import com.bmwcarit.barefoot.matcher.MatcherCandidate;
import com.bmwcarit.barefoot.matcher.MatcherKState;
import com.bmwcarit.barefoot.matcher.MatcherSample;
import com.bmwcarit.barefoot.roadmap.Road;
import com.bmwcarit.barefoot.roadmap.RoadMap;
import com.bmwcarit.barefoot.roadmap.RoadPoint;
import com.bmwcarit.barefoot.roadmap.TimePriority;
import com.bmwcarit.barefoot.scheduler.StaticScheduler;
import com.bmwcarit.barefoot.scheduler.StaticScheduler.InlineScheduler;
import com.bmwcarit.barefoot.scheduler.Task;
import com.bmwcarit.barefoot.spatial.Geography;
import com.bmwcarit.barefoot.spatial.SpatialOperator;
import com.bmwcarit.barefoot.topology.Dijkstra;
import com.bmwcarit.barefoot.tracker.TemporaryMemory.Factory;
import com.bmwcarit.barefoot.tracker.TemporaryMemory.Publisher;
import com.bmwcarit.barefoot.tracker.TemporaryMemory.TemporaryElement;
import com.bmwcarit.barefoot.util.AbstractServer;
import com.bmwcarit.barefoot.util.Stopwatch;

;

/**
 * Tracker server (stand-alone) for Hidden Markov Model online map matching. It is a
 * {@link AbstractServer} that performs online map matching; and is configurable with a properties
 * file. It pushes updates via a ZeroMQ publisher port to subscribing listeners.
 */
public class TrackerServer extends AbstractServer {
    private final static Logger logger = LoggerFactory.getLogger(TrackerServer.class);
    private final static SpatialOperator spatial = new Geography();
    private final RoadMap map;

    /**
     * Creates a {@link TrackerServer} object as stand-alone online map matching server. The
     * provided {@link Properties} object may provide the following properties:
     *

     *
server properties: see {@link AbstractServer#AbstractServer(Properties, ResponseFactory)}
     *

     *
matcher.radius.max (see {@link Matcher#setMaxRadius(double)})

     *
matcher.distance.max (see {@link Matcher#setMaxDistance(double)})

     *
matcher.lambda (see {@link Matcher#setLambda(double)})

     *
matcher.sigma (see {@link Matcher#setSigma(double)})

     *
tracker.port (optional, default: 1235)

     *
tracker.ttl (seconds, optional, default: 60, sets time to live of state information for
     * tracked objects which is infinite if set to zero)

     *

     *
     * @param properties {@link Properties} object with (optional) server and matcher settings.
     * @param map {@link RoadMap} object with the map to be matched with.
     */
    public TrackerServer(Properties properties, RoadMap map) {
        super(properties, new MatcherResponseFactory(properties, map));
        this.map = map;
    }

    /**
     * Gets {@link RoadMap} object of the server.
     *
     * @return {@link RoadMap} object of the server.
     */
    public RoadMap getMap() {
        return this.map;
    }

    /**
     * Gets {@link Matcher} object of the server.
     *
     * @return {@link Matcher} object of the server.
     */
    public Matcher getMatcher() {
        return ((MatcherResponseFactory) getResponseFactory()).matcher;
    }

    private static class MatcherResponseFactory extends ResponseFactory {
        private final Matcher matcher;
        private final int TTL;
        private final int interval;
        private final double distance;
        private final double sensitive;
        private final TemporaryMemory<State> memory;

        public MatcherResponseFactory(Properties properties, RoadMap map) {
            matcher = new Matcher(map, new Dijkstra<Road, RoadPoint>(), new TimePriority(),
                    new Geography());

            matcher.setMaxRadius(Double.parseDouble(properties.getProperty("matcher.radius.max",
                    Double.toString(matcher.getMaxRadius()))));
            matcher.setMaxDistance(Double.parseDouble(properties.getProperty("matcher.distance.max",
                    Double.toString(matcher.getMaxDistance()))));
            matcher.setLambda(Double.parseDouble(properties.getProperty("matcher.lambda",
                    Double.toString(matcher.getLambda()))));
            matcher.setSigma(Double.parseDouble(
                    properties.getProperty("matcher.sigma", Double.toString(matcher.getSigma()))));
            interval = Integer.parseInt(properties.getProperty("matcher.interval.min", "1000"));
            distance = Integer.parseInt(properties.getProperty("matcher.distance.min", "0"));
            sensitive = Double.parseDouble(
                    properties.getProperty("tracker.monitor.sensitive", Double.toString(0d)));
            TTL = Integer.parseInt(properties.getProperty("tracker.state.ttl", "60"));
            int port = Integer.parseInt(properties.getProperty("tracker.port", "1235"));
            memory = new TemporaryMemory<>(new Factory<State>() {
                @Override
                public State newInstance(String id) {
                    return new State(id);
                }
            }, new StatePublisher(port));

            logger.info("tracker.state.ttl={}", TTL);
            logger.info("tracker.port={}", port);
            logger.info("tracker.monitor.sensitive={}", sensitive);
            int matcherThreads = Integer.parseInt(properties.getProperty("matcher.threads",
                    Integer.toString(Runtime.getRuntime().availableProcessors())));

            StaticScheduler.reset(matcherThreads, (long) 1E4);

            logger.info("matcher.radius.max={}", matcher.getMaxRadius());
            logger.info("matcher.distance.max={}", matcher.getMaxDistance());
            logger.info("matcher.lambda={}", matcher.getLambda());
            logger.info("matcher.sigma={}", matcher.getSigma());
            logger.info("matcher.threads={}", matcherThreads);
            logger.info("matcher.interval.min={}", interval);
            logger.info("matcher.distance.min={}", distance);
        }

        @Override
        protected ResponseHandler response(String request) {
            return new ResponseHandler(request) {
                @Override
                protected RESULT response(String request, StringBuilder response) {
                    try {
                        JSONObject json = new JSONObject(request);

                        if (!json.optString("id").isEmpty()) {
                            if (!json.optString("time").isEmpty()
                                    && !json.optString("point").isEmpty()) {

                                final MatcherSample sample = new MatcherSample(json);
                                final State state = memory.getLocked(sample.id());

                                if (state.inner.sample() != null) {
                                    if (sample.time() < state.inner.sample().time()) {
                                        state.unlock();
                                        logger.warn("received out of order sample");
                                        return RESULT.ERROR;
                                    }
                                    if (spatial.distance(sample.point(),
                                            state.inner.sample().point()) < Math.max(0, distance)) {
                                        state.unlock();
                                        logger.debug("received sample below distance threshold");
                                        return RESULT.SUCCESS;
                                    }
                                    if ((sample.time() - state.inner.sample().time()) < Math.max(0,
                                            interval)) {
                                        state.unlock();
                                        logger.debug("received sample below interval threshold");
                                        return RESULT.SUCCESS;
                                    }
                                }

                                final AtomicReference<Set<MatcherCandidate>> vector =
                                        new AtomicReference<>();
                                InlineScheduler scheduler = StaticScheduler.scheduler();
                                scheduler.spawn(new Task() {
                                    @Override
                                    public void run() {
                                        Stopwatch sw = new Stopwatch();
                                        sw.start();
                                        vector.set(matcher.execute(state.inner.vector(),
                                                state.inner.sample(), sample));
                                        sw.stop();
                                        logger.debug("state update of object {} processed in {} ms",
                                                sample.id(), sw.ms());
                                    }
                                });

                                if (!scheduler.sync()) {
                                    state.unlock();
                                    logger.error("matcher execution error");
                                    return RESULT.ERROR;
                                } else {
                                    boolean publish = true;
                                    MatcherSample previousSample = state.inner.sample();
                                    MatcherCandidate previousEstimate = state.inner.estimate();
                                    state.inner.update(vector.get(), sample);

                                    if (previousSample != null && previousEstimate != null) {
                                        if (spatial.distance(previousSample.point(),
                                                sample.point()) < sensitive
                                                && previousEstimate.point().edge()
                                                        .id() == state.inner.estimate().point()
                                                                .edge().id()) {
                                            publish = false;
                                            logger.debug("unpublished update");
                                        }
                                    }

                                    state.updateAndUnlock(TTL, publish);
                                    return RESULT.SUCCESS;
                                }
                            } else {
                                String id = json.getString("id");
                                logger.debug("received state request for object {}", id);

                                State state = memory.getIfExistsLocked(id);

                                if (state != null) {
                                    response.append(state.inner.toJSON().toString());
                                    state.unlock();
                                } else {
                                    JSONObject empty = new JSONObject();
                                    empty.put("id", id);
                                    response.append(empty.toString());
                                }

                                return RESULT.SUCCESS;
                            }
                        } else if (json.optJSONArray("roads") != null) {
                            logger.debug("received road data request");

                            return RESULT.SUCCESS;
                        } else {
                            throw new RuntimeException(
                                    "JSON request faulty or incomplete: " + request);
                        }
                    } catch (Exception e) {
                        logger.error("{}", e.getMessage());
                        e.printStackTrace();
                        return RESULT.ERROR;
                    }
                }
            };
        }
    }

    private static class State extends TemporaryElement<State> {
        final MatcherKState inner = new MatcherKState();

        public State(String id) {
            super(id);
        }
    };

    private static class StatePublisher extends Thread implements Publisher<State> {
        private BlockingQueue<String> queue = new LinkedBlockingDeque<>();
        private ZMQ.Context context = null;
        private ZMQ.Socket socket = null;

        public StatePublisher(int port) {
            context = ZMQ.context(1);
            socket = context.socket(ZMQ.PUB);
            socket.bind("tcp://*:" + port);
            this.setDaemon(true);
            this.start();
        }

        @Override
        public void run() {
            while (true) {
                try {
                    String message = queue.take();
                    socket.send(message);
                } catch (InterruptedException e) {
                    logger.warn("state publisher interrupted");
                    return;
                }
            }
        }

        @Override
        public void publish(String id, TrackerServer.State state) {
            try {
                JSONObject json = state.inner.toMonitorJSON();
                json.put("id", id);
                queue.put(json.toString());
            } catch (Exception e) {
                logger.error("update failed: {}", e.getMessage());
                e.printStackTrace();
            }
        }

        @Override
        public void delete(String id, long time) {
            try {
                JSONObject json = new JSONObject();
                json.put("id", id);
                json.put("time", time);
                queue.put(json.toString());
                logger.debug("delete object {}", id);
            } catch (Exception e) {
                logger.error("delete failed: {}", e.getMessage());
                e.printStackTrace();
            }
        }
    }
}


text:
<bill session="115" type="sc" number="21" updated="2017-09-11T02:39:34Z">
  <state datetime="2017-06-29">REFERRED</state>
  <status>
    <introduced datetime="2017-06-29"/>
  </status>
  <introduced datetime="2017-06-29"/>
  <titles>
    <title type="official" as="introduced">A concurrent resolution urging the Government of the People's Republic of China to unconditionally release Liu Xiaobo, together with his wife Liu Xia, to allow them to freely meet with friends, family, and counsel and seek medical treatment wherever they desire.</title>
    <title type="display">A concurrent resolution urging the Government of the People's Republic of China to unconditionally release Liu Xiaobo, together with his wife Liu Xia, to allow them to freely meet with friends, family, and counsel and seek medical treatment wherever they desire.</title>
  </titles>
  <sponsor bioguide_id="R000595"/>
  <cosponsors>
    <cosponsor bioguide_id="C001098" joined="2017-06-29"/>
    <cosponsor bioguide_id="D000563" joined="2017-07-11"/>
    <cosponsor bioguide_id="M001176" joined="2017-06-29"/>
  </cosponsors>
  <actions>
    <action datetime="2017-06-29">
      <text>Introduced in Senate</text>
    </action>
    <action datetime="2017-06-29" state="REFERRED">
      <text>Referred to the Committee on Foreign Relations.</text>
      <reference ref="CR S3866" label="text of measure as introduced"/>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="SSFR" name="Senate Foreign Relations" activity="Referral"/>
  </committees>
  <relatedbills>
    <bill type="hc" session="115" relation="unknown" number="67"/>
  </relatedbills>
  <subjects>
    <term name="International affairs"/>
    <term name="Asia"/>
    <term name="China"/>
    <term name="Congressional tributes"/>
    <term name="Detention of persons"/>
    <term name="Human rights"/>
    <term name="Protest and dissent"/>
    <term name="Sovereignty, recognition, national governance and status"/>
  </subjects>
  <amendments/>
  <summary date="2017-06-29T04:00:00Z" status="Introduced in Senate">Recognizes Liu Xiaobo for his decades of peaceful struggle for basic human rights and democracy in the People's Republic of China.

Urges the Chinese government to unconditionally release Liu Xiaobo and his wife, Liu Xia, and the President to seek their humanitarian transfer from China so that Liu Xiaobo can seek medical treatment in the United States or elsewhere overseas.</summary>
  <committee-reports/>
</bill>


text:
package edu.iu.grid.oim.model.db.record;

import java.sql.ResultSet;
import java.sql.SQLException;

public class CampusGridFieldOfScienceRecord extends RecordBase
{
	@Key public Integer campusgrid_id;
	@Key public Integer field_of_science_id;

	//load from existing record
	public CampusGridFieldOfScienceRecord(ResultSet rs) throws SQLException { super(rs); }
	//for creating new record
	public CampusGridFieldOfScienceRecord() {}
}


text:
var AWS = require('./core');
require('./credentials');
require('./credentials/credential_provider_chain');

/**
 * The main configuration class used by all service objects to set
 * the region, credentials, and other options for requests.
 *
 * By default, credentials and region settings are left unconfigured.
 * This should be configured by the application before using any
 * AWS service APIs.
 *
 * In order to set global configuration options, properties should
 * be assigned to the global {AWS.config} object.
 *
 * @see AWS.config
 *
 * @!attribute credentials
 *   @return [AWS.Credentials] the AWS credentials to sign requests with.
 *
 * @!attribute region
 *   @example Set the global region setting to us-west-2
 *     AWS.config.update({region: 'us-west-2'});
 *   @return [AWS.Credentials] The region to send service requests to.
 *   @see http://docs.amazonwebservices.com/general/latest/gr/rande.html
 *     A list of available endpoints for each AWS service
 *
 * @!attribute maxRetries
 *   @return [Integer] the maximum amount of retries to perform for a
 *     service request. By default this value is calculated by the specific
 *     service object that the request is being made to.
 *
 * @!attribute maxRedirects
 *   @return [Integer] the maximum amount of redirects to follow for a
 *     service request. Defaults to 10.
 *
 * @!attribute paramValidation
 *   @return [Boolean] whether input parameters should be validated against
 *     the operation description before sending the request. Defaults to true.
 *
 * @!attribute computeChecksums
 *   @return [Boolean] whether to compute checksums for payload bodies when
 *     the service accepts it (currently supported in S3 only).
 *
 * @!attribute sslEnabled
 *   @return [Boolean] whether SSL is enabled for requests
 *
 * @!attribute s3ForcePathStyle
 *   @return [Boolean] whether to force path style URLs for S3 objects
 *
 * @!attribute httpOptions
 *   @return [map] A set of options to pass to the low-level HTTP request.
 *     Currently supported options are:
 *
 *     * **proxy** [String] — the URL to proxy requests through
 *     * **agent** [http.Agent, https.Agent] — the Agent object to perform
 *       HTTP requests with. Used for connection pooling. Defaults to the global
 *       agent (`http.globalAgent`) for non-SSL connections. Note that for
 *       SSL connections, a special Agent object is used in order to enable
 *       peer certificate verification. This feature is only supported in the
 *       Node.js environment.
 *     * **timeout** [Integer] — The number of milliseconds to wait before
 *       giving up on a connection attempt. Defaults to no timeout.
 *
 * @!attribute logger
 *   @return [#write,#log] an object that responds to .write() (like a stream)
 *     or .log() (like the console object) in order to log information about
 *     requests
 *
 * @!attribute signatureVersion
 *   @return [String] the signature version to sign requests with (overriding
 *     the API configuration). Possible values are: 'v2', 'v3', 'v4'.
 */
AWS.Config = AWS.util.inherit({

  /**
   * Creates a new configuration object. This is the object that passes
   * option data along to service requests, including credentials, security,
   * region information, and some service specific settings.
   *
   * @example Creating a new configuration object with credentials and region
   *   var config = new AWS.Config({
   *     accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-west-2'
   *   });
   * @option options accessKeyId [String] your AWS access key ID.
   * @option options secretAccessKey [String] your AWS secret access key.
   * @option options sessionToken [AWS.Credentials] the optional AWS
   *   session token to sign requests with.
   * @option options credentials [AWS.Credentials] the AWS credentials
   *   to sign requests with. You can either specify this object, or
   *   specify the accessKeyId and secretAccessKey options directly.
   * @option options credentialProvider [AWS.CredentialProviderChain] the
   *   provider chain used to resolve credentials if no static `credentials`
   *   property is set.
   * @option options region [String] the region to send service requests to.
   *   See {region} for more information.
   * @option options maxRetries [Integer] the maximum amount of retries to
   *   attempt with a request. See {maxRetries} for more information.
   * @option options maxRedirects [Integer] the maximum amount of redirects to
   *   follow with a request. See {maxRedirects} for more information.
   * @option options sslEnabled [Boolean] whether to enable SSL for
   *   requests.
   * @option options paramValidation [Boolean] whether parameter validation
   *   is on.
   * @option options computeChecksums [Boolean] whether to compute checksums
   *   for payload bodies when the service accepts it (currently supported
   *   in S3 only)
   * @option options s3ForcePathStyle [Boolean] whether to force path
   *   style URLs for S3 objects.
   * @option options httpOptions [map] A set of options to pass to the low-level
   *   HTTP request. Currently supported options are:
   *
   *   * **proxy** [String] — the URL to proxy requests through
   *   * **agent** [http.Agent, https.Agent] — the Agent object to perform
   *     HTTP requests with. Used for connection pooling. Defaults to the global
   *     agent (`http.globalAgent`) for non-SSL connections. Note that for
   *     SSL connections, a special Agent object is used in order to enable
   *     peer certificate verification. This feature is only available in the
   *     Node.js environment.
   *   * **timeout** [Integer] — Sets the socket to timeout after timeout
   *     milliseconds of inactivity on the socket. Defaults to no timeout.
   * @option options apiVersion [String, Date] a String in YYYY-MM-DD format
   *   (or a date) that represents the latest possible API version that can be
   *   used in all services (unless overridden by `apiVersions`). Specify
   *   'latest' to use the latest possible version.
   * @option options apiVersions [map<String, String|Date>] a map of service
   *   identifiers (the lowercase service class name) with the API version to
   *   use when instantiating a service. Specify 'latest' for each individual
   *   that can use the latest available version.
   * @option options logger [#write,#log] an object that responds to .write()
   *   (like a stream) or .log() (like the console object) in order to log
   *   information about requests
   * @option options signatureVersion [String] the signature version to sign
   *   requests with (overriding the API configuration). Possible values are:
   *   'v2', 'v3', 'v4'.
   */
  constructor: function Config(options) {
    if (options === undefined) options = {};
    options = this.extractCredentials(options);

    AWS.util.each.call(this, this.keys, function (key, value) {
      this.set(key, options[key], value);
    });
  },

  /**
   * @overload update(options, allowUnknownKeys = false)
   *   Updates the current configuration object with new options.
   *
   *   @example Update maxRetries property of a configuration object
   *     config.update({maxRetries: 10});
   *   @param [Object] options a map of option keys and values.
   *   @param [Boolean] allowUnknownKeys whether unknown keys can be set on
   *     the configuration object. Defaults to `false`.
   *   @see constructor
   */
  update: function update(options, allowUnknownKeys) {
    allowUnknownKeys = allowUnknownKeys || false;
    options = this.extractCredentials(options);
    AWS.util.each.call(this, options, function (key, value) {
      if (allowUnknownKeys || this.keys.hasOwnProperty(key)) this[key] = value;
    });
  },

  /**
   * @api private
   */
  getCredentials: function getCredentials(callback) {
    var self = this;

    function finish(err) {
      callback(err, err ? null : self.credentials);
    }

    function credError(msg, err) {
      return new AWS.util.error(err || new Error(), {
        code: 'CredentialsError', message: msg
      });
    }

    function getAsyncCredentials() {
      self.credentials.get(function(err) {
        if (err) {
          var msg = 'Could not load credentials from ' +
            self.credentials.constructor.name;
          err = credError(msg, err);
        }
        finish(err);
      });
    }

    function getStaticCredentials() {
      var err = null;
      if (!self.credentials.accessKeyId || !self.credentials.secretAccessKey) {
        err = credError('Missing credentials');
      }
      finish(err);
    }

    if (self.credentials) {
      if (typeof self.credentials.get === 'function') {
        getAsyncCredentials();
      } else { // static credentials
        getStaticCredentials();
      }
    } else if (self.credentialProvider) {
      self.credentialProvider.resolve(function(err, creds) {
        if (err) {
          err = credError('Could not load credentials from any providers', err);
        }
        self.credentials = creds;
        finish(err);
      });
    } else {
      finish(credError('No credentials to load'));
    }
  },

  /**
   * Loads configuration data from a JSON file into this config object.
   * @note Loading configuration will reset all existing configuration
   *   on the object.
   * @!macro nobrowser
   * @param path [String] the path to load configuration from
   * @return [AWS.Config] the same configuration object
   */
  loadFromPath: function loadFromPath(path) {
    this.clear();

    var options = JSON.parse(AWS.util.readFileSync(path));
    var fileSystemCreds = new AWS.FileSystemCredentials(path);
    var chain = new AWS.CredentialProviderChain();
    chain.providers.unshift(fileSystemCreds);
    chain.resolve(function (err, creds) {
      if (err) throw err;
      else options.credentials = creds;
    });

    this.constructor(options);

    return this;
  },

  /**
   * Clears configuration data on this object
   *
   * @api private
   */
  clear: function clear() {
    /*jshint forin:false */
    AWS.util.each.call(this, this.keys, function (key) {
      delete this[key];
    });

    // reset credential provider
    this.set('credentials', undefined);
    this.set('credentialProvider', undefined);
  },

  /**
   * Sets a property on the configuration object, allowing for a
   * default value
   * @api private
   */
  set: function set(property, value, defaultValue) {
    if (value === undefined) {
      if (defaultValue === undefined) {
        defaultValue = this.keys[property];
      }
      if (typeof defaultValue === 'function') {
        this[property] = defaultValue.call(this);
      } else {
        this[property] = defaultValue;
      }
    } else {
      this[property] = value;
    }
  },

  /**
   * All of the keys with their default values.
   *
   * @constant
   * @api private
   */
  keys: {
    credentials: null,
    credentialProvider: null,
    region: null,
    logger: null,
    apiVersions: {},
    apiVersion: null,
    endpoint: undefined,
    httpOptions: {},
    maxRetries: undefined,
    maxRedirects: 10,
    paramValidation: true,
    sslEnabled: true,
    s3ForcePathStyle: false,
    computeChecksums: true,
    dynamoDbCrc32: true
  },

  /**
   * Extracts accessKeyId, secretAccessKey and sessionToken
   * from a configuration hash.
   *
   * @api private
   */
  extractCredentials: function extractCredentials(options) {
    if (options.accessKeyId && options.secretAccessKey) {
      options = AWS.util.copy(options);
      options.credentials = new AWS.Credentials(options);
    }
    return options;
  }
});

/**
 * @return [AWS.Config] The global configuration object singleton instance
 * @readonly
 * @see AWS.Config
 */
AWS.config = new AWS.Config();


text:
from datetime import datetime

from canvas.core.courses import get_courses, get_course_people
from canvas.core.io import write_xlsx_file, tada

from canvas.core.assignments import get_assignments

def turnitin_api_assignments():
    terms = ['2016-3FA']
    programs = []
    synergis = True
    course_whitelist = []
    header = ['term', 'program', 'SIS ID', 'assignment name', 'assignment URL', 'due date', 'submission types',
              'points', 'rubric with grading criteria', 'rubric with CLOs', 'group assignment', 'faculty of record',
              'lti', 'api']
    rows = []

    for course in get_courses(terms, programs, synergis, course_whitelist):
        course_id = course['id']
        course_sis_id = course['sis_course_id']
        program = course['course_sis_info']['program']
        for assignment in get_assignments(course_id):
            api = 'turnitin_enabled' in assignment and assignment['turnitin_enabled']
            lti = 'external_tool' in assignment['submission_types']
            if api or lti:
                rubric_has_criteria = ''
                rubric_has_clos = ''
                if 'rubric' in assignment:
                    for criterion in assignment['rubric']:
                        if 'outcome_id' in criterion:
                            rubric_has_clos = 'X'
                        if 'id' in criterion:
                            rubric_has_criteria = 'X'
                row = [terms[0],
                       program,
                       course_sis_id,
                       assignment['name'],
                       assignment['html_url'],
                       assignment['due_at'][0:10] if assignment['due_at'] else '',
                       ', '.join(assignment['submission_types']),
                       assignment['points_possible'] if assignment['points_possible'] else '',
                       rubric_has_criteria,
                       rubric_has_clos,
                       'X' if 'group_category_id' in assignment and assignment['group_category_id'] else '',
                       ', '.join([p['name'] for p in get_course_people(course_id, 'Faculty of record')]),
                       'X' if lti else '',
                       'X' if api else '']
                rows.append(row)
                print(row)

    write_xlsx_file('turnitin_api_&_assignments_{}_{}'
                    .format(terms[0], datetime.now().strftime('%Y.%m.%d.%H.%M.%S')), header, rows)

if __name__ == '__main__':
    turnitin_api_assignments()
    tada()


text:
package org.elasticsearch.xpack.core.ml.action;

import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.test.AbstractWireSerializingTestCase;
import org.elasticsearch.xpack.core.ml.action.DeleteTrainedModelAction.Request;

public class DeleteTrainedModelsRequestTests extends AbstractWireSerializingTestCase<Request> {

    @Override
    protected Request createTestInstance() {
        return new Request(randomAlphaOfLengthBetween(1, 20));
    }

    @Override
    protected Writeable.Reader<Request> instanceReader() {
        return Request::new;
    }
}


text:
layout: post
title: "Bài viết sử dụng markdown"
category : advertising
tagline: "(P.1)"
tags : [video, ads, online, marketing]
---

{% include JB/setup %}

## Markdown

Khi không có kẻ thật lâu đứng nhìn
Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg

Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg

<!-- must have a image with ALT -->
![Hình ảnh](https://octodex.github.com/images/yaktocat.png)

Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg

<!-- must have 2 link to trust site -->
Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg [keyword](http://wikipedia.org/keyword) Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg Lorem ispsum kaka hungyr kjiongg


text:
package com.google.cloud.video.livestream.v1.samples;

// [START livestream_v1_generated_LivestreamService_ListEvents_sync]
import com.google.cloud.video.livestream.v1.ChannelName;
import com.google.cloud.video.livestream.v1.Event;
import com.google.cloud.video.livestream.v1.ListEventsRequest;
import com.google.cloud.video.livestream.v1.LivestreamServiceClient;

public class SyncListEvents {

  public static void main(String[] args) throws Exception {
    syncListEvents();
  }

  public static void syncListEvents() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (LivestreamServiceClient livestreamServiceClient = LivestreamServiceClient.create()) {
      ListEventsRequest request =
          ListEventsRequest.newBuilder()
              .setParent(ChannelName.of("[PROJECT]", "[LOCATION]", "[CHANNEL]").toString())
              .setPageSize(883849137)
              .setPageToken("pageToken873572522")
              .setFilter("filter-1274492040")
              .setOrderBy("orderBy-1207110587")
              .build();
      for (Event element : livestreamServiceClient.listEvents(request).iterateAll()) {
        // doThingsWith(element);
      }
    }
  }
}
// [END livestream_v1_generated_LivestreamService_ListEvents_sync]


text:
class CableReady::ChannelGenerator < Rails::Generators::NamedBase
  source_root File.expand_path("templates", __dir__)

  class_option :stream_from, type: :string
  class_option :stream_for, type: :string
  class_option :stimulus, type: :boolean

  def check_options
    raise "Can't specify --stream-from and --stream-for at the same time" if options.key?(:stream_from) && options.key?(:stream_for)
  end

  def create_channel
    generate "channel", file_name
  end

  def enhance_channels
    if using_broadcast_to?
      gsub_file "app/channels/#{file_name}_channel.rb", /# stream_from.*\n/, "stream_for #{resource}.find(params[:id])\n"
      template "app/javascript/controllers/%file_name%_controller.js" if using_stimulus?
    else
      prepend_to_file "app/javascript/channels/#{file_name}_channel.js", "import CableReady from 'cable_ready'\n"
      inject_into_file "app/javascript/channels/#{file_name}_channel.js", after: "// Called when there's incoming data on the websocket for this channel\n" do
        <<-JS
    if (data.cableReady) CableReady.perform(data.operations)
        JS
      end

      gsub_file "app/channels/#{file_name}_channel.rb", /# stream_from.*\n/, "stream_from \"#{identifier}\"\n"
    end
  end

  private

  def option_given?
    options.key?(:stream_from) || options.key?(:stream_for)
  end

  def using_broadcast_to?
    @using_broadcast_to ||= option_given? ? options.key?(:stream_for) : yes?("Are you streaming to a resource using broadcast_to? (y/N)")
  end

  def using_stimulus?
    @using_stimulus ||= options.fetch(:stimulus) {
      yes?("Are you going to use a Stimulus controller to subscribe to this channel? (y/N)")
    }
  end

  def resource
    return @resource if @resource

    stream_for = options.fetch(:stream_for) {
      ask("Which resource are you streaming for?", default: class_name)
    }

    stream_for = file_name if stream_for == "stream_for"
    @resource = stream_for.camelize
  end

  def identifier
    return @identifier if @identifier

    stream_from = options.fetch(:stream_from) {
      ask("What is the stream identifier that goes into stream_from?", default: file_name)
    }

    stream_from = file_name if stream_from == "stream_from"
    @identifier = stream_from.underscore
  end
end


text:
local select, tostring, term, type = select, tostring, term, type
local queueEvent, pullEvent = os.queueEvent, os.pullEvent
local grin = grin
local insert, remove = table.insert, table.remove

local write, print = write, print

local function doWrite(write, ...)
    local sum = 0
    local n = select('#', ...)
    for i = 1, n do
        if i > 1 then
            sum = sum + (write("\t") or 0)
        end

        sum = sum + (write(tostring(select(n, ...))) or 0)
    end

    return sum
end

local function doPrint(write, ...)
    return doWrite(write, ...) +  write("\n")
end

--- Basic stdin: just reads from terminal
function stdIn(read)
    return {readLine = read, close = function() end}
end

--- Basic stdout: just writes to terminal
function stdOut()
    return {write = write, writeLine = print, flush = function() end, close = function() end}
end

--- Stderr: coloured stdout. Nothing fancy
function stdErr()
    local stderr = stdOut()

    function stderr.write(x)
        if type(x) ~= "string" then error("Expected string", 2) end

        local old = term.getTextColor()
        if term.isColor() then term.setTextColor(colors.red) end
        write(tostring(x))
        if term.isColor() then term.setTextColor(old) end
    end

    function stderr.writeLine(...)
        local old = term.getTextColor()
        if term.isColor() then term.setTextColor(colors.red) end
        local n = doPrint(write, ...)
        if term.isColor() then term.setTextColor(old) end

        return n
    end

    return stderr
end

--- An output that redirects to a file
function fileOut(path, mode)
    if mode == "append" then
        mode = "a"
    elseif mode == "write" then
        mode = "w"
    end

    local stdout = fs.open(path, mode)
    if not stdout then error("File could not be opened: " .. fname, 0) end

    local oldWriteLine = stdout.writeLine
    stdout.writeLine = function(...)
        doWrite(stdout.write, ...)
        oldWriteLine("")
        return 1
    end

    stdout.isPiped = true

    return stdout
end

--- Simply stores a list of lines
function linesOut()
    local lineBuffer = ""
    local lines = {}

    local stdout = {isPiped = true, writeLine = print}
    function stdout.write(s)
        grin.expect("string", s)
        local nLines = 0

        local pos, len = 1, #s
        while pos <= len do
            local newPos = s:find("\n", pos)

            if newPos then
                insert(lines, lineBuffer .. s:sub(pos, newPos - 1))
                lineBuffer = ""
                nLines = nLines + 1
            else
                newPos = len
                lineBuffer = lineBuffer .. s:sub(pos, newPos)
            end

            pos = newPos + 1
        end

        return nLines
    end

    function stdout.writeLine(...)
        return doPrint(stdout.write, ...)
    end

    function stdout.flush() end

    function stdout.close()
        if lineBuffer ~= "" then
            insert(lines, lineBuffer)
            lineBuffer = ""
        end
    end

    return stdout, lines
end

--- A command pipe
function pipe()
    local lineBuffer = ""
    local lines = {}
    local CLOSE = {}

    local stdout = {isPiped = true}
    local next_stdin = { isPiped = true }
    function stdout.write(s)
        grin.expect("string", s)
        local nLines = 0

        local pos, len = 1, #s
        while pos <= len do
            local newPos = s:find("\n", pos)

            if newPos then
                insert(lines, lineBuffer .. s:sub(pos, newPos - 1))
                lineBuffer = ""
                nLines = nLines + 1
            else
                newPos = len
                lineBuffer = lineBuffer .. s:sub(pos, newPos)
            end

            pos = newPos + 1
        end

        if nLines > 0 then
            queueEvent("clamshell_pipeline_buffer_update")
        end
        return nLines
    end

    function stdout.writeLine(...)
        return doPrint(stdout.write, ...)
    end

    function stdout.flush() end

    function stdout.close()
        if lineBuffer ~= "" then
            insert(lines, lineBuffer)
            lineBuffer = ""
        end
        insert(lines, CLOSE)
        queueEvent("clamshell_pipeline_buffer_update")
    end

    function next_stdin.readLine()
        while not lines[1] do
            pullEvent("clamshell_pipeline_buffer_update")
        end
        if lines[1] == CLOSE then
            return
        end
        return remove(lines, 1)
    end

    function next_stdin.close()
    end

    return stdout, next_stdin
end

function createPrint(stream)
    return function(...)
        local lines = stream.writeLine(...)
        stream.flush()
        return lines
    end
end


text:
// Compress/CopyCoder.cpp

#include "StdAfx.h"

#include "../../../C/Alloc.h"

#include "../Common/StreamUtils.h"

#include "CopyCoder.h"

namespace NCompress {

static const UInt32 kBufferSize = 1 << 17;

CCopyCoder::~CCopyCoder()
{
  ::MidFree(_buffer);
}

STDMETHODIMP CCopyCoder::Code(ISequentialInStream *inStream,
    ISequentialOutStream *outStream,
    const UInt64 * /* inSize */, const UInt64 *outSize,
    ICompressProgressInfo *progress)
{
  if (_buffer == 0)
  {
    _buffer = (Byte *)::MidAlloc(kBufferSize);
    if (_buffer == 0)
      return E_OUTOFMEMORY;
  }

  TotalSize = 0;
  for (;;)
  {
    UInt32 size = kBufferSize;
    if (outSize != 0)
      if (size > *outSize - TotalSize)
        size = (UInt32)(*outSize - TotalSize);
    RINOK(inStream->Read(_buffer, size, &size));
    if (size == 0)
      break;
    if (outStream)
    {
      RINOK(WriteStream(outStream, _buffer, size));
    }
    TotalSize += size;
    if (progress != NULL)
    {
      RINOK(progress->SetRatioInfo(&TotalSize, &TotalSize));
    }
  }
  return S_OK;
}

STDMETHODIMP CCopyCoder::GetInStreamProcessedSize(UInt64 *value)
{
  *value = TotalSize;
  return S_OK;
}

HRESULT CopyStream(ISequentialInStream *inStream, ISequentialOutStream *outStream, ICompressProgressInfo *progress)
{
  CMyComPtr<ICompressCoder> copyCoder = new NCompress::CCopyCoder;
  return copyCoder->Code(inStream, outStream, NULL, NULL, progress);
}

}


text:
author: steph_kim
categories: languages
excerpt: "Develop your algorithm in R"
image:
    teaser: /language_logos/r.svg
layout: article
show_related: true
tags: [algo-guide-lang]
title:  "R"
---

Before you get started learning about R algorithm development, make sure you go through our Getting Started Guide to learn how to create your first algorithm, understand permissions available, versioning, using the CLI, and more.

Table of contents

* [Available libraries](#available-libraries)
* [Write your first algorithm](#write-your-first-algorithm)
* [Saving and loading R models](#saving-and-loading-r-models)
* [Managing dependencies](#managing-dependencies)
* [I/O for your algorithms](#io-for-your-algorithms)
* [Error handling](#error-handling)
* [Publishing Algorithmia Insights](#publishing-algorithmia-insights)
* [Algorithm checklist](#algorithm-checklist)
* [Publish algorithm](#publish-algorithm)
* [Conclusion and resources](#conclusion-and-resources)

## Available libraries

Algorithmia makes a number of libraries available to make algorithm development easier.

The full R language and standard library version 3.3.6 is available for you to use in your algorithms, which you can find through the "Environment" drop-down when creating a new algorithm:

Furthermore, algorithms can call other algorithms and manage data on the Algorithmia platform via the Algorithmia R language Client.

## Write your first algorithm

If you've followed the Getting Started Guide, you'll notice in your algorithm editor, there is boilerplate code that returns "Hello" and whatever you input to the console.

The main thing to note about the algorithm is that it's wrapped in the algorithm() function.

The algorithm() function defines the input point of the algorithm. We use the algorithm() function in order to make different algorithms standardized. This makes them easily chained and helps authors think about designing their algorithms in a way that makes them easy to leverage and predictable for end users.
{: .notice-info}

Go ahead and remove the boilerplate code below that's inside the algorithm() function because we'll be writing a different algorithm in this tutorial:

## Saving and loading R models

When you have an R model that has been serialized as an .rds file, you can deploy it easily on Algorithmia. All you need to do is save your model:

{% highlight r %}
saveRDS(iris_fit_naive, "./naive_bayes_iris.rds")
{% endhighlight %}

Then follow the instructions for how to work with data using the Data Api in the [R Client Docs]({{site.baseurl}}/clients/r) in order to upload your saved model to Algorithmia hosted data or you can store it in Dropbox or an S3 bucket. To find out more about working with data check out the [Data Portal]({{site.baseurl}}/data).

Here are a couple of demos to show you how to load your hosted .rds file inside your algorithm:

* [Arima Time Series Forecasting Model](https://algorithmia.com/algorithms/demo/rdemo)
* [Naive Bayes Iris Classication Model](https://algorithmia.com/algorithms/demo/irisrdemo)

## Managing dependencies

Now that you have created your algorithm, you can add dependencies.

Algorithmia supports adding 3rd party dependencies via the CRAN (Comprehensive R Archive Network) dependency file.

On the algorithm editor page there is a button on the top right that says "Dependencies". Click that button and you'll see a modal window:

As you can see in the dependency file above, there are four different ways you can load packages in R.
If you want the latest version from CRAN, than you simply type in the dependency name (this example uses the package e1071):

{% highlight bash %}
e1071
{% endhighlight %}

If you wanted that same package in an older version, all you have to do is install from CRAN the exact version by finding it in the packages archive, which in this instance, should be listed in the e1071 docs found under "Old Sources". There you'll find the archived packages, so simply choose your version and load your dependency:

{% highlight bash %}
https://cran.r-project.org/src/contrib/Archive/e1071/e1071_1.6-6.tar.gz
{% endhighlight %}

Or, if you need to pull a dependency off of GitHub instead, all you need to do is install the package with:

{% highlight bash %}
-g /cran/e1071
{% endhighlight %}

Similar to how you would install through dev.tools() in R.

And finally, if you're having issues with version conflicts, for instance package A requires version of package B while package C requires a different version of package B, then you can install with in your dependency file using install.packages():

{% highlight bash %}
-e install.packages("e1071")
{% endhighlight %}

The last format will take longer to load the dependencies than the other formats, so it's best to use it as a last resort.

Note, that if you do add dependencies, you will still need to import those packages via library() to your algorithm file as you would do for any R script.
{: .notice-info}

For example, to make use of e1071, you would include the line:

{% highlight bash %}
e1071
{% endhighlight %}

in the dependencies file and the line

{% highlight bash %}
library(e1071)
{% endhighlight %}

in the main file.

The Algorithmia dependency is already installed for your convenience and relies on R version 3.3.1. For more information about Algorithmia's R package visit:
Algorithmia's CRAN package documentation.

This guide won't depend on any external dependencies so you can close the dependencies window.

Note: if you see an error similar to:
{% highlight bash %}
Error: Failed to start algorithm - Loading required package: methods
Error: package or namespace load failed...
{% endhighlight %}
You'll need to try and add different versions of certain R packages.
{: .notice-info}

If you're using *tidyverse*, add the following lines to your dependencies:
{% highlight bash %}
tidyverse
-t https://cran.r-project.org/src/contrib/Archive/R6/R6_2.2.2.tar.gz
-t https://cran.r-project.org/src/contrib/httr_1.3.1.tar.gz
-t https://cran.r-project.org/src/contrib/jsonlite_1.5.tar.gz
withr
{% endhighlight %}

If you still get an error, try a different version directly from the CRAN archives:

{% highlight bash %}
tidyverse
-t https://cran.r-project.org/src/contrib/Archive/R6/R6_2.2.2.tar.gz
-t https://cran.r-project.org/src/contrib/Archive/httr/httr_1.4.0.tar.gz
-t https://cran.r-project.org/src/contrib/Archive/jsonlite/jsonlite_1.5.tar.gz
withr
{% endhighlight %}

For *dplyr*, use:
{% highlight bash %}
dplyr
-t https://cran.r-project.org/src/contrib/Archive/R6/R6_2.2.2.tar.gz
withr
{% endhighlight %}

If you're using both *caret* and *nnet* in the same Algorithm add:
{% highlight bash %}
caret
-t https://cran.r-project.org/src/contrib/Archive/R6/R6_2.2.2.tar.gz
-t https://cran.r-project.org/src/contrib/nnet_7.3-12.tar.gz
{% endhighlight %}

## I/O for your algorithms

Now let's get started on the hands-on portion of the guide:

The first algorithm that we'll create will take a JSON formatted object passed as input by the user which is deserialized into a R list before the algorithm is called.

It will output a JSON formatted object which the user will consume with an API call to the algorithm path which is found at the bottom of the algorithm description page.

This path is based on your Algorithmia user name and the name of your algorithm, so if you are "demo" and your algorithm is "TokenizeText", then the path for version 0.1.1 of your algorithm will be demo/TokenizeText/0.1.1

Note that Algorithmia uses `rjson` to automatically (de)serialize input and output for you. If you are used to using `jsonlite` or another JSON package, certain datastructures (especially matrices and dataframes) will be structured differently in the I/O. We recommend reviewing [this excellent guide](https://rstudio-pubs-static.s3.amazonaws.com/31702_9c22e3d1a0c44968a4a1f9656f1800ab.html) which explains the differences.
{: .notice-warning}

### Working with basic data structures

Below is a code sample showing how to create an algorithm working with basic user input.

You'll also see some error handling within the algorithm, but we recommend that you take a look at our Better Error Handling Guide for more information.

{% highlight r %}
library(algorithmia)

# Note that you don't pass in your API key when creating an algorithm
client <- getAlgorithmiaClient()

# Create a generic error function
AlgorithmError <- function(error){
  stop(error, call. = FALSE)
}

algorithm <- function(input){
  # Finds the minimum and maximum numbers.
  tryCatch({
    if(typeof(input) == "list" & length(input$numbers) > 1){

      user_max <- max(input$numbers)
      user_min <- min(input$numbers)
      return(list(min_num = user_min, max_num = user_max))
    } else {
      print("Please pass in a valid input")
    }

  }, error = function(e) {
    AlgorithmError(paste("Please pass in a valid input", "\n", e))
  }
  )
}

{% endhighlight %}

Go ahead and type or paste the code sample above in the Algorithmia code editor after removing the "Hello World" boilerplate code.

Now compile the new code sample and when that's done test the code in the console by passing in the input and hitting enter on your keyboard:

{% highlight bash %}
{"numbers": [1, 4, 2, 6, 3]}
{% endhighlight %}

You should see the minimum and maximum of the numbers in the list returned in the console:
{% highlight bash %}
{"max_num":6, "min_num":1}
{% endhighlight %}

### Working with data stored on Algorithmia

This next code snippet shows how to create an algorithm working with a data file that a user has stored using Algorithmia's [Hosted Data Source]({{site.baseurl}}/data/hosted).

Files stored in [Hosted Data]({{site.baseurl}}/data/hosted) must be transferred into the algorithm before use, via the [getFile](https://algorithmia.com/developers/api/?r#files) method. Alternately, their contents can be transferred using [getString, getJson, or getBytes](https://algorithmia.com/developers/api/?r#files).
{: .notice-warning}

#### Prerequisites
If you wish to follow along working through the example yourself, create a text file that contains any unstructured text such as a chapter from a public domain book or article. We used a chapter from [Burning Daylight, by Jack London](https://en.wikisource.org/wiki/Burning_Daylight) which you can copy and paste into a text file. Or copy and paste it from here: Chapter One Burning Daylight, by Jack London. Then you will can upload it into one of your [Data Collections](/data/hosted).

This example shows how to create an algorithm that takes a user's file which is stored in a data collection on the Algorithmia platform. It then splits up the text into sentences and then splits those sentences up into words:

{% highlight r %}
library(algorithmia)

client <- getAlgorithmiaClient()

# Create a generic error function
AlgorithmError <- function(error){
  stop(error, call. = FALSE)
}

algorithm <- function(input){
  tryCatch({
    # Download contents of file as a string
    if (client$file(input$user_file)$exists()) {
      # Get the contents of the file as a string.
      text <- client$file(input$user_file)$getString()
      sentences <- strsplit(text, "[.]")
      # Split up each sentence into words.
      words <- strsplit(unlist(sentences), "[ ]")
      print(words)
    }
    }, error = function(e) {
     AlgorithmError(paste("Please pass in a valid input", "\n", e))
   })
}
{% endhighlight %}

After you paste the above code into the Algorithmia code editor you can compile and then test the example by passing in a file that you've hosted in [Data Collections](/data/hosted).

Following the example below replace the path to your data collection with your user name (it will appear already if you are logged in), data collection name, and data file name which you can find under "My Collections" in [Data Collections](/data/hosted):

{% highlight bash %}
{"user_file": "data://YOUR_USERNAME/data_collection_dir/data_file.txt"}
{% endhighlight %}

The code above with return both the original text and the sentence split up into words.

This guide uses a chapter from the public domain book [Burning Daylight, by Jack London](https://en.wikisource.org/wiki/Burning_Daylight), but for brevity we'll only show the first sentence in "text" and "words":

{% highlight bash %}
{"text": "It was a quiet night in the Shovel.", "words": [['It', 'was', 'a', 'quiet', 'night', 'in', 'the', 'Shovel']]}
{% endhighlight %}

When you are creating an algorithm be mindful of the data types you require from the user and the output you return to them. Our advice is to create algorithms that allow for a few different input types such as a file, a sequence or a URL.
{: .notice-info}

#### Working with JSON data

Note that we use the rjson package to parse JSON within your algorithm.

### Working with directories

While running, algorithms have access to a temporary filesystem located at `/tmp`, the contents of which do not persist across calls to the algorithm. While the Data API allows you to get the contents of the files you want to work with as JSON, a string, or raw bytes, in some cases you might need your algorithm to read and write files locally. This can be useful as a temporary location to store files downloaded from Hosted Data, such as raw data for processing or models to be loaded into your algorithms. It can also be used to write new files before uploading them via the Data API.

For reference, [this gist](https://gist.github.com/StephanieKim/56af1aeb6dcd895e2c914bad8c35876c) provides an example of iterating over data in a directory, processing it, and writing new data to a file, while [this template for ALBERT and Tensorflow](https://algorithmia.com/algorithms/asli/albert_template/source) provides an example of using the `/tmp` directory to load a model.

### Writing files for the user to consume

Sometimes it is more appropriate to write your output to a file than to return it directly to the caller.  In these cases, you may need to create a temporary file, then copy it to a [Data URI](http://docs.algorithmia.com/#data-api-specification) (usually one which the caller specified in their request, or a [Temporary Algorithm Collection]({{site.baseurl}}/data/hosted#temporary-algorithm-collections)):

{% highlight r %}
# {"target_file":"data://username/collection/filename.txt"}
file_uri <- input$target_file
tempfile <- sprintf("/tmp/%s.tmp",UUIDgenerate())
save_some_output_to(tempfile)
client$file(file_uri)$putFile(tempfile)
{% endhighlight %}

### Calling other algorithms and managing data

To call other algorithms or manage data from your algorithm, use the Algorithmia R Client which is automatically available to any algorithm you create on the Algorithmia platform. For more detailed information on how to work with data see the [Data API docs](http://docs.algorithmia.com/).

You may call up to {{site.data.stats.platform.max_num_parallel_algo_requests}} other algorithms, either in parallel or recursively.

Here is an example of creating an algorithm that relies on data from another algorithm:

{% highlight r %}
library(algorithmia)

client <- getAlgorithmiaClient()

# Create a generic error function
AlgorithmError <- function(error){
  stop(error, call. = FALSE)
}

scrape_web <- function(input){
  # Call algorithm that returns main text content from a URL.
  tryCatch({
    algo <- client$algo("util/Url2Text/0.1.4")
    if ("URL" %in% names(input) & startsWith(input$URL, "http") || startsWith(input$URL, "https")) {
      response <- algo$pipe(list(input$URL))$result
      return(response)
    }
  }, error = function(e) {
    AlgorithmError(paste("Please pass in a valid input", "\n", e))
  })
}

algorithm <- function(input){
  tryCatch({
    # Take user input of URL and return text as words.
    text = scrape_web(input)
    # Split text into lists of sentences
    sentences = strsplit(text, "[.]")
    # Split up each sentence into words
    words <- strsplit(unlist(sentences), "[ ]")
    print(words)
  }, error = function(e) {
    AlgorithmError(paste("Please pass in a valid input", "\n", e))
  })
}
{% endhighlight %}

This should return a split up list of strings:

As you can see from these examples, fields that are passed into your algorithm by the user such as scalar values and sequences such as lists, dictionaries, tuples and bytearrays (binary byte sequence such as an image file) can be handled as you would any Python data structure within your algorithm.

For an example that takes and processes image data check out the [Places 365 Classifier's source code](https://algorithmia.com/algorithms/deeplearning/Places365Classifier).

## Error handling

In the above code examples we showed how to create an AlgorithmError function which you should use for handling errors within your algorithm. This way the user can tell the difference between a standard R library error and an error thrown by your algorithm:

{% highlight r %}
AlgorithmError <- function(error){
  stop(error, call. = FALSE)
}
{% endhighlight %}

And then raise the error with a helpful error message:

{% highlight r %}
tryCatch({
    # Run your code
  }, error = function(e) {
    AlgorithmError(paste("Please pass in a valid input", "\n", e))
})
{% endhighlight %}

If you are creating an algorithm that relies on calling another algorithm you may use Algorithmia error messages for catching errors thrown by that algorithm:

{% highlight r %}
algo <- client$algo("util/Url2Text/0.1.4")
# Try calling without valid input
algo$pipe(list())$error$message
{% endhighlight %}

For more information on error handling see the Better Error Handling Guide.

## Publishing Algorithmia Insights

This feature is available to [Algorithmia Enterprise](/enterprise) users only.
{: .notice-enterprise}

Inference-related metrics (a feature of [Algorithmia Insights](../algorithmia-enterprise/algorithmia-insights)) can be reported via the `report_insights` method of the Algorithmia client. For example, to report a list:

{% highlight r %}
# Report Algorithmia Insights
client$report_insights(list(faces_in_image=4)})
{% endhighlight %}

## Algorithm checklist

Before you are ready to publish your algorithm it's important to go through this [Algorithm Checklist]({{site.baseurl}}/algorithm-development/algorithm-checklist) and check out this blog post for Advanced Algorithm Development .

Both links will go over important best practices such as how to create a good algorithm description, add links to external documentation and other important information.

## Publish algorithm

Once you've developed your algorithm, you can publish it and make it available for others to use.

On the upper right hand side of the algorithm page you'll see a purple button "Publish" which will bring up a modal:

In this modal, you'll see a Changes tab, a Sample I/O tab, and one called Versioning.

Changes shows you your commit history and release notes.

Sample I/O is where you'll create your sample input and output for the user to try under Try the API in the Run tab. When you add a sample input, make sure to test it out with all the inputs that you accept since users will be able to test your algorithm with their own inputs.

Under the Versioning tab, you can select whether your algorithm will be for public use or private use as well as set the royalty. The algorithm can either be royalty-free or charge per-call. If you opt to have the algorithm charge a royalty, as the author, you will earn 70% of the royalty cost.

Check out [Algorithm Pricing]({{site.baseurl}}/pricing) for more information on how much algorithms will cost to run.

Under Semantic Versioning you can choose which kind of release your change should fall under: Major, Minor, or Revision.

If you are satisfied with your algorithm and settings, go ahead and hit publish. Congratulations, you're an algorithm developer!

## Conclusion and resources

In this guide we covered how to create an algorithm, work with different types of data and learned how to publish an algorithm.

## Additional resources

* [Algorithmia CRAN package documentation](https://cran.r-project.org/web/packages/algorithmia/vignettes/introduction-to-algorithmia.html)
* [Algorithmia R client documentation]({{site.baseurl}}/clients/r)
* [Hosted data documentation]({{site.baseurl}}/data)
* [Algorithmia API documentation](http://docs.algorithmia.com/?r)


text:
from odoo import fields, models
from odoo.exceptions import UserError

class Order(models.Model):
    _name = 'nursery.order'

    name = fields.Datetime(default=fields.Datetime.now)
    plant_id = fields.Many2one("nursery.plant", required=True)
    customer_id = fields.Many2one("nursery.customer")
    state = fields.Selection([
        ('draft', 'Draft'),
        ('confirm', 'Confirmed'),
        ('cancel', 'Canceled')
    ], default='draft')
    last_modification = fields.Datetime(readonly=True)

    def write(self, values):
        # helper to "YYYY-MM-DD"
        values['last_modification'] = fields.Datetime.now()

        return super(Order, self).write(values)

    def unlink(self):
        # self is a recordset
        for order in self:
           if order.state == 'confirm':
            raise UserError("You can not delete confirmed orders")

        return super(Order, self).unlink()


text: This package provides methods to process common ECG signals for human identification purposes


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace MsiFanControl
{
	static class Util
	{
		public static bool isInstalled()
		{
			// TODO: also some sanity checks on registry?

			string syswow64 = Environment.GetFolderPath(Environment.SpecialFolder.SystemX86);
			string filename = "MsiWmiAcpiMof.dll";

			return System.IO.File.Exists(syswow64 + System.IO.Path.DirectorySeparatorChar + filename);
		}

		public static void WmiQueryForeach<T>(ManagementObjectSearcher searcher, Func<ManagementObject, uint, T> factory, Action<ManagementObject, T> worker) where T: class
		{
			using (var enumerator = searcher.Get().GetEnumerator())
			{
				uint index = 0;

				while (enumerator.MoveNext())
				{
					var obj = (ManagementObject)enumerator.Current;
					var model = factory(obj, index);

					worker(obj, model);

					index += 1;
				}
			}
		}
	}
}


text:
class GameBase;
class GuiConvexEditorUndoAction;
class ConvexEditorTool;
class ConvexEditorCreateTool;

class GuiConvexEditorCtrl : public EditTSCtrl
{
   typedef EditTSCtrl Parent;

   friend class GuiConvexEditorUndoAction;

public:

   GuiConvexEditorCtrl();
   virtual ~GuiConvexEditorCtrl();

   DECLARE_CONOBJECT( GuiConvexEditorCtrl );

   // SimObject
   virtual bool onAdd();
   virtual void onRemove();
   static void initPersistFields();

   // GuiControl
   virtual bool onWake();
   virtual void onSleep();
   virtual void setVisible(bool value);

   // EditTSCtrl
   bool onKeyDown( const GuiEvent &event );
   bool onKeyUp( const GuiEvent &event );
   void get3DCursor( GuiCursor *&cursor, bool &visible, const Gui3DMouseEvent &event_ );
   void on3DMouseDown( const Gui3DMouseEvent &event );
   void on3DMouseUp( const Gui3DMouseEvent &event );
   void on3DMouseMove( const Gui3DMouseEvent &event );
   void on3DMouseDragged( const Gui3DMouseEvent &event );
   void on3DMouseEnter( const Gui3DMouseEvent &event );
   void on3DMouseLeave( const Gui3DMouseEvent &event );
   void on3DRightMouseDown( const Gui3DMouseEvent &event );
   void on3DRightMouseUp( const Gui3DMouseEvent &event );
   void renderScene(const RectI & updateRect);
   void updateGizmo();

   void updateShape( ConvexShape *shape, S32 offsetFace = -1 );
   static void synchClientObject( const ConvexShape *serverConvex );

   void updateGizmoPos();

   bool setActiveTool( ConvexEditorTool *tool );

   void drawFacePlane( ConvexShape *shape, S32 faceId );

   void scaleFace( ConvexShape *shape, S32 faceId, Point3F scale );

   void translateFace( ConvexShape *shape, S32 faceId, const Point3F &displace );

   void updateModifiedFace( ConvexShape *shape, S32 faceId );

   bool isShapeValid( ConvexShape *shape );

   void setupShape( ConvexShape *shape );

   void setPivotPos( ConvexShape *shape, S32 faceId, const Gui3DMouseEvent &event );

   void cleanMatrix( MatrixF &mat );

   S32 getEdgeByPoints( ConvexShape *shape, S32 faceId, S32 pId0, S32 pId1 );

   bool getEdgesTouchingPoint( ConvexShape *shape, S32 faceId, S32 pId, Vector< U32 > &edgeIdxList, S32 excludeEdge = -1 );

   void hollowSelection();
   void hollowShape( ConvexShape *shape, F32 thickness );

   void recenterSelection();
   void recenterShape( ConvexShape *shape );
   void dropSelectionAtScreenCenter();
   void splitSelectedFace();

   SceneObject* createPolyhedralObject(const char* className, SceneObject* geometryProvider);
   ConvexShape* createConvexShapeFrom(SceneObject* polyObject);
   Point2F getSelectedFaceUVOffset();
   Point2F getSelectedFaceUVScale();
   const char* getSelectedFaceMaterial();
   bool getSelectedFaceHorzFlip();
   bool getSelectedFaceVertFlip();
   float getSelectedFaceZRot();

   void setSelectedFaceUVOffset(Point2F offset);
   void setSelectedFaceUVScale(Point2F offset);
   void setSelectedFaceMaterial(const char* materialName);
   void setSelectedFaceHorzFlip(bool flipped);
   void setSelectedFaceVertFlip(bool flipped);
   void setSelectedFaceZRot(float degrees);
   void toggleGridSnapping();
   void setGridSnapSize(float gridSize);

   void updateShape();

   float getGridSnapSize() { return mGridPlaneSize; }
   /// Interface with Tools.
   /// @{

      MatrixF getCameraMat() const { return mLastCameraQuery.cameraMatrix; }

      enum UndoType
      {
         ModifyShape = 0,
         CreateShape,
         DeleteShape,
         HollowShape
      };

      void submitUndo( UndoType type, ConvexShape *shape );
      void submitUndo( UndoType type, const Vector< ConvexShape* > &shape );

   /// @}

   bool hasSelection() const;
   void clearSelection();
   void setSelection( ConvexShape *shape, S32 faceId );
   void handleDeselect();
   bool handleEscape();
   bool handleDelete();
   bool handleTab();
public:

	StringTableEntry mMaterialName;
protected:

   void _prepRenderImage( SceneManager* sceneGraph, const SceneRenderState* sceneState );
   void _renderObject( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *matInst );

   bool _cursorCast( const Gui3DMouseEvent &event, ConvexShape **hitShape, S32 *hitFace );
   static bool _cursorCastCallback( RayInfo* ri );

protected:

   bool mIsDirty;

   U32 mSavedGizmoFlags;

   Vector<SimObjectPtr<ConvexShape>> mSelectedBrushes;
   struct selectedFace
   {
      SimObjectPtr<ConvexShape> mOwnerBrush;
      U32 faceId;
   };
   Vector<selectedFace> mSelectedFaces;

   struct selectedVert
   {
      SimObjectPtr<ConvexShape> mOwnerBrush;
      U32 vertId;
   };
   Vector<selectedVert>  mSelectedVerts;
   /// The selected ConvexShape.
   SimObjectPtr<ConvexShape> mConvexSEL;

   /// The highlighted ConvexShape ( mouse over ).
   SimObjectPtr<ConvexShape> mConvexHL;

   S32 mFaceSEL;
   S32 mFaceHL;

   MatrixF mFaceSavedXfm;

   ConvexShape::Geometry mSavedGeometry;
   Vector< MatrixF > mSavedSurfaces;
   Vector< MatrixF > mLastValidShape;

   Point3F mSavedPivotPos;

   bool mCtrlDown;
   bool mSavedUndo;
   bool mHasGeometry;
   bool mDragging;
   bool mMouseDown;
   bool mHasCopied;
   RayInfo mLastRayInfo;

   bool mGridSnap;

   Gui3DMouseEvent mMouseDownEvent;

   Point3F mGizmoMatOffset;

   Point3F mPivotPos;
   bool mUsingPivot;
   bool mSettingPivot;

   UndoAction *mLastUndo;
   UndoManager *mUndoManager;

   struct ConvexShapeProxy
   {
      ConvexShape* shapeProxy;
      SceneObject* targetObject;
      String targetObjectClass;
      bool dirty;
   };

   Vector<ConvexShapeProxy> mProxyObjects;

   ConvexEditorTool *mActiveTool;
   ConvexEditorCreateTool *mCreateTool;
};

class GuiConvexEditorUndoAction : public UndoAction
{
   friend class GuiConvexEditorCtrl;
public:

   GuiConvexEditorUndoAction( const UTF8* actionName ) : UndoAction( actionName ), mEditor(NULL), mObjId(0)
   {
   }

   GuiConvexEditorCtrl *mEditor;

   SimObjectId mObjId;

   Vector< MatrixF > mSavedSurfaces;
   MatrixF mSavedObjToWorld;
   Point3F mSavedScale;

   virtual void undo();
   virtual void redo() { undo(); }
};

class ConvexEditorTool
{
public:

   enum EventResult
   {
      NotHandled = 0,
      Handled = 1,
      Done = 2,
      Failed = 3
   };

   ConvexEditorTool( GuiConvexEditorCtrl *editor )
      : mEditor( editor ), mDone( false ) {}
   virtual ~ConvexEditorTool() {}

   virtual void onActivated( ConvexEditorTool *prevTool ) {}
   virtual void onDeactivated( ConvexEditorTool *newTool ) {}

   virtual EventResult onKeyDown( const GuiEvent &event ) { return NotHandled; }
   virtual EventResult on3DMouseDown( const Gui3DMouseEvent &event ) { return NotHandled; }
   virtual EventResult on3DMouseUp( const Gui3DMouseEvent &event ) { return NotHandled; }
   virtual EventResult on3DMouseMove( const Gui3DMouseEvent &event ) { return NotHandled; }
   virtual EventResult on3DMouseDragged( const Gui3DMouseEvent &event ) { return NotHandled; }
   virtual EventResult on3DMouseEnter( const Gui3DMouseEvent &event ) { return NotHandled; }
   virtual EventResult on3DMouseLeave( const Gui3DMouseEvent &event ) { return NotHandled; }
   virtual EventResult on3DRightMouseDown( const Gui3DMouseEvent &event ) { return NotHandled; }
   virtual EventResult on3DRightMouseUp( const Gui3DMouseEvent &event ) { return NotHandled; }

   virtual void renderScene(const RectI & updateRect) {}
   virtual void render2D() {}

   bool isDone() { return mDone; }

public:
	GuiConvexEditorCtrl *mEditor;
protected:
   bool mDone;
};

class ConvexEditorCreateTool : public ConvexEditorTool
{
   typedef ConvexEditorTool Parent;
public:
   ConvexEditorCreateTool( GuiConvexEditorCtrl *editor );
   virtual ~ConvexEditorCreateTool() {}

   virtual void onActivated( ConvexEditorTool *prevTool );
   virtual void onDeactivated( ConvexEditorTool *newTool );

   virtual EventResult on3DMouseDown( const Gui3DMouseEvent &event );
   virtual EventResult on3DMouseUp( const Gui3DMouseEvent &event );
   virtual EventResult on3DMouseMove( const Gui3DMouseEvent &event );
   virtual EventResult on3DMouseDragged( const Gui3DMouseEvent &event );

   virtual void renderScene(const RectI & updateRect);

   ConvexShape* extrudeShapeFromFace( ConvexShape *shape, S32 face );

protected:

   S32 mStage;
   ConvexShape *mNewConvex;
   PlaneF mCreatePlane;

   MatrixF mTransform;
   Point3F mStart;
   Point3F mEnd;
   Point3F mPlaneSizes;
};

#endif // _GUICONVEXSHAPEEDITORCTRL_H_