text:
<TITLE>Review for All the President's Men (1976)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

All the President's Men (1976)

reviewed by
John Lee

All the Presidentís Men, 1976

 by John Lee

     Itís not easy to make a gripping movie about politics but All the
Presidentís Men relies for its suspense on the chase of investigative
journalism rather than on the politicians themselves.  Nixon and other
key players of the Watergate farce are kept in the background on
strategically placed T.V. screens and in the headlines of
not-so-casually-placed newspapers.  The real drama in All the
Presidentís Men is in how Bob Woodward (played as an earnest newsroom
virgin by Robert Redford) and Carl Bernstein (the only slightly more
worldly Dustin Hofmann) hang on to the story, ìpursue the money,î and
eventually uncover the web of lies that brings down the presidency.
     On one level, Alan J. Pakulaís movie operates like a how-to, and
sometimes a how-not-to, guide for investigative journalists.  Our two
heroes meet when Woodward catches Bernstein ìimprovingî - or is it just
stealing? - his early report on the arrest of the Watergate burglars.
Establishing himself as the voice of reason, Woodward agrees that
Bernsteinís re-write has improved the piece.  The partnership is formed,
and the two are assigned to cover the case full-time.  Following their
own hunches about snatched facts that just donít add up, they start to
dig into why the burglars seem to have ever higher links to members of
the Republican Party and, eventually, to the White House.
     The task of uncovering the intrigue is laborious (days spent
checking library records and searching personnel lists, for example),
but we know Woodward and Bernstein are  on to something big, so even the
most mundane phone call is made exciting because it might provide the
next part of the puzzle.  These cold calls are presented as a major tool
of the investigative reporter, although most of the people called by
Woodward and Bernstein seem to be remarkably poor liars.  Most stutter
monotone denials that would raise the suspicions of the least
experienced hack.  And the White House librarian who denies even talking
to Bernstein five minutes after their telephone conversation, wouldnít
pass a lie detector test on any question.
     Although both reporters are remarkably persistent, itís their
different approaches to sources - like the good cop/bad cop routine -
that gains them most ground in their investigation.  Woodward doesnít
like sources to think heís pushing them too far but his passive approach
often lulls them to go further than they intended.  The secretary in his
newsroom, for example, quietly places some vital information on his desk
after he has apologised for even suggesting that she might procure it.
In contrast, Bernstein flirts and cajoles information out of potential
female sources, tricks his way past a secretary, and calls people for
information late at night when they are relaxed and out of the office: a
well-used tool of the investigative reporter.
     The two are also helped in their investigation by the ìcharacter
that knows too much,î played by Hal Holbrook, who meets Woodward in the
shadows of an underground car lot.  Although based on a real person,
heís an unsatisfying presence in the movie, and too much of a cliche, to
add to the suspense of the story.
     Ben Bradlee, the editor of The Washington Post, in an Oscar-winning
performance by Jason Robards, offers much more convincing support.
Although Robards overplays the omnipotent know-it-all, his character is
important in the story - and particularly to those movie-watchers who
might be interested in trying investigate reporting for themselves.
Heís not swayed by the story until the evidence uncovered starts to
become overwhelming.  In the chase for dirt, he never loses sight of the
need for corroboration.  If Woodward and Bernstein find two sources, he
demands three.  His mantra - ìcold, hard factsî - becomes the key to the
success of the investigation, and particularly influences Woodward.

                                                            -30-

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

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

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

Broken URLs inthe reviews are the responsibility of the author.

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

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

redpajama_set_name: RedPajamaGithub


text:
//@HEADER
// ***************************************************
//
// HPCG: High Performance Conjugate Gradient Benchmark
//
// Contact:
// Michael A. Heroux ( maherou@sandia.gov)
// Jack Dongarra     (dongarra@eecs.utk.edu)
// Piotr Luszczek    (luszczek@eecs.utk.edu)
//
// ***************************************************
//@HEADER

/*!
 @file Vector.hpp

 HPCG data structures for dense vectors
 */

#ifndef VECTOR_HPP
#define VECTOR_HPP
#include <cassert>
#include <cstdlib>
#include "Geometry.hpp"

struct Vector_STRUCT {
  local_int_t localLength;  //!< length of local portion of the vector
  double * values;          //!< array of values
  /*!
   This is for storing optimized data structres created in OptimizeProblem and
   used inside optimized ComputeSPMV().
   */
  void * optimizationData;

};
typedef struct Vector_STRUCT Vector;

/*!
  Initializes input vector.

  @param[in] v
  @param[in] localLength Length of local portion of input vector
 */
inline void InitializeVector(Vector & v, local_int_t localLength) {
  v.localLength = localLength;
  v.values = new double[localLength];
  v.optimizationData = 0;
  return;
}

/*!
  Fill the input vector with zero values.

  @param[inout] v - On entrance v is initialized, on exit all its values are zero.
 */
inline void ZeroVector(Vector & v) {
  local_int_t localLength = v.localLength;
  double * vv = v.values;
  for (int i=0; i<localLength; ++i) vv[i] = 0.0;
  return;
}
/*!
  Multiply (scale) a specific vector entry by a given value.

  @param[inout] v Vector to be modified
  @param[in] index Local index of entry to scale
  @param[in] value Value to scale by
 */
inline void ScaleVectorValue(Vector & v, local_int_t index, double value) {
  assert(index>=0 && index < v.localLength);
  double * vv = v.values;
  vv[index] *= value;
  return;
}
/*!
  Fill the input vector with pseudo-random values.

  @param[in] v
 */
inline void FillRandomVector(Vector & v) {
  local_int_t localLength = v.localLength;
  double * vv = v.values;
  for (int i=0; i<localLength; ++i) vv[i] = rand() / (double)(RAND_MAX) + 1.0;
  return;
}
/*!
  Copy input vector to output vector.

  @param[in] v Input vector
  @param[in] w Output vector
 */
inline void CopyVector(const Vector & v, Vector & w) {
  local_int_t localLength = v.localLength;
  assert(w.localLength >= localLength);
  double * vv = v.values;
  double * wv = w.values;
  for (int i=0; i<localLength; ++i) wv[i] = vv[i];
  return;
}

/*!
  Deallocates the members of the data structure of the known system matrix provided they are not 0.

  @param[in] A the known system matrix
 */
inline void DeleteVector(Vector & v) {

  delete [] v.values;
  v.localLength = 0;
  return;
}

#endif // VECTOR_HPP


text:
import logging
import simplejson
import datetime

from django.contrib.auth import login, load_backend, BACKEND_SESSION_KEY
from django.core.exceptions import MultipleObjectsReturned
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_noop
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.conf import settings
from django.template.loader import render_to_string

from avatar.templatetags.avatar_tags import avatar_url

from .models import *
from .forms import ComposeForm, ReplyForm
from .utils import now

@login_required
def inbox(request, template_name='messages/inbox.html'):
    """
    Displays a list of received messages for the current user.
    Optional Arguments:
        ``template_name``: name of the template to use.
    """
    only_read = request.GET.get("only_read", False)
    only_unread = request.GET.get("only_unread", False)
    only_unreplied = request.GET.get("only_unreplied", None)

    read = None
    if only_read:
        read = True
    elif only_unread:
        read = False

    if only_unreplied:
        only_unreplied = True

    thread_list = Participant.objects.inbox_for(request.user, read=read, only_unreplied=only_unreplied)

    return render_to_response(template_name, {
        'thread_list': thread_list,
        'only_read': only_read,
        'only_unread': only_unread,
        'only_unreplied': only_unreplied,
    }, context_instance=RequestContext(request))

@login_required
def search(request, template_name="messages/search.html"):
    from haystack.query import SearchQuerySet #include here, so the dependency is only needed when used
    search_term = request.GET.get("q")
    results = SearchQuerySet().filter(content=search_term,
                                    participants=request.user.pk)\
                                    .order_by('-last_message').models(Thread)
                    # leads to error in haystack: .order_by("-last_message")
    return render_to_response(template_name, {
                                  "thread_results": results,
                                  "search_term": search_term,
                                }, context_instance=RequestContext(request))

@login_required
def outbox(request, template_name='messages/inbox.html'):
    """
    Displays a list of sent messages by the current user.
    Optional arguments:
        ``template_name``: name of the template to use.
    """
    thread_list = Participant.objects.outbox_for(request.user)
    return render_to_response(template_name, {
        'thread_list': thread_list,
    }, context_instance=RequestContext(request))

@login_required
def trash(request, template_name='messages/trash.html'):
    """
    Displays a list of deleted messages.
    Optional arguments:
        ``template_name``: name of the template to use
    Hint: A Cron-Job could periodicly clean up old messages, which are deleted
    by sender and recipient.
    """
    message_list = Participant.objects.trash_for(request.user)
    return render_to_response(template_name, {
        'message_list': message_list,
    }, context_instance=RequestContext(request))

