text:
import Canvas from 'canvas/Canvas.js';
import GetContext from 'canvas/GetContext.js';
import BackgroundColor from 'canvas/BackgroundColor.js';
import AddToDOM from 'dom/AddToDOM.js';
import MoveHorizontal from 'canvas/effects/MoveHorizontal.js';
import Loader from 'loader/Loader.js';

export default class CanvasTest {

    constructor () {

        this.canvas = Canvas(320, 200);

        this.pic = null;

        BackgroundColor(this.canvas, 'rgb(200, 50, 50)');
        AddToDOM(this.canvas, 'game');

        this.loader = new Loader();

        this.loader.path = 'assets/';

        this.loader.image('agent-t-buggin-acf_logo').then((file) => this.loadComplete(file));

        this.loader.start();

    }

    loadComplete (file) {

        this.pic = file.data;

        //  Draw the image in its initial state
        GetContext(this.canvas).drawImage(this.pic, 0, 0);

        //  Move it left by 100px
        // MoveHorizontal(this.canvas, -100, false);
        MoveHorizontal(this.canvas, -100, true);

        //  Move it right by 100px
        // MoveHorizontal(this.canvas, 100, false);
        // MoveHorizontal(this.canvas, 100, true);

    }

}

new CanvasTest();


text:
<?php

namespace Phalcon\Mvc\Model {

	/**
	 * Phalcon\Mvc\Model\Resultset
	 *
	 * This component allows to Phalcon\Mvc\Model returns large resulsets with the minimum memory consumption
	 * Resulsets can be traversed using a standard foreach or a while statement. If a resultset is serialized
	 * it will dump all the rows into a big array. Then unserialize will retrieve the rows as they were before
	 * serializing.
	 *
	 *
	 *
	 * //Using a standard foreach
	 * $robots = Robots::find(array("type='virtual'", "order" => "name"));
	 * foreach ($robots as $robot) {
	 *  echo $robot->name, "\n";
	 * }
	 *
	 * //Using a while
	 * $robots = Robots::find(array("type='virtual'", "order" => "name"));
	 * $robots->rewind();
	 * while ($robots->valid()) {
	 *  $robot = $robots->current();
	 *  echo $robot->name, "\n";
	 *  $robots->next();
	 * }
	 *
	 *
	 */

	abstract class Resultset implements \Phalcon\Mvc\Model\ResultsetInterface, \Iterator, \Traversable, \SeekableIterator, \Countable, \ArrayAccess, \Serializable {

		const TYPE_RESULT_FULL = 0;

		const TYPE_RESULT_PARTIAL = 1;

		const HYDRATE_RECORDS = 0;

		const HYDRATE_OBJECTS = 2;

		const HYDRATE_ARRAYS = 1;

		protected $_type;

		protected $_result;

		protected $_cache;

		protected $_isFresh;

		protected $_pointer;

		protected $_count;

		protected $_activeRow;

		protected $_rows;

		protected $_errorMessages;

		protected $_hydrateMode;

		/**
		 * Moves cursor to next row in the resultset
		 *
		 */
		public function next(){ }

		/**
		 * Gets pointer number of active row in the resultset
		 *
		 * @return int
		 */
		public function key(){ }

		/**
		 * Rewinds resultset to its beginning
		 *
		 */
		public function rewind(){ }

		/**
		 * Changes internal pointer to a specific position in the resultset
		 *
		 * @param int $position
		 */
		public function seek($position){ }

		/**
		 * Counts how many rows are in the resultset
		 *
		 * @return int
		 */
		public function count(){ }

		/**
		 * Checks whether offset exists in the resultset
		 *
		 * @param int $index
		 * @return boolean
		 */
		public function offsetExists($property){ }

		/**
		 * Gets row in a specific position of the resultset
		 *
		 * @param int $index
		 * @return \Phalcon\Mvc\ModelInterface
		 */
		public function offsetGet($property){ }

		/**
		 * Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface
		 *
		 * @param int $index
		 * @param \Phalcon\Mvc\ModelInterface $value
		 */
		public function offsetSet($property, $value){ }

		/**
		 * Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface
		 *
		 * @param int $offset
		 */
		public function offsetUnset($property){ }

		/**
		 * Returns the internal type of data retrieval that the resultset is using
		 *
		 * @return int
		 */
		public function getType(){ }

		/**
		 * Get first row in the resultset
		 *
		 * @return \Phalcon\Mvc\ModelInterface
		 */
		public function getFirst(){ }

		/**
		 * Get last row in the resultset
		 *
		 * @return \Phalcon\Mvc\ModelInterface
		 */
		public function getLast(){ }

		/**
		 * Set if the resultset is fresh or an old one cached
		 *
		 * @param boolean $isFresh
		 * @return \Phalcon\Mvc\Model\Resultset
		 */
		public function setIsFresh($isFresh){ }

		/**
		 * Tell if the resultset if fresh or an old one cached
		 *
		 * @return boolean
		 */
		public function isFresh(){ }

		/**
		 * Sets the hydration mode in the resultset
		 *
		 * @param int $hydrateMode
		 * @return \Phalcon\Mvc\Model\Resultset
		 */
		public function setHydrateMode($hydrateMode){ }

		/**
		 * Returns the current hydration mode
		 *
		 * @return int
		 */
		public function getHydrateMode(){ }

		/**
		 * Returns the associated cache for the resultset
		 *
		 * @return \Phalcon\Cache\BackendInterface
		 */
		public function getCache(){ }

		/**
		 * Returns current row in the resultset
		 *
		 * @return \Phalcon\Mvc\ModelInterface
		 */
		public function current(){ }

		/**
		 * Returns the error messages produced by a batch operation
		 *
		 * @return \Phalcon\Mvc\Model\MessageInterface[]
		 */
		public function getMessages(){ }

		/**
		 * Deletes every record in the resultset
		 *
		 * @param Closure $conditionCallback
		 * @return boolean
		 */
		public function delete($conditionCallback=null){ }

		/**
		 * Filters a resultset returning only those the developer requires
		 *
		 *
		 * $filtered = $robots->filter(function($robot){
		 *		if ($robot->id < 3) {
		 *			return $robot;
		 *		}
		 *	});
		 *
		 *
		 * @param callback $filter
		 * @return \Phalcon\Mvc\Model[]
		 */
		public function filter($filter){ }

	}
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using Duende.Bff.EntityFramework;
using Duende.IdentityServer.Services;
using Duende.IdentityServer.Validation;
using IdentityExpress.Identity;
using IdentityExpress.Manager.Api.AccessTokenValidation;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Logging;
using Rsk.Samples.IdentityServer4.AdminUiIntegration.Demo;
using Rsk.Samples.IdentityServer4.AdminUiIntegration.Middleware;
using Rsk.Samples.IdentityServer4.AdminUiIntegration.Services;

namespace Rsk.Samples.IdentityServer4.AdminUiIntegration
{
    public class Startup
    {
        public Startup(IWebHostEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();

            IsDemo = Configuration.GetValue("IsDemo", false);
        }

        public IConfigurationRoot Configuration { get; }
        private bool IsDemo { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            //add memory cache for custom identity server event sink
            //limit cache to preserving the last 10 error or failure identity server events
            services.AddMemoryCache(options =>
            {
                options.SizeLimit = 10;
            });

            // configure databases
            Action<DbContextOptionsBuilder> identityBuilder;
            Action<DbContextOptionsBuilder> identityServerBuilder;
            var identityConnectionString = Configuration.GetValue("IdentityConnectionString", Configuration.GetValue<string>("DbConnectionString"));
            var identityServerConnectionString = Configuration.GetValue("IdentityServerConnectionString", Configuration.GetValue<string>("DbConnectionString"));
            var migrationAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            switch (Configuration.GetValue<string>("DbProvider"))
            {
                case "SqlServer":
                    identityBuilder = x => x.UseSqlServer(identityConnectionString, options => options.MigrationsAssembly(migrationAssembly));
                    identityServerBuilder = x => x.UseSqlServer(identityServerConnectionString, options => options.MigrationsAssembly(migrationAssembly));
                    break;
                case "MySql":
                    identityBuilder = x => x.UseMySql(identityConnectionString,  new MySqlServerVersion(new Version(5, 6, 49)), options => options.MigrationsAssembly(migrationAssembly));
                    identityServerBuilder = x => x.UseMySql(identityServerConnectionString, new MySqlServerVersion(new Version(5, 6, 49)),options => options.MigrationsAssembly(migrationAssembly));
                    break;
                case "PostgreSql":
                    identityBuilder = x => x.UseNpgsql(identityConnectionString, options => options.MigrationsAssembly(migrationAssembly));
                    identityServerBuilder = x => x.UseNpgsql(identityServerConnectionString, options => options.MigrationsAssembly(migrationAssembly));
                    break;
                default:
                    identityBuilder = x => x.UseSqlite(identityConnectionString, options => options.MigrationsAssembly(migrationAssembly));
                    identityServerBuilder = x => x.UseSqlite(identityServerConnectionString, options => options.MigrationsAssembly(migrationAssembly));
                    break;
            }

            // configure test-suitable X-Forwarded headers and CORS policy
            services.AddSingleton<XForwardedPrefixMiddleware>();

            services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
                options.RequireHeaderSymmetry = false;
                options.ForwardLimit = 10;

                options.KnownNetworks.Clear();
                options.KnownProxies.Clear();
            });

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            });

            // configure ASP.NET Identity
            services
                .AddIdentityExpressAdminUiConfiguration(identityBuilder) // ASP.NET Core Identity Registrations for AdminUI
                .AddDefaultTokenProviders()
                .AddIdentityExpressUserClaimsPrincipalFactory(); // Claims Principal Factory for loading AdminUI users as .NET Identities

            services.AddScoped<IUserStore<IdentityExpressUser>>(
                x => new IdentityExpressUserStore(x.GetService<IdentityExpressDbContext>())
                {
                    AutoSaveChanges = true
                });

            // Add ServerSideSessions
            services.AddBff()
                .AddEntityFrameworkServerSideSessions(options =>
                {
                    options.UseSqlServer(identityServerConnectionString);
                });

            // configure IdentityServer
            services.AddIdentityServer(options =>
                {
                    options.KeyManagement.Enabled = false; // disabled to only use test cert
                    options.LicenseKey = null; // for development only
                    options.Events.RaiseErrorEvents = true;
                    options.Events.RaiseFailureEvents = true;
                    options.Events.RaiseSuccessEvents = true;
                })
                .AddOperationalStore(options => options.ConfigureDbContext = identityServerBuilder)
                .AddConfigurationStore(options => options.ConfigureDbContext = identityServerBuilder)
                .AddAspNetIdentity<IdentityExpressUser>() // configure IdentityServer to use ASP.NET Identity
                .AddSigningCredential(GetEmbeddedCertificate()) // embedded test cert for testing only
                .AddServerSideSessions();

            // Demo services - DO NOT USE IN PRODUCTION
            if (IsDemo)
            {
                services.AddTransient<ICorsPolicyService, DemoCorsPolicy>();
                services.AddTransient<IRedirectUriValidator, DemoRedirectUriValidator>();
            }

            // configure the ASP.NET Identity cookie to work on HTTP for testing only
            services.Configure<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme, options =>
            {
                options.Cookie.SameSite = SameSiteMode.Lax;
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                options.Cookie.IsEssential = true;
            });

            // optional Google authentication
            var googleClientId = Configuration.GetValue<string>("Google_ClientId");
            var googleClientSecret = Configuration.GetValue<string>("Google_ClientSecret");
            if (!string.IsNullOrWhiteSpace(googleClientId) && !string.IsNullOrWhiteSpace(googleClientSecret))
            {
                services
                    .AddAuthentication()
                    .AddGoogle(options =>
                    {
                        options.SignInScheme = "Identity.External"; // ASP.NET Core Identity Extneral User Cookie
                        options.ClientId = googleClientId; // ClientId Configured within Google Admin
                        options.ClientSecret = googleClientSecret; // ClientSecret Generated within Google Admin
                    });
            }

            services.AddMvc();
            services.AddMvcCore().AddAuthorization();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.Authority = "https://localhost:5001";
                    options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
                    options.Audience = "admin_api";

                    // if token does not contain a dot, it is a reference token
                    options.ForwardDefaultSelector = Selector.ForwardReferenceToken("introspection");
                })
                .AddOAuth2Introspection("introspection", options =>
                {
                    options.Authority = "https://localhost:5001";
                    options.ClientId = "admin_api";
                    options.ClientSecret = "adminUiWebhooksSecret";
                });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("webhook", builder =>
                {
                    builder.AddAuthenticationSchemes("Bearer");
                    builder.RequireScope("admin_ui_webhooks");
                });
            });

			services.AddSingleton<IEventSink, CustomEventSink>();
            services.AddSingleton<IEventStore, ErrorEventStore>();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseDeveloperExceptionPage();

            app.UseMiddleware<XForwardedPrefixMiddleware>();
            app.UseForwardedHeaders();

            app.UseStaticFiles();
            app.UseRouting();
            app.UseCors();

            app.UseIdentityServer();
            app.UseAuthorization();

            app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
        }

        private static X509Certificate2 GetEmbeddedCertificate()
        {
            try
            {
                using (var certStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(@"Rsk.Samples.IdentityServer4.AdminUiIntegration.CN=RSKSampleIdentityServer.pfx"))
                {
                    var rawBytes = new byte[certStream.Length];
                    for (var index = 0; index < certStream.Length; index++)
                    {
                        rawBytes[index] = (byte)certStream.ReadByte();
                    }

                    return new X509Certificate2(rawBytes, "Password123!", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
                }
            }
            catch (Exception)
            {
                return new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + "CN=RSKSampleIdentityServer.pfx", "Password123!");
            }
        }
    }
}


