text:
package org.archive.crawler.admin.ui;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.ReflectionException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.archive.crawler.admin.CrawlJob;
import org.archive.crawler.admin.CrawlJobHandler;
import org.archive.crawler.settings.ComplexType;
import org.archive.crawler.settings.CrawlerSettings;
import org.archive.crawler.settings.ListType;
import org.archive.crawler.settings.MapType;
import org.archive.crawler.settings.ModuleAttributeInfo;
import org.archive.crawler.settings.ModuleType;
import org.archive.crawler.settings.SettingsHandler;
import org.archive.crawler.settings.XMLSettingsHandler;
import org.archive.crawler.settings.refinements.Refinement;
import org.archive.util.IoUtils;

/**
 * Utility methods used configuring jobs in the admin UI.
 *
 * Methods are mostly called by the admin UI jsp.
 *
 * @author stack
 * @version $Date: 2009-11-25 02:36:10 +0000 (Wed, 25 Nov 2009) $, $Revision: 6707 $
 */
public class JobConfigureUtils {
    private static Logger logger = Logger.getLogger(JobConfigureUtils.class
            .getName());
    public static final String ACTION = "action";
    public static final String SUBACTION = "subaction";
    public static final String FILTERS = "filters";
    private static final String MAP = "map";
    private static final String FILTER = "filter";
    private static final Object ADD = "add";
    private static final Object MOVEUP = "moveup";
    private static final Object MOVEDOWN = "movedown";
    private static final Object REMOVE = "remove";
    private static final Object GOTO = "goto";
    private static final Object DONE = "done";
    private static final Object CONTINUE = "continue"; // keep editting

    /**
     * Check passed crawljob CrawlJob setting. Call this method at start of
     * page.
     *
     * @param job
     *            Current CrawlJobHandler.
     * @param request
     *            Http request.
     * @param response
     *            Http response.
     * @return Crawljob.
     */
    protected static CrawlJob getAndCheckJob(CrawlJob job,
            HttpServletRequest request, HttpServletResponse response) {
        return job;
    }

    /**
     * This methods updates a ComplexType with information passed to it by a
     * HttpServletRequest. It assumes that for every 'simple' type there is a
     * corresponding parameter in the request. A recursive call will be made for
     * any nested ComplexTypes. For each attribute it will check if the relevant
     * override is set (name.override parameter equals 'true'). If so the
     * attribute setting on the specified domain level (settings) will be
     * rewritten. If it is not we well ensure that it isn't being overridden.
     *
     * @param mbean
     *            The ComplexType to update
     * @param settings
     *            CrawlerSettings for the domain to override setting for. null
     *            denotes the global settings.
     * @param request
     *            The HttpServletRequest to use to update the ComplexType
     * @param expert
     *            if true expert settings will be updated, otherwise they will
     *            be ignored.
     */
    public static void writeNewOrderFile(ComplexType mbean,
            CrawlerSettings settings, HttpServletRequest request, boolean expert) {
        // If mbean is transient or a hidden expert setting.
        if (mbean.isTransient() || (mbean.isExpertSetting() && expert == false)) {
            return;
        }

        MBeanAttributeInfo a[] = mbean.getMBeanInfo(settings).getAttributes();
        for (int n = 0; n < a.length; n++) {
            checkAttribute((ModuleAttributeInfo) a[n], mbean, settings,
                    request, expert);
        }
    }

    /**
     * Process passed attribute. Check if needs to be written and if so, write
     * it.
     *
     * @param att
     *            Attribute to process.
     * @param mbean
     *            The ComplexType to update
     * @param settings
     *            CrawlerSettings for the domain to override setting for. null
     *            denotes the global settings.
     * @param request
     *            The HttpServletRequest to use to update the ComplexType
     * @param expert
     *            if true expert settings will be updated, otherwise they will
     *            be ignored.
     */
    @SuppressWarnings("unchecked")
    protected static void checkAttribute(ModuleAttributeInfo att,
            ComplexType mbean, CrawlerSettings settings,
            HttpServletRequest request, boolean expert) {
        // The attributes of the current attribute.
        Object currentAttribute = null;
        try {
            currentAttribute = mbean.getAttribute(settings, att.getName());
        } catch (Exception e) {
            logger.severe("Failed getting " + mbean.getAbsoluteName()
                    + " attribute " + att.getName() + ": " + e.getMessage());
            return;
        }

        if (logger.isLoggable(Level.FINE)) {
            logger.fine("MBEAN: " + mbean.getAbsoluteName() + " "
                    + att.getName() + " TRANSIENT " + att.isTransient() + " "
                    + att.isExpertSetting() + " " + expert);
        }

        if (att.isTransient() == false
                && (att.isExpertSetting() == false || expert)) {
            if (currentAttribute instanceof ComplexType) {
                writeNewOrderFile((ComplexType) currentAttribute, settings,
                        request, expert);
            } else {
                String attName = att.getName();
                // Have a 'setting'. Let's see if we need to update it (if
                // settings == null update all, otherwise only if override
                // is set.
                String attAbsoluteName = mbean.getAbsoluteName() + "/"
                        + attName;
                boolean override = (request.getParameter(attAbsoluteName
                        + ".override") != null)
                        && (request.getParameter(attAbsoluteName + ".override")
                                .equals("true"));
                if (settings == null || override) {
                    if (currentAttribute instanceof ListType) {
                        try {
                            ListType list = (ListType)currentAttribute;
                            Class cls = list.getClass();
                            Constructor constructor = cls.getConstructor(String.class, String.class);
                            list = (ListType) constructor.newInstance(list.getName(), list.getDescription());
                            String[] elems = request
                                    .getParameterValues(attAbsoluteName);
                            for (int i = 0; elems != null && i < elems.length; i++) {
                                list.add(elems[i]);
                            }
                            writeAttribute(attName, attAbsoluteName, mbean,
                                    settings, list);
                        } catch (Exception e) {
                            e.printStackTrace();
                            logger.severe("Setting new list values on "
                                    + attAbsoluteName + ": " + e.getMessage());
                            return;
                        }
                    } else {
                        writeAttribute(attName, attAbsoluteName, mbean,
                                settings, request.getParameter(attAbsoluteName));
                    }

                } else if (settings != null && override == false) {
                    // Is not being overridden. Need to remove possible
                    // previous overrides.
                    try {
                        mbean.unsetAttribute(settings, attName);
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.severe("Unsetting attribute on "
                                + attAbsoluteName + ": " + e.getMessage());
                        return;
                    }
                }
            }
        }
    }