@login_required
def compose(request, recipient=None, form_class=ComposeForm,
        template_name='messages/compose.html', success_url=None, recipient_filter=None):
    """
    Displays and handles the ``form_class`` form to compose new messages.
    Required Arguments: None
    Optional Arguments:
        ``recipient``: username of a `django.contrib.auth` User, who should
                       receive the message, optionally multiple usernames
                       could be separated by a '+'
        ``form_class``: the form-class to use
        ``template_name``: the template to use
        ``success_url``: where to redirect after successfull submission
    """
    recipients = []
    if request.method == "POST":
        sender = request.user
        form = form_class(data=request.POST, recipient_filter=recipient_filter)
        if form.is_valid():
            form.save(sender=request.user)
            if success_url is None:
                success_url = reverse('messages_inbox')
            if request.GET.has_key('next'):
                success_url = request.GET['next']
            return HttpResponseRedirect(success_url)
    else:
        form = form_class()
        if recipient is not None:
            recipients = [u for u in User.objects.filter(username__in=[r.strip() for r in recipient.split('+')])]
            form.fields['recipient'].initial = recipients
    return render_to_response(template_name, {
        'form': form,
        'recipients': recipients,
    }, context_instance=RequestContext(request))

@login_required
def delete(request, thread_id, success_url=None):
    """
    Marks a message as deleted by sender or recipient. The message is not
    really removed from the database, because two users must delete a message
    before it's save to remove it completely.
    A cron-job should prune the database and remove old messages which are
    deleted by both users.
    As a side effect, this makes it easy to implement a trash with undelete.

    You can pass ?next=/foo/bar/ via the url to redirect the user to a different
    page (e.g. `/foo/bar/`) than ``success_url`` after deletion of the message.
    """
    user = request.user
    right_now = now()
    thread = get_object_or_404(Thread, id=thread_id)
    try:
        user_part = get_object_or_404(Participant, user=user, thread=thread)
    except MultipleObjectsReturned:
        user_part = Participant.objects.filter(user = user, thread = thread)[0]

    if request.GET.has_key('next'):
        success_url = request.GET['next']
    elif success_url is None:
        success_url = reverse('messages_inbox')

    user_part.deleted_at = right_now
    user_part.save()
    return HttpResponseRedirect(success_url)

@login_required
def undelete(request, thread_id, success_url=None):
    """
    Recovers a message from trash. This is achieved by removing the
    ``(sender|recipient)_deleted_at`` from the model.
    """
    user = request.user
    thread = get_object_or_404(Thread, id=thread_id)
    user_part = get_object_or_404(Participant, user=user, thread=thread)

    if request.GET.has_key('next'):
        success_url = request.GET['next']
    elif success_url is None:
        success_url = reverse('messages_inbox')

    user_part.deleted_at = None
    user_part.save()
    return HttpResponseRedirect(success_url)

@login_required
def view(request, thread_id, form_class=ReplyForm,
        success_url=None, recipient_filter=None, template_name='messages/view.html'):
    """
    Shows a single message.``message_id`` argument is required.
    The user is only allowed to see the message, if he is either
    the sender or the recipient. If the user is not allowed a 404
    is raised.
    If the user is the recipient and the message is unread
    ``read_at`` is set to the current datetime.
    """
    user = request.user
    thread = get_object_or_404(Thread, id=thread_id)

    """
    Reply stuff
    """
    if request.method == "POST":
        form = form_class(request.POST)
        if form.is_valid():
            form.save(sender=user, thread=thread)
            if success_url is None:
                success_url = reverse('messages_detail', args=(thread.id,))
            return HttpResponseRedirect(success_url)
    else:
        form = form_class()

    now = datetime.datetime.now()
    try:
        participant = get_object_or_404(Participant, thread=thread, user=request.user)
    except MultipleObjectsReturned:
        participant = Participant.objects.filter(thread=thread, user=request.user)[0]
    message_list = []
    # in this view we want the last message last
    for message in thread.all_msgs.all().order_by("sent_at"):
        unread = True
        if participant.read_at and message.sent_at <= participant.read_at:
            unread = False
        message_list.append((message, unread,))
    participant.read_thread()
    return render_to_response(template_name, {
        'thread': thread,
        'message_list': message_list,
        'form': form,
        'participant': participant,
    }, context_instance=RequestContext(request))

@login_required
def batch_update(request, success_url=None):
    """
    Gets an array of message ids which can be either deleted or marked as
    read/unread
    """
    if request.method == "POST":
        ids = request.POST.getlist("batchupdateids")
        if ids:
            threads = Thread.objects.filter(pk__in=ids)
            for thread in threads:
                participant = thread.participants.filter(user=request.user)
                if participant:
                    participant = participant[0]
                    if request.POST.get("action") == "read":
                        participant.read_at = now()
                    elif request.POST.get("action") == "delete":
                        participant.deleted_at = now()
                    elif request.POST.get("action") == "unread":
                        participant.read_at = None
                    participant.save()
        else:
            raise Http404

    else:
        # this should only happen when hacked or developer uses wrong, therefore
        # return simple message
        return HttpResponse("Only Post allowed", code=400)

    if success_url:
        return HttpResponseRedirect(success_url)
    else:
        # either go to last page, or to inbox as fallback
        referer = request.META.get('HTTP_REFERER', None)
        if referer:
            return HttpResponseRedirect(referer)
        else:
            return HttpResponseRedirect(reverse("messages_inbox"))

@login_required
def message_ajax_reply(request, thread_id,
                  template_name="messages/message_list_view.html"):
    thread = get_object_or_404(Thread, id=thread_id)
    if request.POST:
        form = ReplyForm(request.POST)
        if form.is_valid():
            try:
                (thread, new_message) = form.save(sender=request.user, thread=thread)
            except Exception, e:
                logging.exception(e)
                return HttpResponse(status=500, content="Message could not be sent")

            return render_to_response(template_name,{
                "message": new_message,
            }, context_instance=RequestContext(request))
        else:
            return HttpResponse(status=400, content="Invalid Form")

@login_required
def recipient_search(request):
    term = request.GET.get("term")
    users = User.objects.filter(username__icontains=term)
    if request.GET.get("format") == "json":
        data = []
        for user in users:
            avatar_img_url = avatar_url(user, size=50)
            data.append({"id": user.username,
                         "url": reverse("user_page",args=(user.username,)),
                         "name": "%s" % user.username,
                         "img": avatar_img_url})

        return HttpResponse(simplejson.dumps(data),
                            content_type='application/json')


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef SHARED_LIBRARIES_H_
#define SHARED_LIBRARIES_H_

#ifndef MOZ_ENABLE_PROFILER_SPS
#error This header does not have a useful implementation on your platform!
#endif

#include <algorithm>
#include <vector>
#include <string>
#include <stdlib.h>
#include <stdint.h>
#ifndef SPS_STANDALONE
#include <nsID.h>
#endif

class SharedLibrary {
public:

  SharedLibrary(uintptr_t aStart,
                uintptr_t aEnd,
                uintptr_t aOffset,
                const std::string& aBreakpadId,
                const std::string& aName)
    : mStart(aStart)
    , mEnd(aEnd)
    , mOffset(aOffset)
    , mBreakpadId(aBreakpadId)
    , mName(aName)
  {}

  SharedLibrary(const SharedLibrary& aEntry)
    : mStart(aEntry.mStart)
    , mEnd(aEntry.mEnd)
    , mOffset(aEntry.mOffset)
    , mBreakpadId(aEntry.mBreakpadId)
    , mName(aEntry.mName)
  {}

  SharedLibrary& operator=(const SharedLibrary& aEntry)
  {
    // Gracefully handle self assignment
    if (this == &aEntry) return *this;

    mStart = aEntry.mStart;
    mEnd = aEntry.mEnd;
    mOffset = aEntry.mOffset;
    mBreakpadId = aEntry.mBreakpadId;
    mName = aEntry.mName;
    return *this;
  }

  bool operator==(const SharedLibrary& other) const
  {
    return (mStart == other.mStart) &&
           (mEnd == other.mEnd) &&
           (mOffset == other.mOffset) &&
           (mName == other.mName) &&
           (mBreakpadId == other.mBreakpadId);
  }

  uintptr_t GetStart() const { return mStart; }
  uintptr_t GetEnd() const { return mEnd; }
  uintptr_t GetOffset() const { return mOffset; }
  const std::string &GetBreakpadId() const { return mBreakpadId; }
  const std::string &GetName() const { return mName; }

private:
  SharedLibrary() {}

  uintptr_t mStart;
  uintptr_t mEnd;
  uintptr_t mOffset;
  std::string mBreakpadId;
  std::string mName;
};

