text:
package com.intel.analytics.bigdl.dllib.common

import java.io.{InputStream, ObjectInputStream, ObjectStreamClass}

import com.intel.analytics.bigdl.dllib.utils.Log4Error

final class CheckedObjectInputStream(checkedClass: Class[_], inputStream: InputStream)
  extends ObjectInputStream(inputStream) {

  private var firstCall: Boolean = true

  @throws[ClassNotFoundException]("if no associated class can be found")
  @throws[UnsupportedOperationException]("if the identified class is not valid " +
    "for the declared serialization classes")
  override protected def resolveClass(objectStreamClass: ObjectStreamClass): Class[_] = {
    if (firstCall) {
      firstCall = false
      val resolvedClass = super.resolveClass(objectStreamClass)
      if (checkedClass.isAssignableFrom(resolvedClass)) {
        resolvedClass
      } else {
        Log4Error.invalidOperationError(false, s"Illegal serialization of class:" +
          s" $resolvedClass. Supported objects must be instances of ${checkedClass.getName}")
        null
      }
    } else {
      super.resolveClass(objectStreamClass)
    }
  }
}


text:
package org.apache.cloudstack.api.response;

import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseResponse;
import org.apache.cloudstack.api.EntityReference;

import com.cloud.serializer.Param;
import com.cloud.storage.Volume;
import com.google.gson.annotations.SerializedName;

@SuppressWarnings("unused")
public class VolumeDetailResponse extends BaseResponse{
    @SerializedName(ApiConstants.ID)
    @Param(description = "ID of the volume")
    private String id;

    @SerializedName(ApiConstants.NAME)
    @Param(description = "name of the volume detail")
    private String name;

    @SerializedName(ApiConstants.VALUE)
    @Param(description = "value of the volume detail")
    private String value;

    @SerializedName(ApiConstants.DISPLAY_VOLUME) @Param(description="an optional field whether to the display the volume to the end user or not.")
    private Boolean displayVm;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getName() {

        return name;
    }

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

    public Boolean getDisplayVm() {
        return displayVm;
    }

    public void setDisplayVm(Boolean displayVm) {
        this.displayVm = displayVm;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

require_once(DIR_INC.'modules/tangra_cms/pages/vpage/vpt/vpage_manage_wp_abs.class.php');
require_once(DIR_INC.'modules/tangra_cms/classes/ci/ci_types/tcms_ci_normal_ci_dbc.class.php');
require_once(DIR_INC.'modules/tangra_cms/classes/settings/tcms_settings_images_dbc.class.php');
require_once(DIR_INC.'modules/tangra_cms/classes/ci/tcms_ci_image_dbc.class.php');
require_once(DIR_INC.'modules/tangra_cms/classes/ci/tcms_ci_attachment_dbc.class.php');

class VPage_Man_Product_WP extends VPage_Manage_WP_Abs {
	protected function _manage() {
		$vpage = $this->get_vpage();

		$title = $this->load_system_attribute('title');
		$this->export('title', $title);

		$meta_description = $this->load_system_attribute('meta_description');
		$this->export('meta_description', $meta_description);

		$content_ci = $this->load_content_item('content');
		if ($content_ci) {
			$ci_normal_ci = new TCMS_CI_Normal_CI_DBC();
			$dbc = $this->get_dbc();
			if ($ci_normal_ci->load_by_id($dbc, $content_ci->get_ci_id())) {
				$this->export('content', $this->prepare_normal_ci($ci_normal_ci));
				$this->export_images($dbc, $content_ci->get_id());
				$this->export_attachments($dbc, $content_ci->get_id());
				$this->export('ci_id', $content_ci->get_ci_id());
			}
		}

		$intro_ci = $this->load_content_item('intro');
		if ($intro_ci) {
			$ci_normal_ci = new TCMS_CI_Normal_CI_DBC();
			$dbc = $this->get_dbc();
			if ($ci_normal_ci->load_by_id($dbc, $intro_ci->get_ci_id())) {
				$this->export('intro', $this->prepare_normal_ci($ci_normal_ci));
			}
		}

		if ($title && $content_ci) {
			$this->export('can_go_online', 1);
		}

		$view = $this->get_view('default');

		return $view;
	}

	private function prepare_normal_ci(TCMS_CI_Normal_CI_DBC $ci_normal_ci) {
		$ret['id'] = $ci_normal_ci->get_ci()->get_id();
		$ret['content'] = $ci_normal_ci->get_content()->get_value();
		$ret['created'] = $ci_normal_ci->get_ci()->get_created();

		return $ret;
	}

	protected function export_images(DB_Connection $dbc, $ci_id) {
		tangra_if_not_int_throw_e($ci_id);

		$ci_images = TCMS_CI_Image_DBC::load_ci_images($dbc, $ci_id);
		$images = array();
		foreach ($ci_images as  $cii) {
			$tmp = new TCMS_Image_DBC();
			if ($tmp->load_by_id($dbc, $cii->get_image())) {
				$images[] = clone $tmp;
			}
		}
		$this->export('images', $images);

		$settings_images = new TCMS_Settings_Images_DBC();
		$settings_images->load_by_id($dbc, 1);
		$this->export('t1_width', $settings_images->get_thumbnail1_size_x());
		$this->export('t1_height', $settings_images->get_thumbnail1_size_y());
		$this->export('t2_width', $settings_images->get_thumbnail2_size_x());
		$this->export('t2_height', $settings_images->get_thumbnail2_size_y());
	}

	protected function export_attachments(DB_Connection $dbc, $ci_id) {
		tangra_if_not_int_throw_e($ci_id);

		$ci_attachments = TCMS_CI_Attachment_DBC::load_ci_attachments($dbc, $ci_id);
		$attachments = array();
		foreach ($ci_attachments as  $ci) {
			$tmp = new TCMS_Attachment_DBC();
			if ($tmp->load_by_id($dbc, $ci->get_attachment())) {
				$attachments[] = clone $tmp;
			}
		}
		$this->export('attachments', $attachments);
	}
}


text:
using NUnit.Framework;

using SharpRaven.Logging.Filters;

namespace SharpRaven.UnitTests.Logging
{
    [TestFixture]
    public class PhoneNumberFilterTests : FilterTestsBase<PhoneNumberFilter>
    {
        [Test]
        public void JsonKeyContainingPhoneNumber_IsNotScrubbed()
        {
            const string json =
                @"{""culprit"":""SharpRaven.UnitTests.Helper in FirstLevelException"",""event_id55518231234e2400d82f11c490683c2d2"",""exception"":[],""user"": {""username"":""asbjornu""}}";

            var output = Filter.Filter(json);

            Assert.That(output, Is.StringContaining("event_id55518231234e2400d82f11c490683c2d2"));
        }

        [Test]
        public void MatchingPhoneNumber_IsScrubbed()
        {
            MatchingValueIsScrubbed("55518231234");
        }

        [Test]
        public void NonMatchingPhoneNumber_IsNotScrubbed()
        {
            NonMatchingValueIsNotScrubbed("1531");
        }
    }
}


text:
'use strict';
module.exports = options =>{
    return async function test(ctx,next){
        await next();
        if(ctx.request.url == '/test/middlewares'){
            ctx.body = {
                data: false
            };
            // ctx.redirect('/test');

        }else{
        }

    }
}


text:
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.AspNetCore.Components.Web.Infrastructure;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.AspNetCore.Components.WebAssembly.Services;
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
using static Microsoft.AspNetCore.Internal.LinkerFlags;

namespace Microsoft.AspNetCore.Components.WebAssembly.Rendering;

/// <summary>
/// Provides mechanisms for rendering <see cref="IComponent"/> instances in a
/// web browser, dispatching events to them, and refreshing the UI as required.
/// </summary>
internal sealed partial class WebAssemblyRenderer : WebRenderer
{
    private readonly ILogger _logger;

    public WebAssemblyRenderer(IServiceProvider serviceProvider, ILoggerFactory loggerFactory, JSComponentInterop jsComponentInterop)
        : base(serviceProvider, loggerFactory, DefaultWebAssemblyJSRuntime.Instance.ReadJsonSerializerOptions(), jsComponentInterop)
    {
        // The WebAssembly renderer registers and unregisters itself with the static registry
        RendererId = RendererRegistry.Add(this);
        _logger = loggerFactory.CreateLogger<WebAssemblyRenderer>();

        ElementReferenceContext = DefaultWebAssemblyJSRuntime.Instance.ElementReferenceContext;
    }

    public override Dispatcher Dispatcher => NullDispatcher.Instance;

    public Task AddComponentAsync([DynamicallyAccessedMembers(Component)] Type componentType, ParameterView parameters, string domElementSelector)
    {
        var componentId = AddRootComponent(componentType, domElementSelector);
        return RenderRootComponentAsync(componentId, parameters);
    }

    protected override void AttachRootComponentToBrowser(int componentId, string domElementSelector)
    {
        DefaultWebAssemblyJSRuntime.Instance.InvokeVoid(
            "Blazor._internal.attachRootComponentToElement",
            domElementSelector,
            componentId,
            RendererId);
    }

    /// <inheritdoc />
    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        RendererRegistry.TryRemove(RendererId);
    }

    /// <inheritdoc />
    protected override void ProcessPendingRender()
    {
        // For historical reasons, Blazor WebAssembly doesn't enforce that you use InvokeAsync
        // to dispatch calls that originated from outside the system. Changing that now would be
        // too breaking, at least until we can make it a prerequisite for multithreading.
        // So, we don't have a way to guarantee that calls to here are already on our work queue.
        //
        // We do need rendering to happen on the work queue so that incoming events can be deferred
        // until we've finished this rendering process (and other similar cases where we want
        // execution order to be consistent with Blazor Server, which queues all JS->.NET calls).
        //
        // So, if we find that we're here and are not yet on the work queue, get onto it. Either
        // way, rendering must continue synchronously here and is not deferred until later.
        if (WebAssemblyCallQueue.IsInProgress)
        {
            base.ProcessPendingRender();
        }
        else
        {
            WebAssemblyCallQueue.Schedule(this, static @this => @this.CallBaseProcessPendingRender());
        }
    }

    private void CallBaseProcessPendingRender() => base.ProcessPendingRender();

    /// <inheritdoc />
    protected override Task UpdateDisplayAsync(in RenderBatch batch)
    {
#pragma warning disable CS0618 // Type or member is obsolete
        DefaultWebAssemblyJSRuntime.Instance.InvokeUnmarshalled<int, RenderBatch, object>(
            "Blazor._internal.renderBatch",
            RendererId,
            batch);
#pragma warning restore CS0618 // Type or member is obsolete

        if (WebAssemblyCallQueue.HasUnstartedWork)
        {
            // Because further incoming calls from JS to .NET are already queued (e.g., event notifications),
            // we have to delay the renderbatch acknowledgement until it gets to the front of that queue.
            // This is for consistency with Blazor Server which queues all JS-to-.NET calls relative to each
            // other, and because various bits of cleanup logic rely on this ordering.
            var tcs = new TaskCompletionSource();
            WebAssemblyCallQueue.Schedule(tcs, static tcs => tcs.SetResult());
            return tcs.Task;
        }
        else
        {
            // Nothing else is pending, so we can treat the renderbatch as acknowledged synchronously.
            // This lets upstream code skip an expensive code path and avoids some allocations.
            return Task.CompletedTask;
        }
    }

    /// <inheritdoc />
    protected override void HandleException(Exception exception)
    {
        if (exception is AggregateException aggregateException)
        {
            foreach (var innerException in aggregateException.Flatten().InnerExceptions)
            {
                Log.UnhandledExceptionRenderingComponent(_logger, innerException.Message, innerException);
            }
        }
        else
        {
            Log.UnhandledExceptionRenderingComponent(_logger, exception.Message, exception);
        }
    }

    private static partial class Log
    {
        [LoggerMessage(100, LogLevel.Critical, "Unhandled exception rendering component: {Message}", EventName = "ExceptionRenderingComponent")]
        public static partial void UnhandledExceptionRenderingComponent(ILogger logger, string message, Exception exception);
    }
}


text:
from collections import OrderedDict

import nnabla as nn

class Module(object):
    """Module mix-in for the parametric function classes.
    """

