text:
using System;
using System.Configuration;
using System.Net;
using System.Net.Mail;

namespace ServiceBusMonitoring.Alerters
{
    public class EmailAlerter : IAlerter
    {
        private MailMessage message;
        private SmtpClient client;

        public EmailAlerter()
        {
            SetConfiguration();
        }

        public bool Send()
        {
            message.Subject = String.Format("ServiceBusMonitoring: Threshold exceeded for {0}", Queue);
            message.Body = String.Format("The Queue '{0}' in ServiceBus namespace '{1}' contains {2} messages. This exceeds the threshold of {3}", Queue, SBNamespace, MessageCount, Threshold);
            client.Send(message);
            return true;
        }

        public void SetMessageCount(long messageCount)
        {
            MessageCount = messageCount;
        }

        public void SetQueueName(string queueName)
        {
            Queue = queueName;
        }

        public void SetSBNamespace(string nameSpace)
        {
            SBNamespace = nameSpace;
        }

        public void SetThreshold(int threshold)
        {
            Threshold = threshold;
        }

        private void SetConfiguration()
        {
            var toAddr = ConfigurationManager.AppSettings["EmailTo"].ToString();
            var username = ConfigurationManager.AppSettings["EmailUser"].ToString();
            var password = ConfigurationManager.AppSettings["EmailPassword"].ToString();
            var mailHost = ConfigurationManager.AppSettings["EmailHost"].ToString();
            var mailPort = Convert.ToInt32(ConfigurationManager.AppSettings["EmailPort"]);

            client = new SmtpClient(mailHost, mailPort);
            client.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EmailEnableSSL"]);
            client.Credentials = new NetworkCredential(username, password);

            message = new MailMessage();
            message.To.Add(new MailAddress(toAddr));
            message.From = new MailAddress(ConfigurationManager.AppSettings["EmailFrom"].ToString());
        }

        public string SBNamespace { get; private set; }

        public string Queue { get; private set; }

        public long MessageCount { get; private set; }

        public int Threshold { get; private set; }
    }
}


text:
This document contains code snippets that solve frequently asked questions.

## "Sign into Dropbox" Button

Some applications wish to start the Dropbox authorization flow when the user
clicks on a "Sign into Dropbox" button. If the user has already authorized the
application, the button should not be shown. The code below accomplishes this
task, assuming that the signin button is initially hidden.

```javascript
// Try to use cached credentials.
client.authenticate({interactive: false}, function(error, client) {
  if (error) {
    return handleError(error);
  }
  if (client.isAuthenticated()) {
    // Cached credentials are available, make Dropbox API calls.
    doSomethingCool();
  } else {
    // show and set up the "Sign into Dropbox" button
    var button = document.querySelector("#signin-button");
    button.setAttribute("class", "visible");
    button.addEventListener("click", function() {
      // The user will have to click an 'Authorize' button.
      client.authenticate(function(error, client) {
        if (error) {
          return handleError(error);
        }
        doSomethingCool();
      });
    });
  }
});
```

## Binary File Reads

By default, `readFile` assumes that the Dropbox file contents is a UTF-8
encoded string. This works for text files, but is unsuitable for images and
other binary files. When reading binary files, one of the following
[readFile options](http://coffeedoc.info/github/dropbox/dropbox-js/master/classes/Dropbox/Client.html#readFile-instance)
should be used: `arrayBuffer`, `blob` (only works in browsers),
`buffer` (node.js only).

```javascript
client.readFile("an_image.png", arrayBuffer: true, function(error, data) {
  if (error) {
    return handleError(error);
  }
  // data is an ArrayBuffer instance holding the image.
});
```

## Binary File Writes in node.js

When the `data` argument to `writeFile` is a JavaScript string, `writeFile`
uses the UTF-8 encoding to send the contents to the Dropbox. This works for
text files, but is unsuitable for images and other binary files. `Buffer` and
`ArrayBuffer` instances are transmitted without any string encoding, and are
suitable for binary files.

```javascript
fs.readFile("some_image.png", function(error, data) {
  // No encoding passed, readFile produces a Buffer instance
  if (error) {
    return handleNodeError(error);
  }
  client.writeFile("the_image.png", data, function(error, stat) {
    if (error) {
      return handleError(error);
    }
    // The image has been succesfully written.
  });
});
```

redpajama_set_name: RedPajamaGithub


text:
title: Wrecked
devised: true
period: Edinburgh
season: Edinburgh
season_sort: 580
date_start: 2017-08-04
date_end: 2017-08-26
venue: Royal Terrace, Greenside
venue_sort: Greenside

assets:
  - type: poster
    image: WbM3BD4
  - type: flyer
    image: Cdqrs4X
  - type: flyer
    image: QtX7rrb
  - type: logo
    image: NQbXvH2
  - type: coverphoto
    image: R33nQ6f

prod_shots: ggPgWr

links:
  - type: Review
    href: http://edfringereview.com/r/WYh06bDwTo6x5kwRXDx6yg?
    snapshot: fKFbP
    publisher: edfringereview
    author: James Tibbles
    title: "Wrecked"
    date: 2017-08-23
    rating: 4/5
    quote: "The shapes of Trueman's blocking are visually satisfying and he clearly played to each actor's strengths when devising their characters and comic tropes. Every single member of the cast is also completely committed to their character and attentive to their physical characterisation."
  - type: Review
    href: http://edinburgh.fringeguru.com/reviews/edinburgh-2017/wrecked
    snapshot: nCYWi
    publisher: FringeGuru
    author: Caroline Cawley
    title: "Wrecked"
    date: 2017-08-22
    rating: 3/5
    quote: "The six actors all create distinctive characters: Maggie is very serious, Billy is earnest, and Francois is Machiavellian. These different approaches could have been jarring, but instead they highlight the qualities of their characters and it meshes together nicely. However, one thing that all of them have in common is that they are all caricatures of swashbuckling pirates, and are all hopelessly incompetent at leading."

cast:
 - role: Eddie
   name: Maddy Strauss
 - role: Francoise
   name: Emma White
 - role: James
   name: Callum Walker
 - role: Anne
   name: Felicity Chilver
 - role: Billy
   name: Andrew Houghton
 - role: Henry
   name: Miguel Barrulas

crew:
  - role: Director
    name: Chris Trueman
  - role: Producer
    name: Amy Crighton
  - role: Technical Director
    name: Adam Frankland
  - role: Script Editor
    name: Ian Sheard
  - role: Publicity Manager
    name: Keir Birchall

---

 Loosely based on *The Tempest*, this show is an absurd political satire chronicling two days in the lives of six pirates, and one dead parrot, shipwrecked on a tropical island. These buffoonish buccaneers turn on one another, each vying for power, using different ideologies to manipulate their comrades. This fast-paced comedy explores whether institutions can ever be anything but systems for oppression and whether game theory is an accurate description of political practice.


text:
@implementation FIAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    FIViewController *entypoViewController = [FIViewController new];
    entypoViewController.iconClass = [FIEntypoIcon class];

    FIViewController *entypoSocialViewController = [FIViewController new];
    entypoSocialViewController.iconClass = [FIEntypoSocialIcon class];

    FIViewController *iconicViewController = [FIViewController new];
    iconicViewController.iconClass = [FIIconicIcon class];

    FIViewController *fontAwesomeViewController = [FIViewController new];
    fontAwesomeViewController.iconClass = [FIFontAwesomeIcon class];

    UITabBarController *tabbarController = [UITabBarController new];

    NSArray *viewControllers =
    @[
      [[UINavigationController alloc] initWithRootViewController:entypoViewController],
      [[UINavigationController alloc] initWithRootViewController:entypoSocialViewController],
      [[UINavigationController alloc] initWithRootViewController:iconicViewController],
      [[UINavigationController alloc] initWithRootViewController:fontAwesomeViewController]
      ];

    tabbarController.viewControllers = viewControllers;

    self.window.rootViewController = tabbarController;
    [self.window makeKeyAndVisible];
    return YES;
}

@end


text:
module Stupidedi
  using Refinements

  module Schema
    class AbstractElementUse < AbstractUse
      include Inspect

      def_delegators :requirement, :forbidden?, :required?, :optional?

      def_delegators :definition, :code_lists

      # @return [Symbol]
      abstract :id

      # @return [String]
      abstract :name

      # @return [String]
      abstract :description

      # @return [ElementReq]
      abstract :requirement

      # @return [SimpleElementDef, CompositeElementDef]
      abstract :definition

      abstract :simple?

      abstract :component?

      # @return [SimpleElementVal, CompositeElementVal]
      def empty(position)
        definition.empty(self, position)
      end

      # @return [SimpleElementVal, CompositeElementVal]
      def value(object, position)
        definition.value(object, self, position)
      end

      def composite?
        not simple?
      end
    end
  end
end


text:
Dolphin Java Demo
===================

Pure Java Demos for the use of Open Dolphin.
Open Dolphin is used as an external dependency.
For documentation on Open Dolphin see http://open-dolphin.org

Prerequisites
-------------
If you use Java 7u6 or later, you are all set.
Otherwise, JAVAFX_HOME must be set to a 2.1.0 version. (Version 2.2 also works fine.)

Run an initial Demo (LazyLoadingDemo)
> gradlew LayLoadingDemo

To see a choice of demos use:
> gradlew listDemos

How to build
------------
> gradlew clean build

To see a choice of all available gradle tasks use:
> gradlew tasks

Purpose
-------
Showing how to use Open Dolphin with pure Java
- We choose Java FX as UI Technology for our demos but there might be other clients in the future

Project layout
--------------
The multi-project build consists of these subprojects

- shared (code that is needed on both client and server)
- client (visualization)
- server (domain model and control logic)
- combined (for testing the client-server combination)


text:
package org.intellij.lang.xpath.xslt.refactoring;

import com.intellij.lang.refactoring.RefactoringSupportProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.refactoring.RefactoringActionHandler;
import org.intellij.lang.xpath.xslt.XsltSupport;
import org.intellij.lang.xpath.xslt.refactoring.extractTemplate.XsltExtractTemplateAction;
import javax.annotation.Nonnull;

/**
 * @author Dmitry Avdeev
 */
public class XsltRefactoringSupportProvider extends RefactoringSupportProvider {

  @Override
  public boolean isAvailable(@Nonnull PsiElement context) {
    PsiFile containingFile = context.getContainingFile();
    return containingFile != null && XsltSupport.isXsltFile(containingFile);
  }

  @Override
  public RefactoringActionHandler getExtractMethodHandler() {
    return new XsltExtractTemplateAction();
  }
}


text:
// Copyright (C) 2012 iwg molw5
// For conditions of distribution and use, see copyright notice in COPYING

#pragma once

namespace framework
{
    /**
    * \brief Common 32-bit word swap implementation.
    */
    template <typename T>
    FRAMEWORK_ALWAYS_INLINE
    T wswap32 (T&& in)
    {
        static_assert(sizeof(T) == 4, "32-bit type expected");
        uint32_t const x = static_cast <uint32_t> (in);
        return static_cast <T> ((x >> 16) | (x << 16));
    }

    /**
    * \brief Common 64-bit word swap implementation.
    */
    template <typename T>
    FRAMEWORK_ALWAYS_INLINE
    T wswap64 (T&& in)
    {
        static_assert(sizeof(T) == 8, "64-bit type expected");
        uint64_t x = static_cast <uint64_t> (in);
        x = ((x & 0xFFFF0000FFFF0000) >> 16) | ((x & 0x0000FFFF0000FFFF) << 16);
        return static_cast <T> ((x >> 32) | (x << 32));
    }
}

#define FRAMEWORK_WORDSWAP8(x) x
#define FRAMEWORK_WORDSWAP16(x) x
#define FRAMEWORK_WORDSWAP32(x) ::framework::wswap32(x)
#define FRAMEWORK_WORDSWAP64(x) ::framework::wswap64(x)


