text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="A front-end template that helps you build fast, modern mobile web apps.">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
    <title>Material Design Lite</title>

    <meta name="mobile-web-app-capable" content="yes">
    <link rel="icon" sizes="192x192" href="images/android-desktop.png">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="Material Design Lite">
    <link rel="apple-touch-icon-precomposed" href="images/ios-desktop.png">

    <meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">
    <meta name="msapplication-TileColor" content="#3372DF">

    <link rel="shortcut icon" href="images/favicon.png">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="$$hosted_libs_prefix$$/$$version$$/material.teal-red.min.css">
    <link rel="stylesheet" href="styles.css">

          Material Design Lite

              search

              <input class="mdl-textfield__input" type="text" id="search">
              Enter your query...

              Google > Material Design Lite > How to install MDL

How to install MDL

                Cillum dolor esse sit incididunt velit eiusmod magna ad nostrud officia aute dolor dolor. Magna esse ullamco pariatur adipisicing consectetur eu commodo officia. Ex cillum consequat mollit minim elit est deserunt occaecat nisi amet. Quis aliqua nostrud Lorem occaecat sunt. Eiusmod quis amet ullamco aliquip dolore ut incididunt duis adipisicing. Elit consequat nisi eiusmod aute ipsum sunt veniam do est. Occaecat mollit aliquip ut proident consectetur amet ex dolore consectetur aliqua elit.

                Commodo nisi non consectetur voluptate incididunt mollit duis dolore amet amet tempor exercitation. Qui amet aute ea aute id ad aliquip proident. Irure duis qui labore deserunt enim in quis nisi sint consequat aliqua. Ex proident labore et laborum tempor fugiat sint magna veniam minim. Nulla dolor labore adipisicing in enim mollit laboris fugiat eu. Aliquip minim cillum ullamco voluptate non dolore non ex duis fugiat duis ad. Deserunt cillum ad et nisi amet non voluptate culpa qui do. Labore ullamco et minim proident est laborum mollit ad labore deserunt ut irure dolore. Reprehenderit ad ad irure ut irure qui est eu velit eu excepteur adipisicing culpa. Laborum cupidatat ullamco eu duis anim reprehenderit proident aute ad consectetur eiusmod.

                Tempor tempor aliqua in commodo cillum Lorem magna dolore proident Lorem. Esse ad consequat est excepteur irure eu irure quis aliqua qui. Do mollit esse veniam excepteur ut veniam anim minim dolore sit commodo consequat duis commodo. Sunt dolor reprehenderit ipsum minim eiusmod eu consectetur anim excepteur eiusmod. Duis excepteur anim dolor sit enim veniam deserunt anim adipisicing Lorem elit. Cillum sunt do consequat elit laboris nisi consectetur.

Basic MDL Usage

                Cillum dolor esse sit incididunt velit eiusmod magna ad nostrud officia aute dolor dolor. Magna esse ullamco pariatur adipisicing consectetur eu commodo officia. Ex cillum consequat mollit minim elit est deserunt occaecat nisi amet. Quis aliqua nostrud Lorem occaecat sunt. Eiusmod quis amet ullamco aliquip dolore ut incididunt duis adipisicing. Elit consequat nisi eiusmod aute ipsum sunt veniam do est. Occaecat mollit aliquip ut proident consectetur amet ex dolore consectetur aliqua elit.

                Commodo nisi non consectetur voluptate incididunt mollit duis dolore amet amet tempor exercitation. Qui amet aute ea aute id ad aliquip proident. Irure duis qui labore deserunt enim in quis nisi sint consequat aliqua. Ex proident labore et laborum tempor fugiat sint magna veniam minim. Nulla dolor labore adipisicing in enim mollit laboris fugiat eu. Aliquip minim cillum ullamco voluptate non dolore non ex duis fugiat duis ad. Deserunt cillum ad et nisi amet non voluptate culpa qui do. Labore ullamco et minim proident est laborum mollit ad labore deserunt ut irure dolore. Reprehenderit ad ad irure ut irure qui est eu velit eu excepteur adipisicing culpa. Laborum cupidatat ullamco eu duis anim reprehenderit proident aute ad consectetur eiusmod.

                Cillum dolor esse sit incididunt velit eiusmod magna ad nostrud officia aute dolor dolor. Magna esse ullamco pariatur adipisicing consectetur eu commodo officia. Ex cillum consequat mollit minim elit est deserunt occaecat nisi amet. Quis aliqua nostrud Lorem occaecat sunt. Eiusmod quis amet ullamco aliquip dolore ut incididunt duis adipisicing. Elit consequat nisi eiusmod aute ipsum sunt veniam do est. Occaecat mollit aliquip ut proident consectetur amet ex dolore consectetur aliqua elit.

                Commodo nisi non consectetur voluptate incididunt mollit duis dolore amet amet tempor exercitation. Qui amet aute ea aute id ad aliquip proident. Irure duis qui labore deserunt enim in quis nisi sint consequat aliqua. Ex proident labore et laborum tempor fugiat sint magna veniam minim. Nulla dolor labore adipisicing in enim mollit laboris fugiat eu. Aliquip minim cillum ullamco voluptate non dolore non ex duis fugiat duis ad. Deserunt cillum ad et nisi amet non voluptate culpa qui do. Labore ullamco et minim proident est laborum mollit ad labore deserunt ut irure dolore. Reprehenderit ad ad irure ut irure qui est eu velit eu excepteur adipisicing culpa. Laborum cupidatat ullamco eu duis anim reprehenderit proident aute ad consectetur eiusmod.

                Cillum dolor esse sit incididunt velit eiusmod magna ad nostrud officia aute dolor dolor. Magna esse ullamco pariatur adipisicing consectetur eu commodo officia. Ex cillum consequat mollit minim elit est deserunt occaecat nisi amet. Quis aliqua nostrud Lorem occaecat sunt. Eiusmod quis amet ullamco aliquip dolore ut incididunt duis adipisicing. Elit consequat nisi eiusmod aute ipsum sunt veniam do est. Occaecat mollit aliquip ut proident consectetur amet ex dolore consectetur aliqua elit.

                Commodo nisi non consectetur voluptate incididunt mollit duis dolore amet amet tempor exercitation. Qui amet aute ea aute id ad aliquip proident. Irure duis qui labore deserunt enim in quis nisi sint consequat aliqua. Ex proident labore et laborum tempor fugiat sint magna veniam minim. Nulla dolor labore adipisicing in enim mollit laboris fugiat eu. Aliquip minim cillum ullamco voluptate non dolore non ex duis fugiat duis ad. Deserunt cillum ad et nisi amet non voluptate culpa qui do. Labore ullamco et minim proident est laborum mollit ad labore deserunt ut irure dolore. Reprehenderit ad ad irure ut irure qui est eu velit eu excepteur adipisicing culpa. Laborum cupidatat ullamco eu duis anim reprehenderit proident aute ad consectetur eiusmod.

                Cillum dolor esse sit incididunt velit eiusmod magna ad nostrud officia aute dolor dolor. Magna esse ullamco pariatur adipisicing consectetur eu commodo officia. Ex cillum consequat mollit minim elit est deserunt occaecat nisi amet. Quis aliqua nostrud Lorem occaecat sunt. Eiusmod quis amet ullamco aliquip dolore ut incididunt duis adipisicing. Elit consequat nisi eiusmod aute ipsum sunt veniam do est. Occaecat mollit aliquip ut proident consectetur amet ex dolore consectetur aliqua elit.

                Commodo nisi non consectetur voluptate incididunt mollit duis dolore amet amet tempor exercitation. Qui amet aute ea aute id ad aliquip proident. Irure duis qui labore deserunt enim in quis nisi sint consequat aliqua. Ex proident labore et laborum tempor fugiat sint magna veniam minim. Nulla dolor labore adipisicing in enim mollit laboris fugiat eu. Aliquip minim cillum ullamco voluptate non dolore non ex duis fugiat duis ad. Deserunt cillum ad et nisi amet non voluptate culpa qui do. Labore ullamco et minim proident est laborum mollit ad labore deserunt ut irure dolore. Reprehenderit ad ad irure ut irure qui est eu velit eu excepteur adipisicing culpa. Laborum cupidatat ullamco eu duis anim reprehenderit proident aute ad consectetur eiusmod.

Help

Privacy and Terms

User Agreement

    View Source


text:
layout: posts
title: Introducing sandboxfs
authors:
  - jmmv
---

**sandboxfs** is a new project to improve the way sandboxing works in Bazel
by making it more efficient and correct.  It's experimental and subject to
change, but it's available now for you to check out! Read on for details.

## Correct builds