static bool
CompareAddresses(const SharedLibrary& first, const SharedLibrary& second)
{
  return first.GetStart() < second.GetStart();
}

class SharedLibraryInfo {
public:
  static SharedLibraryInfo GetInfoForSelf();
  SharedLibraryInfo() {}

  void AddSharedLibrary(SharedLibrary entry)
  {
    mEntries.push_back(entry);
  }

  const SharedLibrary& GetEntry(size_t i) const
  {
    return mEntries[i];
  }

  // Removes items in the range [first, last)
  // i.e. element at the "last" index is not removed
  void RemoveEntries(size_t first, size_t last)
  {
    mEntries.erase(mEntries.begin() + first, mEntries.begin() + last);
  }

  bool Contains(const SharedLibrary& searchItem) const
  {
    return (mEntries.end() !=
              std::find(mEntries.begin(), mEntries.end(), searchItem));
  }

  size_t GetSize() const
  {
    return mEntries.size();
  }

  void SortByAddress()
  {
    std::sort(mEntries.begin(), mEntries.end(), CompareAddresses);
  }

  void Clear()
  {
    mEntries.clear();
  }

private:
  std::vector<SharedLibrary> mEntries;
};

#endif


text:
namespace GiveCRM.ImportExport.Test
{
    using System;
    using System.IO;
    using NUnit.Framework;

    [TestFixture]
    public class When_using_ExcelXlsImporter
    {
        private string testFileXls = Directory.GetCurrentDirectory() + "/TestData/MemberData.xls";

        [Test]
        public void Should_throw_exception_if_file_stream_null()
        {
            var importer = new ExcelXlsImporter();

            Assert.Throws<ArgumentNullException>(() => importer.Open(null));
        }

        [Test]
        public void Should_set_workbook_from_stream()
        {
            using (FileStream stream = new FileStream(testFileXls, FileMode.Open, FileAccess.Read))
            {
                var importer = new ExcelXlsImporter();
                importer.Open(stream);

                Assert.IsNotNull(importer.Workbook);
            }
        }
    }
}


text:
/*
 * This file ethphy.h represents the PHY layer inclusion file
 * of the UDP/IP stack.
 *
 * Author : Marco Russi
 *
 * Evolution of the file:
 * 10/08/2015 - File created - Marco Russi
 *
*/

#ifndef _ETHPHY_H
#define _ETHPHY_H

/* inclusion files */
#include "fw_common.h"

/* Exported functions prototypes */
EXTERN boolean ETHPHY_Init(void);

#endif
/* End of files */


text:
Fabricator(:revision) do
  rally_uri "http://fabricated_revision_uri.com"
  refresh true
end


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

<title>conrad.weiser.robinhood.api</title>
<meta name="date" content="2017-06-20">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

conrad.weiser.robinhood.api

Classes

ApiMethod

ConfigurationManager

LogHandler

RobinhoodApi


text:
package main

import (
	"io/ioutil"
	"log"
	"net/http"
	"time"

	"github.com/carl-mastrangelo/h2c"
)

func main() {
	go startH1BackendServer()
	go startH2BackendServer()

	time.Sleep(500 * time.Millisecond)

	c := &http.Client{}
	h2c.AttachClearTextUpgrade(c)

	resp, err := c.Get("http://localhost:9902/")
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	log.Println(string(data))

	// Try again, with http 1

	resp, err = c.Get("http://localhost:9901/")
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	data, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	log.Println(string(data))
}

func startH2BackendServer() {
	handler := func(w http.ResponseWriter, r *http.Request) {
		if _, err := w.Write([]byte("Hello, World " + r.Proto)); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}

	s := &http.Server{
		Addr:    ":9902",
		Handler: http.HandlerFunc(handler),
	}
	h2c.AttachClearTextHandler(nil, s)
	log.Fatal(s.ListenAndServe())
}

func startH1BackendServer() {
	handler := func(w http.ResponseWriter, r *http.Request) {
		if _, err := w.Write([]byte("Hello, World " + r.Proto)); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}

	s := &http.Server{
		Addr:    ":9901",
		Handler: http.HandlerFunc(handler),
	}
	log.Fatal(s.ListenAndServe())
}


text:
@implementation ZYDataCenterRequestCondition

- (instancetype)init
{
    if (self = [super init]) {

        self.requestMethod = ZYNetworkRequestMethodPOST;
    }
    return self;
}

- (void)addGetParams:(NSDictionary *)params
{
    NSMutableDictionary *mGetParams = [NSMutableDictionary dictionaryWithDictionary:self.getParams];
    [mGetParams addEntriesFromDictionary:params];
    self.getParams = mGetParams;
}

- (void)addPostParams:(NSDictionary *)params
{
    NSMutableDictionary *mPostParams = [NSMutableDictionary dictionaryWithDictionary:self.postParams];
    [mPostParams addEntriesFromDictionary:params];
    self.postParams = mPostParams;
}

@end


text:
Palindrome = Struct.new(:value, :factors)

class Palindromes

  attr_reader :range
  def initialize(options)
    max = options.fetch(:max_factor)
    min = options.fetch(:min_factor) { 1 }
    @range = (min..max)
  end

  def generate
    @palindromes = {}
    range.each do |i|
      range.each do |j|
        product = i * j
        if palindrome?(product)
          palindrome = @palindromes[product] || Palindrome.new(product, [])
          palindrome.factors << [i, j].sort
          palindrome.factors.uniq!
          @palindromes[product] = palindrome
        end
      end
    end
  end

  def palindrome?(number)
    number.to_s == number.to_s.reverse
  end

  def sort
    @palindromes.sort_by do |key, palindrome|
      key
    end
  end

  def largest
    sort.last[1]
  end

  def smallest
    sort.first[1]
  end

end


text:
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace Stratus
{
  public abstract class ObjectPropertySelectorDrawer<T> : StratusPropertyDrawer
  {
    protected abstract string objectPropertyName { get; }
    protected override void OnDrawProperty(Rect position, SerializedProperty property)
    {
      SerializedProperty objectProperty = property.FindPropertyRelative(objectPropertyName);
      EditorGUI.BeginChangeCheck();
      EditorGUI.PropertyField(position, objectProperty, GUIContent.none);
      bool changed = EditorGUI.EndChangeCheck();
      if (objectProperty.objectReferenceValue != null && !changed)
      {
        position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
        DrawSelector(position, property, property.GetValue<T>());
      }
    }

    protected override float GetPropertyHeight(SerializedProperty property)
    {
      SerializedProperty objectProperty = property.FindPropertyRelative(objectPropertyName);
      return EditorGUIUtility.singleLineHeight * (objectProperty.objectReferenceValue != null ? 2f : 1f);
    }

    protected abstract void DrawSelector(Rect position, SerializedProperty property, T target);

    //protected abstract string[] GetSelectionList

  }

}


text:
---
uid: SolidEdgePart.PropertyDefinitions.Add(System.String,SolidEdgePart.PropertyTypeConstants,System.Object)
summary:
remarks:
syntax:
    parameters:
    - id: DefaultValue
      description: Default value
    - id: Name
      description: Name
    - id: Type
      description: Member of the PropertyTypeConstants constant set that specifies the type of PropertyDefinition to be added.
---


text:
<!--
  ~ Copyright (c) 2010-2017 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->

<role oid="ecb9287d-5852-4bec-9926-4ab1de518e26"
      xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
      xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
      xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3">
    <name>a-test-2b</name>
    <c:description>Exclusive with test-2a/2c</c:description>
    <assignment>
        <policyRule>
            <policyConstraints>
                <exclusion>
                    <targetRef oid="fa636d6a-f016-491c-8cd5-cdcbfd516be5" type="RoleType"/>        <!--  test-2a -->
                </exclusion>
            </policyConstraints>
        </policyRule>
    </assignment>
    <assignment>
        <policyRule>
            <policyConstraints>
                <exclusion>
                    <targetRef oid="dc9beda4-9bb1-40da-8530-c67da19f2b5e" type="RoleType"/>        <!--  test-2c -->
                </exclusion>
            </policyConstraints>
        </policyRule>
    </assignment>
    <assignment>
        <targetRef oid="6bc73701-f1db-4fef-b644-8bfd7b64d97b" type="RoleType"/>      <!-- common-rules -->
    </assignment>
</role>


text: A billion edits.


text:
layout: single
title: Reddit Holiday Greeting Card Exchange
date: 2012-12-10 13:25
categories: Arduino
---

Made with marginallyclever.com for the Reddit Gifts exchange

Source image

Gcode for the drawbot


text:
'use strict';

const Year = require('./year');
const { getDay } = require('../zellars');

const isValidMonth = function(month) {
  if (typeof month !== 'number') {
    return false;
  }
  else if (month%1 !== 0) {
    return false;
  }
  else if (month < 1 || month > 12) {
    return false;
  }
  else {
    return true;
  }
};