text:
package org.apache.solr.analytics.value;

import java.util.Arrays;
import java.util.Iterator;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.analytics.value.FillableTestValue.TestStringValueStream;
import org.junit.Test;

public class CastingStringValueStreamTest extends SolrTestCaseJ4 {

  @Test
  public void objectStreamCastingTest() {
    TestStringValueStream val = new TestStringValueStream();

    // No values
    val.setValues();
    ((AnalyticsValueStream) val)
        .streamObjects(
            value -> {
              fail("There should be no values to stream");
            });

    // Multiple Values
    val.setValues("abc", "def", "ghi");
    Iterator<Object> values = Arrays.<Object>asList("abc", "def", "ghi").iterator();
    ((AnalyticsValueStream) val)
        .streamObjects(
            value -> {
              assertTrue(values.hasNext());
              assertEquals(values.next(), value);
            });
    assertFalse(values.hasNext());
  }

  @Test
  public void constantConversionTest() {
    AnalyticsValueStream val = new TestStringValueStream();
    assertSame(val, val.convertToConstant());
  }
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="Apache Forrest" name="Generator">
<meta name="Forrest-version" content="0.10-dev">
<meta name="Forrest-skin-name" content="pelt">
<title>Apache™ FOP: Quick Start Guide</title>
<link type="text/css" href="skin/basic.css" rel="stylesheet">
<link media="screen" type="text/css" href="skin/screen.css" rel="stylesheet">
<link media="print" type="text/css" href="skin/print.css" rel="stylesheet">
<link type="text/css" href="skin/profile.css" rel="stylesheet">

<link rel="shortcut icon" href="favicon.ico">

<form action="http://www.google.com/search" method="get" class="roundtopsmall">
<input value="xmlgraphics.apache.org" name="sitesearch" type="hidden"><input onFocus="getBlank (this, 'Search the site with google');" size="25" name="q" id="query" type="text" value="Search the site with google">
                    <input name="Search" value="Search" type="submit">
</form>

Home

Version 1.0

Version 1.1

FOP Trunk

Development

The Apache Software Foundation > Apache XML Graphics Project

About

Introduction

Download

Quick Start Guide

Compliance

Getting Help

FAQs

Mailing Lists

License

ASF Sponsorship Program

ASF Thanks

Security

Resources

XSL-FO

Examples

Bugs

Wiki

Other

Project

News

Who We Are

Status

Known Issues

Changes

        XML