As our motto claims, *correctness* is an integral part of Bazel. To achieve
correctness, builds must be *hermetic* and
[*reproducible*](https://reproducible-builds.org/), which means that all
actions invoked by Bazel should be run in a well-defined environment. In
other words: we want actions to run within a sandbox.

Let's consider an example. Think of a `cc_library` target that specifies
`foo.cc` as a source. This `cc_library` rule contains a *compilation
action* that, for this target, turns the `foo.cc` source file into a
`foo.o` object file.  This action will run clang, and it will need to:

*  read `foo.cc`,
*  read all the headers required by `foo.cc`,
*  write `foo.o`, and
*  possibly write some temporary files under `/tmp/`.

To be confident this build is correct, Bazel must ensure that the action
has read-only access to the identified input files and write-only access to
the output and temporary files we expect. Otherwise, Bazel cannot know if
the compiler went astray and read random files from the system, making
future builds inconsistent. One way to achieve these restrictions is by
running each action within a sandbox.

## Current sandboxing techniques

Today, Bazel uses different technologies to implement the sandboxing of
actions. For example, on Linux, Bazel uses PID- and mount-namespaces, and
on macOS, Bazel uses symlinks and the `sandbox(7)` facility. Note that
sandboxing is disabled by default.

However, all these approaches have scalability and performance issues. A
typical build action requires hundreds, if not thousands, of files and
directories to be mapped into the sandbox. Setting these up takes time. On
macOS, this approach is especially problematic because Bazel must create
thousands of symlinks every time it invokes an action, and this is slow.

To make things worse, these approaches also have correctness issues. If
symlinks are used, some tools (e.g. some compilers or linkers) will decide
to extract the real path of such symlinks and work off that path. These
tools may end up "discovering" and consuming undeclared files that are
siblings of the symlink's target.

## Enter sandboxfs

To resolve these issues, we came up with the idea of implementing a FUSE file
system that allows us to *define an arbitrary view of the host's file system
under the mount point*. We call this approach **sandboxfs**.

### sandboxfs is efficient

The view sandboxfs offers is cheaply configured at mount time. With
sandboxfs there is a single system call to configure the mount point versus
thousands of symlink creation and deletion system calls.

The view can also be reconfigured cheaply across different actions,
avoiding the need to remount the FUSE file system on each action, which
would also be costly.

### sandboxfs is correct

The view sandboxfs offers is fully virtual, so sandboxfs can enforce
arbitrary read-only and read/write access permissions on any file or
directory it exposes. Similarly, because the view is virtual, there are no
symlinks involved. sandboxfs exposes real files and directories to the
actions, so actions cannot reach into the original locations.

## Isn't FUSE slow though?

Yes. As you may know, [FUSE is slower than a real file
system](https://www.usenix.org/system/files/conference/fast17/fast17-vangoor.pdf).
This difference is because of the overhead of message-passing between the
kernel and userspace, and because of all the context switches that are
involved in serving a file system operation.

Our hypothesis is that, because builds are generally not I/O bound, the
increased cost of I/O within the sandbox will pay for itself when compared
to the cost of setting up and tearing down the sandbox for each action.  No
more creating thousands of symlinks or defining thousands of mount points.

But for now, that's all that it is: a hypothesis. We haven't finished
stabilizing the sandboxfs code base, which means we haven't profiled nor
tuned it. The integration points with Bazel are still being defined and
implemented, which means it's not yet trivial to test-run Bazel's
sandboxing with sandboxfs.

## But it's here!

Though still in development, there is no reason to keep the code hostage
any longer. We are very happy to announce that, as of today, it's now
available as an open-source project under the Bazel umbrella! See:

> [https://github.com/bazelbuild/sandboxfs/](https://github.com/bazelbuild/sandboxfs/)

Keep in mind that this project is still an experiment and highly subject to
change. In particular, be aware that the command line and the data formats
are most certainly going to mutate (for simplicity if anything). But the
current code is now sufficient to experiment and play with.

As sandboxfs is now an open-source project, please take a look and report
any features you would like to see, any bugs you encounter, and...  if you
decide to delve into the code and address any of the many `TODO`s in it,
feel free to send us your Pull Requests!

Enjoy!

Special credits go to [Pallav Agarwal](https://github.com/pallavagarwal07),
whom we had the pleasure of hosting over a summer internship in the Google
NYC office and who wrote the initial version of sandboxfs.

redpajama_set_name: RedPajamaGithub


text:
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { HolidayGroupSettingsViewPage } from './holiday-group-settings-view';
import { HolidayGroupSettingsService } from '../holiday-group-settings-service';
import { DirectivesModule } from '../../../../directives/directives.module';
@NgModule({
  declarations: [
    HolidayGroupSettingsViewPage,
  ],
  imports: [
    IonicPageModule.forChild(HolidayGroupSettingsViewPage),
    DirectivesModule
  ],
  providers: [HolidayGroupSettingsService]
})
export class HolidayGroupSettingsViewPageModule {}


text:
namespace sketch {

bool cmpByItem(const IntFloatPair& a, const IntFloatPair& b) {
  return a.first < b.first;
}

BitGenerator::BitGenerator() :
    bit_gen_ref_(bit_gen_)
{}

std::vector<uint> FilterOutAboveThreshold(
    const std::vector<IntFloatPair>& candidates, float threshold) {
  std::vector<uint> items;
  for (const auto& [key, value] : candidates) {
    if (value > threshold) {
      items.push_back(key);
    }
  }
  return items;
}

std::pair<std::vector<IntFloatPair>, std::vector<float>> CreateStream(
    int stream_size, int lg_stream_range, double zipf_param) {
  std::vector<IntFloatPair> data;
  uint stream_range = 1 << lg_stream_range;
  std::vector<float> counts(stream_range, 0.0);
  BitGenerator bit_gen;
  absl::BitGenRef& gen = *bit_gen.BitGen();
  absl::zipf_distribution<uint> zipf(stream_range, zipf_param, 1.0);
  ULONG a = absl::uniform_int_distribution<int>(0, stream_range - 1)(gen);
  ULONG b = absl::uniform_int_distribution<int>(0, stream_range - 1)(gen);
  for (int i = 0; i < stream_size; ++i) {
    uint k = Hash(a, b, zipf(gen), stream_range);
    counts.at(k) += 1.0;
    data.emplace_back(k, 1.0);
  }
  return {data, counts};
}

}  // namespace sketch


text:
<?php
/**
 * User: stephen.parker
 * Date: 12/03/2016
 * Time: 19:37
 */

namespace Redis\Service\Factory;

use Zend\Cache\Storage\Adapter\Redis;
use Zend\Cache\Storage\Adapter\RedisOptions;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class RedisFactory implements FactoryInterface
{

    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     *
     * @return Redis
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config = $serviceLocator->get('Config');
        $config = $config['redis'];

        $redisOptions = new RedisOptions();
        $redisOptions->setServer([
            'host'    => $config['host'],
            'port'    => $config['port'],
            'timeout' => 30,
        ]);

        $redisOptions->setLibOptions([
            \Redis::OPT_SERIALIZER => \Redis::SERIALIZER_PHP,
        ]);

        return new Redis($redisOptions);
    }
}


text:
package fr.desaintsteban.liste.envies.enums;

public enum CommentType {
    PRIVATE, // See only by users in the wish list, and hidden by owners
    OWNER, // See by all users in the wish list included by owners
    PUBLIC // See by everone
}


text:
package abs.api.remote;

import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.Properties;

import javax.ws.rs.core.UriBuilder;

import org.eclipse.jetty.server.Server;
import org.glassfish.jersey.jetty.JettyHttpContainerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import abs.api.Context;
import abs.api.Lifecycle;

/**
 * @author Behrooz Nobakht
 */
public class ActorServer implements Lifecycle {

	static {
		LoggingConfiguration.configure();
	}

	private final Logger logger = LoggerFactory.getLogger(getClass());

	private final String host;
	private final Integer port;
	private final URI uri;
	private final ContextApplication application;
	private final Server server;

	public final Context context;

	public ActorServer(Properties properties) throws UnknownHostException {
		host = properties
				.getProperty("host", InetAddress.getLocalHost().getCanonicalHostName());
		port = Integer.valueOf(properties.getProperty("port", "7777"));
		uri = UriBuilder.fromUri("http://" + host).port(port).build();
		application = new ContextApplication(uri);
		ResourceConfig resourceConfig = ResourceConfig.forApplication(application);
		server = JettyHttpContainerFactory.createServer(uri, resourceConfig, true);
		context = application.context;
		logger.info("ABS Actor Context started on: {}", uri);
	}

	@Override
	public void start() throws Exception {
	}

	@Override
	public void stop() throws Exception {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					server.stop();
				} catch (Exception e) {
					logger.error("Failed to stop server on {}: {}", uri, e);
				}
			}
		}).start();
	}

	@Override
	public void initialize() throws Exception {
	}

	public static void main(String[] args) throws UnknownHostException {
		new ActorServer(System.getProperties());
	}

}


text:
package org.ahp.core.messaging;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Anita Onnuvel
 *
 */
public class AhpJmsConsumer implements MessageListener {

    final static Logger LOGGER = LoggerFactory.getLogger( AhpJmsConsumer.class );

    /* (non-Javadoc)
     * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
     */
    @Override
    public void onMessage( Message pMessage ) {
        if ( pMessage instanceof TextMessage ) {
            try {
                LOGGER.debug( "AhpJmsProducer receiving messageID :: " + pMessage.getJMSMessageID() + " TextMessage :: \n" + ( ( TextMessage) pMessage).getText() );
            }
            catch ( JMSException exJms ) {
                throw new RuntimeException( exJms );
            }
        }
        else {
            throw new IllegalArgumentException( "Message must be of type TextMessage" );
        }
    }

}


text:
using System;
using System.Collections.Generic;
namespace CITS.Models
{
    public class ProblemModel : IProblem
    {
        public ProblemModel(string Problem, string Solution, List<String> listOfHints)
        {
            this.Problem = Problem;
            this.Solution = Solution;
            this.Hints = listOfHints;
        }

        public string Problem { get; set; }
        public string Solution { get; set; }
        public List<String> Hints { get; set; }

        public virtual bool IsSolutionCorrect(string candidateSolution)
        {
            throw new NotImplementedException();
        }
    }
}


text:
class DownloadsManager : public QObject
{
    Q_OBJECT
public:
    explicit DownloadsManager(QObject *parent = 0);
    ~DownloadsManager();
    void initManager();
    void changeDownloadDirTo(QString newDir);
    void changeToDir(QString folderName);
    void removeDir(QString dirName);
    void removeFile(QString fileName);
    void stackDownload(QString id, QString fileName);
    void executeDownloads(QString token);
    void upDir();
    QString dir();

signals:
    void downloadDirChanged(QString dir);
    void progress(int);

public slots:
    void fileDownloaded();

private:
    QDir downloadDir;
    QVector<QPair<QString, QString>> downloads;
    int numDownloads, downloadsDone;
    void downloadFile(QString token, QString id, QString fileName);
};

#endif // DOWNLOADSMANAGER_H


text:
<?php

namespace Nfq\WeatherBundle\Location;

class Location {

    private $city;

    public function __construct($city)
    {
        $this->city = $city;
    }

    public function getCityName()
    {
        return $this->city;
    }

}


text:
package com.frameworkset.util;

/**
 *
Description:

 *

 *
Copyright (c) 2020

 * @Date 2022/11/10
 * @author biaoping.yin
 * @version 1.0
 */
public class ValueCastException extends RuntimeException{
	public ValueCastException() {
	}

	public ValueCastException(String message) {
		super(message);
	}

	public ValueCastException(String message, Throwable cause) {
		super(message, cause);
	}

	public ValueCastException(Throwable cause) {
		super(cause);
	}

	public ValueCastException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}
}


text:
import cyclone.locale
import cyclone.web

from snitch import views
from snitch import config
from snitch.storage import DatabaseMixin

class Application(cyclone.web.Application):
    def __init__(self, config_file):
        handlers = [
            (r"/",              views.IndexHandler),
            (r"/lang/(.+)",     views.LangHandler),
            # (r"/dashboard",     views.DashboardHandler),
            # (r"/account",       views.AccountHandler),
            # (r"/signup",        views.SignUpHandler),
            (r"/signin",        views.SignInHandler),
            # (r"/signout",       views.SignOutHandler),
            # (r"/passwd",        views.PasswdHandler),
            (r"/sample/sqlite", views.SampleSQLiteHandler),
        ]

        conf = config.parse_config(config_file)

        # Initialize locales
        if "locale_path" in conf:
            cyclone.locale.load_gettext_translations(conf["locale_path"],
                                                     "snitch")

        # Set up database connections
        # DatabaseMixin.setup(conf)
        DatabaseMixin.sync_db(conf)

        conf["login_url"] = "/signin"
        conf["autoescape"] = None
        cyclone.web.Application.__init__(self, handlers, **conf)


text:
package com.tinkerpop.blueprints.pgm.impls.neo4j;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public class Neo4jTokens {
    public static final String BLUEPRINTS_TYPE = "_blueprints:type";
    public static final String BLUEPRINTS_AUTOKEYS = "_blueprints:autokeys";
    public static final String KEY_SEPARATOR = "!=!";
    public static final String QUERY_HEADER = "%query%";
}


text:
namespace CGAL {

class Show_segments_base: public Qt_widget_styled_layer {
  Q_OBJECT
public:
  typedef Qt_widget_styled_layer::Style Style;

  Show_segments_base(Color c,
                     int linewidth,
                     QObject* parent = 0, const char* name = 0);

  Show_segments_base(Style* style,
                     QString line_color_name,
                     QString line_width_name,
                     QObject* parent = 0, const char* name = 0);

public slots:
  void setColor(QColor);
  void setLineWidth(int);

protected:
  QString color;
  QString width;
}; //end Show_segments_base

} // namespace CGAL

#endif // SHOW_SEGMENTS_BASE_H


text:
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from poscore.models import Alliance, Corporation
from eveapi import EVEAPIConnection

class Command(BaseCommand):
    args = ''
    help = 'Updates alliances from the EVE API'

    def handle(self, *args, **options):
        api = EVEAPIConnection()

        alliance_list = api.eve.AllianceList().alliances
        print 'Updating %d alliances... ' % len(alliance_list)
        with transaction.commit_on_success():
            for alliance in alliance_list:
                allobj, created = Alliance.objects.get_or_create(pk=alliance.allianceID)
                allobj.name = alliance.name
                allobj.save()
                corp_ids = [x.corporationID for x in alliance.memberCorporations]
                Corporation.objects.exclude(pk__in=corp_ids).update(alliance=None)
                Corporation.objects.filter(pk__in=corp_ids).update(alliance=allobj)
        print 'Done'