    def __init__(self):
        pass

    def get_parameters(self, grad_only=True):
        """Get parameters.
        Args:
            grad_only (bool, optional): Return parameters with `need_grad` option as `True`.
            If you set this option as `False`, All parameters are returned. Default is `True`.
        Returns:
            dict: The dictionary of parameter name (`str`) to Variable (:obj:`~nnabla.Variable`).
        """
        params = OrderedDict()

        for v in self.get_modules():
            if not isinstance(v, tuple):
                continue
            prefix, module = v
            for k, v in module.__dict__.items():
                if not isinstance(v, nn.Variable):
                    continue
                pname = k
                name = "{}/{}".format(prefix, pname)
                if grad_only and v.need_grad == False:
                    continue
                params[name] = v
        return params

    def get_modules(self, memo=None, prefix=""):
        """Get modules.

        This function is internally used as the helper method for other methods.

        Args:
            memo (set, optional): Module set in order to memorize to visit.
            prefix (str, optional): Prefix to a specific parameter name.

        Yields:
            `Module`: The module class.
        """
        if memo is None:
            memo = set()

        if self not in memo:
            memo.add(self)
            yield prefix, self
            for k, v in self.__dict__.items():
                if not isinstance(v, Module):
                    continue
                name, module = k, v
                submodule_prefix = "{}/{}".format(prefix,
                                                  name) if prefix != "" else name
                for m in module.get_modules(memo, submodule_prefix):
                    yield m

    def save_parameters(self, path, grad_only=False):
        """Save all parameters into a file with the specified format.

        Currently hdf5 and protobuf formats are supported.

        Args:
            path : path or file object
            grad_only (bool, optional): Return parameters with `need_grad` option as `True`.
        """
        params = self.get_parameters(grad_only=grad_only)
        nn.save_parameters(path, params)

    def load_parameters(self, path):
        """Load parameters from a file with the specified format.

        Args:
            path : path or file object
        """
        nn.load_parameters(path)
        for v in self.get_modules():
            if not isinstance(v, tuple):
                continue
            prefix, module = v
            for k, v in module.__dict__.items():
                if not isinstance(v, nn.Variable):
                    continue
                pname = k
                name = "{}/{}".format(prefix, pname)
                # Substitute
                param0 = v
                param1 = nn.parameter.pop_parameter(name)
                if param0 is None:
                    raise ValueError(
                        "Model does not have {} parameter.".format(name))
                param0.d = param1.d.copy()
                nn.logger.info("`{}` loaded.)".format(name))


text:
package org.aikodi.chameleon.core.variable;

import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.oo.expression.Expression;
import org.aikodi.chameleon.oo.type.DeclarationWithType;
import org.aikodi.chameleon.oo.type.Type;
import org.aikodi.chameleon.oo.type.TypeReference;

/**
 * An interface for variables.
 *
 * @author Marko van Dooren
 */
public interface Variable extends DeclarationWithType {

  /**
   * @return The initialization expression of this variable.
   */
	public Expression getInitialization();

	/**
	 * Set the initialization expression of this variable.
	 *
	 * @param expression The new initialization expression of this variable.
	 */
	public void setInitialization(Expression expression);

  public TypeReference getTypeReference();

  public void setTypeReference(TypeReference ref);