        PDF

Font size:
	           <input value="Reset" class="resetfont" title="Reset text" onclick="ndeSetTextSize('reset'); return false;" type="button">
	           <input value="-a" class="smallerfont" title="Shrink text" onclick="ndeSetTextSize('decr'); return false;" type="button">
	           <input value="+a" class="biggerfont" title="Enlarge text" onclick="ndeSetTextSize('incr'); return false;" type="button">

Apache™ FOP: Quick Start Guide

Everything you need to start using and appreciating Apache™ FOP quickly.

Apache™ FOP Essentials

Hello World with FOP

Apache™ FOP Essentials

The goal of this Quick Start Guide is to help novice users get Apache FOP up and running quickly. Typically, you'll need to:

Download FOP

Build FOP (you can skip this step if you download the binary distribution!)

Configure FOP

Run FOP

Here are some links to help you find out what FOP can do, as well as how and where to get help:

Calling FOP from a Java Application

Using FOP in Servlets

Using FOP in an 'Ant' Build Script

XSL-FO Compliance (what FOP supports and what it doesn't)

FAQs

Getting Help

Mailing Lists

        Once you've familiarized yourself with the basics, you can get more detailed information,
        in the detailed FOP product documentation.

Hello World with FOP

        This section walks you through a "Hello World!" page with Apache FOP. We're assuming you
        download the binary distribution and that you have a Java Runtime Environment (version 1.4
        or later) installed.

          Unpack the downloaded binary distribution to a directory of your choice (for example,
          C:\FOP if you're on Windows). Let's call that
          directory <fop-home>.

          Get a command prompt in the <fop-home> directory and write:

          Windows: fop -fo examples/fo/basic/readme.fo -awt

          Unix: ./fop -fo examples/fo/basic/readme.fo -awt

          If all went well, this should open a window showing you a "readme"-style document.
          This is just to verify that FOP runs correctly.

          Now, take your favorite XML editor and create a small XML file like the following. Replace
          "Frank" with your own first name to make it a bit more personal and save it as
          name.xml:

<name>Frank</name>

          To produce a PDF file from this XML file, we need an XSLT stylesheet that converts the
          XML to XSL-FO. This is the first step in the processing chain. The second step will be
          done by FOP when it reads the generated XSL-FO document and formats it to a PDF document.
          You can copy the following minimal XSLT stylesheet, which takes your first name and
          produces a "Hello World!"-style document (save it as name2fo.xsl):

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:fo="http://www.w3.org/1999/XSL/Format">
  <xsl:output method="xml" indent="yes"/>
  <xsl:template match="/">
    <fo:root>
      <fo:layout-master-set>
        <fo:simple-page-master master-name="A4-portrait"
              page-height="29.7cm" page-width="21.0cm" margin="2cm">
          <fo:region-body/>
        </fo:simple-page-master>
      </fo:layout-master-set>
      <fo:page-sequence master-reference="A4-portrait">
        <fo:flow flow-name="xsl-region-body">
          <fo:block>
            Hello, <xsl:value-of select="name"/>!
          </fo:block>
        </fo:flow>
      </fo:page-sequence>
    </fo:root>
  </xsl:template>
</xsl:stylesheet>

          Finally, let's put the previous two steps together: Go back to the command prompt and
          enter the following command:

          Windows: fop -xml name.xml -xsl name2fo.xsl -pdf name.pdf

          Unix: ./fop -xml name.xml -xsl name2fo.xsl -pdf name.pdf

          You've produced your first PDF with Apache FOP! Please open name.pdf
          in your favorite PDF viewer.

          version 1394416

        Copyright ©
         1999-2012 The Apache Software Foundation. Licensed under Apache License 2.0

    Apache, Apache FOP, the Apache feather logo, and the Apache FOP
    logos are trademarks of The Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners.


text:
/* */
"format cjs";
describe('PosAnimation', function () {
	var el;

	beforeEach(function () {
		el = document.createElement('div');
		this.subject = new L.PosAnimation();
		this.subject._el = el;
	});

	describe('#_onStep', function () {
		it("sets element position and fires step event if it is able to get current position", function () {
			var point = new L.Point(5, 5, true);
			sinon.stub(this.subject, '_getPos').returns(point);
			this.subject.fire = sinon.stub();
			this.subject._onStep();
			expect(this.subject.fire.withArgs('step').calledOnce).to.be(true);
			expect(L.DomUtil.getPosition(this.subject._el)).to.be(point);
		});

		it('stops transition if a position returned', function () {
			sinon.stub(this.subject, '_onTransitionEnd');
			sinon.stub(this.subject, '_getPos').returns(undefined);
			this.subject._onStep();
			expect(this.subject._onTransitionEnd.calledOnce).to.be(true);
		});
	});
});


text:
module RedHillConsulting::ForeignKeyMigrations::ActiveRecord
  module Base
    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods
      def references(table_name, column_name, options = {})
        column_name = column_name.to_s
        if options.has_key?(:references)
          references = options[:references]
          references = [references, :id] unless references.nil? || references.is_a?(Array)
          references
        elsif column_name == 'parent_id'
          [table_name, :id]
        elsif column_name =~ /^(.*)_id$/
          [pluralized_table_name($1), :id]
        end
      end
    end
  end
end


text:
package com.bazaarvoice.emodb.cachemgr.invalidate;

import com.bazaarvoice.emodb.cachemgr.api.CacheRegistry;
import com.bazaarvoice.emodb.cachemgr.api.InvalidationEvent;
import com.bazaarvoice.emodb.cachemgr.api.InvalidationListener;
import com.bazaarvoice.emodb.cachemgr.api.InvalidationScope;
import com.google.inject.Inject;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Listens for {@link InvalidationEvent} and forwards those events to other servers and other
 * data centers based on {@link InvalidationEvent#getScope()}.
 */
public class RemoteInvalidationListener implements InvalidationListener {
    private final RemoteInvalidationProvider _invalidator;

    @Inject
    public RemoteInvalidationListener(CacheRegistry cacheRegistry, RemoteInvalidationProvider invalidator) {
        _invalidator = checkNotNull(invalidator, "invalidator");
        cacheRegistry.addListener(this);
    }

    @Override
    public void handleInvalidation(InvalidationEvent event) {
        InvalidationScope scope = event.getScope();
        // First, flush every individual server in our local data center.
        if (scope == InvalidationScope.DATA_CENTER || scope == InvalidationScope.GLOBAL) {
            _invalidator.invalidateOtherServersInSameDataCenter(event);
        }
        // Next, flush remote data centers.
        if (scope == InvalidationScope.GLOBAL) {
            _invalidator.invalidateOtherDataCenters(event);
        }
    }
}


text:
define(['jquery', 'foo'], function(jquery, bar) {

"use strict";

var pending = { then: function () {} };

module.exports = function (operation) {
    var latestPromise = null;

    return function () {
        var promiseForResult = operation.apply(this, arguments);
        latestPromise = promiseForResult;

        return promiseForResult.then(
            function (value) {
                if (latestPromise === promiseForResult) {
                    return value;
                } else {
                    return pending;
                }
            },
            function (reason) {
                if (latestPromise === promiseForResult) {
                    throw reason;
                } else {
                    return pending;
                }
            }
        );
    };
};

});


text:
<?php
define("FORUM_NOT_FOUND", 0);
define("AUTH_ERROR", 1);
class mybbBot {
  private $lastvisit, $lastactive, $token, $sid, $b, $u, $p, $h;
  function __construct($url, $user, $pass) {
    $this->b = $url;
    $this->p = $pass;
    $this->u = $user;
    if (!file_get_contents($this->b)) throw new myBBException(FORUM_NOT_FOUND);
    if (!$this->login($this->u, $this->p)) throw new myBBException(AUTH_ERROR);
  }
  private function login($user, $password) {
    global $http_response_header;
    $result = $this->connect($this->b . 'member.php', array(
    'username' => $user,
    'password' => $password,
    'action' => "do_login",
    'url' => ""
      )
      );
    $cookies = array();
    foreach ($http_response_header as $hdr) {
      if (preg_match('/^Set-Cookie:\s*([^;]+)/', $hdr, $matches)) {
        parse_str($matches[1], $tmp);
        $cookies += $tmp;
      }
    }
    if (!isset($cookies["mybbuser"])) return false;
    $this->sid = $cookies["sid"];
    $this->token = $cookies["mybbuser"];
    $this->lastvist = $cookies["mybb"]["lastvist"];
    $this->lastactive = $cookies["mybb"]["lastactive"];
    return true;
  }
  private function connect($url, $post) { //Connector function
    global $http_response_header;
    if ($post != null) {
      $opts = array('http' =>
        array(
      'method'  => 'POST',
      'header'  => "Content-type: application/x-www-form-urlencoded\r\n" .
        "Cookie: mybb[referrer]=1; mybb[lastvisit]=" . $this->lastvist . "; mybb[lastactive]=" . $this->lastactive . "; loginattemps=1; mybbuser=" . $this->token . "; sid=" . $this->sid,
      'content' => http_build_query($post)
        )
        );
    }
    else {
      $opts = array('http' =>
        array(
      'method'  => 'GET',
      'header'  => 'Cookie: mybb[referrer]=1; mybb[lastvisit]=' . $this->lastvist . '; mybb[lastactive]=' . $this->lastactive . '; loginattemps=1; mybbuser=' . $this->token . '; sid=' . $this->sid
        )
        );
    }
    return file_get_contents($url, false, stream_context_create($opts));
  }
  public function quickReply($url, $msg) { //Post a new reply to a thread at $url
    $html = new DOMDocument();
    $url = $this->switchIDToURL($url,"showthread.php?tid=");
    $data = $this->connect($url, null);
    $data = substr($data, strpos($data, '<form method="post" action="newreply.php'));
    $data = substr($data, 0, strpos($data, '</form>')+7);
    $html->loadHTML($data);
    $els = $html->getelementsbytagname('input');
    $url = $this->b . $html->getElementById('quick_reply_form')->getAttribute('action');
    $list = array();
    foreach($els as $inp) $list[$inp->getAttribute('name')] = $inp->getAttribute('value');
    $list["message"] = $msg;
    unset($list["previewpost"]);
    $data = $this->connect($url, $list);
    $data = substr($data, strpos($data,"pid=")+4);
    return substr($data, 0, strpos($data, '#'));
  }
  public function newThread($fid,$t,$c){ //Post a new thread in $id section
    $html = new DOMDocument();
    $fid = $this->switchIDToURL($fid,"newthread.php?fid=");
    $data = $this->connect($fid, null);
    if(stripos($data, "Invalid forum") !== false) return false;
    $data = substr($data, strpos($data, '<form action="newthread.php?'));
    $data = substr($data, 0, strpos($data, '</form>')+7);
    $html->loadHTML($data);
    $els = $html->getelementsbytagname('input');
    $fid .= "&processed=1";
    $list = array();
    foreach($els as $inp) $list[$inp->getAttribute('name')] = $inp->getAttribute('value');
    $list["message"] = $c;
    $list["subject"] = $t;
    unset($list["previewpost"]);
    unset($list["savedraft"]);
    unset($list["modoptions[stickthread]"]);
    unset($list["modoptions[closethread]"]);
    unset($list["postpoll"]);
    $data = $this->connect($fid, $list);
    $data = substr($data, strpos($data,"?tid=")+5);
    return substr($data, 0, strpos($data, '"'));
  }
  public function editPost($pid,$t,$c){ //Edits post with $pid
    $html = new DOMDocument();
    $pid = $this->switchIDToURL($pid,"editpost.php?pid=");
    $data = $this->connect($pid, null);
    $data = substr($data, strpos($data, '<form action="editpost.php?'));
    $data = substr($data, 0, strpos($data, '</form>')+7);
    $html->loadHTML($data);
    $els = $html->getelementsbytagname('input');
    $pid .= "&processed=1";
    foreach($els as $inp) $list[$inp->getAttribute('name')] = $inp->getAttribute('value');
    if($c != null) $list["message"] = $c;
    if($t != null) $list["subject"] = $t;
    unset($list["previewpost"]);
    $data = $this->connect($pid, $list);
  }
  public function rateThread($id,$rating){ //Rates the thread with $id
    if($rating > 5 || $rating < 1) return false;
    if($this->connect($this->b . "ratethread.php?tid=" . $id . "&rating=" . $rating . "&my_post_key=" . $this->getPostKey(),null) !== false) return true;
    return false;
  }
  public function getPostKey(){ //Get post key of logged in user
    $data = $this->connect($this->b, null);
    $data = substr($data,strpos($data,'var my_post_key = "')+19);
    return substr($data,0,strpos($data,'"'));
  }
  private function switchIDToURL($id,$url){
    if(is_numeric($id)) $id = $url . $id;
    if(strpos($id, $this->b) === false) $id = $this->b . $id;
    return $id;
  }
  public function deletePost($pid){
    $this->connect($this->b . "editpost.php",
      array(
        "my_post_key" => $this->getPostKey(),
        "delete" => "1",
        "submit" => "1",
        "action" => "deletepost",
        "pid" => $pid));
  }
  public function sendMessage(Array $to, $t, $c){
    $this->connect($this->b . "private.php?action=send",
      array(
        "my_post_key" => $this->getPostKey(),
        "to" => implode(",", $to),
        "submit" => "1",
        "action" => "do_send",
        "subject" => $t,
        "message" => $c,
        "pmid" => "1",
        "do" => "1"));
  }
}
class myBBException extends Exception {
  private $c;
    function __construct($cause) {
      $this->c = $cause;
    }
    public function getCause(){
      return $this->c;
    }
}


text: A hacked up GUI to toggle laptop touchscreen under Linux


text:
type OrGen = () => (number | Generator<string, (arg: number) => void, undefined>);
const g: OrGen = function* () {
    return (num) => console.log(num);
}


text:
class book():
    pass


text:
package eval

import (
	"strconv"

	"github.com/skatsuta/monkey-interpreter/ast"
	"github.com/skatsuta/monkey-interpreter/object"
	"github.com/skatsuta/monkey-interpreter/token"
)

const (
	// FuncNameQuote is a name for quote function.
	FuncNameQuote = "quote"
	// FuncNameUnquote is a name for unquote function.
	FuncNameUnquote = "unquote"
)

func quote(node ast.Node, env object.Environment) object.Object {
	node = evalUnquoteCalls(node, env)
	return &object.Quote{Node: node}
}

func evalUnquoteCalls(quoted ast.Node, env object.Environment) ast.Node {
	modifier := func(node ast.Node) ast.Node {
		call, ok := node.(*ast.CallExpression)
		if !ok || call.Function.TokenLiteral() != FuncNameUnquote || len(call.Arguments) != 1 {
			return node
		}

		unquoted := Eval(call.Arguments[0], env)
		return convertObjectToASTNode(unquoted)
	}
	return ast.Modify(quoted, modifier)
}

func convertObjectToASTNode(obj object.Object) ast.Node {
	switch obj := obj.(type) {
	case *object.Integer:
		base := 10
		t := token.Token{
			Type:    token.INT,
			Literal: strconv.FormatInt(obj.Value, base),
		}
		return &ast.IntegerLiteral{Token: t, Value: obj.Value}
	case *object.Boolean:
		var t token.Token
		if obj.Value {
			t = token.Token{Type: token.TRUE, Literal: "true"}
		} else {
			t = token.Token{Type: token.FALSE, Literal: "false"}
		}
		return &ast.Boolean{Token: t, Value: obj.Value}
	case *object.Quote:
		return obj.Node
	default:
		return nil
	}
}


text:
package game.combat;

import java.util.Scanner;

import utility.Gender;
import utility.Orientation;
import utility.Pronoun;
import utility.Quad;

/**
 * Test the combat system for some battlers.
 *
 * @author Aaron Carson
 * @version Aug 5, 2015
 */
public class CombatInterfaceTester
{
	private static final String	DASHED_LINE	= "------------------------------------------------------------";

	// ***********************************************************************
	// FIELDS
	// ***********************************************************************

	Battler						hero;
	Battler						monster;

	// ***********************************************************************
	// CONSTRUCTOR
	// ***********************************************************************

	/**
	 * Initialize values or a new simulation.
	 */
	public CombatInterfaceTester() {
		hero = createHero("John");
		monster = createGenericWeakMonster("goblin");
	}

	// ***********************************************************************
	// METHODS
	// ***********************************************************************

	/**
	 * Create the Hero to use in this simulation.
	 *
	 * @param name The name of the hero.
	 * @return a new, unfortunate Hero.
	 */
	public Battler createHero(String name) {
		TestBattler hero = new TestBattler();

		// vital stats.
		hero.setName(name);
		hero.setGender(Gender.MALE);
		hero.setHealth(65);

		// attack statistics (# of attacks, range, critical, miss chance)
		hero.setAttacks(2);
		hero.setRange(16);
		hero.setMissChance(5);
		hero.setCritRate(5);
		hero.setCritMultiplier(2);

		// battle-related stats
		hero.setPower(8);
		hero.setDefense(1);
		hero.setAccuracy(1);
		hero.setEvasion(1);
		hero.setLuck(10);

		// all done
		return hero;
	}

	/**
	 * Create a generic, weak monster to use in this simulation.
	 *
	 * @param name The name.
	 * @return A new monster of the given name, with default TestBattler stats.
	 */
	public Battler createGenericWeakMonster(String name) {
		TestBattler monster = new TestBattler();
		monster.setName(name);
		monster.setGender(Gender.NEUTER);
		monster.setGeneric(true);
		monster.setHealth(40);
		monster.setRange(16);
		monster.setAttacks(3);

		// set battle stats
		monster.setPower(7);
		monster.setDefense(5);
		monster.setAccuracy(10);
		monster.setEvasion(10);
		monster.setLuck(1);

		// set position
		monster.setQuad(TestBattler.getAdjacentQuad(hero.getQuad(),
				Orientation.ABOVE));
		// all other stats are
		return monster;

	}

	// ***********************************************************************
	// Simulations
	// ***********************************************************************

	/**
	 * All that happens is the hero and monster in question duke it out until
	 * one side wins.
	 */
	public int runAttackSimulation(boolean waitForInput) {
		Scanner scanner = new Scanner(System.in);
		boolean gameOver = false;
		int time = 1;

		// get a local copy of the monster and hero.
		Battler hero = this.hero.getCopy();
		Battler monster = this.monster.getCopy();
		String heroName = Battler.getNameFor(hero);
		String monsterName = Battler.getNameFor(monster);
		System.out.println(DASHED_LINE);
		System.out.printf("Begin Simulation: %s vs %s ...\n", heroName,
				monsterName);
		System.out.println(DASHED_LINE);
		System.out.println("Pre-battle statistics:");
		System.out.println();
		Battler.printStatistics(hero, monster);
		System.out.println();
		Battler.printStatistics(monster, hero);

		// simulation loop
		while (!gameOver) {
			System.out.println(DASHED_LINE);
			System.out.printf("turn :%d\n", time);
			System.out.println(DASHED_LINE);
			System.out.printf("%s: (%d/%d) %s: (%d/%d)\n",
					heroName,			// John
					hero.getHealth() - hero.getDamage(),	// 0
					hero.getHealth(),	// 10
					monsterName,		// Goblin
					monster.getHealth() - monster.getDamage(),// 0
					monster.getHealth() // 5
					);
			if (waitForInput) {
				System.out.print("> ");
				scanner.nextLine();
			}
			System.out.println();

			// take turns fighting.
			if (hero.isReadyToAttack()) Battler.attack(hero, monster);
			if (monster.isReadyToAttack()) Battler.attack(monster, hero);
			time++;
			System.out.println();

			// check if game over.
			if (hero.hasLethalDamage() || monster.hasLethalDamage()) {
				gameOver = true;
			}
		}

		// report the results
		Battler winner = hero.hasLethalDamage() ? monster : hero;
		Battler loser = winner == hero ? monster : hero;
		System.out.println(DASHED_LINE);
		System.out.println("The battle is over.");
		System.out.printf("%s has defeated %s.\n",
				Battler.getCapitalizedString(Battler.getNameFor(winner)),
				Battler.getNameFor(loser));
		System.out.println();
		// print the CombatStatistics for each hero.
		System.out.println(hero.getCombatStatistics().getStatReadout());
		System.out.println(monster.getCombatStatistics().getStatReadout());

		// hold to exit.
		if (waitForInput) {
			System.out.print("> ");
			scanner.nextLine();
		}

		if (winner == hero) return 1;
		else return 0;
	}

	// ***********************************************************************
	// MAIN
	// ***********************************************************************

	/**
	 * Run a simulation.
	 *
	 * @param args
	 */
	public static void main(String[] args) {
		CombatInterfaceTester tester = new CombatInterfaceTester();
		boolean waitForInput = false;
		int tests = 1;
		int wins = 0;
		for (int i = 0; i < tests; i++){
			wins += tester.runAttackSimulation(waitForInput);
		}
		System.out.println();
		System.out.println("Battles won by hero:    " + wins);
		System.out.println("Battles won by monster: " + (tests - wins));
	}
}


text:
function GetProgress(s)
  return string.match(s, '(%d+)%% decoded');
end


text:
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<Entity>
	<Name>EntityApplication</Name>
	<Description>EntityApplication</Description>
	<SetName>EntityApplications</SetName>
	<Descriptor>Entity Application</Descriptor>
	<SetDescriptor>Entity Applications</SetDescriptor>
	<SqlTable>entitiesapplications</SqlTable>

	<Properties>

		<Property>
			<Name>Id</Name>
			<Description>Id</Description>
			<Type>Id</Type>
			<SqlType>int</SqlType>
		</Property>

		<Property>
			<Name>IdEntity</Name>
			<Description>Entity</Description>
			<Type>IdRef</Type>
			<SqlType>int</SqlType>
			<Reference>Entity</Reference>
		</Property>

		<Property>
			<Name>IdApplication</Name>
			<Description>Application</Description>
			<Type>IdRef</Type>
			<SqlType>int</SqlType>
			<Reference>Application</Reference>
		</Property>

	</Properties>
</Entity>


text:
package python.platform;

public class LogStream extends java.io.OutputStream {
    protected java.lang.String tag;
    protected byte[] buf;
    protected int size;
    protected int count;
    protected int priority;

    public LogStream(int priority, java.lang.String tag, int size) {
        this.tag = tag;
        this.priority = priority;
        this.size = size;

        buf = new byte[size];
    }

    public void write(int b) {
        if (b != '\n') {
            buf[count] = (byte) b;
            count++;
        }

        if (b == '\n' || count == size) {
            android.util.Log.println(priority, tag, new java.lang.String(buf, 0, count));
            count = 0;
        }
    }
}


text:
@implementation TextFieldsViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self tableView].allowsSelection = NO;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MenuCell"];
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MenuCell"];
    }

    if (indexPath.row == 0) {

        // plain text field
        CGRect frame = CGRectMake(5.0, 8.0, 260, 40);
        UITextField *textField = [[UITextField alloc] initWithFrame:frame];

        textField.borderStyle = UITextBorderStyleBezel;
        textField.textColor = [UIColor blackColor];
        textField.font = [UIFont systemFontOfSize:17.0];
        textField.placeholder = @"placeholder text";
        textField.backgroundColor = [UIColor whiteColor];
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.keyboardType = UIKeyboardTypeDefault;
        textField.returnKeyType = UIReturnKeyDone;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;

        [cell addSubview:textField];

    } else if (indexPath.row == 1) {

        // rounded text field
        CGRect frame = CGRectMake(5.0, 8.0, 260, 40);
        UITextField *textField = [[UITextField alloc] initWithFrame:frame];

        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.textColor = [UIColor blackColor];
        textField.font = [UIFont systemFontOfSize:17.0];
        textField.placeholder = @"placeholder text";
        textField.backgroundColor = [UIColor whiteColor];
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.keyboardType = UIKeyboardTypeDefault;
        textField.returnKeyType = UIReturnKeyDone;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;

        [cell addSubview:textField];

    } else if (indexPath.row == 2) {

        // secure text field

        CGRect frame = CGRectMake(5.0, 8.0, 260, 40);
        UITextField *textField = [[UITextField alloc] initWithFrame:frame];

        textField.borderStyle = UITextBorderStyleBezel;
        textField.textColor = [UIColor blackColor];
        textField.font = [UIFont systemFontOfSize:17.0];
        textField.placeholder = @"password text";
        textField.backgroundColor = [UIColor whiteColor];
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.keyboardType = UIKeyboardTypeDefault;
        textField.returnKeyType = UIReturnKeyDone;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.secureTextEntry = TRUE;

        [cell addSubview:textField];

    }

    return cell;
}

@end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>MIPS Pipelined Scoreboard Machine Simulator: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

MIPS Pipelined Scoreboard Machine Simulator
    1.4

Label Member List

This is the complete list of members for Label, including all inherited members.

getLineNum()	Label

getMemoryLocation()	Variable

getName()	Variable

getSize()	Variable

getValue()	Variable

getValueBin()	Variable

getValueFloat()	Variable

holdsString	Variable	protected

isString()	Variable

Label()	Label

Label(string name)	Label

name	Variable	protected

setLineNum(int lineNum)	Label

sizeBytes	Variable	protected

storedAt	Variable	protected

storeFloat(float number)	Variable

storeNumber(qword number)	Variable

storeString(string line)	Variable

value	Variable	protected

Variable()	Variable

Variable(string name, int size, address storedAt)	Variable

<address class="footer">
Generated by