text:
title: Soap Bubble
baseurl: ../
date: 2016-02-21
categories: cognition communication
toolFile: soapbubble.swf
toolWidth: 800
toolHeight: 600
navGroup: learningtools
---


text:
/* Override default style */
select:-moz-ui-invalid {
  box-shadow: none;
}

select.notinvalid {
  background-color: green;
}
select.notinvalid:-moz-ui-invalid {
  background-color: red;
}

select.invalid {
  background-color: red;
}
select.invalid:-moz-ui-invalid {
  background-color: green;
}


text:
layout: contributor-profile
credit-name: Takim Williams
first-name: Takim
last-name: Williams
file-as: w
role: Author
role-2:
role-3:
title: Takim Williams — Work in Fireside
description:
twitter-handle:
profile-pic: takim-williams.jpg
website-url:
short-name: takim-williams
permalink: takim-williams
bio-spanish:
---
Takim Williams graduated from Princeton University in 2016 with a minor in creative writing. Founder and former editor-in-chief of _Figments_, Princeton's campus publication for speculative fiction, Takim is the creator of the _#InContext_ blog for the Human Trafficking Institute. His debut novel, _The Experiment Himself_, is scheduled for release in late 2018 from Inkshares in partnership with Nerdist. Takim is searching for a version of Christian faith that is viable in the modern world. If the Rapture happens before the Singularity, he will ask for an extension.


text:
layout: post
title: A regra "não seja um idiota"
permalink: /cod/
isStaticPost: true
---