  /**
   * @return the type of this variable.
   *
   * @throws LookupException An error occur while looking up the type of
   *         this variable.
   */
  public Type getType() throws LookupException;

}


text:
@interface DCHEventOperationTicket ()

@property (nonatomic, copy) id <DCHEvent> event;
@property (nonatomic, weak) id eventHandler;

@end

@implementation DCHEventOperationTicket

@synthesize event = _event;
@synthesize eventHandler = _eventHandler;
@synthesize working = _working;
@synthesize canceled = _canceled;
@synthesize finished = _finished;

- (void)dealloc {
    do {
        self.eventHandler = nil;
        self.event = nil;
    } while (NO);
}

- (instancetype)initWithEvent:(id <DCHEvent>)event andHandler:(id)handler {
    if (!event || !handler) {
        return nil;
    }
    self = [self init];
    if (self) {
        self.event = event;
        self.eventHandler = handler;
    }
    return self;
}

- (NSString *)UUID {
    return [self dch_createMemoryID];
}

@end


text:
title: Descartes Rule of Signs
localeTitle: Regla de signos de Descartes
---
## Regla de signos de Descartes

Esto es un talón. [Ayuda a nuestra comunidad a expandirla](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/descartes-rule-of-signs/index.md) .

[Esta guía rápida de estilo ayudará a asegurar que su solicitud de extracción sea aceptada](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Más información:


text:
package io.luna.game.service;

import com.google.common.base.Stopwatch;
import io.luna.game.model.EntityState;
import io.luna.game.model.World;
import io.luna.game.model.mob.Player;
import io.luna.game.model.mob.persistence.PlayerData;
import io.luna.game.service.LoginService.LoginRequest;
import io.luna.net.client.LoginClient;
import io.luna.net.codec.login.LoginRequestMessage;
import io.luna.net.codec.login.LoginResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;

import static io.luna.util.ThreadUtils.awaitTerminationUninterruptibly;
import static org.apache.logging.log4j.util.Unbox.box;

/**
 * A {@link AuthenticationService} implementation that handles login requests.
 *
 * @author lare96 <http://github.com/lare96>
 */
public final class LoginService extends AuthenticationService<LoginRequest> {

    /**
     * The asynchronous logger.
     */
    private static final Logger logger = LogManager.getLogger();

    /**
     * The login request model.
     */
    public static final class LoginRequest {

        /**
         * The player.
         */
        private final Player player;

        /**
         * The player's client.
         */
        private final LoginClient client;

        /**
         * The login request message.
         */
        private final LoginRequestMessage message;

        /**
         * The loaded data.
         */
        private volatile PlayerData loadedData;

        /**
         * Creates a new {@link LoginRequest}.
         *
         * @param player The player.
         * @param client The player's client.
         * @param message The login request message.
         */
        public LoginRequest(Player player, LoginClient client, LoginRequestMessage message) {
            this.player = player;
            this.client = client;
            this.message = message;
        }
    }

    /**
     * Creates a new {@link LoginService}.
     *
     * @param world The world.
     */
    public LoginService(World world) {
        super(world);
    }

    @Override
    void addRequest(String username, LoginRequest request) {
        if (!pending.containsKey(username)) {
            logger.trace("Sending {}'s login request to a worker...", username);
            workers.execute(() -> {
                var client = request.client;
                try {
                    var player = request.player;
                    var timer = Stopwatch.createStarted();
                    var loadedData = PERSISTENCE.load(username);
                    var response = client.getLoginResponse(loadedData, player.getPassword());
                    if (response == LoginResponse.NORMAL) {
                        if (pending.putIfAbsent(username, request) == null) {
                            request.loadedData = loadedData;
                            logger.debug("Finished loading {}'s data (took {}ms).", username, box(timer.elapsed().toMillis()));
                        } else {
                            client.disconnect();
                        }
                    } else {
                        // Load wasn't successful, disconnect with login response.
                        client.sendLoginResponse(player, response);
                    }
                } catch (Exception e) {
                    logger.error(new ParameterizedMessage("Issue servicing {}'s login request!", username), e);
                    client.disconnect();
                }
            });
        }
    }

    @Override
    boolean canFinishRequest(String username, LoginRequest request) {
        return true;
    }

    @Override
    void finishRequest(String username, LoginRequest request) {
        logger.trace("Sending {}'s final login response.", username);
        var player = request.player;
        var client = request.client;
        if (client.sendFinalLoginResponse(player, request.loadedData, request.message)) {
            world.getPlayers().add(player);
            player.setState(EntityState.ACTIVE);
            logger.info("{} has logged in.", username);
        }
    }

    @Override
    protected void shutDown() throws Exception {
        logger.trace("A shutdown of the login service has been requested.");
        workers.shutdownNow();
        awaitTerminationUninterruptibly(workers);
        logger.fatal("The login service has been shutdown.");
    }
}


text:
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "/dist/";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({

/***/ 0:
/***/ function(module, exports, __webpack_require__) {

	module.exports = __webpack_require__(137);

/***/ },

/***/ 3:
/***/ function(module, exports) {

	/* globals __VUE_SSR_CONTEXT__ */

	// this module is a runtime utility for cleaner component module output and will
	// be included in the final webpack user bundle

	module.exports = function normalizeComponent (
	  rawScriptExports,
	  compiledTemplate,
	  injectStyles,
	  scopeId,
	  moduleIdentifier /* server only */
	) {
	  var esModule
	  var scriptExports = rawScriptExports = rawScriptExports || {}

	  // ES6 modules interop
	  var type = typeof rawScriptExports.default
	  if (type === 'object' || type === 'function') {
	    esModule = rawScriptExports
	    scriptExports = rawScriptExports.default
	  }

	  // Vue.extend constructor export interop
	  var options = typeof scriptExports === 'function'
	    ? scriptExports.options
	    : scriptExports

	  // render functions
	  if (compiledTemplate) {
	    options.render = compiledTemplate.render
	    options.staticRenderFns = compiledTemplate.staticRenderFns
	  }

	  // scopedId
	  if (scopeId) {
	    options._scopeId = scopeId
	  }

	  var hook
	  if (moduleIdentifier) { // server build
	    hook = function (context) {
	      // 2.3 injection
	      context = context || (this.$vnode && this.$vnode.ssrContext)
	      // 2.2 with runInNewContext: true
	      if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
	        context = __VUE_SSR_CONTEXT__
	      }
	      // inject component styles
	      if (injectStyles) {
	        injectStyles.call(this, context)
	      }
	      // register component module identifier for async chunk inferrence
	      if (context && context._registeredComponents) {
	        context._registeredComponents.add(moduleIdentifier)
	      }
	    }
	    // used by ssr in case component is cached and beforeCreate
	    // never gets called
	    options._ssrRegister = hook
	  } else if (injectStyles) {
	    hook = injectStyles
	  }

	  if (hook) {
	    // inject component registration as beforeCreate hook
	    var existing = options.beforeCreate
	    options.beforeCreate = existing
	      ? [].concat(existing, hook)
	      : [hook]
	  }

	  return {
	    esModule: esModule,
	    exports: scriptExports,
	    options: options
	  }
	}

/***/ },

/***/ 10:
/***/ function(module, exports) {

	module.exports = require("element-ui/lib/utils/clickoutside");

/***/ },

/***/ 14:
/***/ function(module, exports) {

	module.exports = require("element-ui/lib/mixins/emitter");

/***/ },

/***/ 137:
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	exports.__esModule = true;

	var _dropdown = __webpack_require__(138);

	var _dropdown2 = _interopRequireDefault(_dropdown);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	/* istanbul ignore next */
	_dropdown2.default.install = function (Vue) {
	  Vue.component(_dropdown2.default.name, _dropdown2.default);
	};

	exports.default = _dropdown2.default;

/***/ },

/***/ 138:
/***/ function(module, exports, __webpack_require__) {

	var Component = __webpack_require__(3)(
	  /* script */
	  __webpack_require__(139),
	  /* template */
	  null,
	  /* styles */
	  null,
	  /* scopeId */
	  null,
	  /* moduleIdentifier (server only) */
	  null
	)

	module.exports = Component.exports

/***/ },

/***/ 139:
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	exports.__esModule = true;

	var _clickoutside = __webpack_require__(10);

	var _clickoutside2 = _interopRequireDefault(_clickoutside);

	var _emitter = __webpack_require__(14);

	var _emitter2 = _interopRequireDefault(_emitter);

	var _button = __webpack_require__(140);

	var _button2 = _interopRequireDefault(_button);

	var _buttonGroup = __webpack_require__(141);

	var _buttonGroup2 = _interopRequireDefault(_buttonGroup);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	exports.default = {
	  name: 'ElDropdown',

	  componentName: 'ElDropdown',

	  mixins: [_emitter2.default],

	  directives: { Clickoutside: _clickoutside2.default },

	  components: {
	    ElButton: _button2.default,
	    ElButtonGroup: _buttonGroup2.default
	  },

	  props: {
	    trigger: {
	      type: String,
	      default: 'hover'
	    },
	    menuAlign: {
	      type: String,
	      default: 'end'
	    },
	    type: String,
	    size: String,
	    splitButton: Boolean,
	    hideOnClick: {
	      type: Boolean,
	      default: true
	    }
	  },

	  data: function data() {
	    return {
	      timeout: null,
	      visible: false
	    };
	  },
	  mounted: function mounted() {
	    this.$on('menu-item-click', this.handleMenuItemClick);
	    this.initEvent();
	  },

	  watch: {
	    visible: function visible(val) {
	      this.broadcast('ElDropdownMenu', 'visible', val);
	    }
	  },

	  methods: {
	    show: function show() {
	      var _this = this;

	      clearTimeout(this.timeout);
	      this.timeout = setTimeout(function () {
	        _this.visible = true;
	      }, 250);
	    },
	    hide: function hide() {
	      var _this2 = this;

	      clearTimeout(this.timeout);
	      this.timeout = setTimeout(function () {
	        _this2.visible = false;
	      }, 150);
	    },
	    handleClick: function handleClick() {
	      this.visible = !this.visible;
	    },
	    initEvent: function initEvent() {
	      var trigger = this.trigger,
	          show = this.show,
	          hide = this.hide,
	          handleClick = this.handleClick,
	          splitButton = this.splitButton;

	      var triggerElm = splitButton ? this.$refs.trigger.$el : this.$slots.default[0].elm;

	      if (trigger === 'hover') {
	        triggerElm.addEventListener('mouseenter', show);
	        triggerElm.addEventListener('mouseleave', hide);

	        var dropdownElm = this.$slots.dropdown[0].elm;

	        dropdownElm.addEventListener('mouseenter', show);
	        dropdownElm.addEventListener('mouseleave', hide);
	      } else if (trigger === 'click') {
	        triggerElm.addEventListener('click', handleClick);
	      }
	    },
	    handleMenuItemClick: function handleMenuItemClick(command, instance) {
	      if (this.hideOnClick) {
	        this.visible = false;
	      }
	      this.$emit('command', command, instance);
	    }
	  },

	  render: function render(h) {
	    var _this3 = this;

	    var hide = this.hide,
	        splitButton = this.splitButton,
	        type = this.type,
	        size = this.size;

	    var handleClick = function handleClick(_) {
	      _this3.$emit('click');
	    };

	    var triggerElm = !splitButton ? this.$slots.default : h(
	      'el-button-group',
	      null,
	      [h(
	        'el-button',
	        {
	          attrs: { type: type, size: size },
	          nativeOn: {
	            'click': handleClick
	          }
	        },
	        [this.$slots.default]
	      ), h(
	        'el-button',
	        { ref: 'trigger', attrs: { type: type, size: size },
	          'class': 'el-dropdown__caret-button' },
	        [h(
	          'i',
	          { 'class': 'el-dropdown__icon el-icon-caret-bottom' },
	          []
	        )]
	      )]
	    );

	    return h(
	      'div',
	      { 'class': 'el-dropdown', directives: [{
	          name: 'clickoutside',
	          value: hide
	        }]
	      },
	      [triggerElm, this.$slots.dropdown]
	    );
	  }
	};

/***/ },

/***/ 140:
/***/ function(module, exports) {

	module.exports = require("element-ui/lib/button");

/***/ },

/***/ 141:
/***/ function(module, exports) {

	module.exports = require("element-ui/lib/button-group");

/***/ }

/******/ });


text:
drop table if exists tz_test, date_time_types;

create table tz_test (id int auto_increment, ts datetime, dtltz datetime with local time zone, dttz datetime with time zone);
set timezone '+10:00';
insert into tz_test(ts, dtltz, dttz) values (datetime'1980-10-01 2:00:00.999', datetimeltz'1980-10-01 2:00:00.999', datetimetz'1980-10-01 2:00:00.999 Asia/Yakutsk');

create table date_time_types(a date, b time, c timestamp, d datetime);
insert into date_time_types values(date'2000-10-10', time'12:13:14', timestamp'2019-12-10 3:40:56', datetime'2019-12-10 3:40:56.999');

set timezone 'Asia/Seoul';
--test: implicit conversion from date/time constant values to ts types
update tz_test set ts=date'1999-09-09', dtltz=date'1999-09-09', dttz=date'1999-09-09';
select * from tz_test order by 1;
update tz_test set ts=time'22:22:22', dtltz=time'22:22:22', dttz=time'22:22:22';
select * from tz_test order by 1;
update tz_test set ts=timestamp'1989-11-17 20:23:23', dtltz=timestamp'1989-11-17 20:23:23', dttz=timestamp'1989-11-17 20:23:23';
select * from tz_test order by 1;
update tz_test set ts=datetime'2010-10-23 05:59:59.999', dtltz=datetime'2010-10-23 05:59:59.999', dttz=datetime'2010-10-23 05:59:59.999';
select * from tz_test order by 1;

--test: implicit conversion from date/time types to ts types
update tz_test set ts=(select a from date_time_types), dtltz=(select a from date_time_types), dttz=(select a from date_time_types);
select * from tz_test order by 1;
update tz_test set ts=(select b from date_time_types), dtltz=(select b from date_time_types), dttz=(select b from date_time_types);
select * from tz_test order by 1;
update tz_test set ts=(select c from date_time_types), dtltz=(select c from date_time_types), dttz=(select c from date_time_types);
select * from tz_test order by 1;
update tz_test set ts=(select d from date_time_types), dtltz=(select d from date_time_types), dttz=(select d from date_time_types);
select * from tz_test order by 1;

drop table tz_test, date_time_types;

set timezone 'Asia/Seoul';


text:
package app

import (
	// This file exists to force the desired plugin implementations to be linked.
	// This should probably be part of some configuration fed into the build for a
	// given binary target.

	"fmt"

	"k8s.io/kubernetes/cmd/kube-controller-manager/app/options"

	// Cloud providers
	_ "k8s.io/kubernetes/pkg/cloudprovider/providers"

	// Volume plugins
	"k8s.io/kubernetes/pkg/cloudprovider"
	"k8s.io/kubernetes/pkg/cloudprovider/providers/aws"
	"k8s.io/kubernetes/pkg/cloudprovider/providers/gce"
	"k8s.io/kubernetes/pkg/cloudprovider/providers/openstack"
	"k8s.io/kubernetes/pkg/util/io"
	"k8s.io/kubernetes/pkg/volume"
	"k8s.io/kubernetes/pkg/volume/aws_ebs"
	"k8s.io/kubernetes/pkg/volume/cinder"
	"k8s.io/kubernetes/pkg/volume/gce_pd"
	"k8s.io/kubernetes/pkg/volume/host_path"
	"k8s.io/kubernetes/pkg/volume/nfs"

	"github.com/golang/glog"
)