 1.8.12
</address>


text:
A toy programming language, tentatively called EL3 (embedded lisp-like language)

The main goal behind it is to create a very simple scripting language for C++
programs to use, with a similar syntax to lisp. It likely won't ever be a
serious alternative to a proper scripting language; this is mostly just a
learning excercise about creating programming languages.

Will use ( ) style lists for calling functions with arguments, and { } for blocks
which aren't evaluated immediately (and can be used to create functions). The
formal language grammar is still up in the air.

It will only have local storage on a stack. Non-scoped allocation would need to
be done C++ side and exposed via native functions.

Probable built-in functions to add:

- standard operators, +, -, *, /, %, <, >, == etc.
- 'def' or 'let' style function to add stuff to the symbol table.
- conditionals like 'if', loops with 'for', 'while' etc.

Trivial currently working example programs:

*1 + 2 using a lambda function*

    ({ :x -> + x 1 } 2)

*double numbers in a list*

    (map [1 2 3] { :x -> * 2 x })

*count down from 10*

    (let [:x 10] {
        while { x } {
            (echo x)
            (= :x (- x 1))
        }
    })


text:
#ifndef HB_OT_POST_TABLE_HH
#define HB_OT_POST_TABLE_HH

#include "hb-open-type-private.hh"

namespace OT {

/*
 * post -- PostScript
 */

#define HB_OT_TAG_post HB_TAG('p','o','s','t')

struct postV2Tail
{
  inline bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
    return_trace (numberOfGlyphs.sanitize (c) &&
		  c->check_array (glyphNameIndex, sizeof (USHORT), numberOfGlyphs));
  }

  USHORT	numberOfGlyphs;		/* Number of glyphs (this should be the
					 * same as numGlyphs in 'maxp' table). */
  USHORT	glyphNameIndex[VAR];	/* This is not an offset, but is the
					 * ordinal number of the glyph in 'post'
					 * string tables. */
  BYTE		namesX[VAR];		/* Glyph names with length bytes [variable]
					 * (a Pascal string). */

  DEFINE_SIZE_ARRAY2 (2, glyphNameIndex, namesX);
};

struct post
{
  static const hb_tag_t tableTag = HB_OT_TAG_post;

  inline bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
    if (unlikely (!c->check_struct (this)))
      return_trace (false);
    if (version.to_int () == 0x00020000)
    {
      const postV2Tail &v2 = StructAfter<postV2Tail>(*this);
      return_trace (v2.sanitize (c));
    }
    return_trace (true);
  }

  public:
  FixedVersion<>version;		/* 0x00010000 for version 1.0
					 * 0x00020000 for version 2.0
					 * 0x00025000 for version 2.5 (deprecated)
					 * 0x00030000 for version 3.0 */
  Fixed		italicAngle;		/* Italic angle in counter-clockwise degrees
					 * from the vertical. Zero for upright text,
					 * negative for text that leans to the right
					 * (forward). */
  FWORD		underlinePosition;	/* This is the suggested distance of the top
					 * of the underline from the baseline
					 * (negative values indicate below baseline).
					 * The PostScript definition of this FontInfo
					 * dictionary key (the y coordinate of the
					 * center of the stroke) is not used for
					 * historical reasons. The value of the
					 * PostScript key may be calculated by
					 * subtracting half the underlineThickness
					 * from the value of this field. */
  FWORD		underlineThickness;	/* Suggested values for the underline
					   thickness. */
  ULONG		isFixedPitch;		/* Set to 0 if the font is proportionally
					 * spaced, non-zero if the font is not
					 * proportionally spaced (i.e. monospaced). */
  ULONG		minMemType42;		/* Minimum memory usage when an OpenType font
					 * is downloaded. */
  ULONG		maxMemType42;		/* Maximum memory usage when an OpenType font
					 * is downloaded. */
  ULONG		minMemType1;		/* Minimum memory usage when an OpenType font
					 * is downloaded as a Type 1 font. */
  ULONG		maxMemType1;		/* Maximum memory usage when an OpenType font
					 * is downloaded as a Type 1 font. */
/*postV2Tail	v2[VAR];*/
  DEFINE_SIZE_STATIC (32);
};

} /* namespace OT */

#endif /* HB_OT_POST_TABLE_HH */


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.osconfig.v1alpha.model;

/**
 * A response message for listing all revisions for a OS policy assignment.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the OS Config API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class ListOSPolicyAssignmentRevisionsResponse extends com.google.api.client.json.GenericJson {

  /**
   * The pagination token to retrieve the next page of OS policy assignment revisions.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String nextPageToken;

  /**
   * The OS policy assignment revisions
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<OSPolicyAssignment> osPolicyAssignments;

  /**
   * The pagination token to retrieve the next page of OS policy assignment revisions.
   * @return value or {@code null} for none
   */
  public java.lang.String getNextPageToken() {
    return nextPageToken;
  }

  /**
   * The pagination token to retrieve the next page of OS policy assignment revisions.
   * @param nextPageToken nextPageToken or {@code null} for none
   */
  public ListOSPolicyAssignmentRevisionsResponse setNextPageToken(java.lang.String nextPageToken) {
    this.nextPageToken = nextPageToken;
    return this;
  }

  /**
   * The OS policy assignment revisions
   * @return value or {@code null} for none
   */
  public java.util.List<OSPolicyAssignment> getOsPolicyAssignments() {
    return osPolicyAssignments;
  }

  /**
   * The OS policy assignment revisions
   * @param osPolicyAssignments osPolicyAssignments or {@code null} for none
   */
  public ListOSPolicyAssignmentRevisionsResponse setOsPolicyAssignments(java.util.List<OSPolicyAssignment> osPolicyAssignments) {
    this.osPolicyAssignments = osPolicyAssignments;
    return this;
  }

  @Override
  public ListOSPolicyAssignmentRevisionsResponse set(String fieldName, Object value) {
    return (ListOSPolicyAssignmentRevisionsResponse) super.set(fieldName, value);
  }

  @Override
  public ListOSPolicyAssignmentRevisionsResponse clone() {
    return (ListOSPolicyAssignmentRevisionsResponse) super.clone();
  }

}


text:
package br.com.thiago.loja.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import javax.swing.JOptionPane;

import br.com.thiago.loja.fabrica.Fabrica;
import br.com.thiago.loja.model.Cliente;
import br.com.thiago.loja.view.ClienteFrame;

public class ClienteDAO implements MainDAO<Cliente>{

	private EntityManager em = Fabrica.getEntityManager();

	@Override
    public Cliente buscar(Long id){
        return this.em.find(Cliente.class, id);
    }

	@Override
	public void salvar(Cliente cliente) {
		if(buscarPorCodigo(cliente.getCodigo()) != null){
			JOptionPane.showMessageDialog(null, "Já existe um cliente com este código.", "", JOptionPane.INFORMATION_MESSAGE);
		} else {
	    	this.em.getTransaction().begin();
	        this.em.merge(cliente);
	        this.em.flush();
	        this.em.getTransaction().commit();
	        this.em.close();
	        ClienteFrame.limpar();
            JOptionPane.showMessageDialog(null, "Cliente salvo!", "", JOptionPane.INFORMATION_MESSAGE);
		}
    }