__Essa regra "Não seja um idiota" é uma versão mais breve e casual do Código de Conduta maior. [Leia a versão completa](http://meta.wikimedia.org/wiki/Don%27t_be_a_dick).__

Google Developer Groups se orgulham de serem uma comunidade aberta, respeitosa e inclusiva. Isto significa que comportamentos inadequados não são permitidos em eventos GDG. Sabemos que isto não é óbvio a todos, então aqui está um lembrete de coisas que não permitimos: piadas ou comentários ofensivos sobre sexo/sexualidade/raça/religião/nacionalidade/tamanho corporal, demonstrações pornográficas em público, tocar em pessoas sem permissão ou continuar interagindo com alguém que já tenha lhe pedido para parar. Comportamento inadequando contínuo pode resultar em ser expulso de um evento ou capítulo do GDG.

O GDG DevFest Nordeste 2014 é um evento sem fins lucrativos e que tem como principais objetivos promover a divulgação, debate e compartilhamento de ideias, experiências e conhecimento entre especialistas, profissionais e estudantes de tecnologia. Esse código de conduta será aplicado durante o evento em todas as instâncias, e para todos os membros da comunidade ou envolvidos no evento.

Se alguém está te incomodando, por favor informe aos [Organizadores do GDG]({{ site.baseurl }}/team/) imediatamente e eles tomarão as ações necessárias. Nós desejamos manter os GDG DevFests fantásticos.

######Contatos:

- DevFest Nordeste, [contato@devfestne.com.br](mailto:contato@devfestne.com.br)

<img class="img-responsive feature-image" src="{{ site.baseurl }}/img/posts/cod.jpg" style="display:none">


text:
namespace scene_lab {

/// @file
/// Pointer and keyboard controls for Scene Lab. This class provides a simple
/// interface for button and key presses, and for tracking the camera's facing
/// when the mouse moves like in a first-person shooter.
/// TODO: Add gamepad and virtual thumbstick support.
class EditorController {
 public:
  static const int kNumButtons = 10;  // max buttons from fplbase/input.h

  /// Initialize the controller.
  EditorController(const SceneLabConfig* config,
                   fplbase::InputSystem* input_system)
      : config_(config),
        input_system_(input_system),
        mouse_locked_(false),
        facing_current_(mathfu::kZeros3f),
        facing_previous_(mathfu::kZeros3f),
        pointer_current_(mathfu::kZeros2f),
        pointer_previous_(mathfu::kZeros2f) {
    for (int i = 0; i < kNumButtons; i++) {
      buttons_previous_[i] = buttons_current_[i] = false;
    }
  }

  /// Call this every frame to update the *WentDown() functions.
  void Update();

  /// ButtonWentDown() returns true only on the first frame the given button is
  /// being pressed. Buttons are numbered 0 thru kNumButtons-1. The primary
  /// button is number 0.
  bool ButtonWentDown(int button) const {
    return buttons_current_[button] && !buttons_previous_[button];
  }
  /// ButtonWentUp() returns true only on the first frame the given button has
  /// stopped being pressed.
  bool ButtonWentUp(int button) const {
    return buttons_previous_[button] && !buttons_current_[button];
  }
  /// ButtonIsDown() returns true while the given button is being held down.
  bool ButtonIsDown(int button) const { return buttons_current_[button]; }
  /// ButtonIsUp() returns true while the given button is not being held down.
  /// Equivalent to ButtonIsDown(button);
  bool ButtonIsUp(int button) const { return !buttons_current_[button]; }

  /// KeyWentDown() returns true on the first frame a given key is being
  /// pressed.
  bool KeyWentDown(fplbase::FPL_Keycode key) const {
    return input_system_->GetButton(key).went_down();
  }
  /// KeyWentUp() returns true on the first frame after a given key has stopped
  /// being pressed.
  bool KeyWentUp(fplbase::FPL_Keycode key) const {
    return input_system_->GetButton(key).went_up();
  }
  /// KeyIsDown() returns true while the given key is being held down.
  bool KeyIsDown(fplbase::FPL_Keycode key) const {
    return input_system_->GetButton(key).is_down();
  }
  /// KeyIsUp() returns true while the given key is not being held down.
  /// Equivalent to !KeyIsDown(key).
  bool KeyIsUp(fplbase::FPL_Keycode key) const {
    return !input_system_->GetButton(key).is_down();
  }

  /// Get the direction we are facing. If the mouse is locked, then moving it
  /// will cause your facing to change like in a first-person shooter.
  const mathfu::vec3& GetFacing() const { return facing_current_; }

  /// Set the current facing to a specific value.
  void SetFacing(const mathfu::vec3& facing) {
    facing_current_ = facing_previous_ = facing;
  }

  /// Get the on-screen pointer position. This is probably only useful is the
  /// mouse is unlocked.
  const mathfu::vec2& GetPointer() const { return pointer_current_; }

  /// Get the delta in on-screen pointer position from the previous update.
  mathfu::vec2 GetPointerDelta() const {
    return pointer_current_ - pointer_previous_;
  }

  /// Lock the mouse into the middle of the screen, which will start updating
  /// facing.
  void LockMouse() {
    mouse_locked_ = true;
    input_system_->SetRelativeMouseMode(true);
  }

  /// Stop locking the mouse to the middle of the screen; it will no longer
  /// update facing, but will update pointer location instead.
  void UnlockMouse() {
    mouse_locked_ = false;
    input_system_->SetRelativeMouseMode(false);
  }

  /// Get the position of a screen point in the world, as a ray from the camera
  /// position with a direction.
  bool ScreenPointToWorldRay(const GenericCamera& camera,
                             const ViewportSettings& viewport,
                             const mathfu::vec2& screen_point,
                             const mathfu::vec2i& screen_size,
                             mathfu::vec3* near, mathfu::vec3* dir) const;

  /// Is the mouse locked? If so, moving the mouse changes our facing. If not,
  /// moving the mouse moves the mouse pointer.
  bool mouse_locked() const { return mouse_locked_; }

  MATHFU_DEFINE_CLASS_SIMD_AWARE_NEW_DELETE

 private:
  const SceneLabConfig* config_;
  fplbase::InputSystem* input_system_;

  bool mouse_locked_;

  mathfu::vec3 facing_current_;
  mathfu::vec3 facing_previous_;

  mathfu::vec2 pointer_current_;
  mathfu::vec2 pointer_previous_;

  bool buttons_current_[kNumButtons];
  bool buttons_previous_[kNumButtons];
};

}  // namespace scene_lab

#endif  // SCENE_LAB_EDITOR_CONTROLLER_H_


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

<title>RxTaskPool.TaskCreator (Apache Tomcat 8.0.14 API Documentation)</title>
<meta name="date" content="2014-09-24">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache Tomcat 8.0.14

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.catalina.tribes.transport

Interface RxTaskPool.TaskCreator

All Known Implementing Classes:

BioReceiver, NioReceiver, ReceiverBase

Enclosing class:

RxTaskPool

public static interface RxTaskPool.TaskCreator

Method Summary

Methods

Modifier and Type
Method and Description

AbstractRxTask
createRxTask()

Method Detail

createRxTask

AbstractRxTask createRxTask()

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache Tomcat 8.0.14

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2000-2014 Apache Software Foundation. All Rights Reserved.


text:
package com.google.cloud.dataflow.sdk.transforms.windowing;

import com.google.cloud.dataflow.sdk.annotations.Experimental;
import com.google.cloud.dataflow.sdk.annotations.Experimental.Kind;
import com.google.cloud.dataflow.sdk.coders.Coder;
import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException;
import com.google.cloud.dataflow.sdk.transforms.DoFn;
import com.google.cloud.dataflow.sdk.transforms.GroupByKey;
import com.google.cloud.dataflow.sdk.transforms.PTransform;
import com.google.cloud.dataflow.sdk.transforms.ParDo;
import com.google.cloud.dataflow.sdk.transforms.display.DisplayData;
import com.google.cloud.dataflow.sdk.util.AssignWindowsDoFn;
import com.google.cloud.dataflow.sdk.util.WindowingStrategy;
import com.google.cloud.dataflow.sdk.util.WindowingStrategy.AccumulationMode;
import com.google.cloud.dataflow.sdk.values.PCollection;

import org.joda.time.Duration;

import javax.annotation.Nullable;

/**
 * {@code Window} logically divides up or groups the elements of a
 * {@link PCollection} into finite windows according to a {@link WindowFn}.
 * The output of {@code Window} contains the same elements as input, but they
 * have been logically assigned to windows. The next
 * {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey GroupByKeys},
 * including one within composite transforms, will group by the combination of
 * keys and windows.

 *
See {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey}
 * for more information about how grouping with windows works.
 *
 *
 Windowing

 *
 *
Windowing a {@code PCollection} divides the elements into windows based
 * on the associated event time for each element. This is especially useful
 * for {@code PCollection}s with unbounded size, since it allows operating on
 * a sub-group of the elements placed into a related window. For {@code PCollection}s
 * with a bounded size (aka. conventional batch mode), by default, all data is
 * implicitly in a single window, unless {@code Window} is applied.
 *
 *
For example, a simple form of windowing divides up the data into
 * fixed-width time intervals, using {@link FixedWindows}.
 * The following example demonstrates how to use {@code Window} in a pipeline
 * that counts the number of occurrences of strings each minute:
 *
 *
 {@code
 * PCollection<String> items = ...;
 * PCollection<String> windowed_items = items.apply(
 *   Window.<String>into(FixedWindows.of(Duration.standardMinutes(1))));
 * PCollection<KV<String, Long>> windowed_counts = windowed_items.apply(
 *   Count.<String>perElement());
 * }

 *
 *
Let (data, timestamp) denote a data element along with its timestamp.
 * Then, if the input to this pipeline consists of
 * {("foo", 15s), ("bar", 30s), ("foo", 45s), ("foo", 1m30s)},
 * the output will be
 * {(KV("foo", 2), 1m), (KV("bar", 1), 1m), (KV("foo", 1), 2m)}
 *
 *
Several predefined {@link WindowFn}s are provided:
 *

 *
 {@link FixedWindows} partitions the timestamps into fixed-width intervals.
 *
 {@link SlidingWindows} places data into overlapping fixed-width intervals.
 *
 {@link Sessions} groups data into sessions where each item in a window
 *       is separated from the next by no more than a specified gap.
 *

 *
 *
Additionally, custom {@link WindowFn}s can be created, by creating new
 * subclasses of {@link WindowFn}.
 *
 *
 Triggers

 *
 *
{@link Window.Bound#triggering(TriggerBuilder)} allows specifying a trigger to control when
 * (in processing time) results for the given window can be produced. If unspecified, the default
 * behavior is to trigger first when the watermark passes the end of the window, and then trigger
 * again every time there is late arriving data.
 *
 *
Elements are added to the current window pane as they arrive. When the root trigger fires,
 * output is produced based on the elements in the current pane.
 *
 *
Depending on the trigger, this can be used both to output partial results
 * early during the processing of the whole window, and to deal with late
 * arriving in batches.
 *
 *
Continuing the earlier example, if we wanted to emit the values that were available
 * when the watermark passed the end of the window, and then output any late arriving
 * elements once-per (actual hour) hour until we have finished processing the next 24-hours of data.
 * (The use of watermark time to stop processing tends to be more robust if the data source is slow
 * for a few days, etc.)
 *
 *
 {@code
 * PCollection<String> items = ...;
 * PCollection<String> windowed_items = items.apply(
 *   Window.<String>into(FixedWindows.of(Duration.standardMinutes(1)))
 *      .triggering(
 *          AfterWatermark.pastEndOfWindow()
 *              .withLateFirings(AfterProcessingTime
 *                  .pastFirstElementInPane().plusDelayOf(Duration.standardHours(1))))
 *      .withAllowedLateness(Duration.standardDays(1)));
 * PCollection<KV<String, Long>> windowed_counts = windowed_items.apply(
 *   Count.<String>perElement());
 * }

 *
 *
On the other hand, if we wanted to get early results every minute of processing
 * time (for which there were new elements in the given window) we could do the following:
 *
 *
 {@code
 * PCollection<String> windowed_items = items.apply(
 *   Window.<String>into(FixedWindows.of(Duration.standardMinutes(1))
 *      .triggering(
 *      .triggering(
 *          AfterWatermark.pastEndOfWindow()
 *              .withEarlyFirings(AfterProcessingTime
 *                  .pastFirstElementInPane().plusDelayOf(Duration.standardMinutes(1))))
 *      .withAllowedLateness(Duration.ZERO));
 * }

 *
 *
After a {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey} the trigger is set to
 * a trigger that will preserve the intent of the upstream trigger.  See
 * {@link Trigger#getContinuationTrigger} for more information.
 *
 *
See {@link Trigger} for details on the available triggers.
 */
public class Window {

  /**
   * Specifies the conditions under which a final pane will be created when a window is permanently
   * closed.
   */
  public enum ClosingBehavior {
    /**
     * Always fire the last pane. Even if there is no new data since the previous firing, an element
     * with {@link PaneInfo#isLast()} {@code true} will be produced.
     */
    FIRE_ALWAYS,
    /**
     * Only fire the last pane if there is new data since the previous firing.
     *
     *
This is the default behavior.
     */
    FIRE_IF_NON_EMPTY;
  }

  /**
   * Creates a {@code Window} {@code PTransform} with the given name.
   *
   *
See the discussion of Naming in
   * {@link com.google.cloud.dataflow.sdk.transforms.ParDo} for more explanation.
   *
   *
The resulting {@code PTransform} is incomplete, and its input/output
   * type is not yet bound.  Use {@link Window.Unbound#into} to specify the
   * {@link WindowFn} to use, which will also bind the input/output type of this
   * {@code PTransform}.
   */
  public static Unbound named(String name) {
    return new Unbound().named(name);
  }

  /**
   * Creates a {@code Window} {@code PTransform} that uses the given
   * {@link WindowFn} to window the data.
   *
   *
The resulting {@code PTransform}'s types have been bound, with both the
   * input and output being a {@code PCollection<T>}, inferred from the types of
   * the argument {@code WindowFn}.  It is ready to be applied, or further
   * properties can be set on it first.
   */
  public static <T> Bound<T> into(WindowFn<? super T, ?> fn) {
    return new Unbound().into(fn);
  }

  /**
   * Sets a non-default trigger for this {@code Window} {@code PTransform}.
   * Elements that are assigned to a specific window will be output when
   * the trigger fires.
   *
   *
Must also specify allowed lateness using {@link #withAllowedLateness} and accumulation
   * mode using either {@link #discardingFiredPanes()} or {@link #accumulatingFiredPanes()}.
   */
  @Experimental(Kind.TRIGGER)
  public static <T> Bound<T> triggering(TriggerBuilder<?> trigger) {
    return new Unbound().triggering(trigger);
  }

  /**
   * Returns a new {@code Window} {@code PTransform} that uses the registered WindowFn and
   * Triggering behavior, and that discards elements in a pane after they are triggered.
   *
   *
Does not modify this transform.  The resulting {@code PTransform} is sufficiently
   * specified to be applied, but more properties can still be specified.
   */
  @Experimental(Kind.TRIGGER)
  public static <T> Bound<T> discardingFiredPanes() {
    return new Unbound().discardingFiredPanes();
  }

  /**
   * Returns a new {@code Window} {@code PTransform} that uses the registered WindowFn and
   * Triggering behavior, and that accumulates elements in a pane after they are triggered.
   *
   *
Does not modify this transform.  The resulting {@code PTransform} is sufficiently
   * specified to be applied, but more properties can still be specified.
   */
  @Experimental(Kind.TRIGGER)
  public static <T> Bound<T> accumulatingFiredPanes() {
    return new Unbound().accumulatingFiredPanes();
  }

  /**
   * Override the amount of lateness allowed for data elements in the pipeline. Like
   * the other properties on this {@link Window} operation, this will be applied at
   * the next {@link GroupByKey}. Any elements that are later than this as decided by
   * the system-maintained watermark will be dropped.
   *
   *
This value also determines how long state will be kept around for old windows.
   * Once no elements will be added to a window (because this duration has passed) any state
   * associated with the window will be cleaned up.
   */
  @Experimental(Kind.TRIGGER)
  public static <T> Bound<T> withAllowedLateness(Duration allowedLateness) {
    return new Unbound().withAllowedLateness(allowedLateness);
  }

  /**
   * An incomplete {@code Window} transform, with unbound input/output type.
   *
   *
Before being applied, {@link Window.Unbound#into} must be
   * invoked to specify the {@link WindowFn} to invoke, which will also
   * bind the input/output type of this {@code PTransform}.
   */
  public static class Unbound {
    String name;

    Unbound() {}

    Unbound(String name) {
      this.name = name;
    }

    /**
     * Returns a new {@code Window} transform that's like this
     * transform but with the specified name.  Does not modify this
     * transform.  The resulting transform is still incomplete.
     *
     *
See the discussion of Naming in
     * {@link com.google.cloud.dataflow.sdk.transforms.ParDo} for more
     * explanation.
     */
    public Unbound named(String name) {
      return new Unbound(name);
    }

    /**
     * Returns a new {@code Window} {@code PTransform} that's like this
     * transform but that will use the given {@link WindowFn}, and that has
     * its input and output types bound.  Does not modify this transform.  The
     * resulting {@code PTransform} is sufficiently specified to be applied,
     * but more properties can still be specified.
     */
    public <T> Bound<T> into(WindowFn<? super T, ?> fn) {
      return new Bound<T>(name).into(fn);
    }

    /**
     * Sets a non-default trigger for this {@code Window} {@code PTransform}.
     * Elements that are assigned to a specific window will be output when
     * the trigger fires.
     *
     *
{@link com.google.cloud.dataflow.sdk.transforms.windowing.Trigger}
     * has more details on the available triggers.
     *
     *
Must also specify allowed lateness using {@link #withAllowedLateness} and accumulation
     * mode using either {@link #discardingFiredPanes()} or {@link #accumulatingFiredPanes()}.
     */
    @Experimental(Kind.TRIGGER)
    public <T> Bound<T> triggering(TriggerBuilder<?> trigger) {
      return new Bound<T>(name).triggering(trigger);
    }

    /**
     * Returns a new {@code Window} {@code PTransform} that uses the registered WindowFn and
     * Triggering behavior, and that discards elements in a pane after they are triggered.
     *
     *
Does not modify this transform.  The resulting {@code PTransform} is sufficiently
     * specified to be applied, but more properties can still be specified.
     */
    @Experimental(Kind.TRIGGER)
    public <T> Bound<T> discardingFiredPanes() {
      return new Bound<T>(name).discardingFiredPanes();
    }

    /**
     * Returns a new {@code Window} {@code PTransform} that uses the registered WindowFn and
     * Triggering behavior, and that accumulates elements in a pane after they are triggered.
     *
     *
Does not modify this transform.  The resulting {@code PTransform} is sufficiently
     * specified to be applied, but more properties can still be specified.
     */
    @Experimental(Kind.TRIGGER)
    public <T> Bound<T> accumulatingFiredPanes() {
      return new Bound<T>(name).accumulatingFiredPanes();
    }

    /**
     * Override the amount of lateness allowed for data elements in the pipeline. Like
     * the other properties on this {@link Window} operation, this will be applied at
     * the next {@link GroupByKey}. Any elements that are later than this as decided by
     * the system-maintained watermark will be dropped.
     *
     *
This value also determines how long state will be kept around for old windows.
     * Once no elements will be added to a window (because this duration has passed) any state
     * associated with the window will be cleaned up.
     *
     *
Depending on the trigger this may not produce a pane with {@link PaneInfo#isLast}. See
     * {@link ClosingBehavior#FIRE_IF_NON_EMPTY} for more details.
     */
    @Experimental(Kind.TRIGGER)
    public <T> Bound<T> withAllowedLateness(Duration allowedLateness) {
      return new Bound<T>(name).withAllowedLateness(allowedLateness);
    }

    /**
     * Override the amount of lateness allowed for data elements in the pipeline. Like
     * the other properties on this {@link Window} operation, this will be applied at
     * the next {@link GroupByKey}. Any elements that are later than this as decided by
     * the system-maintained watermark will be dropped.
     *
     *
This value also determines how long state will be kept around for old windows.
     * Once no elements will be added to a window (because this duration has passed) any state
     * associated with the window will be cleaned up.
     */
    @Experimental(Kind.TRIGGER)
    public <T> Bound<T> withAllowedLateness(Duration allowedLateness, ClosingBehavior behavior) {
      return new Bound<T>(name).withAllowedLateness(allowedLateness, behavior);
    }
  }

  /**
   * A {@code PTransform} that windows the elements of a {@code PCollection<T>},
   * into finite windows according to a user-specified {@code WindowFn}.
   *
   * @param <T> The type of elements this {@code Window} is applied to
   */
  public static class Bound<T> extends PTransform<PCollection<T>, PCollection<T>> {

    @Nullable private final WindowFn<? super T, ?> windowFn;
    @Nullable private final Trigger<?> trigger;
    @Nullable private final AccumulationMode mode;
    @Nullable private final Duration allowedLateness;
    @Nullable private final ClosingBehavior closingBehavior;
    @Nullable private final OutputTimeFn<?> outputTimeFn;

    private Bound(String name,
        @Nullable WindowFn<? super T, ?> windowFn, @Nullable Trigger<?> trigger,
        @Nullable AccumulationMode mode, @Nullable Duration allowedLateness,
        ClosingBehavior behavior, @Nullable OutputTimeFn<?> outputTimeFn) {
      super(name);
      this.windowFn = windowFn;
      this.trigger = trigger;
      this.mode = mode;
      this.allowedLateness = allowedLateness;
      this.closingBehavior = behavior;
      this.outputTimeFn = outputTimeFn;
    }

    private Bound(String name) {
      this(name, null, null, null, null, null, null);
    }

    /**
     * Returns a new {@code Window} {@code PTransform} that's like this
     * transform but that will use the given {@link WindowFn}, and that has
     * its input and output types bound.  Does not modify this transform.  The
     * resulting {@code PTransform} is sufficiently specified to be applied,
     * but more properties can still be specified.
     */
    private Bound<T> into(WindowFn<? super T, ?> windowFn) {
      try {
        windowFn.windowCoder().verifyDeterministic();
      } catch (NonDeterministicException e) {
        throw new IllegalArgumentException("Window coders must be deterministic.", e);
      }

      return new Bound<>(
          name, windowFn, trigger, mode, allowedLateness, closingBehavior, outputTimeFn);
    }

    /**
     * Returns a new {@code Window} {@code PTransform} that's like this
     * {@code PTransform} but with the specified name.  Does not
     * modify this {@code PTransform}.
     *
     *
See the discussion of Naming in
     * {@link com.google.cloud.dataflow.sdk.transforms.ParDo} for more
     * explanation.
     */
    public Bound<T> named(String name) {
      return new Bound<>(
          name, windowFn, trigger, mode, allowedLateness, closingBehavior, outputTimeFn);
    }

    /**
     * Sets a non-default trigger for this {@code Window} {@code PTransform}.
     * Elements that are assigned to a specific window will be output when
     * the trigger fires.
     *
     *
{@link com.google.cloud.dataflow.sdk.transforms.windowing.Trigger}
     * has more details on the available triggers.
     *
     *
Must also specify allowed lateness using {@link #withAllowedLateness} and accumulation
     * mode using either {@link #discardingFiredPanes()} or {@link #accumulatingFiredPanes()}.
     */
    @Experimental(Kind.TRIGGER)
    public Bound<T> triggering(TriggerBuilder<?> trigger) {
      return new Bound<T>(
          name,
          windowFn,
          trigger.buildTrigger(),
          mode,
          allowedLateness,
          closingBehavior,
          outputTimeFn);
    }

   /**
    * Returns a new {@code Window} {@code PTransform} that uses the registered WindowFn and
    * Triggering behavior, and that discards elements in a pane after they are triggered.
    *
    *
Does not modify this transform.  The resulting {@code PTransform} is sufficiently
    * specified to be applied, but more properties can still be specified.
    */
    @Experimental(Kind.TRIGGER)
   public Bound<T> discardingFiredPanes() {
     return new Bound<T>(
         name,
         windowFn,
         trigger,
         AccumulationMode.DISCARDING_FIRED_PANES,
         allowedLateness,
         closingBehavior,
         outputTimeFn);
   }

   /**
    * Returns a new {@code Window} {@code PTransform} that uses the registered WindowFn and
    * Triggering behavior, and that accumulates elements in a pane after they are triggered.
    *
    *
Does not modify this transform.  The resulting {@code PTransform} is sufficiently
    * specified to be applied, but more properties can still be specified.
    */
   @Experimental(Kind.TRIGGER)
   public Bound<T> accumulatingFiredPanes() {
     return new Bound<T>(
         name,
         windowFn,
         trigger,
         AccumulationMode.ACCUMULATING_FIRED_PANES,
         allowedLateness,
         closingBehavior,
         outputTimeFn);
   }

    /**
     * Override the amount of lateness allowed for data elements in the pipeline. Like
     * the other properties on this {@link Window} operation, this will be applied at
     * the next {@link GroupByKey}. Any elements that are later than this as decided by
     * the system-maintained watermark will be dropped.
     *
     *
This value also determines how long state will be kept around for old windows.
     * Once no elements will be added to a window (because this duration has passed) any state
     * associated with the window will be cleaned up.
     *
     *
Depending on the trigger this may not produce a pane with {@link PaneInfo#isLast}. See
     * {@link ClosingBehavior#FIRE_IF_NON_EMPTY} for more details.
     */
    @Experimental(Kind.TRIGGER)
    public Bound<T> withAllowedLateness(Duration allowedLateness) {
      return new Bound<T>(
          name, windowFn, trigger, mode, allowedLateness, closingBehavior, outputTimeFn);
    }

    /**
     * (Experimental) Override the default {@link OutputTimeFn}, to control
     * the output timestamp of values output from a {@link GroupByKey} operation.
     */
    @Experimental(Kind.OUTPUT_TIME)
    public Bound<T> withOutputTimeFn(OutputTimeFn<?> outputTimeFn) {
      return new Bound<T>(
          name, windowFn, trigger, mode, allowedLateness, closingBehavior, outputTimeFn);
    }

    /**
     * Override the amount of lateness allowed for data elements in the pipeline. Like
     * the other properties on this {@link Window} operation, this will be applied at
     * the next {@link GroupByKey}. Any elements that are later than this as decided by
     * the system-maintained watermark will be dropped.
     *
     *
This value also determines how long state will be kept around for old windows.
     * Once no elements will be added to a window (because this duration has passed) any state
     * associated with the window will be cleaned up.
     */
    @Experimental(Kind.TRIGGER)
    public Bound<T> withAllowedLateness(Duration allowedLateness, ClosingBehavior behavior) {
      return new Bound<T>(name, windowFn, trigger, mode, allowedLateness, behavior, outputTimeFn);
    }

    /**
     * Get the output strategy of this {@link Window.Bound Window PTransform}. For internal use
     * only.
     */
    // Rawtype cast of OutputTimeFn cannot be eliminated with intermediate variable, as it is
    // casting between wildcards
    public WindowingStrategy<?, ?> getOutputStrategyInternal(
        WindowingStrategy<?, ?> inputStrategy) {
      WindowingStrategy<?, ?> result = inputStrategy;
      if (windowFn != null) {
        result = result.withWindowFn(windowFn);
      }
      if (trigger != null) {
        result = result.withTrigger(trigger);
      }
      if (mode != null) {
        result = result.withMode(mode);
      }
      if (allowedLateness != null) {
        result = result.withAllowedLateness(allowedLateness);
      }
      if (closingBehavior != null) {
        result = result.withClosingBehavior(closingBehavior);
      }
      if (outputTimeFn != null) {
        result = result.withOutputTimeFn(outputTimeFn);
      }
      return result;
    }

    /**
     * Get the {@link WindowFn} of this {@link Window.Bound Window PTransform}.
     */
    public WindowFn<? super T, ?> getWindowFn() {
      return windowFn;
    }

    @Override
    public void validate(PCollection<T> input) {
      WindowingStrategy<?, ?> outputStrategy =
          getOutputStrategyInternal(input.getWindowingStrategy());

      // Make sure that the windowing strategy is complete & valid.
      if (outputStrategy.isTriggerSpecified()
          && !(outputStrategy.getTrigger().getSpec() instanceof DefaultTrigger)) {
        if (!(outputStrategy.getWindowFn() instanceof GlobalWindows)
            && !outputStrategy.isAllowedLatenessSpecified()) {
          throw new IllegalArgumentException("Except when using GlobalWindows,"
              + " calling .triggering() to specify a trigger requires that the allowed lateness be"
              + " specified using .withAllowedLateness() to set the upper bound on how late data"
              + " can arrive before being dropped. See Javadoc for more details.");
        }

        if (!outputStrategy.isModeSpecified()) {
          throw new IllegalArgumentException(
              "Calling .triggering() to specify a trigger requires that the accumulation mode be"
              + " specified using .discardingFiredPanes() or .accumulatingFiredPanes()."
              + " See Javadoc for more details.");
        }
      }
    }

    @Override
    public PCollection<T> apply(PCollection<T> input) {
      WindowingStrategy<?, ?> outputStrategy =
          getOutputStrategyInternal(input.getWindowingStrategy());
      PCollection<T> output;
      if (windowFn != null) {
        // If the windowFn changed, we create a primitive, and run the AssignWindows operation here.
        output = assignWindows(input, windowFn);
      } else {
        // If the windowFn didn't change, we just run a pass-through transform and then set the
        // new windowing strategy.
        output = input.apply(Window.<T>identity());
      }
      return output.setWindowingStrategyInternal(outputStrategy);
    }

    private <T, W extends BoundedWindow> PCollection<T> assignWindows(
        PCollection<T> input, WindowFn<? super T, W> windowFn) {
      return input.apply("AssignWindows", ParDo.of(new AssignWindowsDoFn<T, W>(windowFn)));
    }

    @Override
    public void populateDisplayData(DisplayData.Builder builder) {
      super.populateDisplayData(builder);

      if (windowFn != null) {
        builder
            .add(DisplayData.item("windowFn", windowFn.getClass())
              .withLabel("Windowing Function"))
            .include(windowFn);
      }

      if (allowedLateness != null) {
        builder.addIfNotDefault(DisplayData.item("allowedLateness", allowedLateness)
              .withLabel("Allowed Lateness"),
            Duration.millis(BoundedWindow.TIMESTAMP_MAX_VALUE.getMillis()));
      }

      if (trigger != null && !(trigger instanceof DefaultTrigger)) {
        builder.add(DisplayData.item("trigger", trigger.toString())
          .withLabel("Trigger"));
      }

      if (mode != null) {
        builder.add(DisplayData.item("accumulationMode", mode.toString())
          .withLabel("Accumulation Mode"));
      }

      if (closingBehavior != null) {
        builder.add(DisplayData.item("closingBehavior", closingBehavior.toString())
          .withLabel("Window Closing Behavior"));
      }

      if (outputTimeFn != null) {
        builder.add(DisplayData.item("outputTimeFn", outputTimeFn.getClass())
          .withLabel("Output Time Function"));
      }
    }

    @Override
    protected Coder<?> getDefaultOutputCoder(PCollection<T> input) {
      return input.getCoder();
    }

    @Override
    protected String getKindString() {
      return "Window.Into()";
    }
  }

  /////////////////////////////////////////////////////////////////////////////

  private static <T> PTransform<PCollection<? extends T>, PCollection<T>> identity() {
    return ParDo.named("Identity").of(new DoFn<T, T>() {
      @Override public void processElement(ProcessContext c) {
        c.output(c.element());
      }
    });
  }

  /**
   * Creates a {@code Window} {@code PTransform} that does not change assigned
   * windows, but will cause windows to be merged again as part of the next
   * {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey}.
   */
  public static <T> Remerge<T> remerge() {
    return new Remerge<T>();
  }

  /**
   * {@code PTransform} that does not change assigned windows, but will cause
   *  windows to be merged again as part of the next
   * {@link com.google.cloud.dataflow.sdk.transforms.GroupByKey}.
   */
  public static class Remerge<T> extends PTransform<PCollection<T>, PCollection<T>> {
    @Override
    public PCollection<T> apply(PCollection<T> input) {
      WindowingStrategy<?, ?> outputWindowingStrategy = getOutputWindowing(
          input.getWindowingStrategy());

      return input.apply(Window.<T>identity())
          .setWindowingStrategyInternal(outputWindowingStrategy);
    }

    private <W extends BoundedWindow> WindowingStrategy<?, W> getOutputWindowing(
        WindowingStrategy<?, W> inputStrategy) {
      if (inputStrategy.getWindowFn() instanceof InvalidWindows) {
        @SuppressWarnings("unchecked")
        InvalidWindows<W> invalidWindows = (InvalidWindows<W>) inputStrategy.getWindowFn();
        return inputStrategy.withWindowFn(invalidWindows.getOriginalWindowFn());
      } else {
        return inputStrategy;
      }
    }
  }
}


text:
//////////////////////////////////////////////////////////////////////////////////
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Furry Builder
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////////

using System;
using System.Reactive;
using System.Reactive.Linq;
using FluffIt.System.Reactive.StaticExtensions;
using Microsoft.Reactive.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FluffIt.System.Reactive.Tests.ObservableExtensionsTests
{
    [TestClass]
    public class GivenValueObservable
    {
        [TestMethod]
        public void WhenSelectUnit_ThenResultIsUnit()
        {
            var validator = false;

            var testScheduler = new TestScheduler();

            var source = Observable
                .Return(true, testScheduler)
                .SelectUnit();

            testScheduler.AdvanceBy(1);

            source.Subscribe(
                u =>
                {
                    validator = true;
                    Assert.IsInstanceOfType(u, typeof (Unit));
                });

            testScheduler.AdvanceBy(1);

            Assert.IsTrue(validator);
        }

        [TestMethod]
        public void WhenSelectManyDisposePrevious()
        {
            var outterRanCount = 0;
            var innerRanCount = 0;

            var testSchedulerOutter = new TestScheduler();
            var testSchedulerInner = new TestScheduler();

            Observable
                .Range(0, 2, testSchedulerOutter)
                .SelectManyDisposePrevious(
                    _ =>
                    {
                        ++outterRanCount;

                        return ObservableEx.DeferedStart(() => ++innerRanCount, testSchedulerInner);
                    })
                .Subscribe();

            testSchedulerOutter.AdvanceBy(2);
            testSchedulerInner.AdvanceBy(4);

            Assert.AreEqual(2, outterRanCount);
            Assert.AreEqual(1, innerRanCount);
        }

        [TestMethod]
        public void WhenSelectUnitWithNull_ThenResultIsUnit()
        {
            var validator = false;

            var testScheduler = new TestScheduler();

            var source = Observable
                .Return((object) null, testScheduler)
                .SelectUnit();

            testScheduler.AdvanceBy(1);

            source.Subscribe(
                u =>
                {
                    validator = true;
                    Assert.IsInstanceOfType(u, typeof (Unit));
                });

            testScheduler.AdvanceBy(1);

            Assert.IsTrue(validator);
        }

        [TestMethod]
        public void WhenSubscribeSafe_ThenErrorIsHandled()
        {
            var isHandled = false;

            var testScheduler = new TestScheduler();

            Observable
                .Return(Unit.Default, testScheduler)
                .SubscribeSafe(
                    _ => { throw new Exception(); },
                    ex => isHandled = true
                );

            testScheduler.AdvanceBy(1);

            Assert.IsTrue(isHandled);
        }

        [TestMethod]
        public void WhenSubscribeSafeWithPreviousValue_ThenErrorIsHandled()
        {
            var isHandled = false;

            var testScheduler = new TestScheduler();

            Observable
                .Return(Unit.Default, testScheduler)
                .WithPreviousValue()
                .SubscribeSafe(
                    v => { throw new Exception(); },
                    ex => isHandled = true
                );

            testScheduler.AdvanceBy(1);

            Assert.IsTrue(isHandled);
        }

        [TestMethod]
        public void WhenSubscribeSafeWithPreviousValue_ThenValuesAreValid()
        {
            var testScheduler = new TestScheduler();

            var prev = 0;
            var curr = 0;

            Observable
                .Range(1, 2, testScheduler)
                .WithPreviousValue()
                .SubscribeSafe(
                    v =>
                    {
                        prev = v.PreviousValue;
                        curr = v.CurrentValue;
                    });

            testScheduler.AdvanceBy(2);

            Assert.AreEqual(1, prev);
            Assert.AreEqual(2, curr);
        }

        [TestMethod]
        public void WhenSelectWithPreviousValue_ThenValuesAreValid()
        {
            var testScheduler = new TestScheduler();

            var prev = 0;
            var curr = 0;

            Observable
                .Range(1, 2, testScheduler)
                .WithPreviousValue()
                .Select(
                    v =>
                    {
                        prev = v.PreviousValue;
                        curr = v.CurrentValue;

                        return Unit.Default;
                    })
                .Subscribe();

            testScheduler.AdvanceBy(2);

            Assert.AreEqual(1, prev);
            Assert.AreEqual(2, curr);
        }

        [TestMethod]
        public void WhenDoWithPreviousValue_ThenValuesAreValid()
        {
            var testScheduler = new TestScheduler();

            var prev = 0;
            var curr = 0;

            Observable
                .Range(1, 2, testScheduler)
                .WithPreviousValue()
                .Do(
                    v =>
                    {
                        prev = v.PreviousValue;
                        curr = v.CurrentValue;
                    })
                .Subscribe();

            testScheduler.AdvanceBy(2);

            Assert.AreEqual(1, prev);
            Assert.AreEqual(2, curr);
        }
    }
}


text:
package cmd

import (
	"bytes"
	"os"
	"testing"

	"github.com/sirupsen/logrus"
	"github.com/stretchr/testify/assert"

	"github.com/antham/doc-hunt/file"

	"github.com/antham/doc-hunt/ui"
	"github.com/antham/doc-hunt/util"
)

func TestAddConfigWithMissingFileDoc(t *testing.T) {
	ui.Error = func(err error) {
		assert.EqualError(t, err, "Missing doc identifier", "Must return a missing file doc error")
	}

	util.ErrorExit = func() {
		t.SkipNow()
	}

	os.Args = []string{"", "config", "add"}

	err := RootCmd.Execute()

	if err != nil {
		logrus.Fatal(err)
	}
}

func TestAddConfigWithMissingFileSources(t *testing.T) {
	ui.Error = func(err error) {
		assert.EqualError(t, err, "Missing source identifiers", "Must return a missing source identifier error")
	}

	util.ErrorExit = func() {
		t.SkipNow()
	}

	os.Args = []string{"", "config", "add", "test"}

	err := RootCmd.Execute()

	if err != nil {
		logrus.Fatal(err)
	}
}

func TestAddConfigWithMoreThanTwoArguments(t *testing.T) {
	ui.Error = func(err error) {
		assert.EqualError(t, err, "No more than 2 arguments expected", "Must return an overflow argument error")
	}

	util.ErrorExit = func() {
		t.SkipNow()
	}

	os.Args = []string{"", "config", "add", "test", "test", "test"}

	err := RootCmd.Execute()

	if err != nil {
		logrus.Fatal(err)
	}
}

func TestAddConfig(t *testing.T) {
	createMocks()
	err := file.Initialize()

	if err != nil {
		logrus.Fatal(err)
	}

	ui.Success = func(msg string) {
		assert.Equal(t, "Config added", msg, "Must display a success message")
	}

	util.SuccessExit = func() {
		t.SkipNow()
	}

	os.Args = []string{"", "config", "add", "doc_file_to_track.txt", "source1.php,source2.php"}

	err = RootCmd.Execute()

	if err != nil {
		logrus.Fatal(err)
	}
}

func TestAddConfigWithDryRun(t *testing.T) {
	createMocks()
	err := file.Initialize()
	output := []byte{}
	out = bytes.NewBuffer(output)

	if err != nil {
		logrus.Fatal(err)
	}

	util.SuccessExit = func() {
		assert.Regexp(t, `doc_file_to_track.txt`, out, "Must render document")
		assert.Regexp(t, `Files matching regexp "source1.php"`, out, "Must render original regexp")
		assert.Regexp(t, `=> source1.php`, out, "Must render source")
		assert.Regexp(t, `Files matching regexp "source2.php"`, out, "Must render original regexp")
		assert.Regexp(t, `=> source2.php`, out, "Must render source")
	}

	os.Args = []string{"", "config", "add", "-n", "doc_file_to_track.txt", "source1.php,source2.php"}

	err = RootCmd.Execute()

	if err != nil {
		logrus.Fatal(err)
	}
}

func TestAddConfigWithDryRunAndMissingSource(t *testing.T) {
	createMocks()
	err := file.Initialize()
	output := []byte{}
	out = bytes.NewBuffer(output)

	if err != nil {
		logrus.Fatal(err)
	}

	util.SuccessExit = func() {
		assert.Regexp(t, `doc_file_to_track.txt`, out, "Must render document")
		assert.Regexp(t, `Files matching regexp "source1.php"`, out, "Must render original regexp")
		assert.Regexp(t, `=> source1.php`, out, "Must render source")
		assert.Regexp(t, `Files matching regexp "s.php"`, out, "Must render original regexp")
		assert.Regexp(t, `=> No files found`, out, "Must render source")
	}

	os.Args = []string{"", "config", "add", "-n", "doc_file_to_track.txt", "source1.php,s.php"}

	err = RootCmd.Execute()

	if err != nil {
		logrus.Fatal(err)
	}
}

func TestParseConfigAddArgsWithUnexistingFileDoc(t *testing.T) {
	createMocks()

	_, _, err := parseConfigAddArgs([]string{"whatever", "test"})

	assert.EqualError(t, err, "Doc whatever is not a valid existing file, nor a valid existing folder, nor a valid URL", "Must return an unexisting doc identifier error")
}

func TestParseConfigAddArgsWithADocFile(t *testing.T) {
	createMocks()

	doc, sources, err := parseConfigAddArgs([]string{"doc_file_to_track.txt", "source1.php,source2.php"})

	assert.NoError(t, err, "Must return no error")
	assert.Regexp(t, "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", doc.ID, "Must return an id")
	assert.Equal(t, "doc_file_to_track.txt", doc.Identifier, "Must return doc file path")
	assert.EqualValues(t, file.DFILE, doc.Category, "Must return a file doc category")
	assert.Equal(t, "source1.php", (*sources)[0].Identifier, "Must return source file regexp")
	assert.EqualValues(t, file.SFILEREG, (*sources)[0].Category, "Must return regexp file type")
	assert.Equal(t, "source2.php", (*sources)[1].Identifier, "Must return source file regexp")
	assert.EqualValues(t, file.SFILEREG, (*sources)[1].Category, "Must return regexp file type")
}

func TestParseConfigAddArgsWithADocURL(t *testing.T) {
	createMocks()

	doc, sources, err := parseConfigAddArgs([]string{"http://google.com", "source1.php,source2.php"})

	assert.Equal(t, "http://google.com", doc.Identifier, "Must return a doc url")
	assert.NoError(t, err, "Must return no error")
	assert.Equal(t, "source1.php", (*sources)[0].Identifier, "Must return source file regexp")
	assert.EqualValues(t, file.SFILEREG, (*sources)[0].Category, "Must return regexp file type")
	assert.Equal(t, "source2.php", (*sources)[1].Identifier, "Must return source file regexp")
	assert.EqualValues(t, file.SFILEREG, (*sources)[1].Category, "Must return regexp file type")
	assert.EqualValues(t, file.DURL, doc.Category, "Must return an URL doc category")
}

func TestParseConfigAddArgsWithADocFolder(t *testing.T) {
	createMocks()
	createSubTestDirectory("test2")

	doc, sources, err := parseConfigAddArgs([]string{"test2", "source1.php,source2.php"})

	assert.Equal(t, "test2", doc.Identifier, "Must return a doc folder")
	assert.NoError(t, err, "Must return no error")
	assert.Equal(t, "source1.php", (*sources)[0].Identifier, "Must return source file regexp")
	assert.EqualValues(t, file.SFILEREG, (*sources)[0].Category, "Must return regexp file type")
	assert.Equal(t, "source2.php", (*sources)[1].Identifier, "Must return source file regexp")
	assert.EqualValues(t, file.SFILEREG, (*sources)[1].Category, "Must return regexp file type")
	assert.EqualValues(t, file.DFOLDER, doc.Category, "Must return a folder doc category")
}

func TestParseConfigAddArgsWithAFileSourceRegexp(t *testing.T) {
	createMocks()
	createSubTestDirectory("test2")

	doc, sources, err := parseConfigAddArgs([]string{"doc_file_to_track.txt", "test2"})

	assert.Equal(t, "doc_file_to_track.txt", doc.Identifier, "Must return a doc file")
	assert.NoError(t, err, "Must return no error")
	assert.Equal(t, "test2", (*sources)[0].Identifier, "Must return sources path")
	assert.EqualValues(t, file.SFILEREG, (*sources)[0].Category, "Must return sources regexp type")
	assert.EqualValues(t, file.DFILE, doc.Category, "Must return a file doc category")
}


text:
<?php
/**
 * ResourceLoader definition for MediaWiki:Filepage.css
 */
class ResourceLoaderFilePageModule extends ResourceLoaderWikiModule {

	/**
	 * @param $context ResourceLoaderContext
	 * @return array
	 */
	protected function getPages( ResourceLoaderContext $context ) {
		return array(
			'MediaWiki:Filepage.css' => array( 'type' => 'style' ),
		);
	}
}


text:
using System;
using Maui.Data.Sheets;
using MSExcel = Microsoft.Office.Interop.Excel;

namespace Maui.Presentation.Excel
{
    internal class ExcelWorksheet : IWorksheet
    {
        private MSExcel.Workbook myWorkbook;

        public ExcelWorksheet( MSExcel.Workbook workbook, MSExcel.Worksheet sheet )
        {
            myWorkbook = workbook;
            ExcelSheet = sheet;
        }

        internal MSExcel.Worksheet ExcelSheet { get; private set; }

        public string Name
        {
            get { return ExcelSheet.Name; }
        }

        public object GetCell( string position )
        {
            return ExcelSheet.get_Range( position, Type.Missing ).Value2;
        }

        public T GetCell<T>( string position )
        {
            return (T)GetCell( position );
        }

        public void SetCell( string position, object value )
        {
            ExcelSheet.get_Range( position, Type.Missing ).Value2 = value;
        }

        public void Save()
        {
            myWorkbook.Save();
        }

        public bool IsEmptyCell( object cell )
        {
            return cell == null;
        }

        public int GetRowCount()
        {
            // excel always have 65535 rows - that creates performance problems
            // so we define the end of the sheet as
            // "the beginning of a block of 10 empty lines"
            int numEmptyRows = 0;
            for ( int row = 1; row < ExcelSheet.Rows.Count; ++row )
            {
                if ( IsEmptyRow( row ) )
                {
                    numEmptyRows++;
                }
                else
                {
                    numEmptyRows = 0;
                }

                if ( numEmptyRows >= 10 )
                {
                    return row - numEmptyRows;
                }
            }

            // fallback if the algorithm above fails
            return ExcelSheet.Rows.Count;
        }

        // a row is interpreted as "empty" if the first 26 colums are empty
        private bool IsEmptyRow( int row )
        {
            for ( char col = 'A'; col <= 'Z'; col++ )
            {
                if ( !IsEmptyCell( GetCell( col.ToString() + row ) ) )
                {
                    return false;
                }
            }

            return true;
        }

        public int GetColumnCount()
        {
            // excel always have 256 columns - until we get performance
            // problems we will return all here
            return ExcelSheet.Columns.Count;
        }
    }
}


text:
+ Language: Any with a mocking framework, e.g. Java, Scala, PHP, C# or Go
+ Level: Easy
+ Requires: Mocking framework, Internet connection, IDE recommended

## Motivation

The London School approach is also known as Outside-In TDD and concentrates more on the behaviour of objects rather than the state. It can lead to a better design than classic TDD if you already have a rough idea of the design. It also supports the "Double Loop of TDD" better, that is start with acceptance test and then fine-tune it with unit tests.

![Double Loop TDD](http://i.imgur.com/EZ84KuV.png)

## Objective

Learn and practice the double loop of TDD with a simple acceptance test. Test your application from the outside, not from the inside. This is an introductory kata and requires no BDD (Behaviour Driven Development) frameworks or such.

This kata is known as the "Bank kata". You can find multiple references on the web, this one is taken from Ruben Straube, see [https://github.com/rubek/bank-kata-softwerkskammer](https://github.com/rubek/bank-kata-softwerkskammer "https://github.com/rubek/bank-kata-softwerkskammer"). A more complex setup can be found on [https://github.com/sandromancuso/Bank-kata](https://github.com/sandromancuso/Bank-kata  "https://github.com/sandromancuso/Bank-kata").

## Coding

### Task

Create a simple bank application with the following features:

- Deposit into Account
- Withdraw from an Account
- Print a bank statement to the console.

Start with an acceptance test, see below. If motivated, follow the [Object Calisthenics](https://github.com/goeckeler/katas/blob/master/Object%20Calisthenics/README.md "Object Calisthenics Rules") rules.

### Acceptance criteria

Statement should have the following the format:

        DATE       | AMOUNT  | BALANCE
        10/04/2014 | 500.00  | 1400.00
        02/04/2014 | -100.00 | 900.00
        01/04/2014 | 1000.00 | 1000.00

Don't bother about spaces and formatting.

### Class under test

You need to start testing from the following `Account` class or similar.

        public class Account {
            public void deposit(int amount);
            public void withdrawal(int amount);
            public void printStatement();
        }

You are not allowed to add any other public method to this class. Those are the only *methods* that are visible from outside.

### Sample Acceptance Test

Proposed acceptance test starting point, here in Java syntax:

      public class PrintStatementFeature {
        @Test public void
          print_statement_containing_transactions_in_reverse_chronological_order() {
              account.deposit(1000);
              account.withdraw(100);
              account.deposit(500);

              account.printStatement();

              verify(console).printLine("DATE | AMOUNT | BALANCE");
              verify(console).printLine("10/04/2014 | 500.00 | 1400.00");
              verify(console).printLine("02/04/2014 | -100.00 | 900.00");
              verify(console).printLine("01/04/2014 | 1000.00 | 1000.00");
        }
      }

This won't compile even after adding Mockito to the classpath. That's on purpose, may be you get an idea why.


text:
<TITLE>Review for O Brother, Where Art Thou? (2000)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

O Brother, Where Art Thou? (2000)

reviewed by
Berge Garabedian

O BROTHER, WHERE ART THOU?
RATING: 7/10 --> Good Movie

For more reviews and movie wallpapers, visit http://www.joblo.com/

You gotta hand it to the Coen brothers. Even with the great success of FARGO
a few years back, they have still managed to maintain their integrity, their
quirky filmmaking nature and their innate ability NOT to sell out. This film
is yet another example of the original work that these guys have been
putting up on the screens for close to 20 years now, with an obvious passion
for their projects and very little priority placed on commercial success.
Don't get me wrong, their films surely pay back their investment and then
some, but much like Woody Allen and his successful streak of films year
after year, the Coen brothers seem to make movies primarily because they've
got a boatload of characters to share with the world, and quirky stories to
divulge. Blockbusters are not what these brothers are about.

PLOT:
Set in the South during the 1930s, three men have just escaped a chain gang
in order to retrieve the treasure which one of them buried before his
capture. On the way to their final destination, the bumbling threesome run
across various colorful characters including a fast-talking one-eyed bible
salesman, a black man who just sold his soul to the devil in return for
musical talent, a trio of sexy sirens, the KKK and many other quirky members
of the Deep South personnel.

CRITIQUE:
Another original piece set forth by the Coen bros, who continue to charm us
with their unique knack for poetic dialogue, quirky characters, musical
melodies and eerily authentic looks at the days of old. And despite this
film being a little slow at times, a little too long for its own good and a
little weak in the "romance" end of the story, it still managed to keep me
entertained for most its outing with plenty of peppered one-liners, a great
chemistry between the three leads, catchy tunes and a rock-solid performance
by George Clooney. Now when the heck did he suddenly become a movie star and
an actor?!? Wow. Here Clooney shines as the leader of this pack of con men,
with a twangy accent in tow, a great delivery of his overly literate
dialogue and a hilarious running gag about his hair. I just could not take
my eyes off this guy when he was on the screen. A great turn for Mr. Clooney
(and a nice Clark Gable-ish 'stache to boot). The other two scoundrels also
follow suit with top-notch performances of their own offbeat personalities
as do the rest of the cast, with plenty of fun and engaging moments of their
own. There was however at least one character for whom I didn't care much.
And seeing as the film did run a little too long, I think it would have been
a tighter flick with a little snip here and there.

But ultimately, much like any other Coen film, you either like it or you
don't. I did and despite many of its characters obviously having graduated
from the RAISING ARIZONA school of highly tuned dialogue (just not as
flat-out funny), I got into it and would recommend it to anyone looking for
something different. This film will doubtfully be a commercial hit because
it simply doesn't have much to say and doesn't entertain on a "general
audience" type of level. Its story isn't a grand one and its over-emphasis
on the use of musical ditties is unlikely to appeal to the masses, but the
film certainly will not disappoint Coen fans and/or anyone looking for a
little variety in their cinematic diet. I for one enjoyed the film on the
whole, thought it could've used a little more structure and one or two less
characters, but appreciated its overall creative outlook. I also can't seem
to get that darn hit song from the movie out of my head, so I guess that's
always a good sign. Love 'em or hate 'em, they're the Coen bros and they're
here to stay.

Little Known Facts about this film and its stars: (taken from the IMDb)
The title of this movie is taken from the title of the film the director
wants to make in Preston Sturgess' Sullivan's Travels. Homage is paid to
that film via a scene in which a lot of chain-gang members are brought to
watch a movie in a theater.
This film is based on Homer's "The Odyssey" and several references can be
found throughout: The names of George Clooney and Holly Hunter's characters
(Ulysses & Penelope), the one-eyed Big Dan as the Cyclops, the three girls
by the river as the Sirens and the old-man disguises at the end of the film.
Stephen Root, who plays the radio station owner in this film, also played a
radio station owner in the TV show "Newsradio".
The character of Tommy Johnson is based on famed blues guitarist Robert
Johnson who, according to folk legend, sold his soul to the Devil at the
crossroads for his legendary talent.

Review Date: November 30, 2000
Director: Joel Coen
Writers: Joel Coen and Ethan Coen
Producer: Ethan Coen
Actors: George Clooney as Everett Ulysses McGill
John Turturro as Pete Hogwallop
Tim Blake Nelson as Delmar O'Donnel
Genre: Comedy
Year of Release: 2000
------------------------------------
JoBlo's Movie Emporium
http://www.joblo.com/
------------------------------------
(c) 2000 Berge Garabedian

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

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

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

Broken URLs inthe reviews are the responsibility of the author.

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

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


text:
// Windows/Control/Window2.h

#ifndef __WINDOWS_CONTROL_WINDOW2_H
#define __WINDOWS_CONTROL_WINDOW2_H

#include "Windows/Window.h"
#include "Windows/Defs.h"

#ifndef _WIN32
typedef void * WNDPROC;
typedef void * CREATESTRUCT;
typedef struct
{
	HWND  hwndFrom;

	UINT  code;
#define NM_DBLCLK       1
#define LVN_ITEMCHANGED 2
#define LVN_COLUMNCLICK 3
#define CBEN_BEGINEDIT  10
#define CBEN_ENDEDITW   11

} NMHDR;
typedef NMHDR * LPNMHDR;

typedef struct tagNMLISTVIEW
{
    NMHDR hdr;
    INT iItem;
    INT iSubItem;
    UINT uNewState;
    UINT uOldState;
    // UINT uChanged;
    // POINT ptAction;
    LPARAM  lParam;
} NMLISTVIEW, *LPNMLISTVIEW;

typedef void * LPNMITEMACTIVATE;

#define NM_RCLICK 1234 /* FIXME */

// FIXME
#define WM_CREATE 1
#define WM_COMMAND 2
#define WM_NOTIFY 3
#define WM_DESTROY 4
#define WM_CLOSE 5

#define HIWORD(l)              ((WORD)((DWORD_PTR)(l) >> 16))
#define LOWORD(l)              ((WORD)((DWORD_PTR)(l) & 0xFFFF))

#endif

namespace NWindows {
namespace NControl {

class CWindow2 // : public CWindow
{
  // LRESULT DefProc(UINT message, WPARAM wParam, LPARAM lParam);
public:
  // CWindow2(HWND newWindow = NULL): CWindow(newWindow){};
  CWindow2() {}
  virtual ~CWindow2() {}

#ifdef _WIN32
  bool CreateEx(DWORD exStyle, LPCTSTR className,
      LPCTSTR windowName, DWORD style,
      int x, int y, int width, int height,
      HWND parentWindow, HMENU idOrHMenu,
      HINSTANCE instance);

  #ifndef _UNICODE
  bool CreateEx(DWORD exStyle, LPCWSTR className,
      LPCWSTR windowName, DWORD style,
      int x, int y, int width, int height,
      HWND parentWindow, HMENU idOrHMenu,
      HINSTANCE instance);
  #endif
#endif

  virtual LRESULT OnMessage(UINT message, WPARAM wParam, LPARAM lParam);
  virtual bool OnCreate(CREATESTRUCT * /* createStruct */) { return true; }
  // virtual LRESULT OnCommand(WPARAM wParam, LPARAM lParam);
  virtual bool OnCommand(WPARAM wParam, LPARAM lParam, LRESULT &result);
  virtual bool OnCommand(int code, int itemID, LPARAM lParam, LRESULT &result);
  virtual bool OnSize(WPARAM /* wParam */, int /* xSize */, int /* ySize */) { return false; }
  virtual bool OnNotify(UINT /* controlID */, LPNMHDR /* lParam */, LRESULT & /* result */) { return false; }
  virtual void OnDestroy() { /* FIXME PostQuitMessage(0); */ }
  virtual void OnClose() { /* FIXME Destroy(); */ }
  /*
  virtual LRESULT  OnHelp(LPHELPINFO helpInfo) { OnHelp(); };
  virtual LRESULT  OnHelp() {};
  virtual bool OnButtonClicked(int buttonID, HWND buttonHWND);
  virtual void OnOK() {};
  virtual void OnCancel() {};
  */

#ifdef _WIN32
  LONG_PTR SetMsgResult(LONG_PTR newLongPtr )
    { return SetLongPtr(DWLP_MSGRESULT, newLongPtr); }
  LONG_PTR GetMsgResult() const
    { return GetLongPtr(DWLP_MSGRESULT); }
#endif
};

}}

#endif


text:
<!-- /* a stylesheet to include in our *.md-based html. */ -->
<!-- /* please leave the begin and end style tags, they let us include the text of this file "inline" in html documents */-->
<style>
#TOC { font-family: 'droid sans',helvetica,sans serif; font-size: 0.8em; position: fixed; right: 0em; top: 0em; background: #e5e5ee; -webkit-box-shadow: 0 0 1em #777777; -moz-box-shadow: 0 0 1em #777777; -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; text-align: left; max-height: 80%; z-index: 200; width: 7em; white-space:nowrap; overflow:hidden; padding-top: 3em; opacity: 0.9; }
#TOC:before { content:"Contents"; font-weight: bold; text-align:right; align:right; display:block; position:fixed; right: 1.5em; top: 1em; background: #e5e5ee; opacity:0.9; }
#TOC:hover { width: auto; padding-right:2em; max-width:80%; overflow:auto !important; opacity:1.0; }
#TOC ul { margin: 0 0 0 1em; padding: 0; }
#TOC li { padding: 0; margin: 1px; list-style: none; overflow:hidden; text-overflow: ellipsis; }

html { font-size: 100%; overflow-y: scroll; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; }

body{ color:#444; font-family:Georgia, Palatino, 'Palatino Linotype', Times, 'Times New Roman', serif; font-size:12px; line-height:1.5em; padding:1em; margin:auto; max-width:48em; background:#fefefe; }

a { color: #0645ad; text-decoration:none;}
a:visited { color: #0b0080; }
a:hover { color: #06e; }
a:active { color:#faa700; }
a:focus { outline: thin dotted; }
a:hover, a:active { outline: 0; }

::-moz-selection {background:rgba(255,255,0,0.3);color:#000}
::selection {background:rgba(255,255,0,0.3);color:#000}

a::-moz-selection {background:rgba(255,255,0,0.3);color:#0645ad}
a::selection {background:rgba(255,255,0,0.3);color:#0645ad}

p { margin:1em 0; }
p.caption { font-style: italic; text-align: right; }

img { max-width:100%; }

h1,h2,h3,h4,h5,h6 { font-weight:normal; color:#111; line-height:1em; }
h4,h5,h6{ font-weight: bold; }
h1 { font-size:2.5em; }
h2 { font-size:2em; }
h3 { font-size:1.5em; }
h4 { font-size:1.2em; }
h5 { font-size:1em; }
h6 { font-size:0.9em; }

blockquote{ color:#666666; margin:0; padding-left: 3em; border-left: 0.5em #eee solid; }
hr { display: block; height: 2px; border: 0; border-top: 1px solid #aaa;border-bottom: 1px solid #eee; margin: 1em 0; padding: 0; }
pre, code, kbd, samp { font-family: 'droid sans mono slashed', 'droid sans mono', monospace, monospace; }
pre { padding:2px; background:#333; color:#9e9; border:1px solid #444; overflow:hidden; text-overflow: ellipsis;}
pre:hover { overflow:visible; width: auto; }
pre:hover code {  background:#333; }
code { padding:2px; background: #f5f5ff; border:1px solid #e5e5ee; font-size:0.9em; }
code.url { padding:2px;  border:none; background:none; font-family:Georgia, Palatino, 'Palatino Linotype', Times, 'Times New Roman', serif; }
pre code { border: none; background:#333; }

b, strong { font-weight: bold; }
dfn { font-style: italic; }
ins { background: #ff9; color: #000; text-decoration: none; }
mark { background: #ff0; color: #000; font-style: italic; font-weight: bold; }
sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; }
sup { top: -0.5em; }
sub { bottom: -0.25em; }
ul, ol { margin: 1em 0; padding: 0 0 0 2em; }
li p:last-child { margin:0 }
dd { margin: 0 0 0 2em; }
img { border: 0; -ms-interpolation-mode: bicubic; vertical-align: middle; }
table { border-collapse: collapse; border-spacing: 0; }
td { vertical-align: top; }

/* TODO: this could use a better color scheme */
code > span.kw { color: #dd7522; font-weight: bold; }
code > span.dt { color: #dd7522; }
code > span.dv { color: #669933; }
code > span.bn { color: #eddd3d; }
code > span.fl { color: #eddd3d; }
code > span.ch { color: #eddd3d; }
code > span.st { color: #669933; }
code > span.co { color: grey; font-style: italic; }
code > span.al { color: #ff0000; font-weight: bold; }
code > span.fu { color: #dd7522; }
code > span.ot { color: #007020; }
code > span.er { color: #ff0000; font-weight: bold; }

@media only screen and (min-width: 480px) { body{font-size:14px;} }

@media only screen and (min-width: 768px) { body{font-size:16px;} }

@media print {
  #TOC { display:none; }
  * { background: transparent !important; color: black !important; filter:none !important; -ms-filter: none !important; }
  body{font-size:12pt; max-width:100%;}
  a, a:visited { text-decoration: none; }
  hr { height: 1px; border:0; border-bottom:1px solid black; }
  a[href]:after { content: " (" attr(href) ")"; }
  abbr[title]:after { content: " (" attr(title) ")"; }
  .ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; }
  pre, blockquote { border: 1px solid #999; padding-right: 1em; page-break-inside: avoid; }
  pre  { font-size: 0.8em; }
  tr, img { page-break-inside: avoid; }
  img { max-width: 100% !important; }
  @page :left { margin: 15mm 20mm 15mm 10mm; }
  @page :right { margin: 15mm 10mm 15mm 20mm; }
  p, h2, h3 { orphans: 3; widows: 3; }
  h2, h3 { page-break-after: avoid; }
}
</style>


text:
#include "AverageOptimizer.h"
#include "FirstOrderOptimizer.h"
#include "OptimizerWithRegularizer.h"

namespace paddle {

// creator for AverageOptimizer
ParameterOptimizer* sgdOptimizerCreate(const OptimizationConfig& optConfig,
                                       const ParameterConfig& paraConfig,
                                       bool isParameterSparse,
                                       bool inPserver) {
  ParameterOptimizer* optimizer = OptimizerWithRegularizer::create(
      optConfig, paraConfig, isParameterSparse, inPserver);
  return AverageOptimizer::create(
      optConfig, optimizer, isParameterSparse, inPserver /*useParameterApply*/);
}

std::vector<ParameterType> sgdOptimizerGetTypes(
    const OptimizationConfig& optConfig, bool inPserver) {
  std::unique_ptr<ParameterOptimizer> optimizer;
  optimizer.reset(
      AverageOptimizer::create(optConfig,
                               ParameterOptimizer::create(optConfig, inPserver),
                               false /*isParameterSparse*/,
                               inPserver));
  CHECK(optimizer) << "fail to create optimizer: "
                   << optConfig.learning_method();
  return optimizer->getParameterTypes();
}

bool useApplyInPserver(const OptimizationConfig& optConfig) {
  auto types = sgdOptimizerGetTypes(optConfig, true /*inPserver*/);
  return types.end() != std::find(types.begin(), types.end(), PARAMETER_APPLY);
}

}  // namespace paddle


text:
import unittest
import sys, os, time
import json

sys.path.append('./')

import browser.firefox as firefox
import cspages.login.loginpage as loginpage
import common.shared as shared
from cstests.smoketests.smokecfg import smokecfg

# from cstests.smoketests import smokecfg as smokecfg

class TestCSLoginLogout(unittest.TestCase):
    def setUp(self):
        # Create a new instance of the Firefox browser
        self.browser = firefox.Firefox('firefox')

    def tearDown(self):
        self.browser.quit_browser()

    def test_success(self):
        self.browser.set_url(smokecfg['cssite'])
        self.loginpage = loginpage.LoginPage(self.browser.get_browser())

        # wait for at most 5 minutes, in case we have an anoyingly slow server
        shared.Shared.wait_for_element(self.browser.get_browser(), 'class_name', 'select-language', waittime = 300)

        # language selection must be done before username and password
        self.loginpage.set_language(smokecfg['language'])

        shared.Shared.wait_for_element(self.browser.get_browser(), 'class_name', 'fields', waittime = 300)

        self.loginpage.set_username(smokecfg['new user account']['username'])
        self.loginpage.set_password(smokecfg['new user account']['password'])
        self.loginpage.login()

        time.sleep(5)

        self.loginpage.logout(directly_logout = True)
        shared.Shared.wait_for_element(self.browser.browser, 'class_name', 'login', waittime = 300)

if __name__ == '__main__':
    unittest.main()


text:
A demo for importing a spreadsheet into mysql database with ruby
#requirement
spreadsheet (1.1.1)

mysql2 (0.4.3)

mysql server version 5.6.23

ruby 2.2.2

It is used to process the spreadsheet(.xls) data and import them into a table in the mysql database

The spreadsheet data and the result: http://pan.baidu.com/s/1hroOCXu

Maybe it is necessary to modify the TransferToDB#initialize function for its static path


text:
class AddPositionToProjectFavorites < ActiveRecord::Migration[4.2]
  def change
    add_column :project_favorites, :position, :integer, null: false, default: 0
  end
end


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

<title>Uses of Class com.microsoft.windowsazure.mobileservices.notifications.Registration</title>
<meta name="date" content="2014-08-12">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.microsoft.windowsazure.mobileservices.notifications.Registration

Packages that use Registration

Package
Description

com.microsoft.windowsazure.mobileservices.notifications

Uses of Registration in com.microsoft.windowsazure.mobileservices.notifications

Subclasses of Registration in com.microsoft.windowsazure.mobileservices.notifications

Modifier and Type
Class and Description

class
GcmNativeRegistration

Represents GCM native registration

class
GcmTemplateRegistration

Represents GCM template registration

class
TemplateRegistration

Represents a template registration

Methods in com.microsoft.windowsazure.mobileservices.notifications that return types with arguments of type Registration

Modifier and Type
Method and Description

com.google.common.util.concurrent.ListenableFuture<Registration>
MobileServicePush.register(java.lang.String pnsHandle,
        java.lang.String[] tags)

Registers the client for native notifications with the specified tags

Methods in com.microsoft.windowsazure.mobileservices.notifications with parameters of type Registration

Modifier and Type
Method and Description

void
RegistrationCallback.onRegister(Registration registration,
          java.lang.Exception exception)

Method to execute when the register is finished

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
# [gulp-nunjucks-with-env](https://github.com/avcs06/gulp-nunjucks-with-env)
> Use [Nunjucks](http://jlongster.github.io/nunjucks/) Environment Class to get more control

*Issues with the output should be reported on the Nunjucks [issue tracker](https://github.com/jlongster/nunjucks/issues).*

## Install

Install with [npm](https://npmjs.org/package/gulp-nunjucks-with-env)

```
npm install --save-dev gulp-nunjucks-with-env
```

## Example : Using Environment Class

```js
var gulp = require('gulp');
var nunjucksRender = require('gulp-nunjucks-with-env');

var environment = nunjucksRender.nunjucks.configure(['src/templates/']);
environment.addFilter('stringify', function(obj) {
    return JSON.stringify(obj);
});
nunjucksRender = nunjucksRender.bind(nunjucksRender,environment);

gulp.task('default', function () {
	return gulp.src('src/templates/*.html')
		.pipe(nunjucksRender())
		.pipe(gulp.dest('dist'));
});
```

Check [Nunjucks API](https://mozilla.github.io/nunjucks/api.html#environment) for more information on Environment Class

*Note: To keep Nunjucks render from eating up all your ram, make sure to specify your watch path. ```nunjucksRender.nunjucks.configure(['src/path/to/templates/']);``` This will also allow you to define your paths relatively.*

## Example : Using with gulp data

```js
var gulp = require('gulp');
var nunjucksRender = require('gulp-nunjucks-render');
var data = require('gulp-data');

function getDataForFile(file){
    return {
        example: 'data loaded for ' + file.relative
    };
}

gulp.task('default', function () {
	nunjucksRender.nunjucks.configure(['src/templates/']);
	return gulp.src('src/templates/*.html')
	  .pipe(data(getDataForFile))
		.pipe(nunjucksRender())
		.pipe(gulp.dest('dist'));
});
```

## Example : Using with pass by reference globals

```js
var gulp = require('gulp');
var nunjucksRender = require('gulp-nunjucks-with-env');

var environment = nunjucksRender.nunjucks.configure(['src/templates/']);
environment.addFilter('stringify', function(obj) {
    return JSON.stringify(obj);
});
var files = {widgetFiles : []};
templateEngine = templateEngine.bind(templateEngine,environment,{},files);

gulp.task('task', function () {
	return gulp.src('src/templates/*.html')
		.pipe(nunjucksRender())
		.pipe(gulp.dest('dist'));
});

gulp.task('newtask',['task'],function() {
  return gulp.src(files.widgetFiles)
		.pipe(/*Some Task*/)
});
```

## API

### nunjucksRender(environment, context, passByReferenceGlobals)

<b>environment (optional) `Environment Class` : </b>
  [`Environment Class`](https://mozilla.github.io/nunjucks/api.html#environment)

<b>context (optional) `Object` : </b>
  Same context as [`nunjucks.render()`](http://jlongster.github.io/nunjucks/api.html#render)
  *Note : You will have to pass empty object {}, if you want to use passByReferenceGlobals*

<b>passByReferenceGlobals (optional) `Object` : </b>
  Parameters from this object will be added to context through pass by reference rather than pass by value

<b>Example : </b>
```
nunjucksRender(environment,{css_path: 'http://company.com/css/'});
```
or
```
nunjucksRender({css_path: 'http://company.com/css/'});
```

For the following template
```
<link rel="stylesheet" href="{{ css_path }}test.css" />
```

Would render
```
<link rel="stylesheet" href="http://company.com/css/test.css" />
```

## License

MIT © [AvcS](http://www.avcs-tips.com)

## Shout-outs

[Sindre Sorhus](http://sindresorhus.com/) who wrote the original [gulp-nunjucks](https://www.npmjs.org/package/gulp-nunjucks) for precompiling Nunjucks templates.

[Carlos G. Limardo](http://limardo.org) updated this to render instead of precompile in [gulp-nunjucks-render](https://www.npmjs.org/package/gulp-nunjucks-render)

I updated this to facilitate using of Environment Class for more control


text:
ARG MULTIARCH_ARCH
FROM multiarch/debian-debootstrap:${MULTIARCH_ARCH}-jessie

MAINTAINER Scaleway <opensource@scaleway.com> (@scaleway)

# Environment
ENV DEBIAN_FRONTEND=noninteractive SCW_BASE_IMAGE=scaleway/debian:jessie

# Configure aptitude
# Note that, `${ARCH}` is set in the multiarch/debian-debootstrap image
COPY ./overlay/etc/apt/ ./overlay-${ARCH}*/etc/apt/ /etc/apt/

# Adding and calling builder-enter
COPY ./overlay-base/usr/local/sbin/scw-builder-enter /usr/local/sbin/
RUN /bin/sh -xe /usr/local/sbin/scw-builder-enter

# Install packages
RUN apt-get -q update && \
    apt-get -y -qq upgrade && \
    apt-get install -y -qq \
	bash-completion \
	bc \
	bootlogd \
	ca-certificates \
	cron \
	curl \
	dbus \
	dstat \
	ethstatus \
	file \
	fio \
	haveged \
	htop \
	ifupdown \
	ioping \
	iotop \
	iperf \
	iptables \
	iputils-ping \
	isc-dhcp-client \
	less \
	libnss-myhostname \
	linux-image-"$(dpkg --print-architecture | sed 's/armhf/armmp/')" \
	locales \
	locate \
	lsb-release \
	lsof \
	make \
	man-db \
	mg \
	module-init-tools \
	mosh \
	nano \
	net-tools \
	netcat \
	ntp \
	ntpdate \
	python-apt \
	python-yaml \
	rsync \
	rsyslog \
	screen \
	shunit2 \
	socat \
	ssh \
	sudo \
	sysstat \
	systemd-sysv \
	tcpdump \
	tmux \
	uuid-runtime \
	vim \
	wget \
	whiptail \
	grub-efi-$(dpkg --print-architecture | sed 's/armhf/arm/') \
    unattended-upgrades \
    && apt-get clean

# Default target
RUN systemctl set-default multi-user

# Enable update-motd.d support
RUN rm -f /etc/motd && ln -s /var/run/motd /etc/motd

# Patch rootfs
COPY ./overlay/ ./overlay-base/ ./overlay-${ARCH}*/ /

# Configure locales
RUN locale-gen

# Configure Systemd
RUN systemctl preset --preset-mode=full $(cat /etc/systemd/system-preset/*scw*.preset | cut -d' ' -f2 | tr '\n' ' ')
RUN systemctl disable \
	systemd-modules-load.service \
	systemd-update-utmp-runlevel \
	proc-sys-fs-binfmt_misc.automount \
	kmod-static-nodes.service

RUN ln -s /etc/systemd/system/networking.service /etc/systemd/system/multi-user.target.wants/networking.service

RUN rm -f /sbin/init \
 && ln -sf ../lib/systemd/systemd /sbin/init

# Fix permissions
RUN chmod 755 /etc/default

# Clean rootfs from image-builder
RUN /usr/local/sbin/scw-builder-leave