// ProbeRecyclableVolumePlugins collects all persistent volume plugins into an easy to use list.
func ProbeRecyclableVolumePlugins(flags options.VolumeConfigFlags) []volume.VolumePlugin {
	allPlugins := []volume.VolumePlugin{}

	// The list of plugins to probe is decided by this binary, not
	// by dynamic linking or other "magic".  Plugins will be analyzed and
	// initialized later.

	// Each plugin can make use of VolumeConfig.  The single arg to this func contains *all* enumerated
	// CLI flags meant to configure volume plugins.  From that single config, create an instance of volume.VolumeConfig
	// for a specific plugin and pass that instance to the plugin's ProbeVolumePlugins(config) func.

	// HostPath recycling is for testing and development purposes only!
	hostPathConfig := volume.VolumeConfig{
		RecyclerMinimumTimeout:   flags.PersistentVolumeRecyclerMinimumTimeoutHostPath,
		RecyclerTimeoutIncrement: flags.PersistentVolumeRecyclerIncrementTimeoutHostPath,
		RecyclerPodTemplate:      volume.NewPersistentVolumeRecyclerPodTemplate(),
	}
	if err := AttemptToLoadRecycler(flags.PersistentVolumeRecyclerPodTemplateFilePathHostPath, &hostPathConfig); err != nil {
		glog.Fatalf("Could not create hostpath recycler pod from file %s: %+v", flags.PersistentVolumeRecyclerPodTemplateFilePathHostPath, err)
	}
	allPlugins = append(allPlugins, host_path.ProbeVolumePlugins(hostPathConfig)...)

	nfsConfig := volume.VolumeConfig{
		RecyclerMinimumTimeout:   flags.PersistentVolumeRecyclerMinimumTimeoutNFS,
		RecyclerTimeoutIncrement: flags.PersistentVolumeRecyclerIncrementTimeoutNFS,
		RecyclerPodTemplate:      volume.NewPersistentVolumeRecyclerPodTemplate(),
	}
	if err := AttemptToLoadRecycler(flags.PersistentVolumeRecyclerPodTemplateFilePathNFS, &nfsConfig); err != nil {
		glog.Fatalf("Could not create NFS recycler pod from file %s: %+v", flags.PersistentVolumeRecyclerPodTemplateFilePathNFS, err)
	}
	allPlugins = append(allPlugins, nfs.ProbeVolumePlugins(nfsConfig)...)

	allPlugins = append(allPlugins, aws_ebs.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, gce_pd.ProbeVolumePlugins()...)
	allPlugins = append(allPlugins, cinder.ProbeVolumePlugins()...)

	return allPlugins
}

// NewVolumeProvisioner returns a volume provisioner to use when running in a cloud or development environment.
// The beta implementation of provisioning allows 1 implied provisioner per cloud, until we allow configuration of many.
// We explicitly map clouds to volume plugins here which allows us to configure many later without backwards compatibility issues.
// Not all cloudproviders have provisioning capability, which is the reason for the bool in the return to tell the caller to expect one or not.
func NewVolumeProvisioner(cloud cloudprovider.Interface, flags options.VolumeConfigFlags) (volume.ProvisionableVolumePlugin, error) {
	switch {
	case cloud == nil && flags.EnableHostPathProvisioning:
		return getProvisionablePluginFromVolumePlugins(host_path.ProbeVolumePlugins(volume.VolumeConfig{}))
	case cloud != nil && aws.ProviderName == cloud.ProviderName():
		return getProvisionablePluginFromVolumePlugins(aws_ebs.ProbeVolumePlugins())
	case cloud != nil && gce.ProviderName == cloud.ProviderName():
		return getProvisionablePluginFromVolumePlugins(gce_pd.ProbeVolumePlugins())
	case cloud != nil && openstack.ProviderName == cloud.ProviderName():
		return getProvisionablePluginFromVolumePlugins(cinder.ProbeVolumePlugins())
	}
	return nil, nil
}

func getProvisionablePluginFromVolumePlugins(plugins []volume.VolumePlugin) (volume.ProvisionableVolumePlugin, error) {
	for _, plugin := range plugins {
		if provisonablePlugin, ok := plugin.(volume.ProvisionableVolumePlugin); ok {
			return provisonablePlugin, nil
		}
	}
	return nil, fmt.Errorf("ProvisionablePlugin expected but not found in %#v: ", plugins)
}

// AttemptToLoadRecycler tries decoding a pod from a filepath for use as a recycler for a volume.
// If successful, this method will set the recycler on the config.
// If unsuccessful, an error is returned. Function is exported for reuse downstream.
func AttemptToLoadRecycler(path string, config *volume.VolumeConfig) error {
	if path != "" {
		recyclerPod, err := io.LoadPodFromFile(path)
		if err != nil {
			return err
		}
		config.RecyclerPodTemplate = recyclerPod
	}
	return nil
}


text:
package de.mannheim.uni.IO;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

import org.apache.commons.lang.WordUtils;

import de.mannheim.uni.IO.ConvertFileToTable.ReadTableType;
import de.mannheim.uni.model.Table;
import de.mannheim.uni.model.TableColumn;
import de.mannheim.uni.pipelines.Pipeline;

public class Triplifier {

	public static final String NT_TYPE = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";
	public static final String NT_LABEL = "<http://www.w3.org/2000/01/rdf-schema#label>";
	public static final String NT_DATATYPE_PROPERTY = "<http://www.w3.org/2002/07/owl#DatatypeProperty>";
	public static final String NT_CLASS = "http://www.w3.org/2002/07/owl#Class";

	public static final String NT_TABLE_NS = "http://table.searchjoins.de/";

	public static void triplifyTable(String tablePath, String outputPath,
			String namespace) {
		ConvertFileToTable reader = new ConvertFileToTable(
				Pipeline.getPipelineFromConfigFile("ss", "searchJoins.conf"));
		Table table = reader.readTable(ReadTableType.search, tablePath);
		triplifyTable(table, outputPath, namespace);

	}