text:
package com.example.expressiontree;

/**
 * @class NullCommand
 *
 * @brief No-op command.  This plays the role of the "ConcreteCommand"
 *        in the Command pattern.
 */
public class NullCommand extends UserCommand {
    /**
     * Constructor that provides the appropriate @a * TreeOps and the
     * requested format.
     */
    NullCommand(TreeOps context) {
        super.treeOps = context;
    }

    /** Set the desired format. */
    public void execute() {
        /** No-op.*/
    }

    /** Print the valid commands available to users. */
    public void printValidCommands(boolean verboseField) {
        Platform platform = Platform.instance();
    	platform.disableAll(verboseField);
        platform.outputMenu("",
                            "",
                            "");
        platform.outputMenu("1a.",
                            "format",
                            "[post-order]");
        platform.outputMenu("1b.",
                            "set",
                            "[variable=value]");
        platform.outputMenu("2.",
                            "expr",
                            "[expression]");
        platform.outputMenu("3a.",
                            "eval",
                            "[post-order]");
        platform.outputMenu("3b.",
                            "print",
                            "[in-order | pre-order | post-order| level-order]");
        platform.outputMenu("0c.",
                            "quit",
                            "");
        platform.outputMenu("",
                            "",
                            "");
    }
}


text:
package com.netflix.astyanax;

import java.nio.ByteBuffer;
import java.util.Date;
import java.util.UUID;

import com.netflix.astyanax.model.ColumnPath;

/**
 * Abstraction for batching column operations on a single row.
 *
 * @author elandau
 *
 * @param <C>
 */
public interface ColumnListMutation<C> {
    /**
     * Generic call to insert a column value with a custom serializer. User this
     * only when you need a custom serializer otherwise use the overloaded
     * putColumn calls to insert common value types.
     *
     * @param <V>
     * @param columnName
     * @param value
     * @param valueSerializer
     * @param ttl
     * @return
     */
    <V> ColumnListMutation<C> putColumn(C columnName, V value, Serializer<V> valueSerializer, Integer ttl);

    /**
     * @deprecated Super columns are being phased out. Use composite columns
     *             instead.
     */
    <SC> ColumnListMutation<SC> withSuperColumn(ColumnPath<SC> superColumnPath);

    ColumnListMutation<C> putColumn(C columnName, String value, Integer ttl);
    ColumnListMutation<C> putColumn(C columnName, String value);

    ColumnListMutation<C> putColumn(C columnName, byte[] value, Integer ttl);
    ColumnListMutation<C> putColumn(C columnName, byte[] value);

    ColumnListMutation<C> putColumn(C columnName, int value, Integer ttl);
    ColumnListMutation<C> putColumn(C columnName, int value);

    ColumnListMutation<C> putColumn(C columnName, long value, Integer ttl);
    ColumnListMutation<C> putColumn(C columnName, long value);

    ColumnListMutation<C> putColumn(C columnName, boolean value, Integer ttl);
    ColumnListMutation<C> putColumn(C columnName, boolean value);

    ColumnListMutation<C> putColumn(C columnName, ByteBuffer value, Integer ttl);
    ColumnListMutation<C> putColumn(C columnName, ByteBuffer value);

    ColumnListMutation<C> putColumn(C columnName, Date value, Integer ttl);
    ColumnListMutation<C> putColumn(C columnName, Date value);

    ColumnListMutation<C> putColumn(C columnName, float value, Integer ttl);
    ColumnListMutation<C> putColumn(C columnName, float value);

    ColumnListMutation<C> putColumn(C columnName, double value, Integer ttl);
    ColumnListMutation<C> putColumn(C columnName, double value);

    ColumnListMutation<C> putColumn(C columnName, UUID value, Integer ttl);
    ColumnListMutation<C> putColumn(C columnName, UUID value);

    ColumnListMutation<C> putEmptyColumn(C columnName, Integer ttl);
    ColumnListMutation<C> putEmptyColumn(C columnName);

    ColumnListMutation<C> incrementCounterColumn(C columnName, long amount);

    ColumnListMutation<C> deleteColumn(C columnName);

    /**
     * The the timestamp for all subsequent column operation in this ColumnListMutation
     * This timestamp does not affect the current timestamp for the entire MutationBatch
     * @param timestamp
     * @return
     */
    ColumnListMutation<C> setTimestamp(long timestamp);

    /**
     * Deletes all columns at the current column path location. Delete at the
     * root of a row effectively deletes the entire row. This operation also
     * increments the internal timestamp by 1 so new mutations can be added to
     * this row.
     *
     * @return
     */
    ColumnListMutation<C> delete();

    /**
     * Set the default TTL to use when null is specified to a column insert. The
     * default TTL is null, which means no TTL.
     *
     * @param ttl
     * @return
     */
    ColumnListMutation<C> setDefaultTtl(Integer ttl);

}


text:
/**
 * Created by Nicholas Hallahan on 1/2/2015.
 * nhallahan@spatialdev.com
 */

package com.spatialdev.osm.model;

import android.test.InstrumentationTestCase;

import java.io.InputStream;

public class OSMXmlParserTest extends InstrumentationTestCase {

    private InputStream in;
    private OSMDataSet ds;

    public void setUp() throws Exception {
        super.setUp();
        OSMColorConfig osmColorConfig = OSMColorConfig.getDefaultConfig();
        in = getInstrumentation().getTargetContext().getResources().getAssets().open("test/osm/spatialdev_small.osm");
        ds = OSMXmlParser.parseFromInputStream(in, osmColorConfig);
    }

    public void tearDown() throws Exception {
        super.tearDown();
    }

    // should be 83 nodes
    public void testNumberOfNodes() throws Exception {
        assertEquals(83, ds.getNodeCount());
    }

    // should be 10 ways
    public void testNumberOfWays() throws Exception {
        assertEquals(10, ds.getWayCount());
    }

    public void testNumberUnlinkedNodes() throws Exception {
        OSMWay w = ds.getWays().get(Long.valueOf(178540022));
        int count = w.getUnlinkedNodesCount();
        assertEquals(0, count);
    }

    public void testNumberLinkedNodes() throws Exception {
        OSMWay w = ds.getWays().get(Long.valueOf(178540022));
        int count = w.getLinkedNodesCount();
        assertEquals(12, count);
    }

    // should be 0 relations
    public void testNumberOfRelations() throws Exception {
        assertEquals(0, ds.getRelationCount());
    }

    public void testNumberStandaloneNodes() throws Exception {
        assertEquals(1, ds.getStandaloneNodesCount());
    }

    public void testNumberClosedWays() throws Exception {
        assertEquals(7, ds.getClosedWaysCount());
    }

    public void testNumberOpenWays() throws Exception {
        assertEquals(3, ds.getOpenWaysCount());
    }

}


text:
package main

import (
	"flag"

	log "github.com/golang/glog"
	"github.com/youtube/vitess/go/exit"
	"github.com/youtube/vitess/go/vt/binlog"
	"github.com/youtube/vitess/go/vt/dbconfigs"
	"github.com/youtube/vitess/go/vt/mysqlctl"
	"github.com/youtube/vitess/go/vt/servenv"
	"github.com/youtube/vitess/go/vt/tableacl"
	"github.com/youtube/vitess/go/vt/tableacl/simpleacl"
	"github.com/youtube/vitess/go/vt/tabletmanager"
	"github.com/youtube/vitess/go/vt/tabletmanager/actionnode"
	"github.com/youtube/vitess/go/vt/tabletserver"
	"github.com/youtube/vitess/go/vt/topo"
	"github.com/youtube/vitess/go/vt/topo/topoproto"
	"golang.org/x/net/context"

	// import mysql to register mysql connection function
	_ "github.com/youtube/vitess/go/mysql"
	// import memcache to register memcache connection function
	_ "github.com/youtube/vitess/go/memcache"
)

var (
	enableRowcache        = flag.Bool("enable-rowcache", false, "enable rowcacche")
	enforceTableACLConfig = flag.Bool("enforce-tableacl-config", false, "if this flag is true, vttablet will fail to start if a valid tableacl config does not exist")
	tableAclConfig        = flag.String("table-acl-config", "", "path to table access checker config file")
	tabletPath            = flag.String("tablet-path", "", "tablet alias")
	overridesFile         = flag.String("schema-override", "", "schema overrides file")
	lockTimeout           = flag.Duration("lock_timeout", actionnode.DefaultLockTimeout, "lock time for wrangler/topo operations")

	agent *tabletmanager.ActionAgent
)

func init() {
	servenv.RegisterDefaultFlags()
}

func main() {
	defer exit.Recover()

	flags := dbconfigs.AppConfig | dbconfigs.DbaConfig |
		dbconfigs.FilteredConfig | dbconfigs.ReplConfig
	dbconfigs.RegisterFlags(flags)
	mysqlctl.RegisterFlags()
	flag.Parse()
	if len(flag.Args()) > 0 {
		flag.Usage()
		log.Errorf("vttablet doesn't take any positional arguments")
		exit.Return(1)
	}

	servenv.Init()

	if *tabletPath == "" {
		log.Errorf("tabletPath required")
		exit.Return(1)
	}
	tabletAlias, err := topoproto.ParseTabletAlias(*tabletPath)

	if err != nil {
		log.Error(err)
		exit.Return(1)
	}

	mycnf, err := mysqlctl.NewMycnfFromFlags(tabletAlias.Uid)
	if err != nil {
		log.Errorf("mycnf read failed: %v", err)
		exit.Return(1)
	}

	dbcfgs, err := dbconfigs.Init(mycnf.SocketFile, flags)
	if err != nil {
		log.Warning(err)
	}
	dbcfgs.App.EnableRowcache = *enableRowcache

	if *tableAclConfig != "" {
		tableacl.Register("simpleacl", &simpleacl.Factory{})
		tableacl.Init(*tableAclConfig)
	} else if *enforceTableACLConfig {
		log.Error("table acl config has to be specified with table-acl-config flag because enforce-tableacl-config is set.")
		exit.Return(1)
	}

	// creates and registers the query service
	qsc := tabletserver.NewQueryServiceControl()
	tabletserver.InitQueryService(qsc)
	binlog.RegisterUpdateStreamService(mycnf)

	// Create mysqld and register the health reporter (needs to be done
	// before initializing the agent, so the initial health check
	// done by the agent has the right reporter)
	mysqld := mysqlctl.NewMysqld("Dba", "App", mycnf, &dbcfgs.Dba, &dbcfgs.App.ConnParams, &dbcfgs.Repl)
	registerHealthReporter(mysqld)

	// Depends on both query and updateStream.
	gRPCPort := int32(0)
	if servenv.GRPCPort != nil {
		gRPCPort = int32(*servenv.GRPCPort)
	}
	agent, err = tabletmanager.NewActionAgent(context.Background(), mysqld, qsc, tabletAlias, dbcfgs, mycnf, int32(*servenv.Port), gRPCPort, *overridesFile, *lockTimeout)
	if err != nil {
		log.Error(err)
		exit.Return(1)
	}

	servenv.OnRun(func() {
		addStatusParts(qsc)
	})
	servenv.OnTerm(func() {
		qsc.DisallowQueries()
		binlog.DisableUpdateStreamService()
		agent.Stop()
	})
	servenv.OnClose(func() {
		// We will still use the topo server during lameduck period
		// to update our state, so closing it in OnClose()
		topo.CloseServers()
	})
	servenv.RunDefault()
}


text:
apt-get update -y
apt-get upgrade -y

# Install Ansible
apt-get install -y software-properties-common
apt-add-repository -y ppa:ansible/ansible
apt-get -y update
apt-get install -y ansible