// function to center the month & year on the first line
const centeredHeader = function(nameOfMonth, year) {
  //calculate leading spaces
  let leadingSpaces = Math.floor((15-nameOfMonth.length)/2);

  let header = "";
  // generate leading spaces
  for (let i = 1; i <= leadingSpaces; i++) {
    header += " ";
  }
  header = `${header}${nameOfMonth} ${year}`;
  return header;
};

// require isLeapYear() to determine days in February
let monthDays = [31,28,31,30,31,30,31,31,30,31,30,31];
let monthNames = ['January','February','March','April',
                  'May','June','July','August','September',
                  'October','November','December'];

// generateMonth()
const generateMonth = function(year, month) {
  let output = [];
  month = month;
  if (!Year.isValidYear(year) || !isValidMonth(month)) {
    console.log('not valid input');
    return false;
  }

  // set February to 29 days if leap year
  if(Year.isLeapYear(year)) {
    monthDays[1] = 29;
  }

  // get the num of days for desired month(1-12) and name of month
  // adjust month for 0-based array indexes
  const daysInMonth = monthDays[month-1];
  const nameOfMonth = monthNames[month-1];

  // create calendar header
  output.push(centeredHeader(nameOfMonth, year));

  // add line for weekdays
  output.push(`Su Mo Tu We Th Fr Sa`);

  // determine day for first day of month
  const firstDay = getDay(2016, 1, 1);

  // output calender to console
  output.forEach((item) => console.log(item));
};

module.exports = {
  "generateMonth": generateMonth,
  "isValidMonth": isValidMonth
};


text:
namespace occa {
  namespace lang {
    argMetadata_t::argMetadata_t() :
      isConst(false),
      isPtr(false),
      dtype(dtype::byte) {}

    argMetadata_t::argMetadata_t(const bool isConst_,
                                 const bool isPtr_,
                                 const dtype_t &dtype_,
                                 const std::string &name_) :
      isConst(isConst_),
      isPtr(isPtr_),
      dtype(dtype_),
      name(name_) {}

    argMetadata_t argMetadata_t::fromJson(const json &j) {
      return argMetadata_t((bool) j["const"],
                           (bool) j["ptr"],
                           dtype_t::fromJson(j["dtype"]),
                           (std::string) j["name"]);
    }

    json argMetadata_t::toJson() const {
      json j;
      j["const"] = isConst;
      j["ptr"]   = isPtr;
      j["dtype"] = dtype::toJson(dtype);
      j["name"]  = name;
      return j;
    }

    kernelMetadata_t::kernelMetadata_t() :
      initialized(false) {}

    bool kernelMetadata_t::isInitialized() const {
      return initialized;
    }

    kernelMetadata_t& kernelMetadata_t::operator += (const argMetadata_t &argInfo) {
      initialized = true;
      arguments.push_back(argInfo);
      return *this;
    }

    kernelMetadata_t kernelMetadata_t::fromJson(const json &j) {
      kernelMetadata_t meta;
      meta.initialized = true;

      meta.name = (std::string) j["name"];

      const jsonArray &argInfos = j["arguments"].array();
      const int argumentCount = (int) argInfos.size();
      for (int i = 0; i < argumentCount; ++i) {
        meta.arguments.push_back(argMetadata_t::fromJson(argInfos[i]));
      }

      return meta;
    }

    json kernelMetadata_t::toJson() const {
      json j;
      j["name"] = name;

      const int argumentCount = (int) arguments.size();
      json &argInfos = j["arguments"].asArray();
      for (int k = 0; k < argumentCount; ++k) {
        argInfos += arguments[k].toJson();
      }

      return j;
    }

    sourceMetadata_t::sourceMetadata_t() {}

    json sourceMetadata_t::getKernelMetadataJson() const {
      json metadataJson(json::array_);

      lang::kernelMetadataMap::const_iterator it = kernelsMetadata.begin();
      while (it != kernelsMetadata.end()) {
        metadataJson += (it->second).toJson();
        ++it;
      }

      return metadataJson;
    }

    json sourceMetadata_t::getDependencyJson() const {
      json metadataJson;

      strHashMap::const_iterator it = dependencyHashes.begin();
      while (it != dependencyHashes.end()) {
        metadataJson.set(it->first, it->second.getFullString());
        ++it;
      }

      return metadataJson;
    }

    sourceMetadata_t sourceMetadata_t::fromBuildFile(const std::string &filename) {
      sourceMetadata_t metadata;

      if (!io::exists(filename)) {
        return metadata;
      }

      json props = json::read(filename);
      jsonArray &kernelMetadata = props["kernel/metadata"].array();
      jsonObject &dependencyHashes_ = props["kernel/dependencies"].object();

      kernelMetadataMap &metadataMap = metadata.kernelsMetadata;
      const int kernelCount = (int) kernelMetadata.size();
      for (int i = 0; i < kernelCount; ++i) {
        kernelMetadata_t kernel = kernelMetadata_t::fromJson(kernelMetadata[i]);
        metadataMap[kernel.name] = kernel;
      }

      jsonObject::iterator it = dependencyHashes_.begin();
      while (it != dependencyHashes_.end()) {
        metadata.dependencyHashes[it->first] = hash_t::fromString(it->second);
        ++it;
      }

      return metadata;
    }
  }
}


text:
package com.seltzer.cucumber;

import com.seltzer.selenium.View;
import com.seltzer.selenium.browser.BrowserDriver;
import com.seltzer.selenium.views.LoginView;
import org.apache.log4j.Logger;

import cucumber.api.java.After;
import cucumber.api.java.Before;
import org.reflections.Reflections;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;

public class Hooks {

    private static Logger log = Logger.getLogger(Hooks.class);

    /**
     * Run this before every scenario
     */
    @Before
    public void beforeScenario() {
        log.info("Starting the browser...");
        BrowserDriver.getCurrentDriver();
        initializeViews();
    }

    /**
     * Run this after every scenario
     */
    @After
    public void afterScenario() {
        log.info("Closing the browser...");
        BrowserDriver.close();
    }