	public static void triplifyTable(Table table, String outputPath,
			String namespace) {
		TableColumn keyColumn = table.getColumns().get(0);
		if (keyColumn == null) {
			System.out.println("The table doesn't contain a key column!!");
			return;
		}

		// holds all triples
		List<String> allTriples = new ArrayList<String>();

		// we assume that the keys are of type as the column header
		String className = NT_TABLE_NS
				+ WordUtils.capitalize(keyColumn.getHeader()).replace(" ", "");

		for (Entry<Integer, String> key : keyColumn.getValues().entrySet()) {
			if (key.getValue().equals("string"))
				continue;
			// create the object
			String keyUri = NT_TABLE_NS
					+ WordUtils.capitalize(key.getValue()).replace(" ", "");

			// add the class and the label
			allTriples.add(makeTriple(keyUri, NT_TYPE, className));
			allTriples.add(makeTriple(keyUri, NT_LABEL, key.getValue()));

			// iterate all columns and add them in a triple with the key
			for (TableColumn objectColumn : table.getColumns()) {
				if (objectColumn.isKey())
					continue;

				String objectValue = objectColumn.getValues().get(key.getKey());

				allTriples.add(makeTriple(keyUri, NT_TABLE_NS
						+ WordUtils.capitalize(objectColumn.getHeader())
								.replace(" ", ""), objectValue));
			}
		}

		// add the class
		allTriples.add(makeTriple(className, NT_TYPE, NT_CLASS));
		allTriples.add(makeTriple(className, NT_LABEL,
				WordUtils.capitalize(keyColumn.getHeader())));

		// add the labels and the types of the columns (properties)
		for (TableColumn objectColumn : table.getColumns()) {
			if (objectColumn.isKey())
				continue;
			String frac = WordUtils.capitalize(objectColumn.getHeader())
					.replace(" ", "");
			allTriples.add(makeTriple(NT_TABLE_NS + frac, NT_TYPE,
					NT_DATATYPE_PROPERTY));
			allTriples.add(makeTriple(NT_TABLE_NS + frac, NT_LABEL,
					WordUtils.capitalize(objectColumn.getHeader())));
		}

		try {
			org.apache.commons.io.FileUtils.writeLines(new File(outputPath),
					allTriples);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String makeTriple(String subject, String predicate,
			String object) {
		String triple = "";
		try {
			triple = addBrackets(subject) + " " + addBrackets(predicate) + " "
					+ addBrackets(object) + " .";
		} catch (Exception e) {
			return null;
		}
		return triple;
	}

	public static String addBrackets(String str) {
		if (str == null)
			return null;
		if (str.contains("http")) {
			if (!str.startsWith("<"))
				str = "<" + str;
			if (!str.endsWith(">"))
				str = str + ">";
		} else {
			if (!str.startsWith("\"")) {
				str = WordUtils.capitalize(str);
				str = "\"" + str;
			}
			if (!str.endsWith("\""))
				str = str + "\"";
			if (!str.endsWith("@en"))
				str = str + "@en";
		}
		return str;
	}

	public static void main(String[] args) {

		triplifyTable("Countries.csv", "Countries.nt", "");
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xemio.GameLibrary.Rendering;

namespace Xemio.GameLibrary.Game.Scenes.Transitions
{
    public interface ITransition
    {
        /// <summary>
        /// Gets a value indicating whether the transition is completed.
        /// </summary>
        bool IsCompleted { get; }
        /// <summary>
        /// Handles a game tick.
        /// </summary>
        /// <param name="elapsed">The elapsed.</param>
        void Tick(float elapsed);
        /// <summary>
        /// Enters the transition.
        /// </summary>
        /// <param name="current">The current.</param>
        /// <param name="next">The next.</param>
        void Enter(Scene current, Scene next);
        /// <summary>
        /// Leaves the transition. NOTE: Current contains now the scene, that was declared as next before.
        /// </summary>
        /// <param name="current">The current.</param>
        void Leave(Scene current);
        /// <summary>
        /// Renders a transition between the specified scenes.
        /// </summary>
        /// <param name="current">The current scenes frame.</param>
        /// <param name="next">The next scenes frame.</param>
        void Render(IRenderTarget current, IRenderTarget next);
    }
}


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

  <title>Description of simpleCache</title>
  <meta name="keywords" content="simpleCache">
  <meta name="description" content="A simple cache that can be used to store results of computations.">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html © 2003 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../m2html.css">

simpleCache

PURPOSE

A simple cache that can be used to store results of computations.

SYNOPSIS

function varargout = simpleCache( op, cache, varargin )

DESCRIPTION

 A simple cache that can be used to store results of computations.

 Can save and retrieve arbitrary values using a vector (includnig char
 vectors) as a key. Especially useful if a function must perform heavy
 computation but is often called with the same inputs (for which it will
 give the same outputs).  Note that the current implementation does a
 linear search for the key (a more refined implementation would use a hash
 table), so it is not meant for large scale usage.

 To use inside a function, make the cache persistent:
  persistent cache; if( isempty(cache) ) cache=simpleCache('init'); end;
 The following line, when placed inside a function, means the cache will
 stay in memory until the matlab environment changes.  For an example
 usage see maskGaussians.

 USAGE - 'init': initialize a cache object
  cache = simpleCache('init');

 USAGE - 'put': put something in cache.  key must be a numeric vector
  cache = simpleCache( 'put', cache, key, val );

 USAGE - 'get': retrieve from cache.  found==1 if obj was found
  [found,val] = simpleCache( 'get', cache, key );

 USAGE - 'remove': free key
  [cache,found] = simpleCache( 'remove', cache, key );

 INPUTS
  op         - 'init', 'put', 'get', 'remove'
  cache      - the cache object being operated on
  varargin   - see USAGE above

 OUTPUTS
  varargout  - see USAGE above

 EXAMPLE
  cache = simpleCache('init');
  hellokey=rand(1,3); worldkey=rand(1,11);
  cache = simpleCache( 'put', cache, hellokey, 'hello' );
  cache = simpleCache( 'put', cache, worldkey, 'world' );
  [f,v]=simpleCache( 'get', cache, hellokey ); disp(v);
  [f,v]=simpleCache( 'get', cache, worldkey ); disp(v);

 See also PERSISTENT, MASKGAUSSIANS

 Piotr's Image&Video Toolbox      Version 2.61
 Copyright 2012 Piotr Dollar.  [pdollar-at-caltech.edu]
 Please email me if you find bugs, or have suggestions or questions!
 Licensed under the Simplified BSD License [see external/bsd.txt]

<address>Generated by m2html © 2003</address>


text:
/* En-tête du programme
*****************************************
Fichier :			sprite.h
Auteur:				Mylène Desrosiers
Date de création :
Description :
Commentaires :
*****************************************/

#include <iostream>
#include <stdio.h>
#include <string>
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "LTexture.h"

#pragma once
class sprite
{

	//champs de la classe

public:
	sprite();
	~sprite();

	bool chargerTexture(std::string nomFichier);

	char get_type();
	SDL_Point get_position();

	SDL_Rect get_rect();

	int get_hauteur();
	int get_largeur();

	void set_position(SDL_Point position);
	void set_type(char type);

	void set_renderer(SDL_Renderer* render);

	void set_hauteur(int hauteur);
	void set_largeur(int largeur);

	void sauter(float vitesse_verticale, float temps_depuis_debut_saut, const float GRAVITE);
	void avancer();

	void render();
protected:

	double angle;

	/*int _position_x;
	int _position_y;*/

	/*
	int _largeur_sprite;
	int _hauteur_sprite;*/

	/*const float GRAVITE = 9.81;*/ //Ajouter dans le magicien

	SDL_RendererFlip flip;

	SDL_Rect rectangle_visible;
	char _type;

	char _direction;

	LTexture _sprite_texture;

	SDL_Point _position;

	char detecter_collision(SDL_Rect a, SDL_Rect b);

};


text:
%%%%%%%%%%%%%%%%%%%
% Lexical + Logic
%%%%%%%%%%%%%%%%%%%
\def\title{Old Problem: Logic + ML often at odds}
\begin{frame}{\title}
\begin{center}
\only{\includegraphics[height=4cm]{../img/spy.png}}
\end{center}
\end{frame}

\begin{frame}[noframenumbering]{\title}
\hh{ML gives us practical, generalizable systems:}
\begin{itemize}
\item[P:] \textit{Ovaries are the female part of the flower, which produces eggs that are needed for making seeds.}
\item[H:] \textit{A flower produces the seeds.}
\end{itemize}
\vspace{2ex}
\hh{...But struggles with logical subtleties}
\begin{itemize}
\item[P:] \textit{Eating candy for dinner is an example of a poor health habit.}
\item[H:] \textit{Eating candy is an example of a good health habit.}
\end{itemize}
\end{frame}

\begin{frame}[noframenumbering]{Make ML more first-order-logic-like}
\hh{Markov Logic Networks}
\begin{itemize}
\item \cite{key:2006richardson-mln}
\item \cite{key:2011niu-tuffy}
\end{itemize}
\vspace{2ex}
\hh{Probabilistic Soft Logic}
\begin{itemize}
\item \cite{key:2012kimmig-psl}
\item \cite{key:2014beltagy-psl}
\end{itemize}
\vspace{2ex}
\hh{Deep Learning + Logic}
\begin{itemize}
\item \cite{key:2015rocktaschen-logic}
\end{itemize}
\end{frame}

\begin{frame}{Find logics that are better for ML}
\begin{center}
  \hh{Natural Logic!}
\end{center}
\footnotetext<.->{\cite{key:1991valencia-natlog,key:2008maccartney-natlog,key:2014icard-natlog}}
\pause

\hh{Logic over natural language}
\begin{itemize}
\item \textit{Instantaneous} and \textit{perfect} semantic parsing!
\item Plays nice with lexical methods
\end{itemize}
\vspace{1ex}
\pause

\hh{Tractable}
\begin{itemize}
\item Polynomial time entailment checking \cite{key:2008maccartney-natlog}.
\end{itemize}
\vspace{1ex}
\pause

\hh{Expressive (for common inferences)}
\begin{itemize}
\item Second-order phenomena; \w{most}; quantifier scoping
\pause
\item No free lunch: shallow quantification; single-premise only
\end{itemize}
\end{frame}


text:
r"""subprocess - Subprocesses with accessible I/O streams

This module allows you to spawn processes, connect to their
input/output/error pipes, and obtain their return codes.  This module
intends to replace several other, older modules and functions, like:

os.system
os.spawn*
os.popen*
popen2.*
commands.*

Information about how the subprocess module can be used to replace these
modules and functions can be found below.

Using the subprocess module
===========================
This module defines one class called Popen:

class Popen(args, bufsize=0, executable=None,
            stdin=None, stdout=None, stderr=None,
            preexec_fn=None, close_fds=False, shell=False,
            cwd=None, env=None, universal_newlines=False,
            startupinfo=None, creationflags=0):

Arguments are:

args should be a string, or a sequence of program arguments.  The
program to execute is normally the first item in the args sequence or
string, but can be explicitly set by using the executable argument.

On UNIX, with shell=False (default): In this case, the Popen class
uses os.execvp() to execute the child program.  args should normally
be a sequence.  A string will be treated as a sequence with the string
as the only item (the program to execute).

On UNIX, with shell=True: If args is a string, it specifies the
command string to execute through the shell.  If args is a sequence,
the first item specifies the command string, and any additional items
will be treated as additional shell arguments.

On Windows: the Popen class uses CreateProcess() to execute the child
program, which operates on strings.  If args is a sequence, it will be
converted to a string using the list2cmdline method.  Please note that
not all MS Windows applications interpret the command line the same
way: The list2cmdline is designed for applications using the same
rules as the MS C runtime.

bufsize, if given, has the same meaning as the corresponding argument
to the built-in open() function: 0 means unbuffered, 1 means line
buffered, any other positive value means use a buffer of
(approximately) that size.  A negative bufsize means to use the system
default, which usually means fully buffered.  The default value for
bufsize is 0 (unbuffered).

stdin, stdout and stderr specify the executed programs' standard
input, standard output and standard error file handles, respectively.
Valid values are PIPE, an existing file descriptor (a positive
integer), an existing file object, and None.  PIPE indicates that a
new pipe to the child should be created.  With None, no redirection
will occur; the child's file handles will be inherited from the
parent.  Additionally, stderr can be STDOUT, which indicates that the
stderr data from the applications should be captured into the same
file handle as for stdout.

If preexec_fn is set to a callable object, this object will be called
in the child process just before the child is executed.

If close_fds is true, all file descriptors except 0, 1 and 2 will be
closed before the child process is executed.

if shell is true, the specified command will be executed through the
shell.

If cwd is not None, the current directory will be changed to cwd
before the child is executed.

If env is not None, it defines the environment variables for the new
process.

If universal_newlines is true, the file objects stdout and stderr are
opened as a text files, but lines may be terminated by any of '\n',
the Unix end-of-line convention, '\r', the Macintosh convention or
'\r\n', the Windows convention.  All of these external representations
are seen as '\n' by the Python program.  Note: This feature is only
available if Python is built with universal newline support (the
default).  Also, the newlines attribute of the file objects stdout,
stdin and stderr are not updated by the communicate() method.

The startupinfo and creationflags, if given, will be passed to the
underlying CreateProcess() function.  They can specify things such as
appearance of the main window and priority for the new process.
(Windows only)

This module also defines two shortcut functions:

call(*popenargs, **kwargs):
    Run command with arguments.  Wait for command to complete, then
    return the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    retcode = call(["ls", "-l"])

check_call(*popenargs, **kwargs):
    Run command with arguments.  Wait for command to complete.  If the
    exit code was zero then return, otherwise raise
    CalledProcessError.  The CalledProcessError object will have the
    return code in the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    check_call(["ls", "-l"])

Exceptions
----------
Exceptions raised in the child process, before the new program has
started to execute, will be re-raised in the parent.  Additionally,
the exception object will have one extra attribute called
'child_traceback', which is a string containing traceback information
from the childs point of view.

The most common exception raised is OSError.  This occurs, for
example, when trying to execute a non-existent file.  Applications
should prepare for OSErrors.

A ValueError will be raised if Popen is called with invalid arguments.

check_call() will raise CalledProcessError, if the called process
returns a non-zero return code.

Security
--------
Unlike some other popen functions, this implementation will never call
/bin/sh implicitly.  This means that all characters, including shell
metacharacters, can safely be passed to child processes.

Popen objects
=============
Instances of the Popen class have the following methods:

poll()
    Check if child process has terminated.  Returns returncode
    attribute.

wait()
    Wait for child process to terminate.  Returns returncode attribute.

communicate(input=None)
    Interact with process: Send data to stdin.  Read data from stdout
    and stderr, until end-of-file is reached.  Wait for process to
    terminate.  The optional input argument should be a string to be
    sent to the child process, or None, if no data should be sent to
    the child.

    communicate() returns a tuple (stdout, stderr).

    Note: The data read is buffered in memory, so do not use this
    method if the data size is large or unlimited.

The following attributes are also available:

stdin
    If the stdin argument is PIPE, this attribute is a file object
    that provides input to the child process.  Otherwise, it is None.

stdout
    If the stdout argument is PIPE, this attribute is a file object
    that provides output from the child process.  Otherwise, it is
    None.

stderr
    If the stderr argument is PIPE, this attribute is file object that
    provides error output from the child process.  Otherwise, it is
    None.

pid
    The process ID of the child process.

returncode
    The child return code.  A None value indicates that the process
    hasn't terminated yet.  A negative value -N indicates that the
    child was terminated by signal N (UNIX only).

Replacing older functions with the subprocess module
====================================================
In this section, "a ==> b" means that b can be used as a replacement
for a.

Note: All functions in this section fail (more or less) silently if
the executed program cannot be found; this module raises an OSError
exception.

In the following examples, we assume that the subprocess module is
imported with "from subprocess import *".

Replacing /bin/sh shell backquote
---------------------------------
output=`mycmd myarg`
==>
output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]

Replacing shell pipe line
-------------------------
output=`dmesg | grep hda`
==>
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

Replacing os.system()
---------------------
sts = os.system("mycmd" + " myarg")
==>
p = Popen("mycmd" + " myarg", shell=True)
pid, sts = os.waitpid(p.pid, 0)

Note:

* Calling the program through the shell is usually not required.

* It's easier to look at the returncode attribute than the
  exitstatus.

A more real-world example would look like this:

try:
    retcode = call("mycmd" + " myarg", shell=True)
    if retcode < 0:
        print >>sys.stderr, "Child was terminated by signal", -retcode
    else:
        print >>sys.stderr, "Child returned", retcode
except OSError, e:
    print >>sys.stderr, "Execution failed:", e

Replacing os.spawn*
-------------------
P_NOWAIT example:

pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
==>
pid = Popen(["/bin/mycmd", "myarg"]).pid

P_WAIT example:

retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
==>
retcode = call(["/bin/mycmd", "myarg"])

Vector example:

os.spawnvp(os.P_NOWAIT, path, args)
==>
Popen([path] + args[1:])

Environment example:

os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
==>
Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})

Replacing os.popen*
-------------------
pipe = os.popen(cmd, mode='r', bufsize)
==>
pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout

pipe = os.popen(cmd, mode='w', bufsize)
==>
pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin

(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdin, child_stdout) = (p.stdin, p.stdout)

(child_stdin,
 child_stdout,
 child_stderr) = os.popen3(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
(child_stdin,
 child_stdout,
 child_stderr) = (p.stdin, p.stdout, p.stderr)

(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)

Replacing popen2.*
------------------
Note: If the cmd argument to popen2 functions is a string, the command
is executed through /bin/sh.  If it is a list, the command is directly
executed.

(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
==>
p = Popen(["somestring"], shell=True, bufsize=bufsize
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)

(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
==>
p = Popen(["mycmd", "myarg"], bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)

The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen,
except that:

* subprocess.Popen raises an exception if the execution fails
* the capturestderr argument is replaced with the stderr argument.
* stdin=PIPE and stdout=PIPE must be specified.
* popen2 closes all filedescriptors by default, but you have to specify
  close_fds=True with subprocess.Popen.
"""

import sys
mswindows = (sys.platform == "win32")

import os
import types
import traceback
import gc
import signal

# Exception classes used by this module.
class CalledProcessError(Exception):
    """This exception is raised when a process run by check_call() returns
    a non-zero exit status.  The exit status will be stored in the
    returncode attribute."""
    def __init__(self, returncode, cmd):
        self.returncode = returncode
        self.cmd = cmd
    def __str__(self):
        return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)

if mswindows:
    import threading
    import msvcrt
    if 0: # <-- change this to use pywin32 instead of the _subprocess driver
        import pywintypes
        from win32api import GetStdHandle, STD_INPUT_HANDLE, \
                             STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
        from win32api import GetCurrentProcess, DuplicateHandle, \
                             GetModuleFileName, GetVersion
        from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
        from win32pipe import CreatePipe
        from win32process import CreateProcess, STARTUPINFO, \
                                 GetExitCodeProcess, STARTF_USESTDHANDLES, \
                                 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
        from win32process import TerminateProcess
        from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
    else:
        from _subprocess import *
        class STARTUPINFO:
            dwFlags = 0
            hStdInput = None
            hStdOutput = None
            hStdError = None
            wShowWindow = 0
        class pywintypes:
            error = IOError
else:
    import select
    import errno
    import fcntl
    import pickle

__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"]

try:
    MAXFD = os.sysconf("SC_OPEN_MAX")
except:
    MAXFD = 256

# True/False does not exist on 2.2.0
#try:
#    False
#except NameError:
#    False = 0
#    True = 1

_active = []

def _cleanup():
    for inst in _active[:]:
        if inst._internal_poll(_deadstate=sys.maxint) >= 0:
            try:
                _active.remove(inst)
            except ValueError:
                # This can happen if two threads create a new Popen instance.
                # It's harmless that it was already removed, so ignore.
                pass

PIPE = -1
STDOUT = -2

def call(*popenargs, **kwargs):
    """Run command with arguments.  Wait for command to complete, then
    return the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    retcode = call(["ls", "-l"])
    """
    return Popen(*popenargs, **kwargs).wait()

def check_call(*popenargs, **kwargs):
    """Run command with arguments.  Wait for command to complete.  If
    the exit code was zero then return, otherwise raise
    CalledProcessError.  The CalledProcessError object will have the
    return code in the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    check_call(["ls", "-l"])
    """
    retcode = call(*popenargs, **kwargs)
    cmd = kwargs.get("args")
    if cmd is None:
        cmd = popenargs[0]
    if retcode:
        raise CalledProcessError(retcode, cmd)
    return retcode

def list2cmdline(seq):
    """
    Translate a sequence of arguments into a command line
    string, using the same rules as the MS C runtime:

    1) Arguments are delimited by white space, which is either a
       space or a tab.

    2) A string surrounded by double quotation marks is
       interpreted as a single argument, regardless of white space
       or pipe characters contained within.  A quoted string can be
       embedded in an argument.

    3) A double quotation mark preceded by a backslash is
       interpreted as a literal double quotation mark.

    4) Backslashes are interpreted literally, unless they
       immediately precede a double quotation mark.

    5) If backslashes immediately precede a double quotation mark,
       every pair of backslashes is interpreted as a literal
       backslash.  If the number of backslashes is odd, the last
       backslash escapes the next double quotation mark as
       described in rule 3.
    """

    # See
    # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
    result = []
    needquote = False
    for arg in seq:
        bs_buf = []

        # Add a space to separate this argument from the others
        if result:
            result.append(' ')

        needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or not arg
        if needquote:
            result.append('"')

        for c in arg:
            if c == '\\':
                # Don't know if we need to double yet.
                bs_buf.append(c)
            elif c == '"':
                # Double backslashes.
                result.append('\\' * len(bs_buf)*2)
                bs_buf = []
                result.append('\\"')
            else:
                # Normal char
                if bs_buf:
                    result.extend(bs_buf)
                    bs_buf = []
                result.append(c)

        # Add remaining backslashes, if any.
        if bs_buf:
            result.extend(bs_buf)

        if needquote:
            result.extend(bs_buf)
            result.append('"')

    return ''.join(result)

class Popen(object):
    def __init__(self, args, bufsize=0, executable=None,
                 stdin=None, stdout=None, stderr=None,
                 preexec_fn=None, close_fds=False, shell=False,
                 cwd=None, env=None, universal_newlines=False,
                 startupinfo=None, creationflags=0):
        """Create new Popen instance."""
        _cleanup()

        self._child_created = False
        if not isinstance(bufsize, (int, long)):
            raise TypeError("bufsize must be an integer")

        if mswindows:
            if preexec_fn is not None:
                raise ValueError("preexec_fn is not supported on Windows "
                                 "platforms")
            if close_fds and (stdin is not None or stdout is not None or
                              stderr is not None):
                raise ValueError("close_fds is not supported on Windows "
                                 "platforms if you redirect stdin/stdout/stderr")
        else:
            # POSIX
            if startupinfo is not None:
                raise ValueError("startupinfo is only supported on Windows "
                                 "platforms")
            if creationflags != 0:
                raise ValueError("creationflags is only supported on Windows "
                                 "platforms")

        self.stdin = None
        self.stdout = None
        self.stderr = None
        self.pid = None
        self.returncode = None
        self.universal_newlines = universal_newlines

        # Input and output objects. The general principle is like
        # this:
        #
        # Parent                   Child
        # ------                   -----
        # p2cwrite   ---stdin--->  p2cread
        # c2pread    <--stdout---  c2pwrite
        # errread    <--stderr---  errwrite
        #
        # On POSIX, the child objects are file descriptors.  On
        # Windows, these are Windows file handles.  The parent objects
        # are file descriptors on both platforms.  The parent objects
        # are None when not using PIPEs. The child objects are None
        # when not redirecting.

        (p2cread, p2cwrite,
         c2pread, c2pwrite,
         errread, errwrite) = self._get_handles(stdin, stdout, stderr)

        self._execute_child(args, executable, preexec_fn, close_fds,
                            cwd, env, universal_newlines,
                            startupinfo, creationflags, shell,
                            p2cread, p2cwrite,
                            c2pread, c2pwrite,
                            errread, errwrite)

        if mswindows:
            if p2cwrite is not None:
                p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
            if c2pread is not None:
                c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
            if errread is not None:
                errread = msvcrt.open_osfhandle(errread.Detach(), 0)

        if p2cwrite is not None:
            self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
        if c2pread is not None:
            if universal_newlines:
                self.stdout = os.fdopen(c2pread, 'rU', bufsize)
            else:
                self.stdout = os.fdopen(c2pread, 'rb', bufsize)
        if errread is not None:
            if universal_newlines:
                self.stderr = os.fdopen(errread, 'rU', bufsize)
            else:
                self.stderr = os.fdopen(errread, 'rb', bufsize)

    def _translate_newlines(self, data):
        data = data.replace("\r\n", "\n")
        data = data.replace("\r", "\n")
        return data

    def __del__(self, sys=sys):
        if not self._child_created:
            # We didn't get to successfully create a child process.
            return
        # In case the child hasn't been waited on, check if it's done.
        self._internal_poll(_deadstate=sys.maxint)
        if self.returncode is None and _active is not None:
            # Child is still running, keep us alive until we can wait on it.
            _active.append(self)

    def communicate(self, input=None):
        """Interact with process: Send data to stdin.  Read data from
        stdout and stderr, until end-of-file is reached.  Wait for
        process to terminate.  The optional input argument should be a
        string to be sent to the child process, or None, if no data
        should be sent to the child.

        communicate() returns a tuple (stdout, stderr)."""

        # Optimization: If we are only using one pipe, or no pipe at
        # all, using select() or threads is unnecessary.
        if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
            stdout = None
            stderr = None
            if self.stdin:
                if input:
                    self.stdin.write(input)
                self.stdin.close()
            elif self.stdout:
                stdout = self.stdout.read()
                self.stdout.close()
            elif self.stderr:
                stderr = self.stderr.read()
                self.stderr.close()
            self.wait()
            return (stdout, stderr)

        return self._communicate(input)

    def poll(self):
        return self._internal_poll()

    if mswindows:
        #
        # Windows methods
        #
        def _get_handles(self, stdin, stdout, stderr):
            """Construct and return tupel with IO objects:
            p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
            """
            if stdin is None and stdout is None and stderr is None:
                return (None, None, None, None, None, None)

            p2cread, p2cwrite = None, None
            c2pread, c2pwrite = None, None
            errread, errwrite = None, None

            if stdin is None:
                p2cread = GetStdHandle(STD_INPUT_HANDLE)
                if p2cread is None:
                    p2cread, _ = CreatePipe(None, 0)
            elif stdin == PIPE:
                p2cread, p2cwrite = CreatePipe(None, 0)
            elif isinstance(stdin, int):
                p2cread = msvcrt.get_osfhandle(stdin)
            else:
                # Assuming file-like object
                p2cread = msvcrt.get_osfhandle(stdin.fileno())
            p2cread = self._make_inheritable(p2cread)

            if stdout is None:
                c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
                if c2pwrite is None:
                    _, c2pwrite = CreatePipe(None, 0)
            elif stdout == PIPE:
                c2pread, c2pwrite = CreatePipe(None, 0)
            elif isinstance(stdout, int):
                c2pwrite = msvcrt.get_osfhandle(stdout)
            else:
                # Assuming file-like object
                c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
            c2pwrite = self._make_inheritable(c2pwrite)

            if stderr is None:
                errwrite = GetStdHandle(STD_ERROR_HANDLE)
                if errwrite is None:
                    _, errwrite = CreatePipe(None, 0)
            elif stderr == PIPE:
                errread, errwrite = CreatePipe(None, 0)
            elif stderr == STDOUT:
                errwrite = c2pwrite
            elif isinstance(stderr, int):
                errwrite = msvcrt.get_osfhandle(stderr)
            else:
                # Assuming file-like object
                errwrite = msvcrt.get_osfhandle(stderr.fileno())
            errwrite = self._make_inheritable(errwrite)

            return (p2cread, p2cwrite,
                    c2pread, c2pwrite,
                    errread, errwrite)

        def _make_inheritable(self, handle):
            """Return a duplicate of handle, which is inheritable"""
            return DuplicateHandle(GetCurrentProcess(), handle,
                                   GetCurrentProcess(), 0, 1,
                                   DUPLICATE_SAME_ACCESS)

        def _find_w9xpopen(self):
            """Find and return absolut path to w9xpopen.exe"""
            w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
                                    "w9xpopen.exe")
            if not os.path.exists(w9xpopen):
                # Eeek - file-not-found - possibly an embedding
                # situation - see if we can locate it in sys.exec_prefix
                w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
                                        "w9xpopen.exe")
                if not os.path.exists(w9xpopen):
                    raise RuntimeError("Cannot locate w9xpopen.exe, which is "
                                       "needed for Popen to work with your "
                                       "shell or platform.")
            return w9xpopen