	@Override
	public void remover(Cliente cliente) {
    	this.em.getTransaction().begin();
        this.em.remove(cliente);
        this.em.flush();
        this.em.getTransaction().commit();
        this.em.close();
	}

	@Override
	public Cliente alterar(Cliente cliente) {
    	this.em.getTransaction().begin();
        this.em.merge(cliente);
        this.em.flush();
        this.em.getTransaction().commit();
        this.em.close();
        ClienteFrame.limpar();
        JOptionPane.showMessageDialog(null, "Cliente salvo!", "", JOptionPane.INFORMATION_MESSAGE);
		return null;
	}

	@Override
	public List<Cliente> listarTodos() {
        TypedQuery<Cliente> query = em.createQuery("SELECT m FROM Cliente m", Cliente.class);
        return query.getResultList();
	}

	public Cliente buscarPorCodigo(Long codigo) {
		try{
			Cliente c = (Cliente) this.em.createNamedQuery("Cliente.findByCodigo").setParameter("codigo", codigo).getSingleResult();
			return c;
		} catch (NoResultException nre){
			return null;
		}
	}

}


text:
using System;
using System.Threading.Tasks;

namespace AsyncConverter.Tests.Test.Data.FixReturnValueToTaskTests
{
    public class Class
    {
        public async Task TestAsync()
        {
            await Task.Factory.StartNew(async () =>
                                        {
                                            Console.WriteLine("foo");
                                            return aw{caret}ait MethodAsync();
                                        });
        }

        public Task<int> MethodAsync()
        {
            return Task.FromResult(5);
        }
    }
}


text:
package cherry.gallery.db.gen.query;

import static com.querydsl.core.types.PathMetadataFactory.*;

import com.querydsl.core.types.dsl.*;

import com.querydsl.core.types.PathMetadata;
import javax.annotation.Generated;
import com.querydsl.core.types.Path;

import com.querydsl.sql.ColumnMetadata;
import java.sql.Types;

/**
 * QAsyncProcessException is a Querydsl query type for BAsyncProcessException
 */
@Generated("com.querydsl.sql.codegen.MetaDataSerializer")
public class QAsyncProcessException extends com.querydsl.sql.RelationalPathBase<BAsyncProcessException> {

    private static final long serialVersionUID = 1921165789;

    public static final QAsyncProcessException asyncProcessException = new QAsyncProcessException("ASYNC_PROCESS_EXCEPTION");

    public final NumberPath<Long> asyncId = createNumber("asyncId", Long.class);

    public final DateTimePath<java.time.LocalDateTime> createdAt = createDateTime("createdAt", java.time.LocalDateTime.class);

    public final StringPath exception = createString("exception");

    public final NumberPath<Long> id = createNumber("id", Long.class);

    public final NumberPath<Integer> lockVersion = createNumber("lockVersion", Integer.class);

    public final DateTimePath<java.time.LocalDateTime> updatedAt = createDateTime("updatedAt", java.time.LocalDateTime.class);

    public final com.querydsl.sql.PrimaryKey<BAsyncProcessException> asyncProcessExceptionPkc = createPrimaryKey(id);

    public QAsyncProcessException(String variable) {
        super(BAsyncProcessException.class, forVariable(variable), "PUBLIC", "ASYNC_PROCESS_EXCEPTION");
        addMetadata();
    }

    public QAsyncProcessException(String variable, String schema, String table) {
        super(BAsyncProcessException.class, forVariable(variable), schema, table);
        addMetadata();
    }

    public QAsyncProcessException(Path<? extends BAsyncProcessException> path) {
        super(path.getType(), path.getMetadata(), "PUBLIC", "ASYNC_PROCESS_EXCEPTION");
        addMetadata();
    }

    public QAsyncProcessException(PathMetadata metadata) {
        super(BAsyncProcessException.class, metadata, "PUBLIC", "ASYNC_PROCESS_EXCEPTION");
        addMetadata();
    }

    public void addMetadata() {
        addMetadata(asyncId, ColumnMetadata.named("ASYNC_ID").withIndex(2).ofType(Types.BIGINT).withSize(19).notNull());
        addMetadata(createdAt, ColumnMetadata.named("CREATED_AT").withIndex(5).ofType(Types.TIMESTAMP).withSize(23).withDigits(10).notNull());
        addMetadata(exception, ColumnMetadata.named("EXCEPTION").withIndex(3).ofType(Types.CLOB).withSize(2147483647).notNull());
        addMetadata(id, ColumnMetadata.named("ID").withIndex(1).ofType(Types.BIGINT).withSize(19).notNull());
        addMetadata(lockVersion, ColumnMetadata.named("LOCK_VERSION").withIndex(6).ofType(Types.INTEGER).withSize(10).notNull());
        addMetadata(updatedAt, ColumnMetadata.named("UPDATED_AT").withIndex(4).ofType(Types.TIMESTAMP).withSize(23).withDigits(10).notNull());
    }

}


text:
from django.utils import unittest
from django.core.exceptions import ObjectDoesNotExist, ValidationError

from dockit.tests.schema.common import SimpleSchema, SimpleDocument, ValidatingDocument, SimpleSchema2

class SchemaTestCase(unittest.TestCase):
    def test_to_primitive(self):
        obj = SimpleSchema(_python_data={'charfield':'charmander'})
        prim_data = obj.to_primitive(obj)
        self.assertEqual(prim_data, {'charfield':'charmander'})

    def test_to_portable_primitive(self):
        obj = SimpleSchema(_python_data={'charfield':'charmander'})
        prim_data = obj.to_portable_primitive(obj)
        self.assertEqual(prim_data, {'charfield':'charmander'})

    def test_to_python(self):
        obj = SimpleSchema(_primitive_data={'charfield':'charmander'})
        py_obj = obj.to_python({'charfield':'charmander'})
        self.assertEqual(obj._primitive_data, py_obj._primitive_data)

    def test_from_portable_primitive(self):
        obj = SimpleSchema(_primitive_data={'charfield':'charmander'})
        assert obj.charfield, 'Failed to initialize python data'
        py_obj = obj.to_python({'charfield':'charmander'})
        py_obj.normalize_portable_primitives()
        self.assertEqual(obj._primitive_data, py_obj._primitive_data)

    def test_traverse(self):
        obj = SimpleSchema(charfield='charmander')
        self.assertEqual(obj.dot_notation('charfield'), 'charmander')

    def test_natural_key_creation(self):
        obj = SimpleDocument()
        obj.save()
        self.assertTrue('@natural_key' in obj._primitive_data)
        self.assertTrue('@natural_key_hash' in obj._primitive_data)
        self.assertTrue(isinstance(obj._primitive_data['@natural_key'], dict))
        self.assertTrue(None not in obj._primitive_data['@natural_key'].values())

class DocumentValidationTestChase(unittest.TestCase):
    def test_validation(self):
        obj = ValidatingDocument()
        try:
            obj.full_clean()
        except ValidationError as error:
            self.assertFalse('allow_null' in error.message_dict)
        else:
            self.fail('Validation is broken')

        obj.with_choices = 'c'
        obj.not_null = 'foo'
        obj.allow_blank = ''
        obj.not_blank = ''
        try:
            obj.subschema = 'Not a schema'
        except ValidationError as error:
            pass
        else:
            self.fail('Setting a subschema should evaluate immediately')

        try:
            obj.full_clean()
        except ValidationError as error:
            self.assertFalse('not_null' in error.message_dict, str(error))
            self.assertFalse('allow_blank' in error.message_dict, str(error))
            self.assertTrue('with_choices' in error.message_dict, str(error))
            self.assertTrue('not_blank' in error.message_dict, str(error))
            self.assertTrue('subschema' in error.message_dict, str(error))
        else:
            self.fail('Validation is broken')

        try:
            obj.subschema = SimpleSchema2()
        except ValidationError as error:
            pass
        else:
            self.fail('Setting a subschema should evaluate immediately')

        obj.with_choices = 'b'
        obj.not_blank = 'foo'
        obj.subschema = SimpleSchema()
        obj.full_clean()


text:
<?php

namespace Magento\TestFramework\TestCase;

/**
 * A parent class for backend controllers - contains directives for admin user creation and authentication
 * @SuppressWarnings(PHPMD.NumberOfChildren)
 * @SuppressWarnings(PHPMD.numberOfChildren)
 */
abstract class AbstractBackendController extends \Magento\TestFramework\TestCase\AbstractController
{
    /**
     * @var \Magento\Backend\Model\Auth\Session
     */
    protected $_session;

    /**
     * @var \Magento\Backend\Model\Auth
     */
    protected $_auth;

    /**
     * The resource used to authorize action
     *
     * @var string
     */
    protected $resource = null;

    /**
     * The uri at which to access the controller
     *
     * @var string
     */
    protected $uri = null;

    protected function setUp()
    {
        parent::setUp();

        $this->_objectManager->get('Magento\Backend\Model\UrlInterface')->turnOffSecretKey();

        $this->_auth = $this->_objectManager->get('Magento\Backend\Model\Auth');
        $this->_session = $this->_auth->getAuthStorage();
        $credentials = $this->_getAdminCredentials();
        $this->_auth->login($credentials['user'], $credentials['password']);
        $this->_objectManager->get('Magento\Security\Model\Plugin\Auth')->afterLogin($this->_auth);
    }

    /**
     * Get credentials to login admin user
     *
     * @return array
     */
    protected function _getAdminCredentials()
    {
        return [
            'user' => \Magento\TestFramework\Bootstrap::ADMIN_NAME,
            'password' => \Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
        ];
    }

    protected function tearDown()
    {
        $this->_auth->getAuthStorage()->destroy(['send_expire_cookie' => false]);
        $this->_auth = null;
        $this->_session = null;
        $this->_objectManager->get('Magento\Backend\Model\UrlInterface')->turnOnSecretKey();
        parent::tearDown();
    }

    /**
     * Utilize backend session model by default
     *
     * @param \PHPUnit_Framework_Constraint $constraint
     * @param string|null $messageType
     * @param string $messageManagerClass
     */
    public function assertSessionMessages(
        \PHPUnit_Framework_Constraint $constraint,
        $messageType = null,
        $messageManagerClass = 'Magento\Framework\Message\Manager'
    ) {
        parent::assertSessionMessages($constraint, $messageType, $messageManagerClass);
    }

    public function testAclHasAccess()
    {
        if ($this->uri === null) {
            $this->markTestIncomplete('AclHasAccess test is not complete');
        }
        $this->dispatch($this->uri);
        $this->assertNotSame(403, $this->getResponse()->getHttpResponseCode());
        $this->assertNotSame(404, $this->getResponse()->getHttpResponseCode());
    }

    public function testAclNoAccess()
    {
        if ($this->resource === null) {
            $this->markTestIncomplete('Acl test is not complete');
        }
        $this->_objectManager->get('Magento\Framework\Acl\Builder')
            ->getAcl()
            ->deny(null, $this->resource);
        $this->dispatch($this->uri);
        $this->assertSame(403, $this->getResponse()->getHttpResponseCode());
    }
}


text:
import pkg_resources
import uuid
import os.path
import IPython.display as ipd
import pystache

from jm.map import Map
import jm.sources
import jm.layers

def _run_js(js, bindings={}, show=True, debug=False):
    js_fname = pkg_resources.resource_filename("jm", os.path.join("js", "{0}.js".format(js)))
    with open(js_fname, "r") as f:
        content = f.read()
    content = pystache.render(content, bindings)
    if debug:
        print(content)
    content = ipd.Javascript(content)
    if show:
        display(content)
        return
    return content

def _uuid():
    return str(uuid.uuid4()).replace("-", "")