# Install Python3
apt-get install python3 -y


text:
using AspNetUpgrade.UpgradeContext;
using Newtonsoft.Json.Linq;

namespace AspNetUpgrade.Actions.ProjectJson
{
    public class UpgradeCompilationOptionsJson : IProjectUpgradeAction
    {

        public void Apply(IProjectUpgradeContext fileUpgradeContext)
        {
            JObject projectJsonObject = fileUpgradeContext.ProjectJsonObject;
            JObject compilationOptions = (JObject)projectJsonObject["compilationOptions"];
            if (compilationOptions != null)
            {
                compilationOptions.Rename("buildOptions");
               // compilationOptions = new JObject();
               // projectJsonObject["compilationOptions"] = compilationOptions;
            }

            var buildOptions = projectJsonObject["buildOptions"];
            if (buildOptions == null)
            {
                buildOptions = new JObject();
                projectJsonObject["buildOptions"] = buildOptions;
            }

            buildOptions["preserveCompilationContext"] = true;

            foreach (var item in ((JObject)projectJsonObject["frameworks"]).Properties())
            {
                var tfmCompilationOptions = ((JObject)item.Value).Property("compilationOptions");
                if (tfmCompilationOptions != null)
                {
                    tfmCompilationOptions.Replace(new JProperty("buildOptions", tfmCompilationOptions.Value));
                }
            }

        }

    }
}


text:
package core

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/trivago/tgo"
	"github.com/trivago/tgo/thealthcheck"
	"sync"
	"time"
)

// SimpleConsumer consumer
//
// This type defines a common baseclass for all consumers. All consumer plugins
// should derive from this class as all required basic functions are already
// implemented in a general way.
//
// Parameters
//
// - Streams: Defines a list of streams a consumer will send to. This parameter
// is mandatory. When using "*" messages will be sent only to the internal "*"
// stream. It will NOT send messages to all streams.
// By default this parameter is set to an empty list.
//
// - ShutdownTimeoutMs: Defines the maximum time in milliseconds a consumer is
// allowed to take to shut down. After this timeout the consumer is always
// considered to have shut down.
// By default this parameter is set to 1000.
//
// - Modulators: Defines a list of modulators to be applied to a message before
// it is sent to the list of streams. If a modulator specifies a stream, the
// message is only sent to that specific stream. A message is saved as original
// after all modulators have been applied.
// By default this parameter is set to an empty list.
//
// - ModulatorRoutines: Defines the number of go routines reserved for
// modulating messages. Setting this parameter to 0 will use as many go routines
// as the specific consumer plugin is using for fetching data. Any other value
// will force the given number fo go routines to be used.
// By default this parameter is set to 0
//
// - ModulatorQueueSize: Defines the size of the channel used to buffer messages
// before they are fetched by the next free modulator go routine. If the
// ModulatorRoutines parameter is set to 0 this parameter is ignored.
// By default this parameter is set to 1024.
type SimpleConsumer struct {
	id              string
	control         chan PluginControl
	runState        *PluginRunState
	routers         []Router       `config:"Streams"`
	shutdownTimeout time.Duration  `config:"ShutdownTimeoutMs" default:"1000" metric:"ms"`
	modulators      ModulatorArray `config:"Modulators"`
	onRoll          func()
	onPrepareStop   func()
	onStop          func()
	enqueueMessage  func(*Message)
	modulatorQueue  MessageQueue
	Logger          logrus.FieldLogger
}

// Configure initializes standard consumer values from a plugin config.
func (cons *SimpleConsumer) Configure(conf PluginConfigReader) {
	cons.id = conf.GetID()
	cons.Logger = conf.GetLogger()
	cons.runState = NewPluginRunState()
	cons.control = make(chan PluginControl, 1)

	numRoutines := conf.GetInt("ModulatorRoutines", 0)
	queueSize := conf.GetInt("ModulatorQueueSize", 1024)

	if numRoutines > 0 {
		cons.Logger.Debugf("Using %d modulator routines", numRoutines)
		cons.modulatorQueue = NewMessageQueue(int(queueSize))
		for i := 0; i < int(numRoutines); i++ {
			go cons.processQueue()
		}
		cons.enqueueMessage = cons.parallelEnqueue
	} else {
		cons.enqueueMessage = cons.directEnqueue
	}

	// Simple health check for the plugin state
	//   Path: "/<plugin_id>/pluginState"
	cons.AddHealthCheckAt("/pluginState", func() (code int, body string) {
		if cons.IsActive() {
			return thealthcheck.StatusOK, fmt.Sprintf("ACTIVE: %s", cons.runState.GetStateString())
		}
		return thealthcheck.StatusServiceUnavailable,
			fmt.Sprintf("NOT_ACTIVE: %s", cons.runState.GetStateString())
	})
}

// GetLogger returns the logger scoped to this plugin
func (cons *SimpleConsumer) GetLogger() logrus.FieldLogger {
	return cons.Logger
}

// AddHealthCheckAt adds a health check at a subpath
// (http://<addr>:<port>/<plugin_id><path>)
func (cons *SimpleConsumer) AddHealthCheckAt(path string, callback thealthcheck.CallbackFunc) {
	thealthcheck.AddEndpoint("/"+cons.GetID()+path, callback)
}

// GetID returns the ID of this consumer
func (cons *SimpleConsumer) GetID() string {
	return cons.id
}

// GetShutdownTimeout returns the duration gollum will wait for this producer
// before canceling the shutdown process.
func (cons *SimpleConsumer) GetShutdownTimeout() time.Duration {
	return cons.shutdownTimeout
}

// Control returns write access to this consumer's control channel.
// See ConsumerControl* constants.
func (cons *SimpleConsumer) Control() chan<- PluginControl {
	return cons.control
}

// GetState returns the state this plugin is currently in
func (cons *SimpleConsumer) GetState() PluginState {
	return cons.runState.GetState()
}

// IsBlocked returns true if GetState() returns waiting
func (cons *SimpleConsumer) IsBlocked() bool {
	return cons.GetState() == PluginStateWaiting
}

// IsActive returns true if GetState() returns initialize, active, waiting or
// prepareStop.
func (cons *SimpleConsumer) IsActive() bool {
	return cons.GetState() <= PluginStatePrepareStop
}

// IsStopping returns true if GetState() returns prepareStop, stopping or dead
func (cons *SimpleConsumer) IsStopping() bool {
	return cons.GetState() >= PluginStatePrepareStop
}

// IsActiveOrStopping is a shortcut for prod.IsActive() || prod.IsStopping()
func (cons *SimpleConsumer) IsActiveOrStopping() bool {
	return cons.IsActive() || cons.IsStopping()
}

// SetRollCallback sets the function to be called upon PluginControlRoll
func (cons *SimpleConsumer) SetRollCallback(onRoll func()) {
	cons.onRoll = onRoll
}

// SetPrepareStopCallback sets the function to be called upon PluginControlPrepareStop
func (cons *SimpleConsumer) SetPrepareStopCallback(onPrepareStop func()) {
	cons.onPrepareStop = onPrepareStop
}

// SetStopCallback sets the function to be called upon PluginControlStop
func (cons *SimpleConsumer) SetStopCallback(onStop func()) {
	cons.onStop = onStop
}

// SetWorkerWaitGroup forwards to Plugin.SetWorkerWaitGroup for this consumer's
// internal plugin state. This method is also called by AddMainWorker.
func (cons *SimpleConsumer) SetWorkerWaitGroup(workers *sync.WaitGroup) {
	cons.runState.SetWorkerWaitGroup(workers)
}

// AddMainWorker adds the first worker to the waitgroup
func (cons *SimpleConsumer) AddMainWorker(workers *sync.WaitGroup) {
	cons.runState.SetWorkerWaitGroup(workers)
	cons.AddWorker()
}

// AddWorker adds an additional worker to the waitgroup. Assumes that either
// MarkAsActive or SetWaitGroup has been called beforehand.
func (cons *SimpleConsumer) AddWorker() {
	cons.runState.AddWorker()
}

// WorkerDone removes an additional worker to the waitgroup.
func (cons *SimpleConsumer) WorkerDone() {
	cons.runState.WorkerDone()
}

// Enqueue creates a new message from a given byte slice and passes it to
// EnqueueMessage. Data is copied to the message.
func (cons *SimpleConsumer) Enqueue(data []byte) {
	cons.EnqueueWithMetadata(data, nil)
}

// EnqueueWithMetadata works like EnqueueWithSequence and allows to set meta data directly
func (cons *SimpleConsumer) EnqueueWithMetadata(data []byte, metaData Metadata) {
	msg := NewMessage(cons, data, metaData, InvalidStreamID)
	cons.enqueueMessage(msg)
}

func (cons *SimpleConsumer) parallelEnqueue(msg *Message) {
	cons.modulatorQueue.Push(msg, 0)
}

func (cons *SimpleConsumer) processQueue() {
loop:
	if msg, hasMore := cons.modulatorQueue.Pop(); hasMore {
		cons.directEnqueue(msg)
		goto loop
	}
}

func (cons *SimpleConsumer) directEnqueue(msg *Message) {
	// Execute configured modulators
	switch cons.modulators.Modulate(msg) {
	case ModulateResultDiscard:
		DiscardMessage(msg, cons.GetID(), "Consumer discarded")
		return

	case ModulateResultFallback:
		if err := RouteOriginal(msg, msg.GetRouter()); err != nil {
			cons.Logger.Error(err)
		}
		return
	}

	CountMessagesEnqueued()
	MessageTrace(msg, cons.GetID(), "Enqueued by consumer")

	// Send message to all routers registered to this consumer
	// Last message will not be cloned.
	numRouters := len(cons.routers)
	lastStreamIdx := numRouters - 1

	for streamIdx := 0; streamIdx < lastStreamIdx; streamIdx++ {
		router := cons.routers[streamIdx]
		msg := msg.Clone()
		msg.SetlStreamIDAsOriginal(router.GetStreamID())

		if err := Route(msg, router); err != nil {
			cons.Logger.Error(err)
		}
	}

	router := cons.routers[lastStreamIdx]
	msg.SetlStreamIDAsOriginal(router.GetStreamID())

	if err := Route(msg, router); err != nil {
		cons.Logger.Error(err)
	}
}

// ControlLoop listens to the control channel and triggers callbacks for these
// messages. Upon stop control message doExit will be set to true.
func (cons *SimpleConsumer) ControlLoop() {
	cons.setState(PluginStateActive)
	defer cons.setState(PluginStateDead)
	defer cons.Logger.Debug("Stopped")

	for {
		command := <-cons.control
		switch command {
		default:
			cons.Logger.Debug("Received untracked command")
			// Do nothing

		case PluginControlStopConsumer:
			cons.Logger.Debug("Preparing for stop")
			cons.setState(PluginStatePrepareStop)

			if cons.onPrepareStop != nil {
				if !tgo.ReturnAfter(cons.shutdownTimeout*5, cons.onPrepareStop) {
					cons.Logger.Error("Timeout during onPrepareStop")
				}
			}

			cons.Logger.Debug("Executing stop command")
			cons.setState(PluginStateStopping)

			if cons.onStop != nil {
				if !tgo.ReturnAfter(cons.shutdownTimeout*5, cons.onStop) {
					cons.Logger.Errorf("Timeout during onStop")
				}
			}

			if cons.modulatorQueue != nil {
				close(cons.modulatorQueue)
			}
			return // ### return ###

		case PluginControlRoll:
			cons.Logger.Debug("Received roll command")
			if cons.onRoll != nil {
				cons.onRoll()
			}
		}
	}
}