        def _execute_child(self, args, executable, preexec_fn, close_fds,
                           cwd, env, universal_newlines,
                           startupinfo, creationflags, shell,
                           p2cread, p2cwrite,
                           c2pread, c2pwrite,
                           errread, errwrite):
            """Execute program (MS Windows version)"""

            if not isinstance(args, types.StringTypes):
                args = list2cmdline(args)

            # Process startup details
            if startupinfo is None:
                startupinfo = STARTUPINFO()
            if None not in (p2cread, c2pwrite, errwrite):
                startupinfo.dwFlags |= STARTF_USESTDHANDLES
                startupinfo.hStdInput = p2cread
                startupinfo.hStdOutput = c2pwrite
                startupinfo.hStdError = errwrite

            if shell:
                startupinfo.dwFlags |= STARTF_USESHOWWINDOW
                startupinfo.wShowWindow = SW_HIDE
                comspec = os.environ.get("COMSPEC", "cmd.exe")
                args = comspec + " /c " + args
                if (GetVersion() >= 0x80000000L or
                        os.path.basename(comspec).lower() == "command.com"):
                    # Win9x, or using command.com on NT. We need to
                    # use the w9xpopen intermediate program. For more
                    # information, see KB Q150956
                    # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
                    w9xpopen = self._find_w9xpopen()
                    args = '"%s" %s' % (w9xpopen, args)
                    # Not passing CREATE_NEW_CONSOLE has been known to
                    # cause random failures on win9x.  Specifically a
                    # dialog: "Your program accessed mem currently in
                    # use at xxx" and a hopeful warning about the
                    # stability of your system.  Cost is Ctrl+C wont
                    # kill children.
                    creationflags |= CREATE_NEW_CONSOLE