def init(acces_token, version="0.40.1"):
    _run_js("init", {"access_token": acces_token, "version": version})
    display(ipd.HTML("<link href=\"https://api.tiles.mapbox.com/mapbox-gl-js/v{0}/mapbox-gl.css\" rel=\"stylesheet\" />".format(version)))

def gj(geojson, layer=jm.layers.Fill, popup=None, padding=20, animate=0):
    m = jm.Map()
    s = jm.sources.GeoJSON(geojson)
    m.add_layer(layer(s, popup=popup))
    m.fit_source(s, padding=padding, animate=animate)
    display(m)
    return m


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Ustilago cruenta J.G. Kühn, 1872

### Remarks
null


text:
using System;
using System.IO;
using Build.DomainModel.MSBuild;
using Build.IO;
using Node = Build.DomainModel.MSBuild.Node;

namespace Build.TaskEngine.Tasks
{
	public class CscTask : ITaskRunner
	{
		private const string CompilerPath = @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Csc.exe";

		private readonly ExpressionEngine.ExpressionEngine _expressionEngine;
		private readonly IFileSystem _fileSystem;

		public CscTask(ExpressionEngine.ExpressionEngine expressionEngine,
		               IFileSystem fileSystem)
		{
			if (expressionEngine == null)
				throw new ArgumentNullException(nameof(expressionEngine));
			if (fileSystem == null)
				throw new ArgumentNullException(nameof(fileSystem));

			_expressionEngine = expressionEngine;
			_fileSystem = fileSystem;
		}

		public void Run(BuildEnvironment environment, Node task, IProjectDependencyGraph graph, ILogger logger)
		{
			var csc = (Csc) task;
			var arguments = new ArgumentBuilder();

			BuildCommandLineArguments(environment, csc, arguments);

			logger.WriteLine(Verbosity.Normal, "  {0} {1}", CompilerPath, arguments);

			CreateDirectories(environment, csc);

			var rootPath = environment.Properties[Properties.MSBuildProjectDirectory];
			string output;
			var exitCode = ProcessEx.Run(CompilerPath, rootPath, arguments, out output);
			logger.WriteMultiLine(Verbosity.Minimal, output, interpretLines: true);

			if (exitCode != 0)
				throw new BuildException(string.Format("csc returned {0}", exitCode));
		}

		private void CreateDirectories(BuildEnvironment environment, Csc csc)
		{
			var root = environment.Properties[Properties.MSBuildProjectDirectory];

			var outputAssembly = _expressionEngine.EvaluateExpression(csc.OutputAssembly, environment);
			var assemblyOutputPath = Path.MakeAbsolute(root, Path.GetDirectory(outputAssembly));
			_fileSystem.CreateDirectory(assemblyOutputPath);

			var outputPdb = _expressionEngine.EvaluateExpression(csc.PdbFile, environment);
			var pdbPath = Path.MakeAbsolute(root, Path.GetDirectory(outputPdb));
			_fileSystem.CreateDirectory(pdbPath);
		}

		private void BuildCommandLineArguments(BuildEnvironment environment, Csc csc, ArgumentBuilder arguments)
		{
			if (AllowUnsafeBlocks(environment, csc))
				arguments.Flag("unsafe");

			arguments.Add("debug", GetDebugType(environment, csc));
			if (EmitDebugInformation(environment, csc))
				arguments.Flag("debug+");

			if (!Optimize(environment, csc))
				arguments.Flag("optimize-");

			var baseAddress = GetBaseAddress(environment, csc);
			if (!string.IsNullOrEmpty(baseAddress))
				arguments.Add("baseaddress", baseAddress);

			arguments.Add("define", GetDefines(environment, csc));
			arguments.Add("nowarn", GetDisabledWarnings(environment, csc));

			if (GetNoLogo(environment, csc))
				arguments.Flag("nologo");

			arguments.Add("target", GetTarget(environment, csc));
			arguments.Add("errorreport", GetErrorReport(environment, csc));
			arguments.Add("platform", GetPlatform(environment, csc));

			if (ErrorEndLocation(environment, csc))
				arguments.Flag("errorendlocation");

			arguments.Add("filealign", GetFileAlignment(environment, csc));

			if (HighEntropyVA(environment, csc))
				arguments.Flag("highentropyva+");

			arguments.Add("out", GetOutputAssembly(environment, csc));

			arguments.Flag("nostdlib+");

			var rootPath = environment.Properties[Properties.MSBuildProjectDirectory];
			var references = _expressionEngine.EvaluateItemList(csc.References, environment);
			foreach (var reference in references)
			{
				AddReference(arguments, reference, rootPath);
			}

			var resources = _expressionEngine.EvaluateItemList(csc.Resources, environment);
			foreach (var resource in resources)
			{
				var include = resource.Include;
				var resourceName = string.Format("EmbeddedResource.{0}", include.Replace('\\', '.'));
				arguments.Add("resource", resource.Include, resourceName);
			}

			var sources = _expressionEngine.EvaluateItemList(csc.Sources, environment);
			foreach (var source in sources)
			{
				arguments.Add(source.Include);
			}

			string outputPath = environment.Properties[Properties.OutputPath];
			_fileSystem.CreateDirectory(outputPath);

			// http://stackoverflow.com/questions/19306194/process-launch-exception-filename-or-extension-is-too-long-can-it-be-caused-b
			int commandLineLength = arguments.Length + CompilerPath.Length + 1;
			if (commandLineLength > 32000) //< The maximum length seems to be 32768, but this one's close enough
			{
				// In order to not exceed the limit we'll have to write the arguments
				// to a file that is then passes as an argument to csc (so that's why that option exists).
				var filename = Path.Combine(outputPath, "csc_arguments.txt");
				File.WriteAllText(filename, arguments.ToString());
				arguments.Clear();

				arguments.Add(string.Format("\"@{0}\"", filename));
			}

			// without this, csc automatically references a bunch of assemblies and then gives us shit
			// that we've included a double reference...
			arguments.Flag("noconfig");
		}

		private void AddReference(ArgumentBuilder arguments, ProjectItem reference, string rootPath)
		{
			string referencePath = reference.Include;
			arguments.Add("reference", referencePath);
		}

		private string GetPlatform(BuildEnvironment environment, Csc csc)
		{
			string platform = _expressionEngine.EvaluateExpression(csc.Platform, environment);
			var prefer32Bit = _expressionEngine.EvaluateCondition(csc.Prefer32Bit, environment);

			const string anyCpu = "AnyCPU";
			const string x86 = "x86";
			const string x64 = "x64";

			switch (platform)
			{
				case anyCpu:
					if (environment.Properties[Properties.OutputType] == "Library")
					{
						return "anycpu";
					}

					return prefer32Bit
							    ? "anycpu32bitpreferred"
							    : "anycpu";

				case x86:
					return "x86";

				case x64:
					return "x64";

				default:
					throw new EvaluationException(
						string.Format(
							"Specified condition \"{0}\" evaluates to \"{1}\" instead of any of the allow values \"{2}\", \"{3}\" or \"{4}\".",
							csc.Platform,
							platform,
							anyCpu, x86, x64)
						);
			}
		}

		private string GetBaseAddress(BuildEnvironment environment, Csc csc)
		{
			var address = csc.BaseAddress;
			var evaluated = _expressionEngine.EvaluateExpression(address, environment);
			return evaluated;
		}

		private string GetOutputAssembly(BuildEnvironment environment, Csc csc)
		{
			var asm = csc.OutputAssembly;
			var evaluated = _expressionEngine.EvaluateExpression(asm, environment);
			return evaluated;
		}

		private bool HighEntropyVA(BuildEnvironment environment, Csc csc)
		{
			var entropy = csc.HighEntropyVA;
			var evaluated = _expressionEngine.EvaluateCondition(entropy, environment);
			return evaluated;
		}

		private string GetFileAlignment(BuildEnvironment environment, Csc csc)
		{
			var alignment = csc.FileAlignment;
			var evaluated = _expressionEngine.EvaluateExpression(alignment, environment);
			return evaluated;
		}

		private bool ErrorEndLocation(BuildEnvironment environment, Csc csc)
		{
			var end = csc.ErrorEndLocation;
			return _expressionEngine.EvaluateCondition(end, environment);
		}

		private string GetErrorReport(BuildEnvironment environment, Csc csc)
		{
			var error = csc.ErrorReport;
			var evaluated = _expressionEngine.EvaluateExpression(error, environment);
			return evaluated;
		}

		private string GetDisabledWarnings(BuildEnvironment environment, Csc csc)
		{
			var disabled = csc.DisabledWarnings;
			var evaluated = _expressionEngine.EvaluateExpression(disabled, environment);
			return evaluated;
		}

		private string GetDefines(BuildEnvironment environment, Csc csc)
		{
			var defines = csc.DefineConstants;
			var evaluated = _expressionEngine.EvaluateExpression(defines, environment);
			return evaluated;
		}

		private string GetDebugType(BuildEnvironment environment, Csc csc)
		{
			var debugType = csc.DebugType;
			var evaluated = _expressionEngine.EvaluateExpression(debugType, environment);
			return evaluated;
		}

		private bool EmitDebugInformation(BuildEnvironment environment, Csc csc)
		{
			var emit = csc.EmitDebugInformation;
			return _expressionEngine.EvaluateCondition(emit, environment);
		}

		private bool Optimize(BuildEnvironment environment, Csc csc)
		{
			var optimize = csc.Optimize;
			return _expressionEngine.EvaluateCondition(optimize, environment);
		}

		private bool AllowUnsafeBlocks(BuildEnvironment environment, Csc csc)
		{
			var allow = csc.AllowUnsafeBlocks;
			return _expressionEngine.EvaluateCondition(allow, environment);
		}

		private bool GetNoLogo(BuildEnvironment environment, Csc csc)
		{
			var target = csc.NoLogo;
			var evaluated = _expressionEngine.EvaluateCondition(target, environment);
			return evaluated;
		}

		private string GetTarget(BuildEnvironment environment, Csc csc)
		{
			var target = csc.TargetType;
			var evaluated = _expressionEngine.EvaluateExpression(target, environment);

			switch (evaluated)
			{
				case "Library":
					return "library";

				case "Exe":
					return "exe";

				case "WinExe":
					return "winexe";

				default:
					throw new Exception(string.Format("Unknown output type: '{0}'", evaluated));
			}
		}
	}
}


text:
<?php

namespace Sylius\Bundle\ResourceBundle\Form\EventSubscriber;

use Sylius\Component\Resource\Model\CodeAwareInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Intl\Exception\UnexpectedTypeException;

/**
 * @author Anna Walasek <anna.walasek@lakion.com>
 */
class AddCodeFormSubscriber implements EventSubscriberInterface
{
    /**
     * @var string
     */
    private $type;

    /**
     * @param string $type
     */
    public function __construct($type = 'text')
    {
        $this->type = $type;
    }

    /**
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return array(
            FormEvents::PRE_SET_DATA => 'preSetData',
        );
    }

    /**
     * @param FormEvent $event
     */
    public function preSetData(FormEvent $event)
    {
        $resource = $event->getData();
        $disabled = false;

        if ($resource instanceof CodeAwareInterface) {
            $disabled = (null !== $resource->getCode());
        } else if (null !== $resource) {
            throw new UnexpectedTypeException($resource, CodeAwareInterface::class);
        }

        $form = $event->getForm();
        $form->add('code', $this->type, array('label' => 'sylius.ui.code', 'disabled' => $disabled));
    }
}


text:
package io.fsq.twofishes.indexer.scalding

import com.twitter.scalding._