// TickerControlLoop is like MessageLoop but executes a given function at
// every given interval tick, too. Note that the interval is not exact. If the
// onTick function takes longer than interval, the next tick will be delayed
// until onTick finishes.
func (cons *SimpleConsumer) TickerControlLoop(interval time.Duration, onTick func()) {
	cons.setState(PluginStateActive)
	go cons.tickerLoop(interval, onTick)
	cons.ControlLoop()
}

func (cons *SimpleConsumer) setState(state PluginState) {
	cons.runState.SetState(state)
}

func (cons *SimpleConsumer) tickerLoop(interval time.Duration, onTimeOut func()) {
	if cons.IsActive() {
		start := time.Now()
		onTimeOut()

		// Delay the next call so that interval is approximated. If the timeout
		// call took longer than expected, the next function will be called
		// immediately.
		nextDelay := interval - time.Since(start)
		if nextDelay < 0 {
			go cons.tickerLoop(interval, onTimeOut)
		} else {
			time.AfterFunc(nextDelay, func() { cons.tickerLoop(interval, onTimeOut) })
		}
	}
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Cyperus monostachyos Link

### Remarks
null


text:
[subject]<?= $creatorName ?> has invited you to use Scalr.[/subject]

Hi <?= $clientFirstname ?>!
<?= $creatorName ?> has invited you to use Scalr.
<?= $creatorName ?> and your colleagues are using Scalr to efficiently manage cloud infrastructure and would like you to join them.

Getting Started:
===============

Log in to Scalr:

You can access Scalr by pointing your browser to: <?= $siteUrl ?>

Your username is your email address: <?= $email ?>

Your password is: <?= $password ?>

Resources and Support
=====================
We suggest exploring and bookmarking the following:

<?php if ($isUrl): ?>
<?= $supportUrl ?> for any support needs
<?php elseif (preg_match('/\.scalr\.com$/', $siteUrl)): ?>
http://support.scalr.com for any support needs
<?php else: ?>
You can find and engage with fellow Scalr users at the Scalr Google
Group. https://groups.google.com/forum/#!forum/scalr-discuss
<?php endif; ?>

Scalr documentation <?= $wikiUrl ?>

Scalr Youtube video tutorials https://www.youtube.com/user/scalrvideos

Thanks for selecting Scalr for your cloud management needs. We're looking forward to working together.
Should you have any other questions, feel free to reach us at sales@scalr.com.
We're here to help.

Cheers,
Team Scalr


text: require 'simple_deploy/misc/attribute_merger'


text:
'use strict';

// Setting up route
angular.module('users').config(['$stateProvider',
    function($stateProvider) {
        // Users state routing
        $stateProvider.
            state('profile', {
                url: '/winter/settings/profile',
                views: {
                    'viewMain': { templateUrl: 'modules/core/views/form.client.view.html' },
                    'viewForm@winter': { templateUrl: 'modules/users/views/settings/edit-profile.client.view.html' }
                }
            }).
            state('password', {
                url: '/winter/settings/password',
                views: {
                    'viewMain': { templateUrl: 'modules/core/views/form.client.view.html' },
                    'viewForm@winter': { templateUrl: 'modules/users/views/settings/change-password.client.view.html' }
                }
            }).
            state('accounts', {
                url: '/winter/settings/accounts',
                views: {
                    'viewMain': { templateUrl: 'modules/core/views/form.client.view.html' },
                    'viewForm@winter': { templateUrl: 'modules/users/views/settings/social-accounts.client.view.html' }
                }
            }).
            state('signup', {
                url: '/winter/signup',
                views: {
                    'viewMain': { templateUrl: 'modules/core/views/form.client.view.html' },
                    'viewForm@winter': { templateUrl: 'modules/users/views/signup.client.view.html' }
                }
            }).
            state('signin', {
                url: '/winter/signin',
                views: {
                    'viewMain': { templateUrl: 'modules/core/views/form.client.view.html' },
                    'viewForm@winter': { templateUrl: 'modules/users/views/signin.client.view.html' }
                }
            });
    }
]);


text:
import { Component, OnDestroy } from '@angular/core';
import {Subscription} from 'rxjs';
import {MspBenefitDataService} from '../../services/msp-benefit-data.service';
import {ActivatedRoute} from '@angular/router';
import {BenefitApplication} from '../../models/benefit-application.model';
import { format } from 'date-fns';

@Component({
  selector: 'msp-confirmation',
  templateUrl: './confirmation.component.html',
  styleUrls: ['./confirmation.component.scss']
})
export class BenefitConfirmationComponent implements OnDestroy {

    lang = require('./i18n');
    confirmationNum: string;
    subscription: Subscription;
    noticeOfAssessment: string;
    isCutOff: boolean;
    isCutOffYear: boolean;

    constructor(private route: ActivatedRoute, public dataService: MspBenefitDataService) {

    }

    ngOnInit(): void {
        this.subscription = this.route.queryParams.subscribe(
            params => {
                this.confirmationNum = params['confirmationNum'];
                this.isCutOff = params['isCutOff'];
                this.isCutOffYear = params['isCutOffyear'];
            }
        );

        if (this.isCutOff) {
            if (this.isCutOffYear === true) {
                this.noticeOfAssessment =  this.lang('./en/index.js').noticeOfAssessmentCutOffyear;

            } else {
                this.noticeOfAssessment = this.lang('./en/index.js').noticeOfAssessmentNonCutOffyear;

            }
        } else if (this.isCutOff === false) {
            this.noticeOfAssessment = this.lang('./en/index.js').noticeOfAssessment;
        }
    }

    ngAfterViewChecked(){
        //this.dataService.removeMspBenefitApp();
    }

    get benefitApp(): BenefitApplication {
        return this.dataService.benefitApp;
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }

    /**
     * Today's date
     * @returns {string}
     */
    get dateStamp(): string {
        return format(new Date(), 'MMMM dd, yyyy');
    }

    // Logic to get the cutoff Date text
   /* get noticeOfAssessment() {

    }*/
}


text:
package com.bouye.gw2.sab.wrappers;

import api.web.gw2.mapping.v2.worlds.World;
import java.util.List;
import java.util.Objects;
import api.web.gw2.mapping.v2.wvw.matches.WvwMatch;

/**
 * Wraps a WvW match.
 * @author Fabrice Bouyé
 */
public final class MatchWrapper {

    private final WvwMatch match;
    private final List<World> worlds;

    public MatchWrapper(final WvwMatch match, final List<World> worlds) {
        Objects.requireNonNull(match);
        Objects.requireNonNull(worlds);
        this.match = match;
        this.worlds = worlds;
    }

    public WvwMatch getMatch() {
        return match;
    }

    public List<World> getWorlds() {
        return worlds;
    }
}


text:
import React from 'react';
import {connect,} from 'react-redux';
import {
    ListView,
    InteractionManager,
} from 'react-native';

import {OnboardingSelectCity as OnboardingSelectCityComponent,} from '../components';
import {fetchCitiesRequest,} from '../actions/cities';
import {selectCity,} from '../actions/onboarding';
import {sortedCities,} from '../selectors/cities';

class OnboardingSelectCityContainer extends React.Component {
  componentDidMount() {
    InteractionManager.runAfterInteractions(() => this.props.fetchCities());
  }

  render() {
    return <OnboardingSelectCityComponent {...this.props} onCitySelect={this._onCitySelect.bind(this)}/>;
  }

  _onCitySelect(id, name) {
    this.props.selectCity(id, name);
  }
}

const citiesDataSource = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2,});

const mapStateToProps = (state) => ({
  isLoading: state.cities.isLoading,
  citiesDataSource: citiesDataSource.cloneWithRows(sortedCities(state)),
});

const mapDispatchToProps = {
  fetchCities: fetchCitiesRequest,
  selectCity: selectCity,
};

export const OnboardingSelectCity = connect(mapStateToProps, mapDispatchToProps)(OnboardingSelectCityContainer);


text:
module Enumerable

  ##
  # Call the given block for each element
  # which is yield by +each+. Return false
  # if one block value is false. Otherwise
  # return true. If no block is given and
  # +self+ is false return false.
  #
  # ISO 15.3.2.2.1
  def all?(&block)
    st = true
    if block
      self.each{|val|
        unless block.call(val)
          st = false
          break
        end
      }
    else
      self.each{|val|
        unless val
          st = false
          break
        end
      }
    end
    st
  end

  ##
  # Call the given block for each element
  # which is yield by +each+. Return true
  # if one block value is true. Otherwise
  # return false. If no block is given and
  # +self+ is true object return true.
  #
  # ISO 15.3.2.2.2
  def any?(&block)
    st = false
    if block
      self.each{|val|
        if block.call(val)
          st = true
          break
        end
      }
    else
      self.each{|val|
        if val
          st = true
          break
        end
      }
    end
    st
  end

  ##
  # Call the given block for each element
  # which is yield by +each+. Append all
  # values of each block together and
  # return this value.
  #
  # ISO 15.3.2.2.3
  def collect(&block)
    ary = []
    self.each{|val|
      ary.push(block.call(val))
    }
    ary
  end

  ##
  # Call the given block for each element
  # which is yield by +each+. Return
  # +ifnone+ if no block value was true.
  # Otherwise return the first block value
  # which had was true.
  #
  # ISO 15.3.2.2.4
  def detect(ifnone=nil, &block)
    ret = ifnone
    self.each{|val|
      if block.call(val)
        ret = val
        break
      end
    }
    ret
  end

  ##
  # Call the given block for each element
  # which is yield by +each+. Pass an
  # index to the block which starts at 0
  # and increase by 1 for each element.
  #
  # ISO 15.3.2.2.5
  def each_with_index(&block)
    i = 0
    self.each{|val|
      block.call(val, i)
      i += 1
    }
    self
  end

  ##
  # Return an array of all elements which
  # are yield by +each+.
  #
  # ISO 15.3.2.2.6
  def entries
    ary = []
    self.each{|val|
      ary.push val
    }
    ary
  end

  ##
  # Alias for find
  #
  # ISO 15.3.2.2.7
  alias find detect

  ##
  # Call the given block for each element
  # which is yield by +each+. Return an array
  # which contains all elements whose block
  # value was true.
  #
  # ISO 15.3.2.2.8
  def find_all(&block)
    ary = []
    self.each{|val|
      ary.push(val) if block.call(val)
    }
    ary
  end

  ##
  # Call the given block for each element
  # which is yield by +each+ and which return
  # value was true when invoking === with
  # +pattern+. Return an array with all
  # elements or the respective block values.
  #
  # ISO 15.3.2.2.9
  def grep(pattern, &block)
    ary = []
    self.each{|val|
      if pattern === val
        ary.push((block)? block.call(val): val)
      end
    }
    ary
  end

  ##
  # Return true if at least one element which
  # is yield by +each+ returns a true value
  # by invoking == with +obj+. Otherwise return
  # false.
  #
  # ISO 15.3.2.2.10
  def include?(obj)
    st = false
    self.each{|val|
      if val == obj
        st = true
        break
      end
    }
    st
  end

  ##
  # Call the given block for each element
  # which is yield by +each+. Return value
  # is the sum of all block values. Pass
  # to each block the current sum and the
  # current element.
  #
  # ISO 15.3.2.2.11
  def inject(*args, &block)
    raise ArgumentError, "too many arguments" if args.size > 2
    flag = true  # 1st element?
    result = nil
    self.each{|val|
      if flag
        # 1st element
        result = (args.empty?)? val: block.call(args[0], val)
        flag = false
      else
        result = block.call(result, val)
      end
    }
    result
  end

  ##
  # Alias for collect
  #
  # ISO 15.3.2.2.12
  alias map collect

  ##
  # Return the maximum value of all elements
  # yield by +each+. If no block is given <=>
  # will be invoked to define this value. If
  # a block is given it will be used instead.
  #
  # ISO 15.3.2.2.13
  def max(&block)
    flag = true  # 1st element?
    result = nil
    self.each{|val|
      if flag
        # 1st element
        result = val
        flag = false
      else
        if block
          result = val if block.call(val, result) > 0
        else
          result = val if (val <=> result) > 0
        end
      end
    }
    result
  end

  ##
  # Return the minimum value of all elements
  # yield by +each+. If no block is given <=>
  # will be invoked to define this value. If
  # a block is given it will be used instead.
  #
  # ISO 15.3.2.2.14
  def min(&block)
    flag = true  # 1st element?
    result = nil
    self.each{|val|
      if flag
        # 1st element
        result = val
        flag = false
      else
        if block
          result = val if block.call(val, result) < 0
        else
          result = val if (val <=> result) < 0
        end
      end
    }
    result
  end

  ##
  # Alias for include?
  #
  # ISO 15.3.2.2.15
  alias member? include?

  ##
  # Call the given block for each element
  # which is yield by +each+. Return an
  # array which contains two arrays. The
  # first array contains all elements
  # whose block value was true. The second
  # array contains all elements whose
  # block value was false.
  #
  # ISO 15.3.2.2.16
  def partition(&block)
    ary_T = []
    ary_F = []
    self.each{|val|
      if block.call(val)
        ary_T.push(val)
      else
        ary_F.push(val)
      end
    }
    [ary_T, ary_F]
  end

  ##
  # Call the given block for each element
  # which is yield by +each+. Return an
  # array which contains only the elements
  # whose block value was false.
  #
  # ISO 15.3.2.2.17
  def reject(&block)
    ary = []
    self.each{|val|
      ary.push(val) unless block.call(val)
    }
    ary
  end

  ##
  # Alias for find_all.
  #
  # ISO 15.3.2.2.18
  alias select find_all

  ##
  # TODO
  # Does this OK? Please test it.
  def __sort_sub__(sorted, work, src_ary, head, tail, &block)
    if head == tail
      sorted[head] = work[head] if src_ary == 1
      return
    end

    # on current step, which is a src ary?
    if src_ary == 0
      src, dst = sorted, work
    else
      src, dst = work, sorted
    end

    key = src[head]    # key value for dividing values
    i, j = head, tail  # position to store on the dst ary

    (head + 1).upto(tail){|idx|
      if ((block)? block.call(src[idx], key): (src[idx] <=> key)) > 0
        # larger than key
        dst[j] = src[idx]
        j -= 1
      else
        dst[i] = src[idx]
        i += 1
      end
    }

    sorted[i] = key

    # sort each sub-array
    src_ary = (src_ary + 1) % 2  # exchange a src ary
    __sort_sub__(sorted, work, src_ary, head, i - 1, &block) if i > head
    __sort_sub__(sorted, work, src_ary, i + 1, tail, &block) if i < tail
  end