            # Start the process
            try:
                hp, ht, pid, tid = CreateProcess(executable, args,
                                         # no special security
                                         None, None,
                                         int(not close_fds),
                                         creationflags,
                                         env,
                                         cwd,
                                         startupinfo)
            except pywintypes.error, e:
                # Translate pywintypes.error to WindowsError, which is
                # a subclass of OSError.  FIXME: We should really
                # translate errno using _sys_errlist (or simliar), but
                # how can this be done from Python?
                raise WindowsError(*e.args)

            # Retain the process handle, but close the thread handle
            self._child_created = True
            self._handle = hp
            self.pid = pid
            ht.Close()

            # Child is launched. Close the parent's copy of those pipe
            # handles that only the child should have open.  You need
            # to make sure that no handles to the write end of the
            # output pipe are maintained in this process or else the
            # pipe will not close when the child process exits and the
            # ReadFile will hang.
            if p2cread is not None:
                p2cread.Close()
            if c2pwrite is not None:
                c2pwrite.Close()
            if errwrite is not None:
                errwrite.Close()

        def _internal_poll(self, _deadstate=None):
            """Check if child process has terminated.  Returns returncode
            attribute."""
            if self.returncode is None:
                if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
                    self.returncode = GetExitCodeProcess(self._handle)
            return self.returncode

        def wait(self):
            """Wait for child process to terminate.  Returns returncode
            attribute."""
            if self.returncode is None:
                obj = WaitForSingleObject(self._handle, INFINITE)
                self.returncode = GetExitCodeProcess(self._handle)
            return self.returncode

        def _readerthread(self, fh, buffer):
            buffer.append(fh.read())

        def _communicate(self, input):
            stdout = None # Return
            stderr = None # Return

            if self.stdout:
                stdout = []
                stdout_thread = threading.Thread(target=self._readerthread,
                                                 args=(self.stdout, stdout))
                stdout_thread.setDaemon(True)
                stdout_thread.start()
            if self.stderr:
                stderr = []
                stderr_thread = threading.Thread(target=self._readerthread,
                                                 args=(self.stderr, stderr))
                stderr_thread.setDaemon(True)
                stderr_thread.start()

            if self.stdin:
                if input is not None:
                    self.stdin.write(input)
                self.stdin.close()

            if self.stdout:
                stdout_thread.join()
            if self.stderr:
                stderr_thread.join()

            # All data exchanged.  Translate lists into strings.
            if stdout is not None:
                stdout = stdout[0]
            if stderr is not None:
                stderr = stderr[0]

            # Translate newlines, if requested.  We cannot let the file
            # object do the translation: It is based on stdio, which is
            # impossible to combine with select (unless forcing no
            # buffering).
            if self.universal_newlines and hasattr(file, 'newlines'):
                if stdout:
                    stdout = self._translate_newlines(stdout)
                if stderr:
                    stderr = self._translate_newlines(stderr)

            self.wait()
            return (stdout, stderr)

        def send_signal(self, sig):
            """Send a signal to the process
            """
            if sig == signal.SIGTERM:
                self.terminate()
            else:
                raise ValueError("Only SIGTERM is supported on Windows")

        def terminate(self):
            """Terminates the process
            """
            TerminateProcess(self._handle, 1)

        kill = terminate

    else:
        #
        # POSIX methods
        #
        def _get_handles(self, stdin, stdout, stderr):
            """Construct and return tupel with IO objects:
            p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
            """
            p2cread, p2cwrite = None, None
            c2pread, c2pwrite = None, None
            errread, errwrite = None, None

            if stdin is None:
                pass
            elif stdin == PIPE:
                p2cread, p2cwrite = os.pipe()
            elif isinstance(stdin, int):
                p2cread = stdin
            else:
                # Assuming file-like object
                p2cread = stdin.fileno()

            if stdout is None:
                pass
            elif stdout == PIPE:
                c2pread, c2pwrite = os.pipe()
            elif isinstance(stdout, int):
                c2pwrite = stdout
            else:
                # Assuming file-like object
                c2pwrite = stdout.fileno()

            if stderr is None:
                pass
            elif stderr == PIPE:
                errread, errwrite = os.pipe()
            elif stderr == STDOUT:
                errwrite = c2pwrite
            elif isinstance(stderr, int):
                errwrite = stderr
            else:
                # Assuming file-like object
                errwrite = stderr.fileno()

            return (p2cread, p2cwrite,
                    c2pread, c2pwrite,
                    errread, errwrite)

        def _set_cloexec_flag(self, fd):
            try:
                cloexec_flag = fcntl.FD_CLOEXEC
            except AttributeError:
                cloexec_flag = 1