class TwofishesImporterJob(
  name: String,
  inputSpec: TwofishesImporterInputSpec,
  args: Args
) extends TwofishesJob(name, args) {

  private def getAllInputFiles(inputSpec: TwofishesImporterInputSpec): Seq[String] = {
    getFilesByRelativePaths(inputSpec.relativeFilePaths) ++
      inputSpec.directories.flatMap(getFilesInDirectoryByEnumerationSpec(_))
  }

  private val inputFiles = getAllInputFiles(inputSpec)

  val lines: TypedPipe[String] = if (inputFiles.nonEmpty) {
    TypedPipe.from(MultipleTextLineFiles(inputFiles: _*))
  } else {
    TypedPipe.empty
  }
}


text:
describe StackerBee::Middleware::ErrorMessage do
  subject { env.response }
  before { middleware.after(env) }

  let(:middleware) { described_class.new }
  let(:env) do
    StackerBee::Middleware::Environment.new.tap do |env|
      env.response.body    = body
      env.response.success = is_success?
    end
  end
  let(:body) { { errortext: message } }
  let(:message) { 'Unable to execute API command deployvirtualmachine ' }
  let(:is_success?) { true }

  it "doesn't apply to HTML responses" do
    expect(middleware.content_types).not_to match 'text/html; charset=utf-8'
  end
  it 'applies to JSON responses' do
    expect(middleware.content_types).to match 'text/javascript; charset=utf-8'
  end

  context 'given an error' do
    let(:is_success?) { false }
    its(:error) { should eq message }
  end

  context 'given a success' do
    let(:is_success?) { true }
    its(:error) { should be_nil }
  end
end


text:
**All references:**
- https://www.programiz.com/python-programming/generator

## Examples

~~~~
def my_gen():
    n = 1
    print('This is printed first')
    # Generator function contains yield statements
    yield n

    n += 1
    print('This is printed second')
    yield n

    n += 1
    print('This is printed at last')
    yield n
~~~~


text:
/********************************************************************
 * Graamar testing - literals
 * This file only tests for failures.  Successes are tested for
 * using the "example" files, which provide a much better - and
 * more readable - set of examples.
 *
 * As a consequence, the logic below is reversed: the test passes
 * if none of the example literals are deemed valid on parsing
*/

'use strict';

var fs = require('fs');
var ohm = require('ohm-js');

console.log("***************************************************")
console.log("Testing Literals")
console.log("***************************************************")

//Read in the grammar & create the parser etc.
var flGrammar = ohm.grammar(fs.readFileSync('../../flujo.ohm'));

//The test cases: all invalid as literals
var expectedInvalidLiterals = [".12e12G", "0xZFG", ".12e12G", "Q1w"]

//arrays to hold the results of testing
var actualInvalidLiterals = []
var actualValidLiterals = []

//run the tests
expectedInvalidLiterals.map(function(testCase){
    var m = flGrammar.match(testCase, "literal")
    if(m.succeeded()) {
       actualValidLiterals.push(testCase)
       //console.log(flGrammar.trace(test, "literal").toString())
    }
    else {
        actualInvalidLiterals.push(testCase)
    }
})

var totalTestsRun = actualValidLiterals.length + actualInvalidLiterals.length
if(totalTestsRun != expectedInvalidLiterals.length) {
    console.log("\n")
    console.log("*** ERROR: not all cases accounted for")
    console.log("*** Test run aborted")
    return(-1)
}
if(actualValidLiterals.length != 0) {
    console.log("***", actualPasses.length, "test cases passed unexpectedly")
    return(-1)
} else {
    console.log("All", actualInvalidLiterals.length, "tests passed")
    return(0)
}


text:
.. This file is part of the OpenDSA eTextbook project. See
.. http://algoviz.org/OpenDSA for more details.
.. Copyright (c) 2012-2016 by the OpenDSA Project Contributors, and
.. distributed under an MIT open source license.

.. avmetadata::
   :author: Cliff Shaffer
   :requires: Huffman coding tree
   :satisfies: Huffman proof
   :topic: Huffman Coding Trees

.. odsalink:: AV/Binary/HuffProofCON.css

Proof of Optimality for Huffman Coding
======================================

Proof of Optimality for Huffman Coding
--------------------------------------

Huffman tree building is an example of a
:term:`greedy algorithm`.
At each step, the algorithm makes a "greedy" decision to merge
the two subtrees with least weight.
This makes the algorithm simple, but does it give the desired result?
This section concludes with a proof that the Huffman tree
indeed gives the most efficient arrangement for the set of letters.
The proof requires the following lemma.

**Lemma:**
For any Huffman tree built by function ``buildHuff`` containing at
least two letters, the two letters with least frequency are stored
in sibling nodes whose depth is at least as deep as any other leaf
nodes in the tree.

**Proof:**
Call the two letters with least frequency :math:`l_1`
and :math:`l_2`.
They must be siblings because ``buildHuff``
selects them in the first step of the construction process.
Assume that :math:`l_1` and :math:`l_2` are
not the deepest nodes in the tree.
In this case, the Huffman tree must either look as shown in
Figure :num:`Figure #HProof`, or effectively symmetrical to
this.
For this situation to occur, the parent of :math:`l_1`
and :math:`l_2`,
labeled :math:`V`, must have greater weight than the node
labeled :math:`X`.
Otherwise, function ``buildHuff`` would have selected node
:math:`V` in place of node :math:`X` as the child of node
:math:`U`.
However, this is impossible because :math:`l_1` and
:math:`l_2` are the letters with least frequency.

.. _HProof:

.. inlineav:: HuffProofCON dgm
   :output: show
   :align: center

   An impossible Huffman tree, showing the situation where the two
   nodes with least weight, :math:`l_1` and
   :math:`l_2`, are not the deepest nodes in the tree.
   Triangles represent subtrees.

Here is the proof.

   **Theorem:**
   Function ``buildHuff`` builds the Huffman tree with the minimum
   external path weight for the given set of letters.

   **Proof:**
   The proof is by induction on :math:`n`, the number of letters.

   * **Base Case:** For :math:`n = 2`, the Huffman tree must have the
     minimum external path weight because there are only two possible
     trees, each with identical weighted path lengths for the two
     leaves.

   * **Induction Hypothesis:** Assume that any tree created by
     ``buildHuff`` that contains :math:`n-1` leaves has minimum
     external path length.

   * **Induction Step:** Given a Huffman tree :math:`\mathbf{T}`
     built by ``buildHuff`` with :math:`n` leaves,
     :math:`n \geq 2`, suppose that
     :math:`w_1 \leq w_2 \leq ... \leq w_n` where
     :math:`w_1` to :math:`w_n` are the weights of the letters.
     Call :math:`V` the parent of the letters with frequencies
     :math:`w_1` and :math:`w_2`.
     From the lemma, we know that the leaf nodes containing the
     letters with frequencies :math:`w_1` and :math:`w_2` are as
     deep as any nodes in :math:`\mathbf{T}`.
     If any other leaf nodes in the tree were deeper, we could reduce
     their weighted path length by swapping them with :math:`w_1` or
     :math:`w_2`.
     But the lemma tells us that no such deeper nodes exist.
     Call :math:`\mathbf{T}'` the Huffman tree that is
     identical to :math:`\mathbf{T}` except that node :math:`V` is
     replaced with a leaf node :math:`V'` whose weight is
     :math:`w_1 + w_2`.
     By the induction hypothesis, :math:`\mathbf{T}'` has minimum
     external path length.
     Returning the children to :math:`V'` restores tree
     :math:`\mathbf{T}`, which must also have minimum external path
     length.

   Thus by mathematical induction, function ``buildHuff`` creates
   the Huffman tree with minimum external path length.

.. TODO::
   :type: Exercise

   Battery of MCQs for content.

.. odsascript:: AV/Binary/HuffProofCON.js


text:
search:
   keywords: ['C#', 'c sharp', 'NET', 'transaction', 'GetPendingObject']
---

# OrientDB-NET - `GetPendingObject<T>()`

This method returns objects from a transaction.

## Retrieve Pending Objects

In cases where you need to operate on particular records already added to a transaction, you can use `GetPendingObject<T>()` to retrieve it.

### Syntax

```
T trx.GetPendingObject<T>(ORID rid)
```
- **`rid`** Defines the Record ID that you want to retrieve.

### Example

For instance, say you want to retrieve a vertex from a transaction:

```csharp
public OVertex fetchVertex(OTransaction trx, ORID rid)
{
   // FETCH VERTEX
   OVertex target = trx.GetPendingObject<OVertex>(rid);
   return target;
}
```


text:
namespace bitwave {
namespace core {

    class BitRequestList : private NotCopyable
    {
    public:
        struct RequestData
        {
            RequestData(int i, int b, int l)
                : index(i),
                  begin(b),
                  length(l)
            {
            }

            int index;      // zero-base piece index
            int begin;      // zero-base byte offset within the piece
            int length;     // request length

            friend bool operator == (const RequestData& left,
                                     const RequestData& right)
            {
                return left.index == right.index &&
                       left.begin == right.begin &&
                       left.length == right.length;
            }
        };

        typedef std::list<RequestData> RequestList;
        typedef RequestList::iterator Iterator;
        typedef RequestList::const_iterator Const_Iterator;

        // add new request to tail
        void AddRequest(int index, int begin, int length);
        void AddRequest(Iterator first, Iterator last);

        // delete request if exists
        void DelRequest(int index, int begin, int length);

        // find request data, if exists return the Iterator, otherwise return End()
        Iterator FindRequest(int index, int begin, int length);

        // splice the element of it from argument brl BitRequestList to
        // target BitRequestList's tail, return the element Iterator in
        // target BitRequestList
        Iterator Splice(BitRequestList& brl, Iterator it);
        void Splice(BitRequestList& brl, Iterator first, Iterator last);

        // return the request is exist or not
        bool IsExistRequest(int index, int begin, int length) const;

        void Clear() { request_list_.clear(); }
        std::size_t Size() const { return request_list_.size(); }
        bool Empty() const { return request_list_.empty(); }
        void Erase(Iterator it) { request_list_.erase(it); }
        Iterator Begin() { return request_list_.begin(); }
        Iterator End() { return request_list_.end(); }
        Const_Iterator Begin() const { return request_list_.begin(); }
        Const_Iterator End() const { return request_list_.end(); }

    private:
        RequestList request_list_;
    };

} // namespace core
} // namespace bitwave

#endif // BIT_REQUEST_LIST_H


text:
package net.minecraft.entity.monster;

import java.util.Calendar;
import net.minecraft.block.Block;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityCreature;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.EnumCreatureAttribute;
import net.minecraft.entity.IEntityLivingData;
import net.minecraft.entity.IRangedAttackMob;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.EntityAIArrowAttack;
import net.minecraft.entity.ai.EntityAIAttackOnCollide;
import net.minecraft.entity.ai.EntityAIAvoidEntity;
import net.minecraft.entity.ai.EntityAIFleeSun;
import net.minecraft.entity.ai.EntityAIHurtByTarget;
import net.minecraft.entity.ai.EntityAILookIdle;
import net.minecraft.entity.ai.EntityAINearestAttackableTarget;
import net.minecraft.entity.ai.EntityAIRestrictSun;
import net.minecraft.entity.ai.EntityAISwimming;
import net.minecraft.entity.ai.EntityAIWander;
import net.minecraft.entity.ai.EntityAIWatchClosest;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.stats.AchievementList;
import net.minecraft.util.BlockPos;
import net.minecraft.util.DamageSource;
import net.minecraft.world.DifficultyInstance;
import net.minecraft.world.World;
import net.minecraft.world.WorldProviderHell;