#  private :__sort_sub__

  ##
  # Return a sorted array of all elements
  # which are yield by +each+. If no block
  # is given <=> will be invoked on each
  # element to define the order. Otherwise
  # the given block will be used for
  # sorting.
  #
  # ISO 15.3.2.2.19
  def sort(&block)
    ary = []
    self.each{|val| ary.push(val)}
    unless ary.empty?
      __sort_sub__(ary, ::Array.new(ary.size), 0, 0, ary.size - 1, &block)
    end
    ary
  end

  ##
  # Alias for entries.
  #
  # ISO 15.3.2.2.20
  alias to_a entries
end


text:
package org.apache.flex.compiler.internal.fxg.dom.transforms;

import static org.apache.flex.compiler.fxg.FXGConstants.*;

import java.util.Collection;

import org.apache.flex.compiler.internal.fxg.dom.DOMParserHelper;
import org.apache.flex.compiler.problems.ICompilerProblem;

public class MatrixNode extends AbstractTransformNode
{
    //--------------------------------------------------------------------------
    //
    // Attributes
    //
    //--------------------------------------------------------------------------

    public double a = 1.0;
    public double b = 0.0;
    public double c = 0.0;
    public double d = 1.0;
    public double tx = 0.0;
    public double ty = 0.0;

    //--------------------------------------------------------------------------
    //
    // IFXGNode Implementation
    //
    //--------------------------------------------------------------------------

    /**
     * @return The unqualified name of a Matrix node, without tag markup.
     */
    @Override
    public String getNodeName()
    {
        return FXG_MATRIX_ELEMENT;
    }

    @Override
    public void setAttribute(String name, String value, Collection<ICompilerProblem> problems)
    {
        if (FXG_A_ATTRIBUTE.equals(name))
            a = DOMParserHelper.parseDouble(this, value, name, a, problems);
        else if (FXG_B_ATTRIBUTE.equals(name))
            b = DOMParserHelper.parseDouble(this, value, name, b, problems);
        else if (FXG_C_ATTRIBUTE.equals(name))
            c = DOMParserHelper.parseDouble(this, value, name, c, problems);
        else if (FXG_D_ATTRIBUTE.equals(name))
            d = DOMParserHelper.parseDouble(this, value, name, d, problems);
        else if (FXG_TX_ATTRIBUTE.equals(name))
            tx = DOMParserHelper.parseDouble(this, value, name, tx, problems);
        else if (FXG_TY_ATTRIBUTE.equals(name))
            ty = DOMParserHelper.parseDouble(this, value, name, ty, problems);
    }

}


text:
namespace app {
namespace Uno {
namespace Platform {

struct TextInputEventArgs;

struct TextInputEventArgs__uType : ::app::Uno::EventArgs__uType
{
};

TextInputEventArgs__uType* TextInputEventArgs__typeof();

void TextInputEventArgs___ObjInit_1(TextInputEventArgs* __this, ::uString* text, int modifiers);
bool TextInputEventArgs__get_Handled(TextInputEventArgs* __this);
bool TextInputEventArgs__get_IsAltKeyPressed(TextInputEventArgs* __this);
bool TextInputEventArgs__get_IsControlKeyPressed(TextInputEventArgs* __this);
bool TextInputEventArgs__get_IsMetaKeyPressed(TextInputEventArgs* __this);
bool TextInputEventArgs__get_IsShiftKeyPressed(TextInputEventArgs* __this);
int TextInputEventArgs__get_Modifiers(TextInputEventArgs* __this);
::uString* TextInputEventArgs__get_Text(TextInputEventArgs* __this);
TextInputEventArgs* TextInputEventArgs__New_2(::uStatic* __this, ::uString* text, int modifiers);
void TextInputEventArgs__set_Handled(TextInputEventArgs* __this, bool value);
void TextInputEventArgs__set_Modifiers(TextInputEventArgs* __this, int value);
void TextInputEventArgs__set_Text(TextInputEventArgs* __this, ::uString* value);

struct TextInputEventArgs : ::app::Uno::EventArgs
{
    bool _Handled;
    ::uStrong< ::uString*> _Text;
    int _Modifiers;

    void _ObjInit_1(::uString* text, int modifiers) { TextInputEventArgs___ObjInit_1(this, text, modifiers); }
    bool Handled() { return TextInputEventArgs__get_Handled(this); }
    bool IsAltKeyPressed() { return TextInputEventArgs__get_IsAltKeyPressed(this); }
    bool IsControlKeyPressed() { return TextInputEventArgs__get_IsControlKeyPressed(this); }
    bool IsMetaKeyPressed() { return TextInputEventArgs__get_IsMetaKeyPressed(this); }
    bool IsShiftKeyPressed() { return TextInputEventArgs__get_IsShiftKeyPressed(this); }
    int Modifiers() { return TextInputEventArgs__get_Modifiers(this); }
    ::uString* Text() { return TextInputEventArgs__get_Text(this); }
    void Handled(bool value) { TextInputEventArgs__set_Handled(this, value); }
    void Modifiers(int value) { TextInputEventArgs__set_Modifiers(this, value); }
    void Text(::uString* value) { TextInputEventArgs__set_Text(this, value); }
};

}}}

#endif


text:
class LzopStreamReader : public StreamReader
{
public:

	// Constructors / Destructor
	//
	LzopStreamReader(const void* base, size_t length);
	virtual ~LzopStreamReader();

	// StreamReader Implementation
	//
	virtual size_t	Read(void* buffer, size_t length);
	virtual void	Seek(size_t position);
	virtual size_t	getPosition(void) { return m_position; }

private:

	LzopStreamReader(const LzopStreamReader&)=delete;
	LzopStreamReader& operator=(const LzopStreamReader&)=delete;

	//-------------------------------------------------------------------------
	// Private Member Functions

	// ReadNextBlock
	//
	// Reads the next block of compressed data from the input stream
	uint32_t ReadNextBlock(void);

	//-------------------------------------------------------------------------
	// Member Variables

	size_t					m_position = 0;		// Current stream position
	uint8_t*				m_block;			// Decompressed block data
	size_t					m_blocklen;			// Block data buffer size
	uint8_t*				m_blockcurrent;		// Pointer into block data
	size_t					m_blockremain;		// Remaining block data
	uint32_t				m_lzoflags;			// LZOP header flags
	intptr_t				m_lzopos;			// Position in LZO stream
	size_t					m_lzoremain;		// Remaining LZOP data
};

//-----------------------------------------------------------------------------

#pragma warning(pop)

#endif	// __LZOPSTREAMREADER_H_


text:
package net.uchoice.exf.core.runtime.resolver;

import java.util.ArrayList;
import java.util.List;

import net.uchoice.exf.model.variable.Variable;
import net.uchoice.exf.model.variable.VariableAdvisor;
import net.uchoice.exf.model.variable.VariableResolver;

public class DefaultVariableResolver implements VariableResolver {

	protected List<VariableAdvisor> advisors = new ArrayList<>();

	@Override
	public void addAdvisor(VariableAdvisor advisor) {
		if (null != advisor) {
			advisors.add(advisor);
		}
	}

	@Override
	public Object resolve(Variable variable) {
		if (null == variable) {
			return null;
		}
		for (VariableAdvisor advisor : advisors) {
			if (advisor.accept(variable)) {
				return advisor.evaluate(variable);
			}
		}
		return null;
	}

}


text:
#ifdef HAVE_CONFIG_H
#include "../../ext_config.h"
#endif

#include <php.h>
#include "../../php_ext.h"
#include "../../ext.h"

#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>

#include "kernel/main.h"
#include "kernel/object.h"
#include "kernel/memory.h"

ZEPHIR_INIT_CLASS(Test_Properties_ProtectedProperties) {

	ZEPHIR_REGISTER_CLASS(Test\\Properties, ProtectedProperties, test, properties_protectedproperties, test_properties_protectedproperties_method_entry, 0);

	/**
	 * This is a protected property with no initial value
	 */
	zend_declare_property_null(test_properties_protectedproperties_ce, SL("someNull"), ZEND_ACC_PROTECTED TSRMLS_CC);

	/**
	 * This is a protected property with initial null value
	 */
	zend_declare_property_null(test_properties_protectedproperties_ce, SL("someNullInitial"), ZEND_ACC_PROTECTED TSRMLS_CC);

	/**
	 * This is a protected property with initial boolean false
	 */
	zend_declare_property_bool(test_properties_protectedproperties_ce, SL("someFalse"), 0, ZEND_ACC_PROTECTED TSRMLS_CC);

	/**
	 * This is a protected property with initial boolean true
	 */
	zend_declare_property_bool(test_properties_protectedproperties_ce, SL("someTrue"), 1, ZEND_ACC_PROTECTED TSRMLS_CC);

	/**
	 * This is a protected property with an initial integer value
	 */
	zend_declare_property_long(test_properties_protectedproperties_ce, SL("someInteger"), 10, ZEND_ACC_PROTECTED TSRMLS_CC);

	/**
	 * This is a protected property with an initial double value
	 */
	zend_declare_property_double(test_properties_protectedproperties_ce, SL("someDouble"), 10.25, ZEND_ACC_PROTECTED TSRMLS_CC);

	/**
	 * This is a protected property with an initial string value
	 */
	zend_declare_property_string(test_properties_protectedproperties_ce, SL("someString"), "test", ZEND_ACC_PROTECTED TSRMLS_CC);

	zend_declare_property_null(test_properties_protectedproperties_ce, SL("someVar"), ZEND_ACC_PROTECTED TSRMLS_CC);

	return SUCCESS;

}