            old = fcntl.fcntl(fd, fcntl.F_GETFD)
            fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)

        def _close_fds(self, but):
            os.closerange(3, but)
            os.closerange(but + 1, MAXFD)

        def _execute_child(self, args, executable, preexec_fn, close_fds,
                           cwd, env, universal_newlines,
                           startupinfo, creationflags, shell,
                           p2cread, p2cwrite,
                           c2pread, c2pwrite,
                           errread, errwrite):
            """Execute program (POSIX version)"""

            if isinstance(args, types.StringTypes):
                args = [args]
            else:
                args = list(args)

            if shell:
                args = ["/bin/sh", "-c"] + args

            if executable is None:
                executable = args[0]

            # For transferring possible exec failure from child to parent
            # The first char specifies the exception type: 0 means
            # OSError, 1 means some other error.
            errpipe_read, errpipe_write = os.pipe()
            self._set_cloexec_flag(errpipe_write)

            gc_was_enabled = gc.isenabled()
            # Disable gc to avoid bug where gc -> file_dealloc ->
            # write to stderr -> hang.  http://bugs.python.org/issue1336
            gc.disable()
            try:
                self.pid = os.fork()
            except:
                if gc_was_enabled:
                    gc.enable()
                raise
            self._child_created = True
            if self.pid == 0:
                # Child
                try:
                    # Close parent's pipe ends
                    if p2cwrite is not None:
                        os.close(p2cwrite)
                    if c2pread is not None:
                        os.close(c2pread)
                    if errread is not None:
                        os.close(errread)
                    os.close(errpipe_read)

                    # Dup fds for child
                    if p2cread is not None:
                        os.dup2(p2cread, 0)
                    if c2pwrite is not None:
                        os.dup2(c2pwrite, 1)
                    if errwrite is not None:
                        os.dup2(errwrite, 2)

                    # Close pipe fds.  Make sure we don't close the same
                    # fd more than once, or standard fds.
                    if p2cread is not None and p2cread not in (0,):
                        os.close(p2cread)
                    if c2pwrite is not None and c2pwrite not in (p2cread, 1):
                        os.close(c2pwrite)
                    if errwrite is not None and errwrite not in (p2cread, c2pwrite, 2):
                        os.close(errwrite)

                    # Close all other fds, if asked for
                    if close_fds:
                        self._close_fds(but=errpipe_write)

                    if cwd is not None:
                        os.chdir(cwd)

                    if preexec_fn:
                        preexec_fn()

                    if env is None:
                        os.execvp(executable, args)
                    else:
                        os.execvpe(executable, args, env)

                except:
                    exc_type, exc_value, tb = sys.exc_info()
                    # Save the traceback and attach it to the exception object
                    exc_lines = traceback.format_exception(exc_type,
                                                           exc_value,
                                                           tb)
                    exc_value.child_traceback = ''.join(exc_lines)
                    os.write(errpipe_write, pickle.dumps(exc_value))

                # This exitcode won't be reported to applications, so it
                # really doesn't matter what we return.
                os._exit(255)

            # Parent
            if gc_was_enabled:
                gc.enable()
            os.close(errpipe_write)
            if p2cread is not None and p2cwrite is not None:
                os.close(p2cread)
            if c2pwrite is not None and c2pread is not None:
                os.close(c2pwrite)
            if errwrite is not None and errread is not None:
                os.close(errwrite)

            # Wait for exec to fail or succeed; possibly raising exception
            data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
            os.close(errpipe_read)
            if data != "":
                os.waitpid(self.pid, 0)
                child_exception = pickle.loads(data)
                for fd in (p2cwrite, c2pread, errread):
                    if fd is not None:
                        os.close(fd)
                raise child_exception

        def _handle_exitstatus(self, sts):
            if os.WIFSIGNALED(sts):
                self.returncode = -os.WTERMSIG(sts)
            elif os.WIFEXITED(sts):
                self.returncode = os.WEXITSTATUS(sts)
            else:
                # Should never happen
                raise RuntimeError("Unknown child exit status!")

        def _internal_poll(self, _deadstate=None):
            """Check if child process has terminated.  Returns returncode
            attribute."""
            if self.returncode is None:
                try:
                    pid, sts = os.waitpid(self.pid, os.WNOHANG)
                    if pid == self.pid:
                        self._handle_exitstatus(sts)
                except os.error:
                    if _deadstate is not None:
                        self.returncode = _deadstate
            return self.returncode

        def wait(self):
            """Wait for child process to terminate.  Returns returncode
            attribute."""
            if self.returncode is None:
                pid, sts = os.waitpid(self.pid, 0)
                self._handle_exitstatus(sts)
            return self.returncode

        def _communicate(self, input):
            read_set = []
            write_set = []
            stdout = None # Return
            stderr = None # Return

            if self.stdin:
                # Flush stdio buffer.  This might block, if the user has
                # been writing to .stdin in an uncontrolled fashion.
                self.stdin.flush()
                if input:
                    write_set.append(self.stdin)
                else:
                    self.stdin.close()
            if self.stdout:
                read_set.append(self.stdout)
                stdout = []
            if self.stderr:
                read_set.append(self.stderr)
                stderr = []

            input_offset = 0
            while read_set or write_set:
                try:
                    rlist, wlist, xlist = select.select(read_set, write_set, [])
                except select.error, e:
                    if e.args[0] == errno.EINTR:
                        continue
                    raise

                if self.stdin in wlist:
                    # When select has indicated that the file is writable,
                    # we can write up to PIPE_BUF bytes without risk
                    # blocking.  POSIX defines PIPE_BUF >= 512
                    chunk = input[input_offset : input_offset + 512]
                    bytes_written = os.write(self.stdin.fileno(), chunk)
                    input_offset += bytes_written
                    if input_offset >= len(input):
                        self.stdin.close()
                        write_set.remove(self.stdin)

                if self.stdout in rlist:
                    data = os.read(self.stdout.fileno(), 1024)
                    if data == "":
                        self.stdout.close()
                        read_set.remove(self.stdout)
                    stdout.append(data)

                if self.stderr in rlist:
                    data = os.read(self.stderr.fileno(), 1024)
                    if data == "":
                        self.stderr.close()
                        read_set.remove(self.stderr)
                    stderr.append(data)

            # All data exchanged.  Translate lists into strings.
            if stdout is not None:
                stdout = ''.join(stdout)
            if stderr is not None:
                stderr = ''.join(stderr)

            # Translate newlines, if requested.  We cannot let the file
            # object do the translation: It is based on stdio, which is
            # impossible to combine with select (unless forcing no
            # buffering).
            if self.universal_newlines and hasattr(file, 'newlines'):
                if stdout:
                    stdout = self._translate_newlines(stdout)
                if stderr:
                    stderr = self._translate_newlines(stderr)

            self.wait()
            return (stdout, stderr)

        def send_signal(self, sig):
            """Send a signal to the process
            """
            os.kill(self.pid, sig)

        def terminate(self):
            """Terminate the process with SIGTERM
            """
            self.send_signal(signal.SIGTERM)

        def kill(self):
            """Kill the process with SIGKILL
            """
            self.send_signal(signal.SIGKILL)

def _demo_posix():
    #
    # Example 1: Simple redirection: Get process list
    #
    plist = Popen(["ps"], stdout=PIPE).communicate()[0]
    print "Process list:"
    print plist

    #
    # Example 2: Change uid before executing child
    #
    if os.getuid() == 0:
        p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
        p.wait()

    #
    # Example 3: Connecting several subprocesses
    #
    print "Looking for 'hda'..."
    p1 = Popen(["dmesg"], stdout=PIPE)
    p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
    print repr(p2.communicate()[0])

    #
    # Example 4: Catch execution error
    #
    print
    print "Trying a weird file..."
    try:
        print Popen(["/this/path/does/not/exist"]).communicate()
    except OSError, e:
        if e.errno == errno.ENOENT:
            print "The file didn't exist.  I thought so..."
            print "Child traceback:"
            print e.child_traceback
        else:
            print "Error", e.errno
    else:
        print >>sys.stderr, "Gosh.  No error."

def _demo_windows():
    #
    # Example 1: Connecting several subprocesses
    #
    print "Looking for 'PROMPT' in set output..."
    p1 = Popen("set", stdout=PIPE, shell=True)
    p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
    print repr(p2.communicate()[0])

    #
    # Example 2: Simple execution of program
    #
    print "Executing calc..."
    p = Popen("calc")
    p.wait()

if __name__ == "__main__":
    if mswindows:
        _demo_windows()
    else:
        _demo_posix()


text:
namespace Lauener.Core.XAML
{
    using System;
    using System.Linq;
    using System.Reflection;
    using System.Windows.Input;

    public abstract class ViewModelBaseBase : ModelBase, IViewModelBaseBase
    {
        private bool working;

        public bool Working
        {
            get
            {
                return this.working;
            }

            set
            {
                this.working = value;
                this.RaisePropertyChanged();
                this.RaisePropertyChanged(nameof(this.NotWorking));
                this.RefreshCommands();
            }
        }

        public bool NotWorking
        {
            get
            {
                return !this.working;
            }

            set
            {
                this.working = !value;
                this.RaisePropertyChanged();
                this.RaisePropertyChanged(nameof(this.Working));
                this.RefreshCommands();
            }
        }

        public virtual void Activated(object sender)
        {
        }

        public virtual void Loaded(object sender)
        {
        }

        public virtual void Deactivated(object sender)
        {
        }

        public virtual void Closed(object sender)
        {
        }

        public virtual void OnNavigatedTo()
        {
        }

        protected void RefreshCommands()
        {
            this.GetType().GetTypeInfo()
                .DeclaredProperties.Where(x => x.PropertyType == typeof(ICommand))
                .Select(commandProperty => commandProperty.GetMethod.Invoke(this, null))
                .OfType<CommandBase>()
                .ForEach(prop => prop.InvokeCanExecuteChanged());
        }

        //protected abstract void ExecuteInUiThread(Action action);
    }
}


text:
package com.manywho.services.twilio.types;

import com.manywho.sdk.enums.ContentType;
import com.manywho.sdk.services.annotations.Id;
import com.manywho.sdk.services.annotations.TypeElement;
import com.manywho.sdk.services.annotations.TypeProperty;

import java.util.List;

@TypeElement(name = Mms.NAME)
public class Mms {
    public final static String NAME = "MMS";

    @Id
    private String id;

    @TypeProperty(name = "To", contentType = ContentType.String, bound = false)
    private String to;

    @TypeProperty(name = "From", contentType = ContentType.String, bound = false)
    private String from;

    @TypeProperty(name = "Body", contentType = ContentType.String, bound = false)
    private String body;

    @TypeProperty(name = "Media", contentType = ContentType.List, bound = false)
    private List<Media> media;

    public Mms() {
    }

    public Mms(String id, String to, String from, String body, List<Media> media) {
        this.id = id;
        this.to = to;
        this.from = from;
        this.body = body;
        this.media = media;
    }

    public String getId() {
        return id;
    }

    public String getTo() {
        return to;
    }

    public String getFrom() {
        return from;
    }

    public String getBody() {
        return body;
    }

    public List<Media> getMedia() {
        return media;
    }
}


text:
require 'spec_helper'

describe Spree::Order do

  before(:each) do
    @order = FactoryGirl.create(:order)
    @payment_method = FactoryGirl.create(:payone_frontend)
  end

#-------------------------------------------------------------------------------------------------
  context "it has no payment" do
    it "last payment is null" do
      expect(@order.last_payment).to eq(nil)
    end

    it "last payment method is null" do
      expect(@order.last_payment_method).to eq(nil)
    end

    it "payone ref number is only order number" do
      expect(@order.payone_ref_number).to eq(@order.number)
    end

  end
#-------------------------------------------------------------------------------------------------
  context "it has a valid payment" do
    before(:each) do
      @payment = FactoryGirl.create(:payment, order: @order, payment_method: @payment_method)
    end

    it "last payment is given" do
      expect(@order.last_payment).not_to eq(nil)
    end

    it "last payment method is given" do
      expect(@order.last_payment_method).not_to eq(nil)
    end

    it "payone ref number has prefix and suffix of payment" do
      @order.last_payment_method.set_preference(:reference_prefix, "prefix")
      @order.last_payment_method.set_preference(:reference_suffix, "suffix")
      expect(@order.payone_ref_number).to eq("prefix#{@order.number}suffix")
    end

    after(:each) do
      @payment.destroy
    end
  end
#-------------------------------------------------------------------------------------------------
  after(:each) do
    @order.destroy
    @payment_method.destroy
  end

end