public class EntitySkeleton extends EntityMob implements IRangedAttackMob
{
    private EntityAIArrowAttack aiArrowAttack = new EntityAIArrowAttack(this, 1.0D, 20, 60, 15.0F);
    private EntityAIAttackOnCollide aiAttackOnCollide = new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.2D, false);

    public EntitySkeleton(World worldIn)
    {
        super(worldIn);
        this.tasks.addTask(1, new EntityAISwimming(this));
        this.tasks.addTask(2, new EntityAIRestrictSun(this));
        this.tasks.addTask(3, new EntityAIFleeSun(this, 1.0D));
        this.tasks.addTask(3, new EntityAIAvoidEntity(this, EntityWolf.class, 6.0F, 1.0D, 1.2D));
        this.tasks.addTask(4, new EntityAIWander(this, 1.0D));
        this.tasks.addTask(6, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F));
        this.tasks.addTask(6, new EntityAILookIdle(this));
        this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, false, new Class[0]));
        this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityPlayer.class, true));
        this.targetTasks.addTask(3, new EntityAINearestAttackableTarget(this, EntityIronGolem.class, true));

        if (worldIn != null && !worldIn.isRemote)
        {
            this.setCombatTask();
        }
    }

    protected void applyEntityAttributes()
    {
        super.applyEntityAttributes();
        this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D);
    }

    protected void entityInit()
    {
        super.entityInit();
        this.dataWatcher.addObject(13, new Byte((byte)0));
    }

    /**
     * Returns the sound this mob makes while it's alive.
     */
    protected String getLivingSound()
    {
        return "mob.skeleton.say";
    }

    /**
     * Returns the sound this mob makes when it is hurt.
     */
    protected String getHurtSound()
    {
        return "mob.skeleton.hurt";
    }

    /**
     * Returns the sound this mob makes on death.
     */
    protected String getDeathSound()
    {
        return "mob.skeleton.death";
    }

    protected void playStepSound(BlockPos pos, Block blockIn)
    {
        this.playSound("mob.skeleton.step", 0.15F, 1.0F);
    }

    public boolean attackEntityAsMob(Entity entityIn)
    {
        if (super.attackEntityAsMob(entityIn))
        {
            if (this.getSkeletonType() == 1 && entityIn instanceof EntityLivingBase)
            {
                ((EntityLivingBase)entityIn).addPotionEffect(new PotionEffect(Potion.wither.id, 200));
            }

            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * Get this Entity's EnumCreatureAttribute
     */
    public EnumCreatureAttribute getCreatureAttribute()
    {
        return EnumCreatureAttribute.UNDEAD;
    }

    /**
     * Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons
     * use this to react to sunlight and start to burn.
     */
    public void onLivingUpdate()
    {
        if (this.worldObj.isDaytime() && !this.worldObj.isRemote)
        {
            float f = this.getBrightness(1.0F);
            BlockPos blockpos = new BlockPos(this.posX, (double)Math.round(this.posY), this.posZ);

            if (f > 0.5F && this.rand.nextFloat() * 30.0F < (f - 0.4F) * 2.0F && this.worldObj.canSeeSky(blockpos))
            {
                boolean flag = true;
                ItemStack itemstack = this.getEquipmentInSlot(4);

                if (itemstack != null)
                {
                    if (itemstack.isItemStackDamageable())
                    {
                        itemstack.setItemDamage(itemstack.getItemDamage() + this.rand.nextInt(2));

                        if (itemstack.getItemDamage() >= itemstack.getMaxDamage())
                        {
                            this.renderBrokenItemStack(itemstack);
                            this.setCurrentItemOrArmor(4, (ItemStack)null);
                        }
                    }

                    flag = false;
                }

                if (flag)
                {
                    this.setFire(8);
                }
            }
        }

        if (this.worldObj.isRemote && this.getSkeletonType() == 1)
        {
            this.setSize(0.72F, 2.535F);
        }

        super.onLivingUpdate();
    }

    /**
     * Handles updating while being ridden by an entity
     */
    public void updateRidden()
    {
        super.updateRidden();

        if (this.ridingEntity instanceof EntityCreature)
        {
            EntityCreature entitycreature = (EntityCreature)this.ridingEntity;
            this.renderYawOffset = entitycreature.renderYawOffset;
        }
    }

    /**
     * Called when the mob's health reaches 0.
     */
    public void onDeath(DamageSource cause)
    {
        super.onDeath(cause);

        if (cause.getSourceOfDamage() instanceof EntityArrow && cause.getEntity() instanceof EntityPlayer)
        {
            EntityPlayer entityplayer = (EntityPlayer)cause.getEntity();
            double d0 = entityplayer.posX - this.posX;
            double d1 = entityplayer.posZ - this.posZ;

            if (d0 * d0 + d1 * d1 >= 2500.0D)
            {
                entityplayer.triggerAchievement(AchievementList.snipeSkeleton);
            }
        }
        else if (cause.getEntity() instanceof EntityCreeper && ((EntityCreeper)cause.getEntity()).getPowered() && ((EntityCreeper)cause.getEntity()).isAIEnabled())
        {
            ((EntityCreeper)cause.getEntity()).func_175493_co();
            this.entityDropItem(new ItemStack(Items.skull, 1, this.getSkeletonType() == 1 ? 1 : 0), 0.0F);
        }
    }

    protected Item getDropItem()
    {
        return Items.arrow;
    }

    /**
     * Drop 0-2 items of this living's type
     */
    protected void dropFewItems(boolean p_70628_1_, int p_70628_2_)
    {
        if (this.getSkeletonType() == 1)
        {
            int i = this.rand.nextInt(3 + p_70628_2_) - 1;

            for (int j = 0; j < i; ++j)
            {
                this.dropItem(Items.coal, 1);
            }
        }
        else
        {
            int k = this.rand.nextInt(3 + p_70628_2_);

            for (int i1 = 0; i1 < k; ++i1)
            {
                this.dropItem(Items.arrow, 1);
            }
        }

        int l = this.rand.nextInt(3 + p_70628_2_);

        for (int j1 = 0; j1 < l; ++j1)
        {
            this.dropItem(Items.bone, 1);
        }
    }

    /**
     * Causes this Entity to drop a random item.
     */
    protected void addRandomDrop()
    {
        if (this.getSkeletonType() == 1)
        {
            this.entityDropItem(new ItemStack(Items.skull, 1, 1), 0.0F);
        }
    }

    /**
     * Gives armor or weapon for entity based on given DifficultyInstance
     */
    protected void setEquipmentBasedOnDifficulty(DifficultyInstance difficulty)
    {
        super.setEquipmentBasedOnDifficulty(difficulty);
        this.setCurrentItemOrArmor(0, new ItemStack(Items.bow));
    }

    /**
     * Called only once on an entity when first time spawned, via egg, mob spawner, natural spawning etc, but not called
     * when entity is reloaded from nbt. Mainly used for initializing attributes and inventory
     */
    public IEntityLivingData onInitialSpawn(DifficultyInstance difficulty, IEntityLivingData livingdata)
    {
        livingdata = super.onInitialSpawn(difficulty, livingdata);

        if (this.worldObj.provider instanceof WorldProviderHell && this.getRNG().nextInt(5) > 0)
        {
            this.tasks.addTask(4, this.aiAttackOnCollide);
            this.setSkeletonType(1);
            this.setCurrentItemOrArmor(0, new ItemStack(Items.stone_sword));
            this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(4.0D);
        }
        else
        {
            this.tasks.addTask(4, this.aiArrowAttack);
            this.setEquipmentBasedOnDifficulty(difficulty);
            this.setEnchantmentBasedOnDifficulty(difficulty);
        }

        this.setCanPickUpLoot(this.rand.nextFloat() < 0.55F * difficulty.getClampedAdditionalDifficulty());

        if (this.getEquipmentInSlot(4) == null)
        {
            Calendar calendar = this.worldObj.getCurrentDate();

            if (calendar.get(2) + 1 == 10 && calendar.get(5) == 31 && this.rand.nextFloat() < 0.25F)
            {
                this.setCurrentItemOrArmor(4, new ItemStack(this.rand.nextFloat() < 0.1F ? Blocks.lit_pumpkin : Blocks.pumpkin));
                this.equipmentDropChances[4] = 0.0F;
            }
        }

        return livingdata;
    }

    /**
     * sets this entity's combat AI.
     */
    public void setCombatTask()
    {
        this.tasks.removeTask(this.aiAttackOnCollide);
        this.tasks.removeTask(this.aiArrowAttack);
        ItemStack itemstack = this.getHeldItem();

        if (itemstack != null && itemstack.getItem() == Items.bow)
        {
            this.tasks.addTask(4, this.aiArrowAttack);
        }
        else
        {
            this.tasks.addTask(4, this.aiAttackOnCollide);
        }
    }

    /**
     * Attack the specified entity using a ranged attack.
     */
    public void attackEntityWithRangedAttack(EntityLivingBase p_82196_1_, float p_82196_2_)
    {
        EntityArrow entityarrow = new EntityArrow(this.worldObj, this, p_82196_1_, 1.6F, (float)(14 - this.worldObj.getDifficulty().getDifficultyId() * 4));
        int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.power.effectId, this.getHeldItem());
        int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.punch.effectId, this.getHeldItem());
        entityarrow.setDamage((double)(p_82196_2_ * 2.0F) + this.rand.nextGaussian() * 0.25D + (double)((float)this.worldObj.getDifficulty().getDifficultyId() * 0.11F));

        if (i > 0)
        {
            entityarrow.setDamage(entityarrow.getDamage() + (double)i * 0.5D + 0.5D);
        }

        if (j > 0)
        {
            entityarrow.setKnockbackStrength(j);
        }

        if (EnchantmentHelper.getEnchantmentLevel(Enchantment.flame.effectId, this.getHeldItem()) > 0 || this.getSkeletonType() == 1)
        {
            entityarrow.setFire(100);
        }

        this.playSound("random.bow", 1.0F, 1.0F / (this.getRNG().nextFloat() * 0.4F + 0.8F));
        this.worldObj.spawnEntityInWorld(entityarrow);
    }

    /**
     * Return this skeleton's type.
     */
    public int getSkeletonType()
    {
        return this.dataWatcher.getWatchableObjectByte(13);
    }

    /**
     * Set this skeleton's type.
     */
    public void setSkeletonType(int p_82201_1_)
    {
        this.dataWatcher.updateObject(13, Byte.valueOf((byte)p_82201_1_));
        this.isImmuneToFire = p_82201_1_ == 1;

        if (p_82201_1_ == 1)
        {
            this.setSize(0.72F, 2.535F);
        }
        else
        {
            this.setSize(0.6F, 1.95F);
        }
    }

    /**
     * (abstract) Protected helper method to read subclass entity data from NBT.
     */
    public void readEntityFromNBT(NBTTagCompound tagCompund)
    {
        super.readEntityFromNBT(tagCompund);

        if (tagCompund.hasKey("SkeletonType", 99))
        {
            int i = tagCompund.getByte("SkeletonType");
            this.setSkeletonType(i);
        }

        this.setCombatTask();
    }

    /**
     * (abstract) Protected helper method to write subclass entity data to NBT.
     */
    public void writeEntityToNBT(NBTTagCompound tagCompound)
    {
        super.writeEntityToNBT(tagCompound);
        tagCompound.setByte("SkeletonType", (byte)this.getSkeletonType());
    }

    /**
     * Sets the held item, or an armor slot. Slot 0 is held item. Slot 1-4 is armor. Params: Item, slot
     */
    public void setCurrentItemOrArmor(int slotIn, ItemStack stack)
    {
        super.setCurrentItemOrArmor(slotIn, stack);

        if (!this.worldObj.isRemote && slotIn == 0)
        {
            this.setCombatTask();
        }
    }

    public float getEyeHeight()
    {
        return this.getSkeletonType() == 1 ? super.getEyeHeight() : 1.74F;
    }

    /**
     * Returns the Y Offset of this entity.
     */
    public double getYOffset()
    {
        return this.isChild() ? 0.0D : -0.35D;
    }
}