PHP_METHOD(Test_Properties_ProtectedProperties, setSomeVar) {

	zval *someVar, someVar_sub;
	ZEPHIR_INIT_THIS();

	ZVAL_UNDEF(&someVar_sub);

	zephir_fetch_params(0, 1, 0, &someVar);

	zephir_update_property_zval(this_ptr, SL("someVar"), someVar);

}

PHP_METHOD(Test_Properties_ProtectedProperties, getSomeVar) {

	ZEPHIR_INIT_THIS();

	RETURN_MEMBER(this_ptr, "someVar");

}

PHP_METHOD(Test_Properties_ProtectedProperties, getSomeNull) {

	ZEPHIR_INIT_THIS();

	RETURN_MEMBER(this_ptr, "someNull");

}

PHP_METHOD(Test_Properties_ProtectedProperties, setSomeNull) {

	zval *param, param_sub;
	ZEPHIR_INIT_THIS();

	ZVAL_UNDEF(&param_sub);

	zephir_fetch_params(0, 1, 0, &param);

	zephir_update_property_zval(this_ptr, SL("someNull"), param);

}

PHP_METHOD(Test_Properties_ProtectedProperties, getSomeNullInitial) {

	ZEPHIR_INIT_THIS();

	RETURN_MEMBER(this_ptr, "someNullInitial");

}

PHP_METHOD(Test_Properties_ProtectedProperties, getSomeFalse) {

	ZEPHIR_INIT_THIS();

	RETURN_MEMBER(this_ptr, "someFalse");

}

PHP_METHOD(Test_Properties_ProtectedProperties, getSomeTrue) {

	ZEPHIR_INIT_THIS();

	RETURN_MEMBER(this_ptr, "someTrue");

}

PHP_METHOD(Test_Properties_ProtectedProperties, getSomeInteger) {

	ZEPHIR_INIT_THIS();

	RETURN_MEMBER(this_ptr, "someInteger");

}

PHP_METHOD(Test_Properties_ProtectedProperties, getSomeDouble) {

	ZEPHIR_INIT_THIS();

	RETURN_MEMBER(this_ptr, "someDouble");

}

PHP_METHOD(Test_Properties_ProtectedProperties, getSomeString) {

	ZEPHIR_INIT_THIS();

	RETURN_MEMBER(this_ptr, "someString");

}


text:
var listXf = require('./helpers/listXf');

var R = require('..');
var eq = require('./shared/eq');

describe('any', function() {
  var odd = function(n) {return n % 2 === 1;};
  var T = function() {return true;};
  var intoArray = R.into([]);

  it('returns true if any element satisfies the predicate', function() {
    eq(R.any(odd, [2, 4, 6, 8, 10, 11, 12]), true);
  });

  it('returns false if all elements fails to satisfy the predicate', function() {
    eq(R.any(odd, [2, 4, 6, 8, 10, 12]), false);
  });

  it('returns true into array if any element satisfies the predicate', function() {
    eq(intoArray(R.any(odd), [2, 4, 6, 8, 10, 11, 12]), [true]);
  });

  it('returns false if all elements fails to satisfy the predicate', function() {
    eq(intoArray(R.any(odd), [2, 4, 6, 8, 10, 12]), [false]);
  });

  it('works with more complex objects', function() {
    var people = [{first: 'Paul', last: 'Grenier'}, {first:'Mike', last: 'Hurley'}, {first: 'Will', last: 'Klein'}];
    var alliterative = function(person) {return person.first.charAt(0) === person.last.charAt(0);};
    eq(R.any(alliterative, people), false);
    people.push({first: 'Scott', last: 'Sauyet'});
    eq(R.any(alliterative, people), true);
  });

  it('can use a configurable function', function() {
    var teens = [{name: 'Alice', age: 14}, {name: 'Betty', age: 18}, {name: 'Cindy', age: 17}];
    var atLeast = function(age) {return function(person) {return person.age >= age;};};
    eq(R.any(atLeast(16), teens), true);
    eq(R.any(atLeast(21), teens), false);
  });

  it('returns false for an empty list', function() {
    eq(R.any(T, []), false);
  });

  it('returns false into array for an empty list', function() {
    eq(intoArray(R.any(T), []), [false]);
  });

  it('dispatches when given a transformer in list position', function() {
    eq(R.any(odd, listXf), {
      any: false,
      f: odd,
      xf: listXf
    });
  });

});


text:
package org.shadowice.flocke.andotp.Activities;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import com.google.android.material.textfield.TextInputLayout;

import androidx.appcompat.widget.Toolbar;

import android.text.Editable;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewStub;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import org.shadowice.flocke.andotp.R;
import org.shadowice.flocke.andotp.Tasks.AuthenticationTask;
import org.shadowice.flocke.andotp.Tasks.AuthenticationTask.Result;
import org.shadowice.flocke.andotp.Utilities.Constants;
import org.shadowice.flocke.andotp.Utilities.EditorActionHelper;
import org.shadowice.flocke.andotp.View.AutoFillable.AutoFillableTextInputEditText;

import static org.shadowice.flocke.andotp.Utilities.Constants.AuthMethod;