    /**
     * Write out attribute.
     *
     * @param attName
     *            Attribute short name.
     * @param attAbsoluteName
     *            Attribute full name.
     * @param mbean
     *            The ComplexType to update
     * @param settings
     *            CrawlerSettings for the domain to override setting for. null
     *            denotes the global settings.
     * @param value
     *            Value to set into the attribute.
     */
    protected static void writeAttribute(String attName,
            String attAbsoluteName, ComplexType mbean,
            CrawlerSettings settings, Object value) {
        try {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("MBEAN SET: " + attAbsoluteName + " " + value);
            }
            mbean.setAttribute(settings, new Attribute(attName, value));
        } catch (Exception e) {
            e.printStackTrace();
            logger.severe("Setting attribute value " + value + " on "
                    + attAbsoluteName + ": " + e.getMessage());
            return;
        }
    }

    /**
     * Check passed job is not null and not readonly.
     * @param job Job to check.
     * @param response Http response.
     * @param redirectBasePath Full path for where to go next if an error.
     * @param currDomain May be null.
     * E.g. "/admin/jobs/per/overview.jsp".
     * @return A job else we've redirected if no job or readonly.
     * @throws IOException
     */
    public static CrawlJob checkCrawlJob(CrawlJob job,
        HttpServletResponse response, String redirectBasePath,
        String currDomain)
    throws IOException {
        if (job == null) {
            // Didn't find any job with the given UID or no UID given.
            response.sendRedirect(redirectBasePath +
                "?message=No job selected");
        } else if (job.isReadOnly()) {
            // Can't edit this job.
            response.sendRedirect(redirectBasePath +
                "?job=" + job.getUID() +
                ((currDomain != null && currDomain.length() > 0)?
                    "&currDomain=" + currDomain: "") +
                "&message=Can't edit a read only job");
        }
        return job;
    }

    /**
     * Handle job action.
     * @param handler CrawlJobHandler to operate on.
     * @param request Http request.
     * @param response Http response.
     * @param redirectBasePath Full path for where to go next if an error.
     * E.g. "/admin/jobs/per/overview.jsp".
     * @param currDomain Current domain.  Pass null for global domain.
     * @param reference
     * @return The crawljob configured.
     * @throws IOException
     * @throws AttributeNotFoundException
     * @throws InvocationTargetException
     * @throws InvalidAttributeValueException
     */
    public static CrawlJob handleJobAction(CrawlJobHandler handler,
            HttpServletRequest request, HttpServletResponse response,
            String redirectBasePath, String currDomain, String reference)
    throws IOException, AttributeNotFoundException, InvocationTargetException,
        InvalidAttributeValueException {

        // Load the job to manipulate
        CrawlJob theJob =
            checkCrawlJob(handler.getJob(request.getParameter("job")),
                response, redirectBasePath, currDomain);

        XMLSettingsHandler settingsHandler = theJob.getSettingsHandler();
        // If currDomain is null, then we're at top-level.
        CrawlerSettings settings = settingsHandler
            .getSettingsObject(currDomain);

        if(reference != null) {
            // refinement
            Refinement refinement = settings.getRefinement(reference);
            settings = refinement.getSettings();
        }

        // See if we need to take any action
        if (request.getParameter(ACTION) != null) {
            // Need to take some action.
            String action = request.getParameter(ACTION);
            String subaction = request.getParameter(SUBACTION);
            if (action.equals(FILTERS)) {
                // Doing something with the filters.
                String map = request.getParameter(MAP);
                if (map != null && map.length() > 0) {
                    String filter = request.getParameter(FILTER);
                    MapType filterMap = (MapType) settingsHandler
                        .getComplexTypeByAbsoluteName(settings, map);
                    if (subaction.equals(ADD)) {
                        // Add filter
                        String className = request.getParameter(map + ".class");
                        String typeName = request.getParameter(map + ".name");
                        if (typeName != null && typeName.length() > 0 &&
                                className != null && className.length() > 0) {
                            ModuleType tmp = SettingsHandler
                                .instantiateModuleTypeFromClassName(
                                    typeName, className);
                            filterMap.addElement(settings, tmp);
                        }
                    } else if (subaction.equals(MOVEUP)) {
                        // Move a filter down in a map
                        if (filter != null && filter.length() > 0) {
                            filterMap.moveElementUp(settings, filter);
                        }
                    } else if (subaction.equals(MOVEDOWN)) {
                        // Move a filter up in a map
                        if (filter != null && filter.length() > 0) {
                            filterMap.moveElementDown(settings, filter);
                        }
                    } else if (subaction.equals(REMOVE)) {
                        // Remove a filter from a map
                        if (filter != null && filter.length() > 0) {
                            filterMap.removeElement(settings, filter);
                        }
                    }
                }
                // Finally save the changes to disk
                settingsHandler.writeSettingsObject(settings);
            } else if (action.equals(DONE)) {
                // Ok, done editing.
                if(subaction.equals(CONTINUE)) {
                    // was editting an override/refinement, simply continue
                    if (theJob.isRunning()) {
                        handler.kickUpdate(); //Just to make sure.
                    }
                    String overParam = ((currDomain != null && currDomain
                            .length() > 0) ? "&currDomain=" + currDomain : "");
                    String refParam =
                        ((reference != null && reference.length() > 0)
                                ? "&reference=" + reference
                                : "");
                    String messageParam = (refParam.length() > 0)
                         ? "&message=Refinement changes saved"
                         : "&message=Override changes saved";
                    response.sendRedirect(redirectBasePath +
                        "?job=" + theJob.getUID() +
                         overParam +
                         refParam +
                         messageParam);
                } else {
                    // on main, truly 'done'
                    if (theJob.isNew()) {
                        handler.addJob(theJob);
                        response.sendRedirect(redirectBasePath
                                + "?message=Job created");
                    } else {
                        if (theJob.isRunning()) {
                            handler.kickUpdate();
                        }
                        if (theJob.isProfile()) {
                            response.sendRedirect(redirectBasePath
                                    + "?message=Profile modified");
                        } else {
                            response.sendRedirect(redirectBasePath
                                    + "?message=Job modified");
                        }
                    }
                }
            } else if (action.equals(GOTO)) {
                // Goto another page of the job/profile settings
                String overParam = ((currDomain != null && currDomain
                        .length() > 0) ? "&currDomain=" + currDomain : "");
                String refParam =
                    ((reference != null && reference.length() > 0)
                            ? "&reference=" + reference
                            : "");
                response.sendRedirect(request.getParameter(SUBACTION) +
                    overParam + refParam);
            }
        }
        return theJob;
    }

    /**
     * Print complete seeds list on passed in PrintWriter.
     * @param hndlr Current handler.
     * @param payload What to write out.
     * @throws AttributeNotFoundException
     * @throws MBeanException
     * @throws ReflectionException
     * @throws IOException
     * @throws IOException
     */
    public static void printOutSeeds(SettingsHandler hndlr, String payload)
    throws AttributeNotFoundException, MBeanException, ReflectionException,
    IOException {
        File seedfile = getSeedFile(hndlr);
        // no matter the encoding of the returned page, or the encoding
        // set on the JSP request before getParameter, the Strings we
        // get back are UTF-8-bytes-as-if-ISO8859-1... so reinterpret
        String utf8 = new String(payload.getBytes("ISO8859-1"),"UTF-8");
        Writer out = new OutputStreamWriter(new FileOutputStream(seedfile, false),"UTF-8");
        IOUtils.copy(
            new StringReader(utf8),
            out);
        out.close();
    }

    /**
     * Print complete seeds list on passed in PrintWriter.
     * @param hndlr Current handler.
     * @param out Writer to write out all seeds to.
     * @throws ReflectionException
     * @throws MBeanException
     * @throws AttributeNotFoundException
     * @throws IOException
     */
    public static void printOutSeeds(SettingsHandler hndlr, Writer out)
    throws AttributeNotFoundException, MBeanException, ReflectionException,
            IOException {
        // getSeedStream looks for seeds on disk and on classpath.
        InputStream is = getSeedStream(hndlr);
        IOUtils.copy(new BufferedReader(new InputStreamReader(is,"UTF-8")), out);
    }

    /**
     * Test whether seeds file is of a size that's reasonable
     * to edit in an HTML textarea.
     * @param h current settingsHandler
     * @return true if seeds size is manageable, false otherwise
     * @throws AttributeNotFoundException
     * @throws MBeanException
     * @throws ReflectionException
     *
     */
    public static boolean seedsEdittableSize(SettingsHandler h)
            throws AttributeNotFoundException, MBeanException,
            ReflectionException {
        return getSeedFile(h).length() <= (32 * 1024); // 32K
    }
    /**
     * @param hndlr Settings handler.
     * @return Seeds file.
     * @throws ReflectionException
     * @throws MBeanException
     * @throws AttributeNotFoundException
     */
    protected static File getSeedFile(SettingsHandler hndlr)
    throws AttributeNotFoundException, MBeanException, ReflectionException {
        String seedsFileStr = (String)((ComplexType)hndlr.getOrder().
            getAttribute("scope")).getAttribute("seedsfile");
        return hndlr.getPathRelativeToWorkingDirectory(seedsFileStr);
    }

    /**
     * Return seeds as a stream.
     * This method will work for case where seeds are on disk or on classpath.
     * @param hndlr SettingsHandler.  Used to find seeds.txt file.
     * @return InputStream on current seeds file.
     * @throws IOException
     * @throws ReflectionException
     * @throws MBeanException
     * @throws AttributeNotFoundException
     */
    protected static InputStream getSeedStream(SettingsHandler hndlr)
    throws IOException, AttributeNotFoundException, MBeanException,
            ReflectionException {
        InputStream is = null;
        File seedFile = getSeedFile(hndlr);
        if (!seedFile.exists()) {
            // Is the file on the CLASSPATH?
            is = SettingsHandler.class.
                getResourceAsStream(IoUtils.getClasspathPath(seedFile));
        } else if(seedFile.canRead()) {
            is = new FileInputStream(seedFile);
        }
        if (is == null) {
            throw new IOException(seedFile + " does not" +
            " exist -- neither on disk nor on CLASSPATH -- or is not" +
            " readable.");
        }
        return is;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>MainActivity</title>
<meta name="date" content="2015-12-11">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

cmput301t4.gameswap.Activities

Class MainActivity

java.lang.Object

Activity

cmput301t4.gameswap.Activities.MainActivity

public class MainActivity
extends Activity

This activity opens when the app launches, it asks for username in order to login
 or let new user create an account

Constructor Summary

Constructors

Constructor and Description

MainActivity()

Method Summary

Methods

Modifier and Type
Method and Description

void
clickedLogin(View view)

Called when user clicks on login button

void
clickedRegister(View view)

Called when user clicks Register button

Button
getLoginButton()

Button
getRegisterButton()

EditText
getUsernameField()

protected void
onCreate(Bundle savedInstanceState)

Creates the main page of the app

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MainActivity

public MainActivity()

Method Detail

onCreate

protected void onCreate(Bundle savedInstanceState)

Creates the main page of the app

Parameters:

savedInstanceState -

clickedLogin

public void clickedLogin(View view)

Called when user clicks on login button

Parameters:

view: - login button view

clickedRegister

public void clickedRegister(View view)

Called when user clicks Register button

Parameters:

view: - register button view

getRegisterButton

public Button getRegisterButton()

getLoginButton

public Button getLoginButton()

getUsernameField

public EditText getUsernameField()

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

redpajama_set_name: RedPajamaGithub


text:
package io.druid.guice.http;

import com.google.inject.Binder;
import com.google.inject.Module;
import com.metamx.http.client.HttpClient;
import com.metamx.http.client.HttpClientConfig;
import com.metamx.http.client.HttpClientInit;
import io.druid.guice.JsonConfigProvider;
import io.druid.guice.LazySingleton;
import io.druid.guice.annotations.Global;

import java.lang.annotation.Annotation;

/**
 */
public class HttpClientModule implements Module
{
  public static HttpClientModule global()
  {
    return new HttpClientModule("druid.global.http", Global.class);
  }

  private final String propertyPrefix;
  private Annotation annotation = null;
  private Class<? extends Annotation> annotationClazz = null;

  public HttpClientModule(String propertyPrefix)
  {
    this.propertyPrefix = propertyPrefix;
  }

  public HttpClientModule(String propertyPrefix, Class<? extends Annotation> annotation)
  {
    this.propertyPrefix = propertyPrefix;
    this.annotationClazz = annotation;
  }

  public HttpClientModule(String propertyPrefix, Annotation annotation)
  {
    this.propertyPrefix = propertyPrefix;
    this.annotation = annotation;
  }

  @Override
  public void configure(Binder binder)
  {
    if (annotation != null) {
      JsonConfigProvider.bind(binder, propertyPrefix, DruidHttpClientConfig.class, annotation);
      binder.bind(HttpClient.class)
            .annotatedWith(annotation)
            .toProvider(new HttpClientProvider(annotation))
            .in(LazySingleton.class);
    } else if (annotationClazz != null) {
      JsonConfigProvider.bind(binder, propertyPrefix, DruidHttpClientConfig.class, annotationClazz);
      binder.bind(HttpClient.class)
            .annotatedWith(annotationClazz)
            .toProvider(new HttpClientProvider(annotationClazz))
            .in(LazySingleton.class);
    } else {
      JsonConfigProvider.bind(binder, propertyPrefix, DruidHttpClientConfig.class);
      binder.bind(HttpClient.class)
            .toProvider(new HttpClientProvider())
            .in(LazySingleton.class);
    }
  }

  public static class HttpClientProvider extends AbstractHttpClientProvider<HttpClient>
  {
    public HttpClientProvider()
    {
    }

    public HttpClientProvider(Annotation annotation)
    {
      super(annotation);
    }

    public HttpClientProvider(Class<? extends Annotation> annotationClazz)
    {
      super(annotationClazz);
    }

    @Override
    public HttpClient get()
    {
      final DruidHttpClientConfig config = getConfigProvider().get().get();

      final HttpClientConfig.Builder builder = HttpClientConfig
          .builder()
          .withNumConnections(config.getNumConnections())
          .withReadTimeout(config.getReadTimeout())
          .withWorkerCount(config.getNumMaxThreads());

      if (getSslContextBinding() != null) {
        builder.withSslContext(getSslContextBinding().getProvider().get());
      }

      return HttpClientInit.createClient(builder.build(), getLifecycleProvider().get());
    }
  }
}


text:
package io.github.satr.aws.lambda.shoppingbot.entities.converters;
// Copyright © 2017, github.com/satr, MIT License

import com.fasterxml.jackson.core.type.TypeReference;
import io.github.satr.aws.lambda.shoppingbot.entities.ShoppingCartItem;

import java.util.List;

public class ShoppingCartItemConverter extends OrderItemInfoConverter<ShoppingCartItem> {
    @Override
    protected TypeReference<List<ShoppingCartItem>> createTypeReference() {
        return new TypeReference<List<ShoppingCartItem>>(){};
    }
}


text:
const fs = require('fs');

class Exporter {
    constructor(config, template, store) {
        this.config = config;
        this.template = template;
        this.store = store;
    }

    run() {
        this.export(this.store.load(), this.store.storeHtmlPath());
    }

    export(data, exportPath) {
        const output = this.template.render(data);
        fs.writeFileSync(exportPath, output, 'utf-8');
    }
}

module.exports = Exporter;


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>Class Alcys\Core\Db\Facade\ConditionFacade</title>

	<link rel="stylesheet" href="resources/bootstrap.min.css?08b23951ef4599ca9cbf1f902d0e8290c9653ddd">
	<link rel="stylesheet" href="resources/style.css?062e9e59e0b8c44fbaaded5b7ffc21f907b78669">

				Overview

							Namespace

Class

							Tree

							Todo

							Download

		<form id="search" class="form-search">
			<input type="hidden" name="cx" value="">
			<input type="hidden" name="ie" value="UTF-8">
			<input type="text" name="q" class="search-query" placeholder="Search">
		</form>

Namespaces

							Alcys

							Core

							Db

							Expression

							Builder

							Facade

							Factory

							QueryBuilder

							MySql

							References

							MySql

							Service

							Statement

							Types

Classes

ConditionFacade

DeleteFacade

InsertFacade

JoinFacade

SelectFacade

UpdateFacade

Interfaces

ConditionFacadeInterface

DeleteFacadeInterface

InsertFacadeInterface

JoinFacadeInterface

SelectFacadeInterface

UpdateFacadeInterface

WhereConditionFacadeInterface

Class ConditionFacade

Class ConditionFacade

Alcys\Core\Db\Facade\ConditionFacade
			 implements
				Alcys\Core\Db\Facade\ConditionFacadeInterface

		Namespace: Alcys\Core\Db\Facade

		Package: Alcys\Core\Db\Facade

			Located at Core/Db/Facade/ConditionFacade.php

Methods summary

				 public

			#
			__construct( Alcys\Core\Db\Expression\ConditionInterface <var>$condition</var>, Alcys\Core\Db\Factory\DbFactoryInterface <var>$dbFactory</var> )

Initialize the facade object.
The constructor arguments will passed from the method which create the instance.

Initialize the facade object.
The constructor arguments will passed from the method which create the instance.

Parameters

<var>$condition</var>

A clean instance of a condition interface.

<var>$dbFactory</var>

The db factory for the creation of reference object.

				 public

			#
			equal( string <var>$column</var>, string <var>$compareValue</var>, string|null <var>$type</var> = null )

Compare in the following style in the where condition:
$column = $compareValue.
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Compare in the following style in the where condition:
$column = $compareValue.
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Parameters

<var>$column</var>

The column name which should compare.

<var>$compareValue</var>

The value for the comparison.

<var>$type</var>

(Optional) Set to 'column' for a comparison with two columns.

Returns

$this The same instance to concatenate methods.

Implementation of

Alcys\Core\Db\Facade\ConditionFacadeInterface::equal()

				 public

			#
			notEqual( string <var>$column</var>, string <var>$compareValue</var>, string|null <var>$type</var> = null )

Compare in the following style in the where condition:
$column != $compareValue.
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Compare in the following style in the where condition:
$column != $compareValue.
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Parameters

<var>$column</var>

The column name which should compare.

<var>$compareValue</var>

The value for the comparison.

<var>$type</var>

(Optional) Set to 'column' for a comparison with two columns.

Returns

$this The same instance to concatenate methods.

Implementation of

Alcys\Core\Db\Facade\ConditionFacadeInterface::notEqual()

				 public

			#
			greater( string <var>$column</var>, string <var>$compareValue</var>, string|null <var>$type</var> = null )

Compare in the following style in the where condition:
$column > $compareValue.
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Compare in the following style in the where condition:
$column > $compareValue.
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Parameters

<var>$column</var>

The column name which should compare.

<var>$compareValue</var>

The value for the comparison.

<var>$type</var>

(Optional) Set to 'column' for a comparison with two columns.

Returns

$this The same instance to concatenate methods.

Implementation of

Alcys\Core\Db\Facade\ConditionFacadeInterface::greater()

				 public

			#
			greaterEqual( string <var>$column</var>, string <var>$compareValue</var>, string|null <var>$type</var> = null )

Compare in the following style in the where condition:
$column >= $compareValue.
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Compare in the following style in the where condition:
$column >= $compareValue.
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Parameters

<var>$column</var>

The column name which should compare.

<var>$compareValue</var>

The value for the comparison.

<var>$type</var>

(Optional) Set to 'column' for a comparison with two columns.

Returns

$this The same instance to concatenate methods.

Implementation of

Alcys\Core\Db\Facade\ConditionFacadeInterface::greaterEqual()

				 public

			#
			lower( string <var>$column</var>, string <var>$compareValue</var>, string|null <var>$type</var> = null )

Compare in the following style in the where condition:
$column < $compareValue.
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Compare in the following style in the where condition:
$column < $compareValue.
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Parameters

<var>$column</var>

The column name which should compare.

<var>$compareValue</var>

The value for the comparison.

<var>$type</var>

(Optional) Set to 'column' for a comparison with two columns.

Returns

$this The same instance to concatenate methods.

Implementation of

Alcys\Core\Db\Facade\ConditionFacadeInterface::lower()

				 public

			#
			lowerEqual( string <var>$column</var>, string <var>$compareValue</var>, string|null <var>$type</var> = null )

Compare in the following style in the where condition:
$column <= $compareValue.
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Compare in the following style in the where condition:
$column <= $compareValue.
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Parameters

<var>$column</var>

The column name which should compare.

<var>$compareValue</var>

The value for the comparison.

<var>$type</var>

(Optional) Set to 'column' for a comparison with two columns.

Returns

$this The same instance to concatenate methods.

Implementation of

Alcys\Core\Db\Facade\ConditionFacadeInterface::lowerEqual()

				 public

			#
			between( string <var>$column</var>, string <var>$firstCompareValue</var>, string <var>$secondCompareValue</var>, string|null <var>$type</var> = null )

Compare in the following style in the where condition:
$column BETWEEN $firstCompareValue AND $secondCompareValue
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Compare in the following style in the where condition:
$column BETWEEN $firstCompareValue AND $secondCompareValue
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Parameters

<var>$column</var>

The column name which should compare.

<var>$firstCompareValue</var>

The first value for the comparison.

<var>$secondCompareValue</var>

The second value for the comparison.

<var>$type</var>

(Optional) Set to 'column' for a comparison with two columns.

Returns

$this The same instance to concatenate methods.

Implementation of

Alcys\Core\Db\Facade\ConditionFacadeInterface::between()

				 public

			#
			notBetween( string <var>$column</var>, string <var>$firstCompareValue</var>, string <var>$secondCompareValue</var>, string|null <var>$type</var> = null )

Compare in the following style in the where condition:
$column NOT BETWEEN $firstCompareValue AND $secondCompareValue
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Compare in the following style in the where condition:
$column NOT BETWEEN $firstCompareValue AND $secondCompareValue
When the type argument isset to 'column', the second argument will interpreted as column.
Otherwise it is like a string or value comparison.

Parameters

<var>$column</var>

The column name which should compare.

<var>$firstCompareValue</var>

The first value for the comparison.

<var>$secondCompareValue</var>

The second value for the comparison.

<var>$type</var>

(Optional) Set to 'column' for a comparison with two columns.

Returns

$this The same instance to concatenate methods.

Implementation of

Alcys\Core\Db\Facade\ConditionFacadeInterface::notBetween()

				 public

			#
			like( string <var>$column</var>, string <var>$compareValue</var>, integer <var>$level</var> = 0 )

Compare in the following style in the where condition:
$column LIKE $compareValue.

Compare in the following style in the where condition:
$column LIKE $compareValue.

Parameters

<var>$column</var>

The column name which should compare.

<var>$compareValue</var>

The value for the comparison.

<var>$level</var>

(Optional) Set the percent sign. Default (non) is zero, before value
                            is 1, after 2 and both 3. If the $compareValue is passed with the %
                            sign, this argument is unnecessary.

Returns

$this Same instance to concatenate methods.

				 public

			#
			isNull( string <var>$column</var> )

Compare in the following style in the where condition:
$column IS NULL.

Compare in the following style in the where condition:
$column IS NULL.

Parameters

<var>$column</var>

Column name for the comparison.

Returns

$this The same instance to concatenate methods.

				 public

			#
			notNull( string <var>$column</var> )

Compare in the following style in the where condition:
$column IS NOT NULL.

Compare in the following style in the where condition:
$column IS NOT NULL.

Parameters

<var>$column</var>

Column name for the comparison.

Returns

$this The same instance to concatenate methods.

				 public

			#
			logicAnd( )

Use this method to set another comparison in connection with a logical and to the condition.

Use this method to set another comparison in connection with a logical and to the condition.

Returns

$this The same instance to concatenate methods.

Implementation of

Alcys\Core\Db\Facade\ConditionFacadeInterface::logicAnd()

				 public

			#
			logicOr( )

Use this method to set another comparison in connection with a logical and to the condition.

Use this method to set another comparison in connection with a logical and to the condition.

Returns

$this The same instance to concatenate methods.

Implementation of

Alcys\Core\Db\Facade\ConditionFacadeInterface::logicOr()

				 public
				Alcys\Core\Db\Expression\Condition

			#
			getCondition( )

Returns

						Alcys\Core\Db\Expression\Condition

Implementation of

Alcys\Core\Db\Facade\ConditionFacadeInterface::getCondition()

Magic methods summary

		 API documentation generated by ApiGen


text:
var $ = require('jquery');

var fileBlock = function(_offset, length, _file, readChunk) {
  var r = new FileReader();
  var blob = _file.slice(_offset, length + _offset);
  r.onload = readChunk;
  r.readAsArrayBuffer(blob);
}

// Based on alediaferia's SO response
// http://stackoverflow.com/questions/14438187/javascript-filereader-parsing-long-file-in-chunks
exports.onFileProgress = function(options, ondata, onerror, onend) {
  var file       = options.file;
  var fileSize   = file.size;
  var chunkSize  = options.bufferSize || 8192;
  var offset     = 0;
  var readChunk = function(evt) {
    if (offset >= fileSize) {
      console.log("Done reading file");
      onend();
      return;
    }
    if (evt.target.error == null) {
      var buffer = evt.target.result;
      var len = buffer.byteLength;
      offset += len;
      ondata(buffer); // callback for handling read chunk
    } else {
      var errorMessage = evt.target.error;
      console.log("Read error: " + errorMessage);
      onerror(errorMessage);
      return;
    }
    fileBlock(offset, chunkSize, file, readChunk);
  }
  fileBlock(offset, chunkSize, file, readChunk);
}

exports.createTokenGenerator = function() {
  // Make call to API to try and get token
  var hasBeenRunTimes = 0;
  return {
    getToken: function(callback) {
    ++hasBeenRunTimes;
    if (hasBeenRunTimes > 5) {
      var err = new Error('Cannot reach server');
      callback(null, err);
      return;
    }
    var url = '/token';
    var tokenRequest = new XMLHttpRequest();
    tokenRequest.open("GET", url, true);
    tokenRequest.onload = function(evt) {
      var token = tokenRequest.responseText;
      callback(token);
    };
    tokenRequest.send();
    },
    getCount: function() { return hasBeenRunTimes; }
  }
};

exports.getToken = (function() {
  // Make call to API to try and get token
  var hasBeenRunTimes = 0;
  return function(callback) {
    hasBeenRunTimes++
    if (hasBeenRunTimes > 5) {
      var err = new Error('Cannot reach server');
      callback(null, err);
      return;
    }
    var url = '/token/speech-to-text';
    var tokenRequest = new XMLHttpRequest();
    tokenRequest.open("GET", url, true);
    tokenRequest.onload = function(evt) {
      var token = tokenRequest.responseText;
      callback(token);
    };
    tokenRequest.send();
  }
})();

exports.initPubSub = function() {
  var o         = $({});
  $.subscribe   = o.on.bind(o);
  $.unsubscribe = o.off.bind(o);
  $.publish     = o.trigger.bind(o);
}


text:
import os
import sys
import unittest

# Django, Flask, psycopg2, and sqlalchemy are only installed in their
# respective testing environments. See tox.ini for details.

try:
    import django
    from django.test.runner import DiscoverRunner
except ImportError:
    django = None

try:
    import flask
    import pytest
except ImportError:
    flask = None

try:
    import psycopg2
except ImportError:
    psycopg2 = None

try:
    import sqlalchemy
except ImportError:
    sqlalchemy = None

def run_unittests(module):
    testsuite = unittest.TestLoader().discover(module)
    result = unittest.TextTestRunner(verbosity=1).run(testsuite)
    sys.exit(any(result.failures or result.errors))

def run_django_tests():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.django.settings')
    django.setup()
    runner = DiscoverRunner()
    failures = runner.run_tests(['tests.django'])
    sys.exit(failures)

def run_flask_tests():
    failures = pytest.main(['tests/flask/tests.py'])
    sys.exit(failures)

def main():
    if django:
        run_django_tests()
    elif flask:
        run_flask_tests()
    elif psycopg2:
        run_unittests('tests.psycopg2')
    elif sqlalchemy:
        run_unittests('tests.sqlalchemy')
    else:
        run_unittests('tests.generic')

if __name__ == '__main__':
    main()


text:
{-# LANGUAGE OverloadedStrings #-}

module Main where

import qualified Data.Map as M
import Github.PostReceive

main :: IO ()
main = start 5678 $ M.fromList [("/", print)]


text:
package com.rhinoforms;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.SimpleHtmlSerializer;
import org.htmlcleaner.TagNode;
import org.w3c.dom.Document;

/**
 * Hacky methods to help build tests
 */
public class TestUtil {

	public static String readFileContents(String filePath) throws IOException {
		StringBuilder builder = new StringBuilder();
		BufferedReader reader = new BufferedReader(new FileReader(filePath));
		try {
			while (reader.ready()) {
				builder.append(reader.readLine());
				builder.append(Constants.NEW_LINE);
			}
		} finally {
			reader.close();
		}
		return builder.toString();
	}

	public static Document createDocument(String dataDocumentString) throws Exception {
		DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		return documentBuilder.parse(new ByteArrayInputStream(dataDocumentString.getBytes()));
	}

	public static String serialiseHtmlCleanerNode(TagNode node) throws IOException {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		CleanerProperties properties = new HtmlCleaner().getProperties();
		properties.setOmitXmlDeclaration(true);
		new SimpleHtmlSerializer(properties).write(node, new OutputStreamWriter(outputStream), "utf-8");
		String actual = new String(outputStream.toByteArray());
		return actual;
	}

}


text:
package GUI;

public enum BlocksType {

}


text:
{% extends "layout.html" %}
{% block title %}Choose Task{% endblock %}
{% block resources %}
{% endblock %}
{% block scripts %}

{% endblock %}
{% block content %}
Host: {{ host }}

Playbook: {{ playbook.label }}

<form id="playbook-form">
  <input type="hidden" name="host" value="{{ host }}">
  <input type="hidden" name="name" value="{{ playbook.name }}">
  {% for field in playbook.fields %}
    {{ field.label }}
    {% if is_dictionary(field.value) %}
      {% set value = helpers[field.value.helper_function](host) %}
    {% else %}
      {% set value = field.value %}
    {% endif %}
    {% if is_string(value) %}
      <input type="text" name="{{ field.name }}" value="{{ value }}">
    {% elif is_boolean(value) %}
      {% if value %}
        <input type="checkbox" name="{{ field.name }}" checked>
      {% else %}
        <input type="checkbox" name="{{ field.name }}">
      {% endif %}
    {% elif is_list(value) %}
      <select name="{{ field.name }}">
        {% for option in value %}
          <option value="{{ option }}">{{ option }}</option>
        {% endfor %}
      </select>
    {% endif %}

  {% endfor %}
  <button type="submit" class="submit">Run</button>
</form>

Log:

{% endblock %}


text:
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
//   contributors may be used to endorse or promote products derived from this
//   software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//

namespace NLog.Time
{
    using System;

    /// <summary>
    /// Current local time retrieved directly from DateTime.Now.
    /// </summary>
    [TimeSource("AccurateLocal")]
    public class AccurateLocalTimeSource : TimeSource
    {
        /// <summary>
        /// Gets current local time directly from DateTime.Now.
        /// </summary>
        public override DateTime Time { get { return DateTime.Now; } }
    }
}


text:
<?php

namespace LiddleDev\LiddleForum\Controllers;

use Validator;
use Illuminate\Support\Facades\Gate;
use Illuminate\Http\Request;
use LiddleDev\LiddleForum\Drivers\Avatar\AvatarInterface;
use LiddleDev\LiddleForum\Drivers\TextEditor\TextEditorInterface;
use LiddleDev\LiddleForum\Helpers\ThreadHelper;
use LiddleDev\LiddleForum\Models\Category;
use LiddleDev\LiddleForum\Models\Thread;
use HTMLPurifier;

class ThreadsController extends LiddleForumBaseController
{
    /**
     * @var AvatarInterface
     */
    private $avatar;

    /**
     * @var TextEditorInterface
     */
    private $textEditor;

    /**
     * @var HTMLPurifier
     */
    private $htmlPurifier;

    public function __construct(AvatarInterface $avatar, TextEditorInterface $textEditor, HTMLPurifier $htmlPurifier)
    {
        $this->avatar = $avatar;
        $this->textEditor = $textEditor;
        $this->htmlPurifier = $htmlPurifier;
    }

    public function getCreate()
    {
        if (Gate::denies('create', Thread::class)) {
            abort(403);
        }

        $categories = Category::orderBy('parent_id')->whereNotNull('parent_id')->get();

        return view('liddleforum::threads.create', [
            'categories' => $categories,
            'textEditor' => $this->textEditor,
        ]);
    }

    public function postCreate(Request $request)
    {
        if (Gate::denies('create', Thread::class)) {
            abort(403);
        }

        $categoryObject = new Category();

        $validator = Validator::make($request->all(), [
            'category' => 'required|exists:' . $categoryObject->getTable() . ',slug',
            'title' => 'required',
            'body' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect()->route('liddleforum.threads.create')
                ->withErrors($validator, 'liddleforum')
                ->withInput();
        }

        $category = Category::where('slug', '=', $request->input('category'))->first();

        $slug = ThreadHelper::generateSlug($request->input('title'));

        $thread = Thread::create([
            'title' => $request->input('title'),
            'category_id' => $category->id,
            'user_id' => \Auth::user()->getKey(),
            'slug' => $slug,
        ]);

        $body = $request->input('body');
        $body = $this->htmlPurifier->purify($body);

        $post = $thread->posts()->create([
            'user_id' => \Auth::user()->getKey(),
            'body' => $body,
        ]);

        $thread->followers()->create([
            'user_id' => \Auth::user()->getKey(),
        ]);

        $request->session()->flash('liddleforum_success', 'Your thread has been created');

        return redirect()->route('liddleforum.threads.view', [
            'thread_slug' => $thread->slug,
        ]);
    }

    public function getThread($thread_slug)
    {
        if ( ! $thread = $this->fetchThread($thread_slug)) {
            abort(404);
        }

        $posts = $thread->posts()->with('user')->orderBy('created_at')->paginate(config('liddleforum.paginate.posts', 10));

        $followingThread = \Auth::check() && (bool)$thread->followers()->where('user_id', '=', \Auth::user()->getKey())->first();

        $thread->views += 1;
        $thread->save();

        return view('liddleforum::threads.view', [
            'thread' => $thread,
            'posts' => $posts,
            'avatar' => $this->avatar,
            'followingThread' => $followingThread,
            'textEditor' => $this->textEditor,
        ]);
    }

    public function getEdit($thread_slug)
    {
        if ( ! $thread = $this->fetchThread($thread_slug)) {
            abort(404);
        }

        if (Gate::denies('edit', $thread)) {
            abort(403);
        }

        return view('liddleforum::threads.edit', [
            'thread' => $thread,
        ]);
    }

    public function postEdit(Request $request, $thread_slug)
    {
        if ( ! $thread = $this->fetchThread($thread_slug)) {
            abort(404);
        }

        if (Gate::denies('edit', $thread)) {
            abort(403);
        }

        $validator = Validator::make($request->all(), [
            'title' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect()->route('liddleforum.threads.edit', ['thread_slug' => $thread_slug])
                ->withErrors($validator, 'liddleforum')
                ->withInput();
        }

        $slug = ThreadHelper::generateSlug($request->input('title'));

        $thread->update([
            'title' => $request->input('title'),
            'slug' => $slug,
        ]);

        $request->session()->flash('liddleforum_success', 'Your thread has been saved');

        return redirect()->route('liddleforum.threads.view', [
            'thread_slug' => $thread->slug,
        ]);
    }

    public function deleteThread(Request $request, $thread_slug)
    {
        if ( ! $thread = $this->fetchThread($thread_slug)) {
            abort(404);
        }

        if (Gate::denies('delete', $thread)) {
            abort(403);
        }

        $category = $thread->category;

        $thread->delete();

        $request->session()->flash('liddleforum_success', 'Your thread has been deleted');
        return redirect()->route('liddleforum.categories.view', ['category' => $category->slug]);
    }

    public function postLock(Request $request, $thread_slug)
    {
        if ( ! $thread = $this->fetchThread($thread_slug)) {
            abort(404);
        }

        if (Gate::denies('lock', $thread)) {
            abort(403);
        }

        $thread->locked = 1;
        $thread->save();

        $request->session()->flash('liddleforum_success', 'Thread has been locked');
        return redirect()->route('liddleforum.threads.view', ['thread_slug' => $thread->slug]);
    }

    public function postUnlock(Request $request, $thread_slug)
    {
        if ( ! $thread = $this->fetchThread($thread_slug)) {
            abort(404);
        }

        if (Gate::denies('lock', $thread)) {
            abort(403);
        }

        $thread->locked = 0;
        $thread->save();

        $request->session()->flash('liddleforum_success', 'Thread has been unlocked');
        return redirect()->route('liddleforum.threads.view', ['thread_slug' => $thread->slug]);
    }

    public function postSticky(Request $request, $thread_slug)
    {
        if ( ! $thread = $this->fetchThread($thread_slug)) {
            abort(404);
        }

        if (Gate::denies('sticky', $thread)) {
            abort(403);
        }

        $thread->stickied = 1;
        $thread->save();

        $request->session()->flash('liddleforum_success', 'Thread has been stickied');
        return redirect()->route('liddleforum.threads.view', ['thread_slug' => $thread->slug]);
    }

    public function postUnsticky(Request $request, $thread_slug)
    {
        if ( ! $thread = $this->fetchThread($thread_slug)) {
            abort(404);
        }

        if (Gate::denies('sticky', $thread)) {
            abort(403);
        }

        $thread->stickied = 0;
        $thread->save();

        $request->session()->flash('liddleforum_success', 'Thread has been unstickied');
        return redirect()->route('liddleforum.threads.view', ['thread_slug' => $thread->slug]);
    }

    public function postFollow(Request $request, $thread_slug)
    {
        if ( ! $thread = $this->fetchThread($thread_slug)) {
            abort(404);
        }

        if (Gate::denies('follow', $thread)) {
            abort(403);
        }

        if ( ! $thread->followers()->where('user_id', '=', \Auth::user()->getKey())->first()) {
            $thread->followers()->create([
                'user_id' => \Auth::user()->getKey(),
            ]);
        }

        $request->session()->flash('liddleforum_success', 'You are now following this thread');
        return redirect()->route('liddleforum.threads.view', ['thread_slug' => $thread->slug]);
    }

    public function postUnfollow(Request $request, $thread_slug)
    {
        if ( ! $thread = $this->fetchThread($thread_slug)) {
            abort(404);
        }

        if (Gate::denies('follow', $thread)) {
            abort(403);
        }

        $thread->followers()->where('user_id', '=', \Auth::user()->getKey())->delete();

        $request->session()->flash('liddleforum_success', 'You have stopped following this thread');
        return redirect()->route('liddleforum.threads.view', ['thread_slug' => $thread->slug]);
    }

    /**
     * @param $thread_slug
     * @return Thread|null
     */
    protected function fetchThread($thread_slug)
    {
        return Thread::where('slug', '=', $thread_slug)->first();
    }
}


text:
package gov.va.isaac.gui.conceptViews.enhanced;

import gov.va.isaac.AppContext;
import gov.va.isaac.ExtendedAppContext;
import gov.va.isaac.gui.util.FxUtils;
import gov.va.isaac.gui.util.Images;
import gov.va.isaac.interfaces.gui.constants.ConceptViewMode;
import gov.va.isaac.interfaces.gui.constants.SharedServiceNames;
import gov.va.isaac.interfaces.gui.views.commonFunctionality.PopupConceptViewI;
import gov.va.isaac.util.Utility;
import gov.va.isaac.util.OTFUtility;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Region;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.Window;
import javax.inject.Named;
import org.glassfish.hk2.api.PerLookup;
import org.ihtsdo.otf.tcc.api.concept.ConceptChronicleBI;
import org.ihtsdo.otf.tcc.api.store.Ts;
import org.ihtsdo.otf.tcc.ddo.concept.ConceptChronicleDdo;
import org.ihtsdo.otf.tcc.ddo.fetchpolicy.RefexPolicy;
import org.ihtsdo.otf.tcc.ddo.fetchpolicy.RelationshipPolicy;
import org.ihtsdo.otf.tcc.ddo.store.FxTerminologyStoreDI;
import org.jvnet.hk2.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Dan Armbrust
 * @author Jesse Efron
 */
public class EnhancedConceptView implements PopupConceptViewI {
	private final Logger LOG = LoggerFactory.getLogger(this.getClass());

	private Stage s;
	private EnhancedConceptViewController controller = null;

	private ObservableList<Integer> conceptHistoryStack = FXCollections.observableArrayList();

	private static int currentConNid;
	private static UUID currentConUuid;
	private static ConceptChronicleDdo currentCon;

	private EnhancedConceptView() throws IOException {
		//This is for HK2 to construct...
		super();

		// Load from FXML.
		URL resource = this.getClass().getResource("EnhancedView.fxml");
		FXMLLoader loader = new FXMLLoader(resource);
		Region root = loader.load();
		root.getStylesheets().add(EnhancedConceptView.class.getResource("EnhancedView.css").toString());
		controller = loader.getController();
		controller.setConceptView(this);
	}

	private void setConcept(ConceptChronicleDdo concept) {
		// Make sure in application thread.
		FxUtils.checkFxUserThread();
		controller.setConcept(concept.getPrimordialUuid(), controller.getViewMode(), conceptHistoryStack);
	}

	@Override
	public void showView(Window parent) {
		s = new Stage();
		s.initOwner(parent);
		s.initModality(Modality.NONE);
		s.initStyle(StageStyle.DECORATED);

		s.setScene(new Scene(getView()));
		s.sizeToScene();

		s.getScene().getStylesheets().add(EnhancedConceptView.class.getResource("/isaac-shared-styles.css").toString());
		s.getIcons().add(Images.CONCEPT_VIEW.getImage());

		// Title will change after concept is set.
		s.setTitle(controller.getTitle());
		s.show();

		//doesn't come to the front unless you do this (on linux, at least)
		Platform.runLater(() ->
		{
			s.setHeight(s.getHeight() + 30);  //coming up slightly to small on linux for some reason
			s.toFront();
		});
	}

	@Override
	public void setConcept(UUID conceptUUID) {
		// TODO this needs to be rewritten so that the dialog displays immediately
		//but with a progress indicator while we wait for the concept to be found..

		Task<ConceptChronicleDdo> task = new Task<ConceptChronicleDdo>()
		{

			@Override
			protected ConceptChronicleDdo call() throws Exception
			{
				LOG.info("Loading concept with UUID " + conceptUUID);
				ConceptChronicleDdo concept = AppContext.getService(FxTerminologyStoreDI.class).getFxConcept(conceptUUID, OTFUtility.getViewCoordinate(),
						RefexPolicy.NONE, RelationshipPolicy.ORIGINATING_RELATIONSHIPS);
				 LOG.info("Finished loading concept with UUID " + conceptUUID);

				return concept;
			}

			@Override
			protected void succeeded()
			{
				try
				{
					currentCon = this.getValue();
					setConcept(currentCon);
				}
				catch (Exception e)
				{
					String title = "Unexpected error loading concept with UUID " + conceptUUID;
					String msg = e.getClass().getName();
					LOG.error(title, e);
					AppContext.getCommonDialogs().showErrorDialog(title, msg, e.getMessage());
				}
			}

			@Override
			protected void failed()
			{
				Throwable ex = getException();
				String title = "Unexpected error loading concept with UUID " + conceptUUID;
				String msg = ex.getClass().getName();
				LOG.error(title, ex);
				AppContext.getCommonDialogs().showErrorDialog(title, msg, ex.getMessage());
			}
		};

		Utility.execute(task);	}

	@Override
	public void setConcept(int conceptNid) {
		//TODO fix threading issues on this too...
		try
		{
			ConceptChronicleBI concept = Ts.get().getConcept(conceptNid);
			if (concept != null)
			{
				setConcept(concept.getPrimordialUuid());
			}
		}
		catch (IOException e)
		{
			String title = "Unexpected error loading concept with nid " + conceptNid;
			String msg = e.getClass().getName();
			LOG.error(title, e);
			AppContext.getCommonDialogs().showErrorDialog(title, msg, e.getMessage());
		}
	}

	@Override
	public UUID getConceptUuid() {
		return currentConUuid;
	}

	@Override
	public int getConceptNid() {
		return currentConNid;
	}

	@Override
	public void setViewMode(ConceptViewMode mode) {
		controller.setViewMode(mode);
	}

	@Override
	public ConceptViewMode getViewMode() {
		return controller.getViewMode();
	}

	@Override
	public Region getView() {
		return controller.getRootNode();
	}

	@Override
	public void viewDiscarded()
	{
		controller.viewDiscarded();
	}
}


text:
class coConstString;
class coString;

class coDynamicString : public coDynamicArray<coChar>
{
	typedef coDynamicArray<coChar> Super;
public:
	coDynamicString() = default;
	coDynamicString(coDynamicString&& _);
	coDynamicString(const coConstString& _s);
	explicit coDynamicString(const coDynamicString& _);
	operator coString&() { return reinterpret_cast<coString&>(*this); }
	operator const coString&() const { return reinterpret_cast<const coString&>(*this); }
	operator coConstString&() { return reinterpret_cast<coConstString&>(*this); }
	operator const coConstString&() const { return reinterpret_cast<const coConstString&>(*this); }

	coDynamicString& operator=(const coDynamicString& _s);
	coDynamicString& operator=(const coConstString& _s);
};


text:
package jp.co.recruit_lifestyle.android.floatingview;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.support.annotation.IntDef;
import android.util.DisplayMetrics;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;

/**
 * FloatingViewを扱うクラスです。
 * TODO:動作がカクカクなので原因を探す
 * TODO:移動を追従する複数表示サポートは第2弾で対応
 */
public class FloatingViewManager implements ScreenChangedListener, View.OnTouchListener, TrashViewListener {

    /**
     * 常に表示するモード
     */
    public static final int DISPLAY_MODE_SHOW_ALWAYS = 1;

    /**
     * 常に非表示にするモード
     */
    public static final int DISPLAY_MODE_HIDE_ALWAYS = 2;

    /**
     * フルスクリーン時に非表示にするモード
     */
    public static final int DISPLAY_MODE_HIDE_FULLSCREEN = 3;

    /**
     * 表示モード
     */
    @IntDef({DISPLAY_MODE_SHOW_ALWAYS, DISPLAY_MODE_HIDE_ALWAYS, DISPLAY_MODE_HIDE_FULLSCREEN})
    @Retention(RetentionPolicy.SOURCE)
    public @interface DisplayMode {
    }

    /**
     * 左右の近い方向に移動
     */
    public static final int MOVE_DIRECTION_DEFAULT = 0;
    /**
     * 常に左に移動
     */
    public static final int MOVE_DIRECTION_LEFT = 1;
    /**
     * 常に右に移動
     */
    public static final int MOVE_DIRECTION_RIGHT = 2;

    /**
     * 移動しない
     */
    public static final int MOVE_DIRECTION_NONE = 3;

    /**
     * 側に近づく方向に移動します
     */
    public static final int MOVE_DIRECTION_NEAREST = 4;

    /**
     * Goes in the direction in which it is thrown
     */
    public static final int MOVE_DIRECTION_THROWN = 5;

    /**
     * Moving direction
     */
    @IntDef({MOVE_DIRECTION_DEFAULT, MOVE_DIRECTION_LEFT, MOVE_DIRECTION_RIGHT,
            MOVE_DIRECTION_NEAREST, MOVE_DIRECTION_NONE, MOVE_DIRECTION_THROWN})
    @Retention(RetentionPolicy.SOURCE)
    public @interface MoveDirection {
    }

    /**
     * Viewの形が円形の場合
     */
    public static final float SHAPE_CIRCLE = 1.0f;

    /**
     * Viewの形が四角形の場合
     */
    public static final float SHAPE_RECTANGLE = 1.4142f;

    /**
     * {@link Context}
     */
    private final Context mContext;

    /**
     * {@link Resources}
     */
    private final Resources mResources;

    /**
     * WindowManager
     */
    private final WindowManager mWindowManager;

    /**
     * {@link DisplayMetrics}
     */
    private final DisplayMetrics mDisplayMetrics;

    /**
     * 操作状態のFloatingView
     */
    private FloatingView mTargetFloatingView;

    /**
     * フルスクリーンを監視するViewです。
     */
    private final FullscreenObserverView mFullscreenObserverView;

    /**
     * FloatingViewを削除するViewです。
     */
    private final TrashView mTrashView;

    /**
     * FloatingViewListener
     */
    private final FloatingViewListener mFloatingViewListener;

    /**
     * FloatingViewの当たり判定用矩形
     */
    private final Rect mFloatingViewRect;

    /**
     * TrashViewの当たり判定用矩形
     */
    private final Rect mTrashViewRect;

    /**
     * タッチの移動を許可するフラグ
     * 画面回転時にタッチ処理を受け付けないようにするためのフラグです
     */
    private boolean mIsMoveAccept;

    /**
     * 現在の表示モード
     */
    @DisplayMode
    private int mDisplayMode;

    /**
     * Windowに貼り付けられたFloatingViewのリスト
     * TODO:第2弾のFloatingViewの複数表示で意味を発揮する予定
     */
    private final ArrayList<FloatingView> mFloatingViewList;

    /**
     * コンストラクタ
     *
     * @param context  Context
     * @param listener FloatingViewListener
     */
    public FloatingViewManager(Context context, FloatingViewListener listener) {
        mContext = context;
        mResources = context.getResources();
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        mDisplayMetrics = new DisplayMetrics();
        mFloatingViewListener = listener;
        mFloatingViewRect = new Rect();
        mTrashViewRect = new Rect();
        mIsMoveAccept = false;
        mDisplayMode = DISPLAY_MODE_HIDE_FULLSCREEN;

        // FloatingViewと連携するViewの構築
        mFloatingViewList = new ArrayList<>();
        mFullscreenObserverView = new FullscreenObserverView(context, this);
        mTrashView = new TrashView(context);
    }

    /**
     * 削除Viewと重なっているかチェックします。
     *
     * @return 削除Viewと重なっている場合はtrue
     */
    private boolean isIntersectWithTrash() {
        // 無効の場合は重なり判定を行わない
        if (!mTrashView.isTrashEnabled()) {
            return false;
        }
        // INFO:TrashViewとFloatingViewは同じGravityにする必要があります
        mTrashView.getWindowDrawingRect(mTrashViewRect);
        mTargetFloatingView.getWindowDrawingRect(mFloatingViewRect);
        return Rect.intersects(mTrashViewRect, mFloatingViewRect);
    }

    /**
     * 画面がフルスクリーンになった場合はViewを非表示にします。
     */
    @Override
    public void onScreenChanged(Rect windowRect, int visibility) {
        // detect status bar
        final boolean isFitSystemWindowTop = windowRect.top == 0;
        boolean isHideStatusBar;
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 && visibility != FullscreenObserverView.NO_LAST_VISIBILITY) {
            // Support for screen rotation when setSystemUiVisibility is used
            isHideStatusBar = isFitSystemWindowTop || (visibility & View.SYSTEM_UI_FLAG_LOW_PROFILE) == View.SYSTEM_UI_FLAG_LOW_PROFILE;
        } else {
            isHideStatusBar = isFitSystemWindowTop;
        }

        // detect navigation bar
        final boolean isHideNavigationBar;
        if (visibility == FullscreenObserverView.NO_LAST_VISIBILITY) {
            // At the first it can not get the correct value, so do special processing
            mWindowManager.getDefaultDisplay().getMetrics(mDisplayMetrics);
            isHideNavigationBar = windowRect.width() - mDisplayMetrics.widthPixels > 0 || windowRect.height() - mDisplayMetrics.heightPixels > 0;
        } else {
            isHideNavigationBar = (visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        }
        final boolean isPortrait = mResources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;

        // touch X offset(navigation bar is on the left side)
        final boolean hasTouchXOffset = windowRect.left > 0;

        // update FloatingView layout
        mTargetFloatingView.onUpdateSystemLayout(isHideStatusBar, isHideNavigationBar, isPortrait, hasTouchXOffset);

        // フルスクリーンでの非表示モードでない場合は何もしない
        if (mDisplayMode != DISPLAY_MODE_HIDE_FULLSCREEN) {
            return;
        }

        mIsMoveAccept = false;
        final int state = mTargetFloatingView.getState();
        // 重なっていない場合は全て非表示処理
        if (state == FloatingView.STATE_NORMAL) {
            final int size = mFloatingViewList.size();
            for (int i = 0; i < size; i++) {
                final FloatingView floatingView = mFloatingViewList.get(i);
                floatingView.setVisibility(isFitSystemWindowTop ? View.GONE : View.VISIBLE);
            }
            mTrashView.dismiss();
        }
        // 重なっている場合は削除
        else if (state == FloatingView.STATE_INTERSECTING) {
            mTargetFloatingView.setFinishing();
            mTrashView.dismiss();
        }
    }

    /**
     * Update ActionTrashIcon
     */
    @Override
    public void onUpdateActionTrashIcon() {
        mTrashView.updateActionTrashIcon(mTargetFloatingView.getMeasuredWidth(), mTargetFloatingView.getMeasuredHeight(), mTargetFloatingView.getShape());
    }

    /**
     * FloatingViewのタッチをロックします。
     */
    @Override
    public void onTrashAnimationStarted(@TrashView.AnimationState int animationCode) {
        // クローズまたは強制クローズの場合はすべてのFloatingViewをタッチさせない
        if (animationCode == TrashView.ANIMATION_CLOSE || animationCode == TrashView.ANIMATION_FORCE_CLOSE) {
            final int size = mFloatingViewList.size();
            for (int i = 0; i < size; i++) {
                final FloatingView floatingView = mFloatingViewList.get(i);
                floatingView.setDraggable(false);
            }
        }
    }

    /**
     * FloatingViewのタッチロックの解除を行います。
     */
    @Override
    public void onTrashAnimationEnd(@TrashView.AnimationState int animationCode) {

        final int state = mTargetFloatingView.getState();
        // 終了していたらViewを削除する
        if (state == FloatingView.STATE_FINISHING) {
            removeViewToWindow(mTargetFloatingView);
        }

        // すべてのFloatingViewのタッチ状態を戻す
        final int size = mFloatingViewList.size();
        for (int i = 0; i < size; i++) {
            final FloatingView floatingView = mFloatingViewList.get(i);
            floatingView.setDraggable(true);
        }

    }

    /**
     * 削除ボタンの表示・非表示を処理します。
     */
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        final int action = event.getAction();

        // 押下状態でないのに移動許可が出ていない場合はなにもしない(回転直後にACTION_MOVEが来て、FloatingViewが消えてしまう現象に対応)
        if (action != MotionEvent.ACTION_DOWN && !mIsMoveAccept) {
            return false;
        }

        final int state = mTargetFloatingView.getState();
        mTargetFloatingView = (FloatingView) v;

        // 押下
        if (action == MotionEvent.ACTION_DOWN) {
            // 処理なし
            mIsMoveAccept = true;
        }
        // 移動
        else if (action == MotionEvent.ACTION_MOVE) {
            // 今回の状態
            final boolean isIntersecting = isIntersectWithTrash();
            // これまでの状態
            final boolean isIntersect = state == FloatingView.STATE_INTERSECTING;
            // 重なっている場合は、FloatingViewをTrashViewに追従させる
            if (isIntersecting) {
                mTargetFloatingView.setIntersecting((int) mTrashView.getTrashIconCenterX(), (int) mTrashView.getTrashIconCenterY());
            }
            // 重なり始めの場合
            if (isIntersecting && !isIntersect) {
                mTargetFloatingView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
                mTrashView.setScaleTrashIcon(true);
            }
            // 重なり終わりの場合
            else if (!isIntersecting && isIntersect) {
                mTargetFloatingView.setNormal();
                mTrashView.setScaleTrashIcon(false);
            }

        }
        // 押上、キャンセル
        else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
            // 重なっている場合
            if (state == FloatingView.STATE_INTERSECTING) {
                // FloatingViewを削除し、拡大状態を解除
                mTargetFloatingView.setFinishing();
                mTrashView.setScaleTrashIcon(false);
            }
            mIsMoveAccept = false;

            // Touch finish callback
            if (mFloatingViewListener != null) {
                final boolean isFinishing = mTargetFloatingView.getState() == FloatingView.STATE_FINISHING;
                final WindowManager.LayoutParams params = mTargetFloatingView.getWindowLayoutParams();
                mFloatingViewListener.onTouchFinished(isFinishing, params.x, params.y);
            }
        }

        // TrashViewにイベントを通知
        // 通常状態の場合は指の位置を渡す
        // 重なっている場合はTrashViewの位置を渡す
        if (state == FloatingView.STATE_INTERSECTING) {
            mTrashView.onTouchFloatingView(event, mFloatingViewRect.left, mFloatingViewRect.top);
        } else {
            final WindowManager.LayoutParams params = mTargetFloatingView.getWindowLayoutParams();
            mTrashView.onTouchFloatingView(event, params.x, params.y);
        }

        return false;
    }

    /**
     * 固定削除アイコンの画像を設定します。
     *
     * @param resId drawable ID
     */
    public void setFixedTrashIconImage(@DrawableRes int resId) {
        mTrashView.setFixedTrashIconImage(resId);
    }

    /**
     * アクションする削除アイコンの画像を設定します。
     *
     * @param resId drawable ID
     */
    public void setActionTrashIconImage(@DrawableRes int resId) {
        mTrashView.setActionTrashIconImage(resId);
    }

    /**
     * 固定削除アイコンを設定します。
     *
     * @param drawable Drawable
     */
    public void setFixedTrashIconImage(Drawable drawable) {
        mTrashView.setFixedTrashIconImage(drawable);
    }

    /**
     * アクション用削除アイコンを設定します。
     *
     * @param drawable Drawable
     */
    public void setActionTrashIconImage(Drawable drawable) {
        mTrashView.setActionTrashIconImage(drawable);
    }

    /**
     * 表示モードを変更します。
     *
     * @param displayMode {@link #DISPLAY_MODE_SHOW_ALWAYS} or {@link #DISPLAY_MODE_HIDE_ALWAYS} or {@link #DISPLAY_MODE_HIDE_FULLSCREEN}
     */
    public void setDisplayMode(@DisplayMode int displayMode) {
        mDisplayMode = displayMode;
        // 常に表示/フルスクリーン時に非表示にするモードの場合
        if (mDisplayMode == DISPLAY_MODE_SHOW_ALWAYS || mDisplayMode == DISPLAY_MODE_HIDE_FULLSCREEN) {
            for (FloatingView floatingView : mFloatingViewList) {
                floatingView.setVisibility(View.VISIBLE);
            }
        }
        // 常に非表示にするモードの場合
        else if (mDisplayMode == DISPLAY_MODE_HIDE_ALWAYS) {
            for (FloatingView floatingView : mFloatingViewList) {
                floatingView.setVisibility(View.GONE);
            }
            mTrashView.dismiss();
        }
    }

    /**
     * TrashViewの表示・非表示を設定します。
     *
     * @param enabled trueの場合は表示
     */
    public void setTrashViewEnabled(boolean enabled) {
        mTrashView.setTrashEnabled(enabled);
    }

    /**
     * TrashViewの表示非表示状態を取得します。
     *
     * @return trueの場合は表示状態(重なり判定が有効の状態)
     */
    public boolean isTrashViewEnabled() {
        return mTrashView.isTrashEnabled();
    }

    /**
     * ViewをWindowに貼り付けます。
     *
     * @param view    フローティングさせるView
     * @param options Options
     */
    public void addViewToWindow(View view, Options options) {
        final boolean isFirstAttach = mFloatingViewList.isEmpty();
        // FloatingView
        final FloatingView floatingView = new FloatingView(mContext);
        floatingView.setInitCoords(options.floatingViewX, options.floatingViewY);
        floatingView.setOnTouchListener(this);
        floatingView.setShape(options.shape);
        floatingView.setOverMargin(options.overMargin);
        floatingView.setMoveDirection(options.moveDirection);
        floatingView.usePhysics(options.usePhysics);
        floatingView.setAnimateInitialMove(options.animateInitialMove);

        // set FloatingView size
        final FrameLayout.LayoutParams targetParams = new FrameLayout.LayoutParams(options.floatingViewWidth, options.floatingViewHeight);
        view.setLayoutParams(targetParams);
        floatingView.addView(view);

        // 非表示モードの場合
        if (mDisplayMode == DISPLAY_MODE_HIDE_ALWAYS) {
            floatingView.setVisibility(View.GONE);
        }
        mFloatingViewList.add(floatingView);
        // TrashView
        mTrashView.setTrashViewListener(this);

        // Viewの貼り付け
        mWindowManager.addView(floatingView, floatingView.getWindowLayoutParams());
        // 最初の貼り付け時の場合のみ、フルスクリーン監視Viewと削除Viewを貼り付け
        if (isFirstAttach) {
            mWindowManager.addView(mFullscreenObserverView, mFullscreenObserverView.getWindowLayoutParams());
            mTargetFloatingView = floatingView;
        } else {
            mWindowManager.removeViewImmediate(mTrashView);
        }
        // 必ずトップに来て欲しいので毎回貼り付け
        mWindowManager.addView(mTrashView, mTrashView.getWindowLayoutParams());
    }

    /**
     * ViewをWindowから取り外します。
     *
     * @param floatingView FloatingView
     */
    private void removeViewToWindow(FloatingView floatingView) {
        final int matchIndex = mFloatingViewList.indexOf(floatingView);
        // 見つかった場合は表示とリストから削除
        if (matchIndex != -1) {
            mWindowManager.removeViewImmediate(floatingView);
            mFloatingViewList.remove(matchIndex);
        }

        // 残りのViewをチェック
        if (mFloatingViewList.isEmpty()) {
            // 終了を通知
            if (mFloatingViewListener != null) {
                mFloatingViewListener.onFinishFloatingView();
            }
        }
    }

    /**
     * ViewをWindowから全て取り外します。
     */
    public void removeAllViewToWindow() {
        mWindowManager.removeViewImmediate(mFullscreenObserverView);
        mWindowManager.removeViewImmediate(mTrashView);
        // FloatingViewの削除
        final int size = mFloatingViewList.size();
        for (int i = 0; i < size; i++) {
            final FloatingView floatingView = mFloatingViewList.get(i);
            mWindowManager.removeViewImmediate(floatingView);
        }
        mFloatingViewList.clear();
    }

    /**
     * FloatingViewを貼り付ける際のオプションを表すクラスです。
     */
    public static class Options {

        /**
         * フローティングさせるViewの矩形(SHAPE_RECTANGLE or SHAPE_CIRCLE)
         */
        public float shape;

        /**
         * 画面外のはみ出しマージン(px)
         */
        public int overMargin;

        /**
         * 画面左下を原点とするFloatingViewのX座標
         */
        public int floatingViewX;

        /**
         * 画面左下を原点とするFloatingViewのY座標
         */
        public int floatingViewY;

        /**
         * Width of FloatingView(px)
         */
        public int floatingViewWidth;

        /**
         * Height of FloatingView(px)
         */
        public int floatingViewHeight;

        /**
         * FloatingViewが吸着する方向
         * ※座標を指定すると自動的にMOVE_DIRECTION_NONEになります
         */
        @MoveDirection
        public int moveDirection;

        /**
         * Use of physics-based animations or (default) ValueAnimation
         */
        public boolean usePhysics;

        /**
         * 初期表示時にアニメーションするフラグ
         */
        public boolean animateInitialMove;

        /**
         * オプションのデフォルト値を設定します。
         */
        public Options() {
            shape = SHAPE_CIRCLE;
            overMargin = 0;
            floatingViewX = FloatingView.DEFAULT_X;
            floatingViewY = FloatingView.DEFAULT_Y;
            floatingViewWidth = FloatingView.DEFAULT_WIDTH;
            floatingViewHeight = FloatingView.DEFAULT_HEIGHT;
            moveDirection = MOVE_DIRECTION_DEFAULT;
            animateInitialMove = true;
        }

    }

}


text:
package org.apache.lucene.store.jdbc.index;

import java.io.IOException;

import org.apache.lucene.store.ConfigurableBufferedIndexOutput;
import org.apache.lucene.store.jdbc.JdbcDirectory;
import org.apache.lucene.store.jdbc.JdbcFileEntrySettings;

/**
 * A simple base class that performs index output memory based buffering. The buffer size can be configured
 * under the {@link #BUFFER_SIZE_SETTING} name.
 *
 * @author kimchy
 */
public abstract class JdbcBufferedIndexOutput extends ConfigurableBufferedIndexOutput implements JdbcIndexConfigurable {

    /**
     * The buffer size setting name. See {@link JdbcFileEntrySettings#setIntSetting(String,int)}.
     * Should be set in bytes.
     */
    public static final String BUFFER_SIZE_SETTING = "indexOutput.bufferSize";

    public void configure(String name, JdbcDirectory jdbcDirectory, JdbcFileEntrySettings settings) throws IOException {
        initBuffer(settings.getSettingAsInt(BUFFER_SIZE_SETTING, DEFAULT_BUFFER_SIZE));
    }
}


text:
package demo.account.event;

import com.fasterxml.jackson.annotation.JsonIgnore;
import demo.account.controller.AccountController;
import demo.account.domain.Account;
import demo.event.Event;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.hateoas.Link;

import javax.persistence.*;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;

/**
 * The domain event {@link AccountEvent} tracks the type and state of events as applied to the {@link Account} domain
 * object. This event resource can be used to event source the aggregate state of {@link Account}.
 * <p>
 * This event resource also provides a transaction log that can be used to append actions to the event.
 *
 * @author Kenny Bastani
 */
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(indexes = { @Index(name = "IDX_ACCOUNT_EVENT", columnList = "entity_id") })
public class AccountEvent extends Event<Account, AccountEventType, Long> {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long eventId;

    @Enumerated(EnumType.STRING)
    private AccountEventType type;

    @OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
    @JsonIgnore
    private Account entity;

    @CreatedDate
    private Long createdAt;

    @LastModifiedDate
    private Long lastModified;

    public AccountEvent() {
    }

    public AccountEvent(AccountEventType type) {
        this.type = type;
    }

    public AccountEvent(AccountEventType type, Account entity) {
        this.type = type;
        this.entity = entity;
    }

    @Override
    public Long getEventId() {
        return eventId;
    }

    @Override
    public void setEventId(Long id) {
        eventId = id;
    }

    @Override
    public AccountEventType getType() {
        return type;
    }

    @Override
    public void setType(AccountEventType type) {
        this.type = type;
    }

    @Override
    public Account getEntity() {
        return entity;
    }

    @Override
    public void setEntity(Account entity) {
        this.entity = entity;
    }

    @Override
    public Long getCreatedAt() {
        return createdAt;
    }

    @Override
    public void setCreatedAt(Long createdAt) {
        this.createdAt = createdAt;
    }

    @Override
    public Long getLastModified() {
        return lastModified;
    }

    @Override
    public void setLastModified(Long lastModified) {
        this.lastModified = lastModified;
    }

    @Override
    public Link getId() {
        return linkTo(AccountController.class).slash("accounts").slash(getEntity().getIdentity()).slash("events")
                .slash(getEventId()).withSelfRel();
    }

    @Override
    public String toString() {
        return "AccountEvent{" +
                "eventId=" + eventId +
                ", type=" + type +
                ", entity=" + entity +
                ", createdAt=" + createdAt +
                ", lastModified=" + lastModified +
                "} " + super.toString();
    }
}


text:
namespace wgt
{
namespace Reflection
{

void initReflectedTypes( IDefinitionManager & definitionManager )
{
	REGISTER_DEFINITION( MetaNoneObj );
	REGISTER_DEFINITION( MetaBase );
	REGISTER_DEFINITION( MetaMinMaxObj );
	REGISTER_DEFINITION( MetaStepSizeObj );
	REGISTER_DEFINITION( MetaDecimalsObj );
	REGISTER_DEFINITION( MetaEnumObj );
	REGISTER_DEFINITION( MetaSliderObj );
	REGISTER_DEFINITION( MetaAttributeDisplayNameObj );
	REGISTER_DEFINITION( MetaGroupObj );
	REGISTER_DEFINITION( MetaDisplayNameObj );
	REGISTER_DEFINITION( MetaDescriptionObj );
	REGISTER_DEFINITION( MetaNoNullObj );
	REGISTER_DEFINITION( MetaColorObj );
	REGISTER_DEFINITION( MetaThumbnailObj );
	REGISTER_DEFINITION( MetaInPlaceObj );
	REGISTER_DEFINITION( MetaSelectedObj );
	REGISTER_DEFINITION( MetaHiddenObj );
	REGISTER_DEFINITION( MetaPanelLayoutObj );
	REGISTER_DEFINITION( MetaCommandObj );
	REGISTER_DEFINITION( MetaNoSerializationObj );
	REGISTER_DEFINITION( MetaUniqueIdObj );
	REGISTER_DEFINITION( MetaOnStackObj );
	REGISTER_DEFINITION( MetaInPlacePropertyNameObj );
	REGISTER_DEFINITION( MetaReadOnlyObj );
	REGISTER_DEFINITION( MetaUrlObj );
}

}
} // end namespace wgt


text:
BWU Dart Archive Downloader
======

[![Star this Repo](https://img.shields.io/github/stars/bwu-dart/bwu_dart_archive_downloader.svg?style=flat)](https://github.com/bwu-dart/bwu_dart_archive_downloader)
[![Pub Package](https://img.shields.io/pub/v/bwu_dart_archive_downloader.svg?style=flat)](https://pub.dartlang.org/packages/bwu_dart_archive_downloader)
[![Build Status](https://travis-ci.org/bwu-dart/bwu_dart_archive_downloader.svg?branch=master)](https://travis-ci.org/bwu-dart/bwu_dart_archive_downloader)
[![Coverage Status](https://coveralls.io/repos/bwu-dart/bwu_dart_archive_downloader/badge.svg?branch=master)](https://coveralls.io/r/bwu-dart/bwu_dart_archive_downloader)

BWU Dart Archive Downloader makes it easy to download files like API docs,
Dartium or content-shell, Dartium for Android APK, Dart Eclipse plugin, or the
Dart SDK from http://gsdview.appspot.com/dart-archive/channels/
Its main purpose is to make maintenance tasks and automatic setup for continuous
integration (CI) as easy as possible.

## Activate the command line tool
To activate the command line tool globally use this command:

```sh
pub global activate bwu_dart_archive_downloader
```
Now you can call the command line tool using

```sh
pub global run bwu_dart_archive_downloader:darc ...
```

or if you have added the `~/.pub-cache/bin` directory to the `PATH` environment
variable just:

```sh
darc
```

## Example 1
Download Dart SDK 1.5.2 from the command line:

```sh
darc down -v1.5.2
```
downloads `dartsdk-linux-x64-release.zip` to the curent working directory.
`Linux x64` is derived from my operating system, but can also be specified by
a parameter.
If you omit the `-v...` parameter the latest version is downloaded.

## Example 2
Download chromedriver 1.5.2 from the command line:

```sh
darc down -adartium -fchromedriver -o_output -v1.5.2 -cstable/release  -e -dxxx -t_extract
```

This results in two subdirectories in the current working directory
- `_output`
- `_extract`

`_output` is the directory where the downloaded file
`chromedriver-linux-x64-release.zip` is stored because of the `-o` parameter.
`_extract` is where the content of the ZIP file is extracted to as specified by
the `-t` parameter.
Because we passed `-dxxx`, the content (`chromedriver-lucid64-full-stable-37942.0`
from `chromedriver-linux-x64-release.zip`) was extracted as `_extract/xxx` which
now contains the file `chromedriver`.
`-cstable/release` can be omitted because it is the default, but it shows how to
select a specific channel.

## Example 3
Download a file from `latest` using the API:

```Dart
import 'dart:io' as io;
import 'package:bwu_dart_archive_downloader/bwu_dart_archive_downloader.dart';

main() async {
  // create an instance of the downloader and specify the download directory.
  final downloader = new DartArchiveDownloader(new io.Directory('temp'));

  // specify the file to download
  final file = new DartiumFile.contentShellZip(
      Platform.getFromSystemPlatform(prefer64bit: true));

  // build the uri for the download file.
  final uri =
      DownloadChannel.stableRelease.getUri(file);

  // start the download
  await downloader.downloadFile(uri);
}

```

## Example 4
Download a file from a specific release using the API:

```Dart
final channel = DownloadChannel.stableRelease;
final downloader =
    new DartArchiveDownloader(new io.Directory('temp/install'));
final version =
    await downloader.findVersion(channel, new Version.parse('1.2.0'));
final uri = await channel.getUri(new SdkFile.dartSdk(
    Platform.getFromSystemPlatform(prefer64bit: true)), version: version);
final file = await downloader.downloadFile(uri);
```

The `dart_update` library provides functions to extract the downloaded archive.


text:
<?php

namespace pantr\core;

interface Status {
	const SUCCESS = 0;
	const FAILURE = 1;
}


text:
module Nhtsa
  module Recalls
    class Manufacturers
      def initialize(year)
        @year = year
      end

      def url
        "#{BASE_URI}#{END_POINT}/#{@year}#{DEFAULT_PARAMS}"
      end

      def manufacturers
        JSON.parse(open(url).read)["Results"].collect{|manufacturer| manufacturer["Make"]}
      end
    end
  end
end


text:
namespace rtHMM {

    static const double pi = 4.0 * std::atan(1.0);

    template<int dims>
    gaussian_distribution<dims>::gaussian_distribution(const mean_type& mn, const variance_type& var) :
        means(mn),
        inverse_sigma(var.inverse())
    {
        compute_norm_factor(var);
    }

    template<int dims>
    double gaussian_distribution<dims>::compute_probability(const value_type& value) const
    {
        auto dev = value - means;
        double tmp = (dev.transpose() * inverse_sigma) * dev;
        return norm_factor * std::exp(-0.5f * tmp);
    }

    template<int dims>
    void gaussian_distribution<dims>::compute_norm_factor(const variance_type& var)
    {
        norm_factor = 1 / (std::pow(2. * pi, static_cast<double>(dims) / 2) * std::sqrt(var.determinant()));
    }

    inline gaussian_distribution<1>::gaussian_distribution(double mn, double var) :
        mean(mn),
        two_times_variance_inverse(1. / (var * 2.)),
        norm_factor(1. / sqrt(2. * var* pi))
    {
    }

    inline gaussian_distribution<1>::gaussian_distribution(const gaussian_distribution<1>::mean_type& mn,
            const gaussian_distribution<1>::variance_type& var) :
        gaussian_distribution(mn(0, 0), var(0, 0))
    {
    }

    inline double gaussian_distribution<1>::compute_probability(const double& value) const
    {
        return norm_factor * exp(-pow(value - mean, 2) * two_times_variance_inverse);
    }

} // namespace rtHMM


text:
<?php

/* @var $installer Mage_Core_Model_Resource_Setup */
$installer = $this;

$connection = $installer->getConnection();
$table      = $installer->getTable('catalog/category_product_indexer_idx');
$connection->addKey($table, 'IDX_PRODUCT_CATEGORY_STORE', array('product_id', 'category_id', 'store_id'));


text:
import React from "react";
import "./cable.scss";
// Output true if connected to another cable of any kind
const CableOutput = ({
  connecting,
  startConnecting,
  id,
  page,
  onMouseDown,
  edit,
  draggingCable,
  cables = [],
  scaleComp = () => {},
  scale = 1,
}) => {
  const cableComponents = cables.reduce((prev, next) => {
    return prev.concat(next.components);
  }, []);
  return (
    <div style={{transform: `scale(${scale})`}}>

      {page && edit && !connecting && (

 startConnecting(evt, id)} />
      )}
      {page && edit &&
}

  );
};

export default CableOutput;


text:
ASpectatorPawn::ASpectatorPawn(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer
	.SetDefaultSubobjectClass<USpectatorPawnMovement>(Super::MovementComponentName)
	.DoNotCreateDefaultSubobject(Super::MeshComponentName)
	)
{
	bCanBeDamaged = false;
	//SetRemoteRoleForBackwardsCompat(ROLE_SimulatedProxy);
	//bReplicates = true;

	BaseEyeHeight = 0.0f;
	bCollideWhenPlacing = false;
	SpawnCollisionHandlingMethod = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;

	static FName CollisionProfileName(TEXT("Spectator"));
	GetCollisionComponent()->SetCollisionProfileName(CollisionProfileName);
}

void ASpectatorPawn::PossessedBy(class AController* NewController)
{
	if (bReplicates)
	{
		Super::PossessedBy(NewController);
	}
	else
	{
		// We don't want the automatic changing of net role in Pawn code since we don't replicate, so don't call Super.
		AController* const OldController = Controller;
		Controller = NewController;

		// dispatch Blueprint event if necessary
		if (OldController != NewController)
		{
			ReceivePossessed(Controller);
		}
	}
}


text:
@implementation CCPlayerPreviewViewModel

@end

NSString *const kPlayerPreviewImageSizeSeparateChar = @"x";  // responce format: "320x640"

@implementation CCPlayerPreviewViewModelBuilder

#pragma mark - Public

+ (void)buildWithServerModels:(NSArray <CCPlayerPreviewServerModel *> *)serverModels
               containerWidth:(CGFloat)containerWidth
                   viewModels:(playersDataBlock)viewModels {
    __block NSMutableArray <CCPlayerPreviewViewModel *> *viewModelsData = [[NSMutableArray alloc] init];

    const char *classNameChar = [NSStringFromClass([CCPlayerPreviewViewModelBuilder class]) UTF8String];
    dispatch_queue_t queue = dispatch_queue_create(classNameChar, DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        [serverModels enumerateObjectsUsingBlock:^(CCPlayerPreviewServerModel *serverModel, NSUInteger idx, BOOL * _Nonnull stop) {
            CCPlayerPreviewViewModel *viewModel = [[CCPlayerPreviewViewModel alloc] init];
            viewModel.nickName = serverModel.nickName;
            viewModel.imageURL = serverModel.imageURL;
            viewModel.playerID = serverModel.playerID;
            viewModel.imageHeight = [self calculateImageHeightForImageSize:serverModel.imageSize containerWidth:containerWidth];
            [viewModelsData addObject:viewModel];
        }];
    });

    dispatch_async(queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            viewModels(viewModelsData);
        });
    });
}

+ (void)buildWithCoreDataModels:(NSArray <CCPlayerPreviewCoreDataModel *> *)coreDataModels
                 containerWidth:(CGFloat)containerWidth
                     viewModels:(playersDataBlock)viewModels {
    __block NSMutableArray <CCPlayerPreviewViewModel *> *viewModelsData = [[NSMutableArray alloc] init];

    const char *classNameChar = [NSStringFromClass([CCPlayerPreviewViewModelBuilder class]) UTF8String];
    dispatch_queue_t queue = dispatch_queue_create(classNameChar, DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        [coreDataModels enumerateObjectsUsingBlock:^(CCPlayerPreviewCoreDataModel *coreDataModel, NSUInteger idx, BOOL * _Nonnull stop) {
            CCPlayerPreviewViewModel *viewModel = [[CCPlayerPreviewViewModel alloc] init];
            viewModel.nickName = coreDataModel.nickName;
            viewModel.imageURL = [NSURL URLWithString:coreDataModel.imageURL];
            viewModel.playerID = (NSInteger)coreDataModel.playerID;
            viewModel.imageHeight = [self calculateImageHeightForImageSize:coreDataModel.imageSize containerWidth:containerWidth];
            [viewModelsData addObject:viewModel];
        }];
    });

    dispatch_async(queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            viewModels(viewModelsData);
        });
    });
}

#pragma mark - Private

+ (CGFloat)calculateImageHeightForImageSize:(NSString *)imageSize containerWidth:(CGFloat)containerWidth {
    NSArray *separateImageSizeArray = [imageSize componentsSeparatedByString:kPlayerPreviewImageSizeSeparateChar];
    NSString *serverImageHeightStr = [separateImageSizeArray lastObject];
    NSString *serverImageWidthStr = [separateImageSizeArray firstObject];
    if (!serverImageHeightStr) {
        return 0.f;
    } else {
        return (serverImageHeightStr.floatValue * containerWidth) / serverImageWidthStr.floatValue;
    }
}

@end


text:
golint ./...
godep go vet ./...
godep go test ./...  -cover
# go tool cover -html=coverage.out
godep go install