    /**
     * Initialize the view containers
     */
    private void initializeViews() {
        try {
            Reflections reflections = new Reflections("com.seltzer");
            Set<Class<? extends View>> classes = reflections.getSubTypesOf(View.class);
            if (classes == null || classes.isEmpty()) {
                 throw new IllegalArgumentException("Must initialize at least one view class");
            } else {
                for (Class each : classes) {
                    Method method = each.getMethod("init");
                    method.invoke(new Object(), null);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}


text:
package com.github.kulebin.myfoursquareapp.view;

import com.github.kulebin.myfoursquareapp.model.Venue;

public class CompleteVenueDisplayData extends VenueDisplayData {

    private final String contact;
    private final String description;

    public CompleteVenueDisplayData(final Venue pVenue) {
        super(pVenue);

        this.contact = pVenue.getContact();
        this.description = pVenue.getDescription();
    }

    public String getContact() {
        return contact;
    }

    public String getDescription() {
        return description;
    }
}


text:
A basic (and experimental) implementation of the OSC Query Proposal at https://github.com/mrRay/OSCQueryProposal

This repository implements an OSC Query Server and Client over TCP/HTTP 1.1, and a utility class for parsing HTTP headers.

## OSCQueryServer

* ZeroConf/Bonjour support
* Adding OSC addresses with the minium info (FULL_PATH, DESCRIPTION, CONTENTS)
* Set TYPE and RANGE for OSC addresses
* GET the full- or partial OSC address space
* Basic error reporting (only 404 yet)
* Basic persistent connection management
* Browser "support"

The repository contains a simple sample app, although it may change very often, it could be considered as buggy, but somehow working.

## OSCQueryClient

* Query full- or partial address space
* Basic error handling (only 404 yet)
* Delegate methods for forwarding reply and error data

## OSCQueryHTTPHeader

This class is used to parse a raw HTTP header and get the HTTP fields as well as some additional info

## System requirements

* Tested on OSX 10.10.3, should work on >=10.8
* 64bit, ARC

## 3rd party code

* CocoaAsyncSocket: https://github.com/robbiehanson/CocoaAsyncSocket


text:
<?php

namespace Yiinitializr\Helpers;

/**
 * Config provides easy access to Yiinitializr configuration file
 *
 * @author Antonio Ramirez <amigo.cobos@gmail.com>
 * @package Yiinitializr.helpers
 * @since 1.0
 */
class Config
{
	/**
	 * @var array the configuration settings
	 */
	private static $_settings;

	private static $_config_dir_path;
	private static $_envlock_file_path;

	/**
	 * Returns a value of the array
	 * @param $value
	 * @return mixed | null if no key is found
	 */
	public static function value($value)
	{
		return ArrayX::get(self::settings(), $value);
	}

	/**
	 * Reads the configuration settings from the file
	 * @return array|mixed
	 * @throws \Exception
	 */
	public static function settings()
	{
		if (null === self::$_settings)
		{
			self::$_settings = file_exists(self::getConfigurationDirectoryPath() . '/settings.php')
				? require_once(self::getConfigurationDirectoryPath() . '/settings.php')
				: array();
			self::$_settings['envlock'] = file_exists(self::getEnvironmentLockFilePath());

		}
		if (empty(self::$_settings))
			throw new \Exception('Unable to find Yiinitialzr settings file!');

		return self::$_settings;
	}

	/**
	 * @param string $content
	 */
	public static function createEnvironmentLockFile($content = '')
	{
		umask(0);
		file_put_contents(self::getEnvironmentLockFilePath(), $content);
		@chmod(self::getEnvironmentLockFilePath(), 0644);
	}

	/**
	 * Returns the configuration directory path
	 * @return string
	 */
	public static function getConfigurationDirectoryPath()
	{
		if (null === self::$_config_dir_path)
			self::$_config_dir_path = dirname(__FILE__) . '/../config';
		return self::$_config_dir_path;
	}

	/**
	 * Returns the environment lock file path
	 * @return string
	 */
	public static function getEnvironmentLockFilePath()
	{
		if (null === self::$_envlock_file_path)
			self::$_envlock_file_path = self::getConfigurationDirectoryPath() . '/env.lock';
		return self::$_envlock_file_path;
	}
}


text:
package org.lanternpowered.server.data.io.store.item;

import org.lanternpowered.server.data.io.store.SimpleValueContainer;
import org.spongepowered.api.data.Keys;
import org.spongepowered.api.data.persistence.DataQuery;
import org.spongepowered.api.data.persistence.DataView;
import org.spongepowered.api.item.inventory.ItemStack;

public class WritableBookItemTypeObjectSerializer extends ItemTypeObjectSerializer {

    public static final DataQuery PAGES = DataQuery.of("pages");

    @Override
    public void serializeValues(ItemStack itemStack, SimpleValueContainer valueContainer, DataView dataView) {
        super.serializeValues(itemStack, valueContainer, dataView);
        valueContainer.remove(Keys.PLAIN_BOOK_PAGES).ifPresent(lines -> dataView.set(PAGES, lines));
    }

    @Override
    public void deserializeValues(ItemStack itemStack, SimpleValueContainer valueContainer, DataView dataView) {
        super.deserializeValues(itemStack, valueContainer, dataView);
        dataView.getStringList(PAGES).ifPresent(lines -> valueContainer.set(Keys.PLAIN_BOOK_PAGES, lines));
    }
}


text:
namespace Spyder.Client.Common
{
    public enum OutputMode
    {
        Normal,
        Scaled,
        OpMon,
        SourceConfig,
        PassiveLeft,
        PassiveRight,
        ActiveStereo,
        SourceMon,

        //Added in X80.
        //Note these are not in the enum order of X80, and explicit serialization/deserialization is required.
        //Enum formats in correct byte order for X20 and X80 are below
        Multiviewer,
        Aux,
        UnscaledAux
    };

    /// <summary>
    /// Output mode enumerations byte-aligned with X80
    /// </summary>
    public enum OutputModeX80
    {
        Normal,
        Multiviewer,
        Scaled,
        Aux,
        UnscaledAux,
        OpMon,
        SourceMon,
        PassiveLeft,
        PassiveRight,
        ActiveStereo
    }

    /// <summary>
    /// Output mode enumerations byte-aligned with 200/300/X20 Spyder
    /// </summary>
    public enum OutputModeX20
    {
        Normal,
        Scaled,
        OpMon,
        SourceConfig,
        PassiveLeft,
        PassiveRight,
        ActiveStereo,
        SourceMon
    };
}


text:
using System;

namespace Sample.DomainEvents.Community
{
    public class ItemRegisted : AggregateRootEvent
    {
        public ItemRegisted(Guid aggregateRootId)
            : base(aggregateRootId) { }
    }

    public class PeopleRegisted : ItemRegisted
    {
        public PeopleRegisted(Guid aggregateRootId, string username, string password, DateTime registerTime)
            : base(aggregateRootId)
        {
            UserName = username;
            Password = password;
            RegisterTime = registerTime;
        }

        public string UserName { get; }
        public string Password { get; }
        public DateTime RegisterTime { get; }
    }

    public class AccountRegistered : PeopleRegisted
    {
        public AccountRegistered(Guid aggregateRootId,
                                 string username,
                                 string password,
                                 string email,
                                 DateTime registerTime)
            : base(aggregateRootId, username, password, registerTime)
        {
            Email = email;
        }

        public string Email { get; }
    }

    public class AccountModified : AggregateRootEvent
    {
        public AccountModified(Guid aggregateRootId, string email)
            : base(aggregateRootId)
        {
            Email = email;
        }

        public string Email { get; }
    }
}


text:
'use strict';

const marko    = require( 'marko' );
const router = require( 'koa-router' )();
const i18n   = require( '../i18n' );
import _ from 'lodash';

// IMPORT DATA, to be extended later
const jsonAPI = require( '../../test/employer.json' );
function getData() {
  return jsonAPI;
}

function findTemplate( template, data ) {
  return `./src/views/${template}.marko`;
}

function getNames( obj ) {
  if ( _.has( obj, 'name' ) ) {
    if ( _.has( obj, 'attribute' ) && _.isArray( obj.attribute ) ) {
      //recurse
      return [ obj.name, _.map( obj.attribute, getNames ) ];
    } else {
      return obj.name;
    }
  }
}

function *index( next ) {
  // get data from backend
  const data  = getData();
  const names = _.flattenDeep( getNames( data ) ); // data loaded

  /*let result = _.reduce( names, ( acc, name ) => `${acc}<li>${name}</li>`, '' );
  result     = `<ul>${result}</ul>`;*/

  //console.log( result );
  this.body = marko.load( findTemplate( 'index' ) ).stream({ names });
  this.type = 'text/html';
  yield next;
}

router.get( '/marko', index );

export default router.routes();


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">
<title>Class Hierarchy (Fluo API 1.0.0-beta-1 API)</title>
<meta name="date" content="2015-06-10">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For All Packages

Package Hierarchies:

io.fluo.api.client,

io.fluo.api.config,

io.fluo.api.data,

io.fluo.api.exceptions,

io.fluo.api.iterator,

io.fluo.api.mini,

io.fluo.api.observer,

io.fluo.api.types

Class Hierarchy

java.lang.Object

io.fluo.api.observer.AbstractObserver (implements io.fluo.api.observer.Observer)

io.fluo.api.types.TypedObserver

io.fluo.api.data.Bytes (implements java.lang.Comparable<T>)

io.fluo.api.data.Column

org.apache.commons.configuration.event.EventSource

org.apache.commons.configuration.AbstractConfiguration (implements org.apache.commons.configuration.Configuration)

org.apache.commons.configuration.CompositeConfiguration (implements java.lang.Cloneable)

io.fluo.api.config.FluoConfiguration

io.fluo.api.client.FluoAdmin.InitOpts

io.fluo.api.client.FluoFactory

io.fluo.api.observer.Observer.ObservedColumn

io.fluo.api.config.ObserverConfiguration

io.fluo.api.data.RowColumn

io.fluo.api.config.ScannerConfiguration (implements java.lang.Cloneable)

io.fluo.api.data.Span

io.fluo.api.data.Span.Builder

io.fluo.api.data.Span.EndBuilder

io.fluo.api.data.Span.EndCFBuilder

io.fluo.api.data.Span.EndCQBuilder

io.fluo.api.data.Span.EndCVBuilder

io.fluo.api.data.Span.KeyBuilder

io.fluo.api.data.Span.StartBuilder

io.fluo.api.data.Span.StartCFBuilder

io.fluo.api.data.Span.StartCQBuilder

io.fluo.api.data.Span.StartCVBuilder

io.fluo.api.types.StringEncoder (implements io.fluo.api.types.Encoder)

java.lang.Throwable (implements java.io.Serializable)

java.lang.Exception

io.fluo.api.client.FluoAdmin.AlreadyInitializedException

io.fluo.api.client.FluoAdmin.TableExistsException

java.lang.RuntimeException

io.fluo.api.exceptions.FluoException

io.fluo.api.exceptions.AlreadySetException

io.fluo.api.exceptions.CommitException

io.fluo.api.types.TypedLoader (implements io.fluo.api.client.Loader)

io.fluo.api.types.TypedSnapshotBase (implements io.fluo.api.client.SnapshotBase)

io.fluo.api.types.TypedSnapshot (implements io.fluo.api.client.Snapshot)

io.fluo.api.types.TypedTransactionBase (implements io.fluo.api.client.TransactionBase)

io.fluo.api.types.TypedTransaction (implements io.fluo.api.client.Transaction)

io.fluo.api.types.TypedSnapshotBase.ColumnsMethods

io.fluo.api.types.TypedSnapshotBase.MapConverter

io.fluo.api.types.TypedSnapshotBase.Value

io.fluo.api.types.TypedSnapshotBase.VisibilityMethods

io.fluo.api.types.TypedTransactionBase.Mutator

io.fluo.api.types.TypedTransactionBase.VisibilityMutator

io.fluo.api.types.TypeLayer

io.fluo.api.types.TypeLayer.QualifierMethods<R>

io.fluo.api.types.TypedSnapshotBase.ValueQualifierBuilder

io.fluo.api.types.TypedTransactionBase.MutatorQualifierMethods

io.fluo.api.types.TypeLayer.CQB

io.fluo.api.types.TypeLayer.RowMethods<R>

io.fluo.api.types.TypedSnapshotBase.ValueRowMethods

io.fluo.api.types.TypedTransactionBase.MutatorRowMethods

io.fluo.api.types.TypeLayer.SimpleFamilyMethods<R1>

io.fluo.api.types.TypeLayer.CFB

io.fluo.api.types.TypeLayer.FamilyMethods<R1,R2>

io.fluo.api.types.TypedSnapshotBase.ValueFamilyMethods

io.fluo.api.types.TypedTransactionBase.MutatorFamilyMethods

io.fluo.api.types.TypeLayer.VisibilityMethods

Interface Hierarchy

java.lang.AutoCloseable

io.fluo.api.client.FluoAdmin

io.fluo.api.client.FluoClient

io.fluo.api.client.LoaderExecutor

io.fluo.api.mini.MiniFluo

io.fluo.api.client.Snapshot (also extends io.fluo.api.client.SnapshotBase)

io.fluo.api.client.Transaction (also extends io.fluo.api.client.TransactionBase)

io.fluo.api.data.Bytes.BytesFactory

io.fluo.api.data.Bytes.WriteUtil

io.fluo.api.types.Encoder

java.util.Iterator<E>

io.fluo.api.iterator.ColumnIterator

io.fluo.api.iterator.RowIterator

io.fluo.api.client.Loader

io.fluo.api.client.Loader.Context

io.fluo.api.observer.Observer

io.fluo.api.observer.Observer.Context

io.fluo.api.client.SnapshotBase

io.fluo.api.client.Snapshot (also extends java.lang.AutoCloseable)

io.fluo.api.client.Transaction (also extends java.lang.AutoCloseable, io.fluo.api.client.TransactionBase)

io.fluo.api.client.TransactionBase

io.fluo.api.client.Transaction (also extends java.lang.AutoCloseable)

Enum Hierarchy

java.lang.Object

java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)

io.fluo.api.observer.Observer.NotificationType

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015 Fluo IO. All rights reserved.


text:
local function greatest_common_divisor(a, b)
    local temp
    while(b > 0) do
        temp = b
        b = a % b
        a = temp
    end
    return a
end

-- Finds the greatest common divisor of an arbitrarily long list of numbers
local function gcd_list(list)
	if #list == 1 then
		return list[1]
	end
	local gcd = list[1]
	for i=2, #list do
        gcd = greatest_common_divisor(gcd, list[i])
	end
    return gcd
end

-- divides input, output and returns values by their greatest common divisor
-- does *not* modify time or any other values
local function reduce_recipe(def)
	local list = {}
	for _, count in pairs(def.input) do
		table.insert(list, count)
	end
	if def.output then
		for _, count in pairs(def.output) do
			table.insert(list, count)
		end
	end
	if def.returns then
		for _, count in pairs(def.returns) do
			table.insert(list, count)
		end
	end
	local gcd = gcd_list(list)
	if gcd ~= 1 then
		for item, count in pairs(def.input) do
			def.input[item] = count/gcd
		end
		if def.output then
			for item, count in pairs(def.output) do
				def.output[item] = count/gcd
			end
		end
		if def.returns then
			for item, count in pairs(def.returns) do
				def.returns[item] = count/gcd
			end
		end
	end
end

-- Turns an item list (as returned by inv:get_list) into a form more easily used by crafting functions
local function itemlist_to_countlist(itemlist)
	local count_list = {}
	for _, stack in ipairs(itemlist) do
		if not stack:is_empty() then
			local name = stack:get_name()
			count_list[name] = (count_list[name] or 0) + stack:get_count()
			-- alias its groups to the item
			if minetest.registered_items[name] then
				for group, _ in pairs(minetest.registered_items[name].groups or {}) do
					if not count_list[group] then count_list[group] = {} end
					count_list[group][name] = true -- using names as keys makes this act as a set
				end
			end
		end
	end
	return count_list
end

-- splits a string into an array of substrings based on a delimiter
local function split(str, delimiter)
    local result = {}
    for match in (str..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match)
    end
    return result
end

-- I apologise for this function.
-- From the items in groupset, checks input_list to find the item
-- with the highest count and adds it to required_input
local function get_highest_count_item_for_group(groupset, input_list, required_input, count)
	local highest_item_name
	local highest_item_count = 0
	for group_item, _ in pairs(groupset) do
		if input_list[group_item] > highest_item_count then
			highest_item_count = input_list[group_item]
			highest_item_name = group_item
		end
	end
	if highest_item_count == 0 then
		return false
	end
	required_input[highest_item_name] = (required_input[highest_item_name] or 0) + count
	return true
end

-- returns the number of times the recipe can be crafted from the given input_list,
-- and also a copy of the recipe with groups substituted for the most common item
-- in the input_list that matches them
local function get_craft_count(input_list, recipe)
	-- Recipe without groups (most common node in group instead)
	local work_recipe = table.copy(recipe)
	work_recipe.input = {}
	local required_input = work_recipe.input
	for item, count in pairs(recipe.input) do
		if string.find(item, ",") then -- special syntax used to require an item that belongs to multiple groups
			local groups = split(item, ",")

			-- This unfortunate block of code builds up an intersection
			-- of the items belonging to each group in the list of groups
			-- that this recipe item slot requires.
			local multigroup_itemset
			for _, group in pairs(groups) do
				if not input_list[group] then
					return 0
				end
				if not multigroup_itemset then
					multigroup_itemset = {}
					for multigroup_item, _ in pairs(input_list[group]) do
						multigroup_itemset[multigroup_item] = true
					end
				else
					local intersect = {}
					for multigroup_item, _ in pairs(input_list[group]) do
						if multigroup_itemset[multigroup_item] then
							intersect[multigroup_item] = true
						end
					end
					multigroup_itemset = intersect
				end
			end

			if not get_highest_count_item_for_group(multigroup_itemset, input_list, required_input, count) then
				return 0
			end
		else
			if not input_list[item] then
				return 0
			end
			-- Groups are a string alias to most common member item
			if type(input_list[item]) == "table" then
				-- find group item with highest count
				if not get_highest_count_item_for_group(input_list[item], input_list, required_input, count) then
					return 0
				end
			else
				required_input[item] = (required_input[item] or 0) + count
			end
		end
	end
	local number = math.huge
	for ingredient, count in pairs(required_input) do
		local max = input_list[ingredient] / count
		if max < 1 then
			return 0
		elseif max < number then
			number = max
		end
	end
	-- Return number of possible crafts as integer
	return math.floor(number), work_recipe
end

-- Used for alphabetizing an array of itemstacks by description
local function compare_stacks_by_desc(stack1, stack2)
	local item1 = stack1:get_name()
	local item2 = stack2:get_name()
	local def1 = minetest.registered_items[item1]
	local def2 = minetest.registered_items[item2]
	return def1.description < def2.description
end

-- Deep equals, used to check for duplicate recipes during registration
local function deep_equals(test1, test2)
	if test1 == test2 then
		return true
	end
	if type(test1) ~= "table" or type(test2) ~= "table" then
		return false
	end
	local value2
	for key, value1 in pairs(test1) do
		value2 = test2[key]
		if value1 ~= value2 and not deep_equals(value1, test2[key]) then
			return false
		end
	end
	for key, _ in pairs(test2) do
		if test1[key] == nil then
			return false
		end
	end
	return true
end

--------------------------------------------------------------------------------------------------------------------
-- Public API

crafting.get_crafting_info = function(craft_type)
	-- ensure the destination tables exist
	crafting.type[craft_type] = crafting.type[craft_type] or {}
	crafting.type[craft_type].recipes = crafting.type[craft_type].recipes or {}
	crafting.type[craft_type].recipes_by_out = crafting.type[craft_type].recipes_by_out or {}
	crafting.type[craft_type].recipes_by_in = crafting.type[craft_type].recipes_by_in or {}

	return crafting.type[craft_type]
end

crafting.register = function(craft_type, def)
	def.returns = def.returns or {}

	reduce_recipe(def)

	-- Strip group: from group names to simplify comparison later
	local groups = {}
	for item, count in pairs(def.input) do
		local group = string.match(item, "^group:(%S+)$")
		if group then
			groups[group] = count
		end
	end
	-- must be done in two steps like this in case the recipe has more than one group item
	-- doing it in the first loop could invalidate the pairs iterator and miss one
	for group, count in pairs(groups) do
		def.input[group] = count
		def.input["group:"..group] = nil
	end

	local crafting_info = crafting.get_crafting_info(craft_type)

	-- Check if this recipe has already been registered. Many different old-style recipes
	-- can reduce down to equivalent recipes in this system, so this is a useful step
	-- to keep things tidy and efficient.
	for _, existing_recipe in pairs(crafting_info.recipes) do
		if deep_equals(def, existing_recipe) then
			return true
		end
	end

	table.insert(crafting_info.recipes, def)

	if def.output then
		local recipes_by_out = crafting_info.recipes_by_out
		for item, _ in pairs(def.output) do
			recipes_by_out[item] = recipes_by_out[item] or {}
			recipes_by_out[item][#recipes_by_out[item]+1] = def
		end
	end

	local recipes_by_in = crafting_info.recipes_by_in
	for item, _ in pairs(def.input) do
		recipes_by_in[item] = recipes_by_in[item] or {}
		recipes_by_in[item][#recipes_by_in[item]+1] = def
	end

	return true
end

-- Registers the provided crafting recipe, and also
-- automatically creates and registers a "reverse" craft of the same type.
-- This should generally only be done with craft that turns one type of item into
-- one other type of item (for example, metal ingots <-> metal blocks), but
-- it will still work if there are multiple inputs.
-- If there's more than one input type it will use "returns" to give them to the
-- player in the reverse craft.
-- Don't use a recipe that has a "group:" input with this, because obviously that
-- can't be turned into an output. The mod will assert if you try to do this.
crafting.register_reversible = function(typeof, forward_def)
	local reverse_def = table.copy(forward_def) -- copy before registering, registration messes with "group:" prefixes
	crafting.register(typeof, forward_def)

	local forward_in = reverse_def.input
	reverse_def.input = crafting.count_list_add(reverse_def.output, reverse_def.returns)

	local most_common_in_name = ""
	local most_common_in_count = 0
	for item, count in pairs(forward_in) do
		assert(string.sub(item, 1, 6) ~= "group:")
		if count > most_common_in_count then
			most_common_in_name = item
			most_common_in_count = count
		end
	end
	reverse_def.output = {[most_common_in_name]=most_common_in_count}
	forward_in[most_common_in_name] = nil
	reverse_def.returns = forward_in

	crafting.register(typeof, reverse_def)
end

-- returns a fuel definition for the item if it is fuel, nil otherwise
-- note: will always return the last-registered definition for a particular item
-- or group.
crafting.is_fuel = function(craft_type, item)
	local fuels = crafting.get_crafting_info(craft_type).recipes_by_in

	-- First check if the item has been explicitly registered as fuel
	if fuels[item] then
		return fuels[item][#fuels[item]]
	end

	-- Failing that, check its groups.
	local def = minetest.registered_items[item]
	if def and def.groups then
		local max = -1
		local fuel_group
		for group, _ in pairs(def.groups) do
			if fuels[group] then
				local last_fuel_def = fuels[group][#fuels[group]]
				if last_fuel_def.burntime > max then
					fuel_group = last_fuel_def -- track whichever is the longest-burning group
					max = fuel_group.burntime
				end
			end
		end
		if fuel_group then
			return fuel_group
		end
	end
	return nil
end

-- Returns a list of all fuel recipes whose ingredients can be satisfied by the item_list
crafting.get_fuels = function(craft_type, item_list)
	local count_list = itemlist_to_countlist(item_list)
	local burnable = {}
	for item, count in pairs(count_list) do
		local recipe = crafting.is_fuel(craft_type, item)
		if recipe then
			table.insert(burnable, recipe)
		end
	end
	return burnable
end

-- Returns a list of all recipes whose ingredients can be satisfied by the item_list
crafting.get_craftable_recipes = function(craft_type, item_list)
	local count_list = itemlist_to_countlist(item_list)
	local craftable = {}
	local recipes = crafting.type[craft_type].recipes
	for i = 1, #recipes do
		local number, recipe = get_craft_count(count_list, recipes[i])
		if number > 0 then
			table.insert(craftable, recipe)
		end
	end
	return craftable
end

-- Returns a list of all the possible item stacks that could be crafted from the provided item list
-- if max_craftable is true the returned stacks will have as many items in them as possible to craft,
-- if max_craftable is false or nil the returned stacks will have only the minimum output
-- if alphabetize is true then the items will be sorted alphabetically by description
-- if alphabetize is false or nil the items will be left in default order
crafting.get_craftable_items = function(craft_type, item_list, max_craftable, alphabetize)
	local count_list = itemlist_to_countlist(item_list)
	local craftable_count_list = {}
	local craftable_stacks = {}
	local chosen_recipe = {}
	local recipes = crafting.type[craft_type].recipes
	for i = 1, #recipes do
		local number, recipe = get_craft_count(count_list, recipes[i])
		if number > 0 then
			if not max_craftable then number = 1 end
			for item, count in pairs(recipe.output) do
				if craftable_count_list[item] and count*number > craftable_count_list[item] then
					craftable_count_list[item] = count*number
					chosen_recipe[item] = recipe
				elseif not craftable_count_list[item] and count*number > 0 then
					craftable_count_list[item] = count*number
					chosen_recipe[item] = recipe
				end
			end
		end
	end
	-- Limit stacks to stack limit
	for item, count in pairs(craftable_count_list) do
		local stack = ItemStack(item)
		local max = stack:get_stack_max()
		if count > max then
			count = max - max % chosen_recipe[item].output[item]
		end
		stack:set_count(count)
		table.insert(craftable_stacks, stack)
	end
	if alphabetize then
		table.sort(craftable_stacks, compare_stacks_by_desc)
	end
	return craftable_stacks
end

-- Returns true if the item name is an input for at least one
-- recipe belonging to the given craft type
crafting.is_possible_input = function(craft_type, item_name)
	local recipes = crafting.type[craft_type].recipes
	local item_def = minetest.registered_items[item_name]
	local groups = item_def.groups or {}
	for i = 1, #recipes do
		if recipes[i].input[item_name] then
			return true
		end
		-- TODO: this group check doesn't handle the dual-group flower/dye thing
		for group, _ in pairs(groups) do
			if recipes[i].input[group] then
				return true
			end
		end
	end
	return false
end

-- Returns true if the item is a possible output for at least
-- one recipe belonging to the given craft type
crafting.is_possible_output = function(craft_type, item_name)
	return crafting.type[craft_type].recipes_by_out[item_name] ~= nil
end

-- adds two count lists together, returns a new count list with the sum of the parameters' contents
crafting.count_list_add = function(list1, list2)
	local out_list = {}
	for item, count in pairs(list1) do
		out_list[item] = count
	end
	for item, count in pairs(list2) do
		if type(count) == "table" then
			-- item is actually a group name, it has a set of items associated with it.
			-- Perform a union with existing set.
			out_list[item] = out_list[item] or {}
			for group_item, _ in pairs(count) do
				out_list[item][group_item] = true
			end
		else
			out_list[item] = (out_list[item] or 0) + count
		end
	end
	return out_list
end

-- Attempts to add the items in count_list to the inventory.
-- Returns a count list containing the items that couldn't be added.
crafting.add_items = function(inv, listname, count_list)
	local leftover_list = {}

	for item, count in pairs(count_list) do
		local leftover = inv:add_item(listname, ItemStack({name=item, count=count}))
		if leftover:get_count() > 0 then
			leftover_list[leftover:get_name()] = leftover:get_count()
		end
	end
	return leftover_list
end

-- Attempts to add the items in count_list to the inventory.
-- If it succeeds, returns true.
-- If it fails, the inventory is not modified and returns false.
crafting.add_items_if_room = function(inv, listname, count_list)
	local old_list = inv:get_list(listname) -- record current inventory

	for item, count in pairs(count_list) do
		local leftover = inv:add_item(listname, ItemStack({name=item, count=count}))
		if leftover:get_count() > 0 then
			inv:set_list(listname, old_list) -- reset inventory
			return false
		end
	end
	return true
end

-- Returns true if there's room in the inventory for all of the items in the count list,
-- false otherwise.
crafting.room_for_items = function(inv, listname, count_list)
	local old_list = inv:get_list(listname) -- record current inventory

	for item, count in pairs(count_list) do
		local leftover = inv:add_item(listname, ItemStack({name=item, count=count}))
		if leftover:get_count() > 0 then
			inv:set_list(listname, old_list) -- reset inventory
			return false
		end
	end
	inv:set_list(listname, old_list) -- reset inventory
	return true
end

-- removes the items in the count_list (formatted as per recipe standards)
-- from the inventory. Returns true on success, false on failure. Does not
-- affect the inventory on failure (removal is atomic)
crafting.remove_items = function(inv, listname, count_list)
	local can_remove = true
	for item, count in pairs(count_list) do
		if not inv:contains_item(listname, ItemStack({name=item, count=count})) then
			can_remove = false
			break
		end
	end
	if can_remove then
		for item, count in pairs(count_list) do
			inv:remove_item(listname, ItemStack({name=item, count=count}))
		end
		return true
	end
	return false
end

-- Drops the contents of a count_list at the given location in the world
crafting.drop_items = function(pos, count_list)
	for item, count in pairs(count_list) do
		minetest.add_item(pos, ItemStack({name=item, count=count}))
	end
end

-- Returns a recipe with the inputs and outputs multiplied to match the requested
-- quantity of ouput items in the crafted stack. Note that the output could
-- actually be larger than crafted_stack if an exactly matching recipe can't be found.
-- returns nil if crafting is impossible with the given source inventory
crafting.get_crafting_result = function(crafting_type, input_list, request_stack)
	local input_count = itemlist_to_countlist(input_list)
	local request_name = request_stack:get_name()
	local request_count = request_stack:get_count()

	local recipes = crafting.type[crafting_type].recipes_by_out[request_name]
	local smallest_remainder = math.huge
	local smallest_remainder_output_count = 0
	local smallest_remainder_recipe = nil
	for i = 1, #recipes do
		local number, recipe = get_craft_count(input_count, recipes[i])
		if number > 0 then
			local output_count = recipe.output[request_name]
			if (request_count % output_count) <= smallest_remainder and output_count > smallest_remainder_output_count then
				smallest_remainder = request_count % output_count
				smallest_remainder_output_count = output_count
				smallest_remainder_recipe = recipe
			end
		end
	end

	if smallest_remainder_recipe then
		local multiple = math.ceil(request_count / smallest_remainder_recipe.output[request_name])
		for input_item, quantity in pairs(smallest_remainder_recipe.input) do
			smallest_remainder_recipe.input[input_item] = multiple * quantity
		end
		for output_item, quantity in pairs(smallest_remainder_recipe.output) do
			smallest_remainder_recipe.output[output_item] = multiple * quantity
		end
		for returned_item, quantity in pairs(smallest_remainder_recipe.returns) do
			smallest_remainder_recipe.returns[returned_item] = multiple * quantity
		end
		return smallest_remainder_recipe
	end
	return nil
end

----------------------------------------------------------------------------------------
-- Run-once code, post server initialization, that purges all uncraftable recipes from the
-- crafting system data.

local group_examples = {}

local function input_exists(input_item)
	if minetest.registered_items[input_item] then
		return true
	end

	if group_examples[input_item] then
		return true
	end

	if not string.match(input_item, ",") then
		return false
	end

	local target_groups = split(input_item, ",")

	for item, def in pairs(minetest.registered_items) do
		local overall_found = true
		for _, target_group in pairs(target_groups) do
			local one_group_found = false
			for group, _ in pairs(def.groups) do
				if group == target_group then
					one_group_found = true
					break
				end
			end
			if not one_group_found then
				overall_found = false
				break
			end
		end
		if overall_found then
			group_examples[input_item] = item
			return true
		end
	end
	return false
end

local function validate_inputs_and_outputs(recipe)
	for item, count in pairs(recipe.input) do
		if not input_exists(item) then
			return false
		end
	end
	if recipe.output then
		for item, count in pairs(recipe.output) do
			if not minetest.registered_items[item] then
				return false
			end
		end
	end
	if recipe.returns then
		for item, count in pairs(recipe.returns) do
			if not minetest.registered_items[item] then
				return false
			end
		end
	end
	return true
end

local purge_uncraftable_recipes = function()
	for item, def in pairs(minetest.registered_items) do
		for group, _ in pairs(def.groups) do
			group_examples[group] = item
		end
	end

	for craft_type, _  in pairs(crafting.type) do
		local i = 1
		local recs = crafting.type[craft_type].recipes
		while i <= #crafting.type[craft_type].recipes do
			if validate_inputs_and_outputs(recs[i]) then
				i = i + 1
			else
				minetest.log("info", "Uncraftable recipe purged from [crafting] mod:\n"..dump(recs[i]))
				table.remove(recs, i)
			end
		end
		for output, _ in pairs(crafting.type[craft_type].recipes_by_out) do
			i = 1
			local outs = crafting.type[craft_type].recipes_by_out[output]
			while i <= #outs do
				if validate_inputs_and_outputs(outs[i]) then
					i = i + 1
				else
					table.remove(outs, i)
				end
			end
		end
		for input, _ in pairs(crafting.type[craft_type].recipes_by_in) do
			i = 1
			local ins = crafting.type[craft_type].recipes_by_in[input]
			while i <= #ins do
				if validate_inputs_and_outputs(ins[i]) then
					i = i + 1
				else
					table.remove(ins, i)
				end
			end
		end
	end

	group_examples = nil -- don't need this any more.
end

minetest.after(0, purge_uncraftable_recipes)


text:
<?php

namespace LFSM\AdminBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class StatutType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('statutlib')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'LFSM\AdminBundle\Entity\Statut'
        ));
    }

    public function getName()
    {
        return 'lfsm_adminbundle_statuttype';
    }
}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using System;
using Microsoft.Azure.Management.StreamAnalytics.Models;

namespace Microsoft.Azure.Commands.StreamAnalytics.Models
{
    public class PSTransformation
    {
        private Transformation transformation;

        public PSTransformation()
        {
            transformation = new Transformation();
        }

        public PSTransformation(Transformation transformation)
        {
            if (transformation == null)
            {
                throw new ArgumentNullException("transformation");
            }

            this.transformation = transformation;
        }

        public string Name
        {
            get
            {
                return transformation.Name;
            }
            internal set
            {
                transformation.Name = value;
            }
        }

        public string JobName { get; set; }

        public string ResourceGroupName { get; set; }

        public TransformationProperties Properties
        {
            get
            {
                return transformation.Properties;
            }
            internal set
            {
                transformation.Properties = value;
            }
        }

        public string PropertiesInJson
        {
            get { return transformation.Properties.ToFormattedString(); }
        }
    }
}


text:
package org.commonjava.indy.core.expire;

import org.commonjava.indy.subsys.datafile.conf.DataFileConfiguration;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.File;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * Created by gli on 16-12-9.
 */
@Ignore("Obsolete")
public class LegacyQuartzDBMigrationActionTest
{
    @Rule
    public TemporaryFolder temp = new TemporaryFolder();

    private static final String INDY_HOME = "var/lib/indy";

    private DataFileConfiguration config;

    private LegacyQuartzDBMigrationAction action;

    private File data;

    @Before
    public void prepare()
            throws Exception
    {
        File file = temp.getRoot();
        data = new File( file, INDY_HOME + "/" + DataFileConfiguration.DEFAULT_DATA_SUBDIR );
        System.setProperty( "indy.home", file.getAbsolutePath() + "/" + INDY_HOME );
        data.mkdirs();
        new File( data, "scheduler.mv.db" ).createNewFile();
        new File( data, "scheduler.trace.db" ).createNewFile();
        new File( data, "content-index" ).mkdir();
        new File( data, "indy" ).mkdir();
        new File( data, "promote" ).mkdir();
        new File( data, "schedule.mv.db" ).createNewFile();
        config = new DataFileConfiguration();

        action = new LegacyQuartzDBMigrationAction( config );

    }

    @Test
    public void test()
            throws Exception
    {
        File dbMv = new File( data, "scheduler.mv.db" );
        File dbTrace = new File( data, "scheduler.mv.db" );
        File index = new File( data, "content-index" );
        File indy = new File( data, "indy" );
        File promote = new File( data, "promote" );
        File normal = new File( data, "schedule.mv.db" );
        assertTrue( dbMv.exists() );
        assertTrue( dbTrace.exists() );
        assertTrue( index.exists() );
        assertTrue( indy.exists() );
        assertTrue( promote.exists() );

        action.migrate();

        assertFalse( dbMv.exists() );
        assertFalse( dbTrace.exists() );
        assertTrue( index.exists() );
        assertTrue( indy.exists() );
        assertTrue( promote.exists() );
        assertTrue( normal.exists() );
    }
}