public class AuthenticateActivity extends BackgroundTaskActivity<AuthenticationTask.Result>
        implements EditText.OnEditorActionListener, View.OnClickListener {
    private final AutoFillableTextInputEditText.AutoFillTextListener autoFillTextListener = text -> startAuthTask(text.toString());

    private AuthMethod authMethod;
    private String newEncryption = "";
    private String existingAuthCredentials;
    private boolean isAuthUpgrade = false;

    private TextInputLayout passwordLayout;
    AutoFillableTextInputEditText passwordInput;
    private Button unlockButton;
    private ProgressBar unlockProgress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (! settings.getScreenshotsEnabled())
            getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);

        authMethod = settings.getAuthMethod();
        newEncryption = getIntent().getStringExtra(Constants.EXTRA_AUTH_NEW_ENCRYPTION);
        existingAuthCredentials = settings.getAuthCredentials();
        if (existingAuthCredentials.isEmpty()) {
            existingAuthCredentials = settings.getOldCredentials(authMethod);
            isAuthUpgrade = true;
        }

        // If our password is still empty at this point, we can't do anything.
        if (existingAuthCredentials.isEmpty()) {
            int missingPwResId = (authMethod == AuthMethod.PASSWORD)
                    ? R.string.auth_toast_password_missing : R.string.auth_toast_pin_missing;
            Toast.makeText(this, missingPwResId, Toast.LENGTH_LONG).show();
            finishWithResult(true, null);
        }
        // If we're not using password or pin for auth method, we have nothing to authenticate here.
        if (authMethod != AuthMethod.PASSWORD && authMethod != AuthMethod.PIN) {
            finishWithResult(true, null);
        }

        setTitle(R.string.auth_activity_title);
        setContentView(R.layout.activity_container);
        initToolbar();
        initPasswordViews();

        setBroadcastCallback(() -> {
                if (settings.getRelockOnScreenOff()) {
                    cancelBackgroundTask();
                }
            });

        getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    private void initToolbar() {
        Toolbar toolbar = findViewById(R.id.container_toolbar);
        toolbar.setNavigationIcon(null);
        setSupportActionBar(toolbar);
    }

    private void initPasswordViews() {
        ViewStub stub = findViewById(R.id.container_stub);
        stub.setLayoutResource(R.layout.content_authenticate);
        View v = stub.inflate();

        initPasswordLabelView(v);
        initPasswordLayoutView(v);
        initPasswordInputView(v);
        initUnlockViews(v);
    }

    private void initPasswordLabelView(View v) {
        int labelMsg = getIntent().getIntExtra(Constants.EXTRA_AUTH_MESSAGE, R.string.auth_msg_authenticate);
        TextView passwordLabel = v.findViewById(R.id.passwordLabel);
        passwordLabel.setText(labelMsg);
    }

    private void initPasswordLayoutView(View v) {
        passwordLayout = v.findViewById(R.id.passwordLayout);
        int hintResId = (authMethod == AuthMethod.PASSWORD) ? R.string.auth_hint_password : R.string.auth_hint_pin;
        passwordLayout.setHint(getString(hintResId));
        if (settings.getBlockAccessibility()) {
            passwordLayout.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && settings.getBlockAutofill()) {
            passwordLayout.setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS);
        }
    }

    private void initPasswordInputView(View v) {
        passwordInput = v.findViewById(R.id.passwordEdit);
        int inputType = (authMethod == AuthMethod.PASSWORD)
                ? (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD)
                : (InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
        passwordInput.setInputType(inputType);
        passwordInput.setTransformationMethod(new PasswordTransformationMethod());
        passwordInput.setOnEditorActionListener(this);
    }

    private void initUnlockViews(View v) {
        unlockButton = v.findViewById(R.id.buttonUnlock);
        unlockButton.setOnClickListener(this);
        unlockProgress = v.findViewById(R.id.unlockProgress);
    }

    @Override
    protected boolean cancelTaskOnScreenOff() {
        return true;
    }

    @Override
    protected void onReturnToCanceledTask() {
        passwordInput.setText("");
        passwordInput.requestFocus();
        InputMethodManager keyboard = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        keyboard.showSoftInput(passwordInput, 0);
    }

    @Override
    protected void setupUiForTaskState(boolean isTaskRunning) {
        passwordLayout.setEnabled(!isTaskRunning);
        passwordInput.setEnabled(!isTaskRunning);
        unlockButton.setEnabled(!isTaskRunning);
        unlockButton.setVisibility(isTaskRunning? View.INVISIBLE : View.VISIBLE);
        unlockProgress.setVisibility(isTaskRunning ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onClick(View view) {
        Editable text = passwordInput.getText();
        startAuthTask(text != null ? text.toString() : "");
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (EditorActionHelper.isActionDoneOrKeyboardEnter(actionId, event)) {
            startAuthTask(v.getText().toString());
            return true;
        }
        return false;
    }

    private void startAuthTask(String plainPassword) {
        AuthenticationTask task = new AuthenticationTask(this, isAuthUpgrade, existingAuthCredentials, plainPassword);
        startBackgroundTask(task);
    }

    @Override
    void onTaskResult(Result result) {
        if (result.authUpgradeFailed) {
            Toast.makeText(this, R.string.settings_toast_auth_upgrade_failed, Toast.LENGTH_LONG).show();
        }
        finishWithResult(result.encryptionKey != null, result.encryptionKey);
    }

    private void finishWithResult(boolean success, byte[] encryptionKey) {
        Intent data = new Intent();
        if (newEncryption != null && !newEncryption.isEmpty())
            data.putExtra(Constants.EXTRA_AUTH_NEW_ENCRYPTION, newEncryption);
        if (encryptionKey != null)
            data.putExtra(Constants.EXTRA_AUTH_PASSWORD_KEY, encryptionKey);
        if (success)
            setResult(RESULT_OK, data);
        finish();
    }

    @Override
    public void onBackPressed() {
        finishWithResult(false, null);
        super.onBackPressed();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (settings.getAutoUnlockAfterAutofill()) {
            passwordInput.setAutoFillTextListener(autoFillTextListener);
        }
    }

    @Override
    protected void onStop() {
        passwordInput.setAutoFillTextListener(null);
        super.onStop();
    }

    @Override
    protected boolean shouldDestroyOnScreenOff() {
        return false;
    }
}


text:
namespace logx
{
	extern const int debug;
	extern const int trace;
	extern const int record;
	extern const int warning;
	extern const int error;
	extern const int fatal;

	class logger;

	class alloctor
	{
	public:
		virtual void *	take(size_t size) = 0;
		virtual void	drop(void *ptr, size_t size) = 0;
	};

	class sink
	{
		friend class logger;
	public:
		sink();
		virtual ~sink();
		virtual void start(int level);
		virtual void write(const char *text, size_t len) = 0;
		virtual void flush();

	public:
		void release();

	private:
		sink *prev;
		sink *next;
		logger *log;
		void *ptr;
		size_t len;
	};

	class uninheritable
	{
		friend class logger;

	private:
		uninheritable();
	};

	class logger : private virtual uninheritable
	{
	private:
		class stream
		{
		public:
			stream(logger &log);
			stream * write(char c);
			stream * write(const char *s);
			stream * write(const char *s, size_t l);

		public:
			logger &_log;
			char buffer[4096];
			int pos;
			stream *next;
		};

	public:
		class printer
		{
			friend class logger;
		private:
			printer(logger &log, const char *name, int level);
			static void nowtime(time_t &sec, int &usec);

		public:
			template <typename... Args>
			void operator () (Args&&... args)
			{
				if (_log._level <= _level && _log._sinks != nullptr)
				{
					time_t sec;
					int usec;
					nowtime(sec, usec);
					stream *init = _log.prepare(_name, _size, _level, sec, usec);
					stream *os = init;
					while (os->next != nullptr)
					{
						os = os->next;
					}
					_log.build(os, args...);
					_log.flush(init, _name, _size, _level, sec, usec);
				}
			}

			template <typename... Args>
			void operator () (bool condition, Args&&... args)
			{
				if (condition)
					return *this(args...);
			}

		private:
			logger &_log;
			const char *_name;
			size_t _size;
			int _level;
		};

		friend class printer;
		friend class sink;
		friend class stream;

	public:
		printer debug;
		printer trace;
		printer record;
		printer warning;
		printer error;
		printer fatal;

	public:
		logger();
		logger(alloctor &m);
		logger(logger &&lhs);
		~logger();
		logger(const logger &) = delete;
		logger & operator = (const logger &) = delete;

	private:
		template <typename T>
		class params;

		template <typename T, typename... Args>
		void build(stream *os, T t, Args&&... args)
		{
			build(params<T>::build(os, t), args...);
		}

		template <typename T>
		void build(stream *os, T t)
		{
			params<T>::build(os, t);
		}

		static void writefmt(logger::stream *os, const char *fmt, const char *name, size_t size, int level, time_t sec, int usec);
		stream * newstream();
		stream * prepare(const char *name, size_t size, int level, time_t sec, int usec);
		void flush(stream *init, const char *name, size_t size, int level, time_t sec, int usec);

		void work(int level, stream *init);

	public:
		logger & level(printer &print);
		logger & level(int level);
		logger & prefix(const char *fmt);
		logger & suffix(const char *fmt);

		template <typename T, typename... Args>
		T * create(Args&&... args)
		{
			T *t = (T *)_alloc.take(sizeof(T));
			new (t)T(args...);
			t->log = this;
			t->ptr = t;
			t->len = sizeof(T);
			add(*t);
			return t;
		}

	private:
		void add(sink &s);

	private:
		alloctor &_alloc;
		int _level;
		char *_prefmt;
		size_t _prelen;
		char *_suffmt;
		size_t _suflen;

		sink *_sinks;
		std::mutex _sinks_mtx;
		stream *_stream;
		std::mutex _stream_mtx;
	};

	template <>
	class logger::params<int>
	{
	public:
		static stream * build(stream *os, int i);
	};
	template <>
	class logger::params<unsigned int>
	{
	public:
		static stream * build(stream *os, unsigned int u);
	};
	template <>
	class logger::params<const char *>
	{
	public:
		static stream * build(stream *os, const char *s);
	};
}

#endif


text: An implementation of JSON Schema for Nim


text:
 section.range-slider {
    position: relative;
    width: 200px;
    height: 35px;
    text-align: center;
}

section.range-slider input {
    pointer-events: none;
    position: absolute;
    overflow: hidden;
    left: 0;
    top: 15px;
    width: 200px;
    outline: none;
    height: 18px;
    margin: 0;
    padding: 0;
}

section.range-slider input::-webkit-slider-thumb {
    pointer-events: all;
    position: relative;
    z-index: 1;
    outline: 0;
}

section.range-slider input::-moz-range-thumb {
    pointer-events: all;
    position: relative;
    z-index: 10;
    -moz-appearance: none;
    width: 9px;
}

section.range-slider input::-moz-range-track {
    position: relative;
    z-index: -1;
    background-color: rgba(0, 0, 0, 1);
    border: 0;
}
section.range-slider input:last-of-type::-moz-range-track {
    -moz-appearance: none;
    background: none transparent;
    border: 0;
}
  section.range-slider input[type=range]::-moz-focus-outer {
  border: 0;
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Will Sweet - Streaming to a Theater Near You</title>
  <link rel="shortcut icon" href="/assets/images/sweet.png">
  <link rel="stylesheet" href="/assets/css/style.css">
  <link rel="alternate" type="application/rss+xml" title="My Blog" href="/feed.xml">
  <link rel="stylesheet" href="/assets/css/highlight.css">

         ← Home

        About

Streaming to a Theater Near You

Expanding the on-demand business model

January 31, 2016

I recently read Fortune's "How to Make a Profit in the New Hollywood," which interestingly explored several trends in the movie industry, including the entrance of streaming services such as Netflix and Amazon into the world of original feature film content.⋅ ⋅ ⋅

Netflix and Amazon are no strangers to original content. Their ballooning subscriber numbers and collective Emmy and Golden Globe nomination tallies over the last several years can attest to that fact. But up to this point, their expertise has been in the realm of television — an industry structured vastly different from that of feature films, especially in terms of distribution.

Keeping this in mind, one statement in the Fortune article really stuck out to me. In the closing paragraph of the piece, Fortune mentions that "simultaneous theater and home release has long been a no-no in Hollywood, with theater chains denouncing it and studios fearing it will cannibalize revenue," adding that, "neither Netflix nor Amazon has figured out how to make the new economics work."

To put this in perspective, Netflix's first attempt to crack the feature film distribution model was to simultaneously release its first film, Beasts of No Nation, both online and in theaters. Ultimately, the film showed in 31 theaters and brought in less $91,000 in ticket sales — enough to make it eligible for Oscar nominations (though it didn't get any) but not enough to make it a very compelling business model moving forward.

I'm not saying that I know all of Netflix's motivations behind employing this strategy, but I believe that there is a better way to structure a theater distribution model for streaming services moving forward. One that could benefit both the streaming services (through exposure to new subscribers and awards) and the theaters (through less burdened revenue generation).

The solution: give theaters the content for free.

This is a radically different approach from the way movies are currently distributed. In the traditional studio distribution model, studios work with distributors to lease their movies to theaters in order to recoup the cost of the film's production. But streaming services don't have to follow this model because they cover production costs through subscription fees — freeing them up to pursue a new approach.

Ticket sales would then take place one of two ways:

Current streaming subscribers could claim free tickets to see the film in theaters — the only limit to the number of tickets the subscriber could claim would be the number of screens his or her subscription allows.

Non-subscribers as well as anyone else could purchase tickets in the traditional sense — that ticket revenue would be split at a pre-negotiated rate between the streaming service and the theater. It's worth noting that tickets for these films could have the potential to be sold for less than the average ticket price of studio movies, since the money would not have to cover any production costs and would automatically be profit for the streaming services.

It's not just the mechanics of the model that work, but it also acts as a value add for both parties:

Theaters will still be able to benefit from the one thing that has kept movie theaters in business throughout years of declining ticket sales — concessions. In the traditional studio model where the distributor leases the film to the theater, tickets are often sold at a loss in order to get people in the door so that theaters can convert that traffic into profit through high margin concession sales. In the proposed model, a free movie or reduced ticket price would get more people in the door and allow the theaters to convert on concession sales without having to take the customary losses on ticket sales (and even giving them a cut of the revenue for non-subscriber ticket sales).

On the streaming service side, theaters would be more likely to show the film (since the content would be a free way to get people in the door and ticket sales to non-subscribers would generate revenue not previously seen in the studio model) giving both the film and the streaming service's ability to create original content more exposure to a wider audience. Looking past the additional revenue from non-subscriber ticket sales, the exposure could lead to more full-time subscribers or even that elusive Academy Award.

I'll admit, there are several core assumptions to this model that, if proven false, cause the entire model to collapse on itself. The biggest assumption of all: people love going to the movies. I'm writing this from my perspective and I personally love the experience of going to a theater. But unlike the people who are keeping theaters in business by buying a $10 bag of popcorn once they've already bought their ticket, I have a hard time shelling out money for concessions when I just paid $13-$18 just to get myself in the door. Change that equation around to where I am getting in the door for free, and that $13-$18 that I just saved might not stay in my pocket for long.

Additionally, it would strike a nice balance between dropping $30+ on a movie night out and doing a yet another movie night in. Who knows, maybe I could finally spring for those sour patch kids that I always see her eyeing.

Disclaimer: I have simplified several areas of the film distribution model for illustrative purposes. Each lease agreement between the theater and the distributor is unique and is likely to have different terms that have varying effect on the financial impact in each unique situation.

            Will Sweet
            Exploring catalysts of technology, business, and behavior

         Tweet

 Share


text:
#ifndef SDM_BALL_MODEL_H
#define SDM_BALL_MODEL_H

#include <limits>
#include <vector>

#include "sdm/covered_point.h"
#include "sdm/model.h"
#include "noir/noir_space.h"
#include "noir/orthotope.h"
#include "rng/random.h"

namespace sdm {

/*
 * This Model implementation consists of a union of Balls Noir Space.
 */
class BallModel : public Model {
 public:
    BallModel(const int &principal_color,
              const double &total_principal_colors,
              const double &total_other_colors):
              Model( principal_color, total_principal_colors,
                     total_other_colors ) {}

    virtual ~BallModel() {}

    /*
     * Expands this model by adding a new Ball using the specified
     * nexus and nearest neighbor points.
     */
    void expand( const noir::Orthotope &region, CoveredPoint *nexus,
                         CoveredPoint *nn, rng::Random *rand,
                         const double &lp, const double &up );

    /*
     * Thicken the last Ball in the model's list.
     */
    void thicken( const noir::Orthotope &region, rng::Random *rand,
                 const double &frac );
};

/*
 * A factory for creating models of type BallModel.
 */
class BallModelFactory : public ModelFactory {
 public:
        BallModelFactory() {}
        virtual ~BallModelFactory() {}

        inline Model* get_model(const int &principal_color,
                                const double &total_principal_colors,
                                const double &total_other_colors) {
            return new BallModel(principal_color, total_principal_colors,
                                 total_other_colors);
        }
 private:
        BallModelFactory(const BallModelFactory&) = delete;
        BallModelFactory& operator=(const BallModelFactory&) = delete;
};

}   // end namespace sdm

#endif   // SDM_BALL_MODEL_H