text:
require_relative 'spec_helper'

describe 'conserver::server' do
  before { allow_any_instance_of(Chef::Recipe).to receive(:search) }
  let(:runner) { ChefSpec::SoloRunner.new }
  let(:node) { runner.node }
  let(:chef_run) { runner.converge(described_recipe) }

  it 'installs ipmitool' do
    expect(chef_run).to include_recipe 'ipmitool'
  end

  it 'installs conserver::client' do
    expect(chef_run).to include_recipe 'conserver::client'
  end

  it 'installs package' do
    expect(chef_run).to upgrade_package 'conserver-server'
  end

  it 'starts service' do
    expect(chef_run).to start_service 'conserver-server'
  end

  it 'enables service' do
    expect(chef_run).to enable_service 'conserver-server'
  end

  context 'server.conf' do
    let(:file) { chef_run.template '/etc/conserver/server.conf' }

    it 'has proper owner' do
      expect(file.owner).to eq 'root'
      expect(file.group).to eq 'root'
    end

    it 'has proper modes' do
      expect(format('%o', file.mode)).to eq '644'
    end

    it 'has daemon opts' do
      expect(chef_run).to render_file(file.name)
        .with_content "OPTS='-p 3109 -M 127.0.0.1'"
    end

    it 'restarts conserver-server' do
      expect(file).to notify('service[conserver-server]').to(:restart)
    end
  end

  context '.ipmipass' do
    before { node.override['conserver']['ipmi']['password'] = 'password' }
    let(:file) { chef_run.file '/etc/conserver/.ipmipass' }

    it 'has proper owner' do
      expect(file.owner).to eq 'conservr'
      expect(file.group).to eq 'root'
    end

    it 'has proper modes' do
      expect(format('%o', file.mode)).to eq '600'
    end

    it 'has password' do
      expect(chef_run).to render_file(file.name)
        .with_content 'password'
    end
  end

  context 'conserver.passwd' do
    before do
      node.override['conserver']['access']['user'] = 'user'
      node.override['conserver']['access']['password'] = 'password'
    end
    let(:file) { chef_run.template '/etc/conserver/conserver.passwd' }

    it 'has proper owner' do
      expect(file.owner).to eq 'conservr'
      expect(file.group).to eq 'root'
    end

    it 'has proper modes' do
      expect(format('%o', file.mode)).to eq '600'
    end

    it 'has user:password' do
      expect(chef_run).to render_file(file.name)
        .with_content 'user:password'
    end

    it 'restarts conserver-server' do
      expect(file).to notify('service[conserver-server]').to(:restart)
    end
  end

  context 'conserver.passwd' do
    before do
      allow_any_instance_of(Chef::Recipe).to receive(:search)
        .with(:node, 'id:* AND chef_environment:_default AND ipmi:address')
        .and_return([
                      {
                        'hostname' => 'node1.example.com',
                        'ipmi' => {
                          'address' => '172.16.2.1'
                        }
                      },
                      {
                        'hostname' => 'node2.example.com',
                        'ipmi' => {
                          'address' => '172.16.2.2'
                        }
                      }
                    ])
    end
    let(:file) { chef_run.template '/etc/conserver/conserver.cf' }

    it 'has proper owner' do
      expect(file.owner).to eq 'root'
      expect(file.group).to eq 'root'
    end

    it 'has proper modes' do
      expect(format('%o', file.mode)).to eq '644'
    end

    it 'has logfile' do
      expect(chef_run).to render_file(file.name)
        .with_content 'logfile /var/log/conserver/&.log'
    end

    it 'has allowed' do
      expect(chef_run).to render_file(file.name)
        .with_content 'allowed 127.0.0.1'
    end

    it 'has console' do
      expect(chef_run).to render_file(file.name)
        .with_content 'console node1.example.com'
    end

    it 'has idletimeout' do
      expect(chef_run).to render_file(file.name)
        .with_content 'idletimeout 4h'
    end

    it 'has exec' do
      cmd  = 'exec /usr/bin/ipmitool '
      cmd += '-f /etc/conserver/.ipmipass '
      cmd += '-H 172.16.2.1 -U root -C 3 -I lanplus sol activate;'

      expect(chef_run).to render_file(file.name).with_content cmd
    end

    it 'restarts conserver-server' do
      expect(file).to notify('service[conserver-server]').to(:restart)
    end
  end
end


text:
#import <UIKit/UIKit.h>

@interface GestureControlViewController : UIViewController

@end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="what_arus_does">Interfejs użytkownika i PR</string>
    <string name="what_awerwa_does">Twórca serwera</string>
    <string name="what_temai_does">Grafik</string>

    <string name="arus_desc">Urodzony w 99 roku, interesuje się kreacją wizerunku i kontaktem z klientami. Za tworzenie interfejsu wziął się po długich namowach kolegów, którzy kazali żeby "wziął się wreszcie za jakąś robotę".</string>
    <string name="awerwa_desc">Twórca serwera</string>
    <string name="temai_desc">Urodzony w 95 roku pasjonat grafiki komputerowej, obecnie student. Wielokrotnie nagradzany za swoją cierpliwość do klientów, którzy oferowali "będzie mnie Pan miał do portfolio".  Złośliwie nazywany przez kolegów mistrzem performance'u, bo nie wypuścił spod swojej myszki dzieła, które nie zawierałoby literówek. Kocha swoje prace okraszać ciemnymi motywami do tego stopnia, że w pierwszej kolejności wykonuje zlecenia na nekrologi i epitafia. </string>
</resources>


text:
title: June 2012 Meetup Details Announced
author: joemccann
layout: post
permalink: /june-2012-meetup-details-announced/
categories:
  - posts
---
Coming in just on the heels of what is to be *the* JavaScript conference of the South, [TXJS][1], Austin JavaScript has brought another out-of-town guest speaker to the June 2012 meetup.

[Mikeal Rogers][2] is one of those developers who needs very little introduction.  Seriously.  He gave me no info to post about whom he is!  You may know him from his work at [Mozilla][3], on [CouchDB][4] and most recently [node][5] including one of the most widely used modules, [request][6].

Mikeal will be talking about node.  That's all he told me.  I foresee a rather bizarre presentation nonetheless.  Word is it may involve Japanese cuisine.

Of course we will followup all of this up with our wildly crowd-pleasing roundtable of JavaScript-related questions.  This is an open forum to present topics of discussion in a rapid-fire manner or simply heckle [@joemccann][7].

  * When: Tuesday, June 19th, 2012 from 7:30-9:00 PM.
  * Where: frog design – 101 West 6th Street – 2nd Floor
  * How: Parking is on the street, or you can take any number of buses to get downtown.
  * Drinks and awesome pizza from [Home Slice][8] will be provided.

Afterwards, the discussion carries on a few blocks away at [The Gingerman][9], where they have over 70 beers on tap.  **We may even have some free rounds of beer courtesy of our awesome sponsors**.

Any questions or suggestions, please feel free to contact Joe ([@joemccann][10]).  Also, be sure to follow us on Twitter: [@AustinJS][11].

 [1]: http://2012.texasjavascript.com
 [2]: http://twitter.com/mikeal
 [3]: http://mozilla.org
 [4]: http://couchdb.apache.org/
 [5]: http://nodejs.org
 [6]: https://github.com/mikeal/request
 [7]: http://twitter.com/joemccann
 [8]: http://www.homeslicepizza.com/
 [9]: http://gingermanpub.com/
 [10]: http://twitter.com/joemccann "Joe McCann on Twitter"
 [11]: http://twitter.com/austinjs "AustinJS on Twitter"


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using AutoMapper.Configuration;
using AutoMapper.XpressionMapper.Extensions;
using static System.Linq.Expressions.Expression;

namespace AutoMapper.Mappers
{
    public class ExpressionMapper : IObjectMapper
    {
        private static TDestination Map<TSource, TDestination>(TSource expression, ResolutionContext context)
            where TSource : LambdaExpression
            where TDestination : LambdaExpression => context.Mapper.MapExpression<TDestination>(expression);

        private static readonly MethodInfo MapMethodInfo = typeof(ExpressionMapper).GetDeclaredMethod(nameof(Map));

        public bool IsMatch(TypePair context) => typeof(LambdaExpression).IsAssignableFrom(context.SourceType)
                                                 && context.SourceType != typeof(LambdaExpression)
                                                 && typeof(LambdaExpression).IsAssignableFrom(context.DestinationType)
                                                 && context.DestinationType != typeof(LambdaExpression);

        public Expression MapExpression(IConfigurationProvider configurationProvider, ProfileMap profileMap, PropertyMap propertyMap, Expression sourceExpression, Expression destExpression, Expression contextExpression) =>
            Call(null,
                MapMethodInfo.MakeGenericMethod(sourceExpression.Type, destExpression.Type),
                sourceExpression,
                contextExpression);

        internal class MappingVisitor : ExpressionVisitor
        {
            private IList<Type> _destSubTypes = new Type[0];

            private readonly IConfigurationProvider _configurationProvider;
            private readonly TypeMap _typeMap;
            private readonly Expression _oldParam;
            private readonly Expression _newParam;
            private readonly MappingVisitor _parentMappingVisitor;

            public MappingVisitor(IConfigurationProvider configurationProvider, IList<Type> destSubTypes)
                : this(configurationProvider, null, Parameter(typeof(Nullable)), Parameter(typeof(Nullable)), null, destSubTypes)
            {
            }

            internal MappingVisitor(IConfigurationProvider configurationProvider, TypeMap typeMap, Expression oldParam, Expression newParam, MappingVisitor parentMappingVisitor = null, IList<Type> destSubTypes = null)
            {
                _configurationProvider = configurationProvider;
                _typeMap = typeMap;
                _oldParam = oldParam;
                _newParam = newParam;
                _parentMappingVisitor = parentMappingVisitor;
                if (destSubTypes != null)
                    _destSubTypes = destSubTypes;
            }

            protected override Expression VisitConstant(ConstantExpression node) => ReferenceEquals(node, _oldParam) ? _newParam : node;

            protected override Expression VisitParameter(ParameterExpression node) => ReferenceEquals(node, _oldParam) ? _newParam : node;

            protected override Expression VisitMethodCall(MethodCallExpression node) => base.VisitMethodCall(GetConvertedMethodCall(node));

            protected override Expression VisitExtension(Expression node) => (int)node.NodeType == 10000 ? node : base.VisitExtension(node);

            private MethodCallExpression GetConvertedMethodCall(MethodCallExpression node)
            {
                if (!node.Method.IsGenericMethod)
                    return node;
                var convertedArguments = Visit(node.Arguments);
                var convertedMethodArgumentTypes = node.Method.GetGenericArguments().Select(t => GetConvertingTypeIfExists(node.Arguments, t, convertedArguments)).ToArray();
                var convertedMethodCall = node.Method.GetGenericMethodDefinition().MakeGenericMethod(convertedMethodArgumentTypes);
                return Call(convertedMethodCall, convertedArguments);
            }

            private static Type GetConvertingTypeIfExists(IList<Expression> args, Type t, IList<Expression> arguments)
            {
                var matchingArgument = args.Where(a => !a.Type.IsGenericType()).FirstOrDefault(a => a.Type == t);
                if (matchingArgument != null)
                {
                    var index = args.IndexOf(matchingArgument);
                    return index < 0 ? t : arguments[index].Type;
                }

                var matchingEnumerableArgument = args.Where(a => a.Type.IsGenericType()).FirstOrDefault(a => a.Type.GetTypeInfo().GenericTypeArguments[0] == t);
                var index2 = args.IndexOf(matchingEnumerableArgument);
                return index2 < 0 ? t : arguments[index2].Type.GetTypeInfo().GenericTypeArguments[0];
            }

            protected override Expression VisitBinary(BinaryExpression node)
            {
                var newLeft = Visit(node.Left);
                var newRight = Visit(node.Right);

                if (newLeft.Type != newRight.Type && newRight.Type == typeof(string))
                    newLeft = Call(newLeft, typeof(object).GetDeclaredMethod("ToString"));
                if (newRight.Type != newLeft.Type && newLeft.Type == typeof(string))
                    newRight = Call(newRight, typeof(object).GetDeclaredMethod("ToString"));
                CheckNullableToNonNullableChanges(node.Left, node.Right, ref newLeft, ref newRight);
                CheckNullableToNonNullableChanges(node.Right, node.Left, ref newRight, ref newLeft);
                return MakeBinary(node.NodeType, newLeft, newRight);
            }

            private static void CheckNullableToNonNullableChanges(Expression left, Expression right, ref Expression newLeft, ref Expression newRight)
            {
                if (GoingFromNonNullableToNullable(left, newLeft))
                    if (BothAreNonNullable(right, newRight))
                        UpdateToNullableExpression(right, out newRight);
                    else if (BothAreNullable(right, newRight))
                        UpdateToNonNullableExpression(right, out newRight);

                if (GoingFromNonNullableToNullable(newLeft, left))
                    if (BothAreNonNullable(right, newRight))
                        UpdateToNullableExpression(right, out newRight);
                    else if (BothAreNullable(right, newRight))
                        UpdateToNonNullableExpression(right, out newRight);
            }

            private static void UpdateToNullableExpression(Expression right, out Expression newRight)
            {
                newRight = right is ConstantExpression expression
                    ? Constant(expression.Value,
                        typeof(Nullable<>).MakeGenericType(right.Type))
                    : throw new AutoMapperMappingException(
                        "Mapping a BinaryExpression where one side is nullable and the other isn't");
            }

            private static void UpdateToNonNullableExpression(Expression right, out Expression newRight)
            {
                if (right is ConstantExpression expression)
                {
                    var t = right.Type.IsNullableType()
                        ? right.Type.GetGenericArguments()[0]
                        : right.Type;
                    newRight = Constant(expression.Value, t);
                }
                else if (right is UnaryExpression)
                    newRight = ((UnaryExpression) right).Operand;
                else
                    throw new AutoMapperMappingException(
                        "Mapping a BinaryExpression where one side is nullable and the other isn't");
            }

            private static bool GoingFromNonNullableToNullable(Expression node, Expression newLeft)
                => !node.Type.IsNullableType() && newLeft.Type.IsNullableType();

            private static bool BothAreNullable(Expression node, Expression newLeft)
                => node.Type.IsNullableType() && newLeft.Type.IsNullableType();

            private static bool BothAreNonNullable(Expression node, Expression newLeft)
                => !node.Type.IsNullableType() && !newLeft.Type.IsNullableType();

            protected override Expression VisitLambda<T>(Expression<T> expression)
            {
                return expression.Parameters.Any(b => b.Type == _oldParam.Type)
                    ? VisitLambdaExpression(expression)
                    : VisitAllParametersExpression(expression);
            }

            private Expression VisitLambdaExpression<T>(Expression<T> expression)
            {
                var convertedBody = Visit(expression.Body);
                var convertedArguments = expression.Parameters.Select(e => Visit(e) as ParameterExpression).ToList();
                return Lambda(convertedBody, convertedArguments);
            }

            private Expression VisitAllParametersExpression<T>(Expression<T> expression)
            {
                var visitors = (
                    from t in expression.Parameters
                    let sourceParamType = t.Type
                    from destParamType in _destSubTypes.Where(dt => dt != sourceParamType)
                    let a = destParamType.IsGenericType() ? destParamType.GetTypeInfo().GenericTypeArguments[0] : destParamType
                    let typeMap = _configurationProvider.ResolveTypeMap(a, sourceParamType)
                    where typeMap != null
                    let oldParam = t
                    let newParam = Parameter(a, oldParam.Name)
                    select new MappingVisitor(_configurationProvider, typeMap, oldParam, newParam, this))
                    .Cast<ExpressionVisitor>()
                    .ToList();

                return visitors.Aggregate(expression as Expression, (e, v) => v.Visit(e));
            }

            protected override Expression VisitMember(MemberExpression node)
            {
                if (node == _oldParam)
                    return _newParam;
                var propertyMap = PropertyMap(node);

                if (propertyMap == null)
                {
                    if (node.Expression is MemberExpression)
                        return GetConvertedSubMemberCall(node);
                    return node;
                }

                var constantVisitor = new IsConstantExpressionVisitor();
                constantVisitor.Visit(node);
                if (constantVisitor.IsConstant)
                    return node;

                SetSorceSubTypes(propertyMap);

                var replacedExpression = Visit(node.Expression);
                if (replacedExpression == node.Expression)
                    replacedExpression = _parentMappingVisitor.Visit(node.Expression);

                if (propertyMap.CustomExpression != null)
                    return propertyMap.CustomExpression.ReplaceParameters(replacedExpression);

                Func<Expression, MemberInfo, Expression> getExpression = MakeMemberAccess;

                return propertyMap.SourceMembers
                    .Aggregate(replacedExpression, getExpression);
            }

            private class IsConstantExpressionVisitor : ExpressionVisitor
            {
                public bool IsConstant { get; private set; }

                protected override Expression VisitConstant(ConstantExpression node)
                {
                    IsConstant = true;

                    return base.VisitConstant(node);
                }
            }

            private Expression GetConvertedSubMemberCall(MemberExpression node)
            {
                var baseExpression = Visit(node.Expression);
                var propertyMap = FindPropertyMapOfExpression(node.Expression as MemberExpression);
                if (propertyMap == null)
                    return node;
                var sourceType = propertyMap.SourceMember.GetMemberType();
                var destType = propertyMap.DestinationPropertyType;
                if (sourceType == destType)
                    return MakeMemberAccess(baseExpression, node.Member);
                var typeMap = _configurationProvider.ResolveTypeMap(sourceType, destType);
                var subVisitor = new MappingVisitor(_configurationProvider, typeMap, node.Expression, baseExpression, this);
                var newExpression = subVisitor.Visit(node);
                _destSubTypes = _destSubTypes.Concat(subVisitor._destSubTypes).ToArray();
                return newExpression;
            }

            private PropertyMap FindPropertyMapOfExpression(MemberExpression expression)
            {
                var propertyMap = PropertyMap(expression);
                return propertyMap == null && expression.Expression is MemberExpression
                    ? FindPropertyMapOfExpression((MemberExpression) expression.Expression)
                    : propertyMap;
            }

            private PropertyMap PropertyMap(MemberExpression node)
                => _typeMap == null
                    ? null
                    : (node.Member.IsStatic()
                        ? null
                        : (!node.Member.DeclaringType.IsAssignableFrom(_typeMap.DestinationType)
                            ? null
                            : _typeMap.GetExistingPropertyMapFor(node.Member)));

            private void SetSorceSubTypes(PropertyMap propertyMap)
            {
                if (propertyMap.SourceMember is PropertyInfo info)
                    _destSubTypes = info.PropertyType.GetTypeInfo().GenericTypeArguments.Concat(new[] { info.PropertyType }).ToList();
                else if (propertyMap.SourceMember is FieldInfo fInfo)
                    _destSubTypes = fInfo.FieldType.GetTypeInfo().GenericTypeArguments;
            }
        }
    }
}


text:
Meteor.startup(function () {
  FastClick.attach(document.body);

  App = {
    subs: {
      feed: Meteor.subscribe('feed'),
      members: Meteor.subscribe('members'),
      userData: Meteor.subscribe('userData')
    }
  }

  enquire.register("screen and (max-width:768px)", {
      match: function() {
        $('body').addClass('mobile');
        snapper.settings({maxPosition: 266});
        snapper.close();
      },

      unmatch: function() {
        $('body').removeClass('mobile');
        snapper.settings({maxPosition: 206});
      }
  })
  .register("screen and (min-width:769px) and (max-width:998px)", {
      match: function() {
        $('body').addClass('tablet');
      },

      unmatch: function() {
        $('body').removeClass('tablet');
      }
  })
  .register("screen and (min-width:999px)", {
      match: function() {
        $('body').addClass('computer');
      },

      unmatch: function() {
        $('body').removeClass('computer');
      }
  })
  .register("screen and (orientation:portrait)", {
      match: function() {
        $('body').addClass('portrait');
      },

      unmatch: function() {
        $('body').removeClass('portrait')
        .scrollLeft(0);
        console.log('leaving portrait')
      }
  })
  .register("screen and (orientation:landscape)", {
      match: function() {
        $('body').addClass('landscape');
      },

      unmatch: function() {
        $('body').removeClass('landscape')
        .scrollLeft(0);
        console.log('leaving landscape')
      }
  });
});


text:
require File.join(File.dirname(__FILE__), "/../../../../spec_helper")

describe "admin/tasks/ant/new.html.erb" do
  include GoUtil, TaskMother, FormUI
  include Admin::TaskHelper

  before :each do
    assigns[:cruise_config] = config = CruiseConfig.new
    set(config, "md5", "abcd1234")
    assigns[:on_cancel_task_vms] = @vms =  java.util.Arrays.asList([vm_for(exec_task('rm')), vm_for(ant_task), vm_for(nant_task), vm_for(rake_task), vm_for(fetch_task)].to_java(TaskViewModel))
    template.stub(:admin_task_create_path).and_return("task_create_path")
    template.stub(:admin_task_update_path).and_return("task_update_path")
  end

  it "should render a simple ant task for new" do
    task = AntTask.new
    assigns[:task] = task
    assigns[:task_view_model] = Spring.bean("taskViewService").getViewModel(task, 'new')

    render "/admin/tasks/plugin/new"

    response.body.should have_tag("form[action=?]", "task_create_path") do
      with_tag("div.fieldset") do
        with_tag("label", "Build file")
        with_tag("input[name='task[buildFile]']")
        with_tag("label", "Target")
        with_tag("input[name='task[target]']")
        with_tag("label", "Working directory")
        with_tag("input[name='task[workingDirectory]']")
      end
    end
  end

  it "should render a simple ant task for edit" do
    task = AntTask.new
    task.setBuildFile("build.xml")
    task.setWorkingDirectory("blah/foo-bar")
    task.setTarget("compile test and just deploy")
    assigns[:task] = task
    assigns[:task_view_model] = Spring.bean("taskViewService").getViewModel(task, 'edit')

    render "/admin/tasks/plugin/edit"
    response.body.should have_tag("form[action=?]", "task_update_path") do
      with_tag("div.fieldset") do
        with_tag("label", "Build file")
        with_tag("input[name='task[buildFile]'][value=?]", task.getBuildFile())
        with_tag("label", "Target")
        with_tag("input[name='task[target]'][value=?]", task.getTarget())
        with_tag("label", "Working directory")
        with_tag("input[name='task[workingDirectory]'][value=?]", task.workingDirectory())
      end
    end
  end

  it "should render error messages if errors are present on the config" do
    task = ant_task
    task.addError(com.thoughtworks.go.config.BuildTask::WORKING_DIRECTORY, "working directory error")
    assigns[:task] = task
    assigns[:task_view_model] = Spring.bean("taskViewService").getViewModel(task, 'edit')

    render "/admin/tasks/plugin/edit"
    response.body.should have_tag("form[action=?]", "task_update_path") do
      with_tag("div.fieldset") do
        with_tag("label", "Build file")
        with_tag("input[name='task[buildFile]'][value=?]", task.getBuildFile())
        with_tag("label", "Target")
        with_tag("input[name='task[target]'][value=?]", task.getTarget())
        with_tag("label", "Working directory")
        with_tag("input[name='task[workingDirectory]'][value=?]", task.workingDirectory())
        with_tag("div.fieldWithErrors input[type='text'][name='task[workingDirectory]']")
        with_tag("div.form_error", "working directory error")
      end
    end
  end

  it "should unhide on cancel ant task for edit" do
    task = AntTask.new
    task.setBuildFile("build.xml")
    task.setWorkingDirectory("blah/foo-bar")
    task.setTarget("compile test and just deploy")
    task.setCancelTask(ant_task())
    assigns[:task] = task
    assigns[:task_view_model] = Spring.bean("taskViewService").getViewModel(task, 'edit')

    render "/admin/tasks/plugin/edit"
    response.body.should have_tag("form[action=?]", "task_update_path") do
      with_tag("option[selected='selected'][value=?]", "ant")
    end
  end
end


text:
<?php

/**
 * Base html block
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Core_Block_Text_Tag extends Mage_Core_Block_Text
{

    protected function _construct()
    {
        parent::_construct();
        $this->setTagParams(array());
    }

    function setTagParam($param, $value=null)
    {
        if (is_array($param) && is_null($value)) {
            foreach ($param as $k=>$v) {
                $this->setTagParam($k, $v);
            }
        } else {
            $params = $this->getTagParams();
            $params[$param] = $value;
            $this->setTagParams($params);
        }
        return $this;
    }

    function setContents($text)
    {
        $this->setTagContents($text);
        return $this;
    }

    protected function _toHtml()
    {
        $this->setText('<'.$this->getTagName().' ');
        if ($this->getTagParams()) {
            foreach ($this->getTagParams() as $k=>$v) {
                $this->addText($k.'="'.$v.'" ');
            }
        }

        $this->addText('>'.$this->getTagContents().'</'.$this->getTagName().'>'."\r\n");
        return parent::_toHtml();
    }

}


text:
package com.krazy.kcfw.modules.cms.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.krazy.kcfw.common.persistence.Page;
import com.krazy.kcfw.common.utils.StringUtils;
import com.krazy.kcfw.common.web.BaseController;
import com.krazy.kcfw.modules.cms.entity.Guestbook;
import com.krazy.kcfw.modules.cms.service.GuestbookService;
import com.krazy.kcfw.modules.sys.utils.DictUtils;
import com.krazy.kcfw.modules.sys.utils.UserUtils;

/**
 * 留言Controller
 * @author krazy
 * @version 2013-3-23
 */
@Controller
@RequestMapping(value = "${adminPath}/cms/guestbook")
public class GuestbookController extends BaseController {

	@Autowired
	private GuestbookService guestbookService;

	@ModelAttribute
	public Guestbook get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return guestbookService.get(id);
		}else{
			return new Guestbook();
		}
	}

	@RequiresPermissions("cms:guestbook:view")
	@RequestMapping(value = {"list", ""})
	public String list(Guestbook guestbook, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<Guestbook> page = guestbookService.findPage(new Page<Guestbook>(request, response), guestbook);
        model.addAttribute("page", page);
		return "modules/cms/guestbookList";
	}

	@RequiresPermissions("cms:guestbook:view")
	@RequestMapping(value = "form")
	public String form(Guestbook guestbook, Model model) {
		model.addAttribute("guestbook", guestbook);
		return "modules/cms/guestbookForm";
	}

	@RequiresPermissions("cms:guestbook:edit")
	@RequestMapping(value = "save")
	public String save(Guestbook guestbook, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, guestbook)){
			return form(guestbook, model);
		}
		if (guestbook.getReUser() == null){
			guestbook.setReUser(UserUtils.getUser());
			guestbook.setReDate(new Date());
		}
		guestbookService.save(guestbook);
		addMessage(redirectAttributes, DictUtils.getDictLabel(guestbook.getDelFlag(), "cms_del_flag", "保存")
				+"留言'" + guestbook.getName() + "'成功");
		return "redirect:" + adminPath + "/cms/guestbook/?repage&status=2";
	}

	@RequiresPermissions("cms:guestbook:edit")
	@RequestMapping(value = "delete")
	public String delete(Guestbook guestbook, @RequestParam(required=false) Boolean isRe, RedirectAttributes redirectAttributes) {
		guestbookService.delete(guestbook, isRe);
		addMessage(redirectAttributes, (isRe!=null&&isRe?"恢复审核":"删除")+"留言成功");
		return "redirect:" + adminPath + "/cms/guestbook/?repage&status=2";
	}

}


text:
import angular from 'angular';
import EpisodeListComponent from './episodeList.component'

const episodeList = angular
    .module('episodeList', [])
    .component('episodeList', EpisodeListComponent)
    .name;

export default episodeList;


text:
<TITLE>Review for 8MM (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

8MM (1999)

reviewed by
Ulrich.Schreglmann

Review: 8MM  (Spoilers)

"Tell me," the sidekick from inside the porn scene asks the hero played by
Nicholas Cage after they've watched a couple of really UGLY movies together
in the line of duty, "were you turned on by these?"  "No.  No I wasn't,"
Cage replies.  "But you weren't exactly turned off, either, were you?
Devil's changing you already."

It is hard to believe he wasn't turned off.  I was.  Big time.  Even
literally turned away.  Whenever the films in film became too ghastly to
look at they probably wouldn't show them on the big screen anyway, but I
wasn't going to chance it.  And I'm certainly not going to go into that
flick a second time to find out.  In a way the movie was so horrible because
we don't see the violence but Cage's reaction to whatever it supposedly is
he's seeing, and his face distorted in disgust may have been a lot more
effective than anything we could have witnessed ourselves.  Inspiring so
much confidence, Cage is unbelievably good at conveying any emotion to the
viewer with just a few facial muscles.

That movie was extreme for something in or close to mainstream--so extreme
in fact it's actually slipping beyond the threshold of the plausible.
That's mainly because it's in its moodiness so revolting it actually FORCES
you to take a step back and think about what you're seeing.

And WHEN you think about it you can't help pondering that this is a little
TOO dirty for actual underground porn scene.  Not "dirty" as in "Naughty,
naughty!" but dirty as in literally expecting the rats and the cockroaches
to crawl out of the linoleum there.  While parts of the world may actually
look like that the fact that you see nothing but this level for what seems
to be well over two hours makes it appear more like the world through the
eyes of a vigilante idealist guardian of mores gone gaga.

Many of the elements are classic film noir--decent professional private
investigator with clientele among the high and the mighty and the filthy
rich is hired by an industry magnate's widow to find out whether her
powerful and revered late husband was actually a monster under his facade
of, well, intimidating callous high-roller.  Of course he was, it turns out.
And of course his lawyer, who looks like Geraldo Rivera, was knowingly
devil's advocate.  When would they ever turn out not to be.

Just like the average movie shows you only the beautiful vistas of town this
movie specializes in the ugly, shot through shutter a little too dark with
filters letting mainly cold colors pass, to make you especially depressed.
Bleah!  In fact the whole movie is literally so dark throughout that when at
but one instant there is a sweeping vista of L.A. basking in midday sunlight
hitting your eyes without warning you're actually blinded for a moment.

Cage's detective is a decent boy, Phillip Marlowe type, though happily
married with child--the idealist family values aspect.  He's being called to
investigate whether a so-called "snuff movie" found in the aforementioned
late industry czar's personal vault--an S&M porn movie in which the victim
is actually being killed--is real or fake.  His widow would like to know
whether the man she loved for most of her life was merely a forgivable
pervert or an actual monstrous menace to society.

In the course of his investigations Cage, P.I. descends into an exaggerated
world of evil and ugliness your run-of-the-mill idealist seems to be
fascinated by.  As for me, after an agonizing couple of minutes my disbelief
just snapped in two from too much suspension.  We see rows of shelves where
kiddie porn photos are being sold and duly have your "Ugh!"-button pushed
but can't help noticing that the place looks SO much like you ought to put a
torch to it--not because of what is available there but because of what the
place looks like anyway--that you go straight through revulsion and out the
other end.

He finds the people who did the movie and hires them with his client's money
in order to find out who they are and to expose them.  Alas, they're on to
him, because the decent old lady's late husband's attourney turns out to
have been in on the making of the movie and to have warned the other bad
guys.  Apparently--in good old noir tradition--he never expected our dutiful
young investigator to get this far in the first place and is now in the act
of damage containment.  This is when the film changes from
bottom-of-an-inkwell depressiveness to an actual suspenseful thriller for
just a few minutes, when action is required of our hero to survive, only to
then descend into a "lone avenger" bit leaving me strangely cold; but that's
possibly just me.

If this review sounds overly negative I'm not sure whether that is what I've
intended to convey.  The movie is a bitter, bitter, bitter pill, but it's
meant to be.  If you can stomach it it's certainly worth watching once.
There are even two or three scenes deliberately hilariously funny, like the
scene where the porn paraphernalia sales dude is seen reading some schmaltzy
novel under the cover of erotic literature in order not to "embarrass
yourself in front of your fellow perverts," or when he tells a guy,
mercifully off-screen, that "this place is like a gas station.  You pay
before you pump."  (There was also some rather shameless product placement
in that flick.  Now I want me one of'em battery operated vaginas!  Just
kidding.)

On a final note I can only say that if I'm naive and that flick was actually
a REALISITC depicition of the underground porn scene I prefer to remain
naive and ignorant, thankyouverymuch!  ("Whataworldwhataworldwhataworld..."
*Mutter, mutter, mutter!*)

(C)OOL mcmxcix
"There's nothing good--unless you do't."  (Erich Kästner)

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

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

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

Broken URLs inthe reviews are the responsibility of the author.

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

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


text:
package com.asakusafw.lang.compiler.analyzer.util;

import static com.asakusafw.lang.compiler.model.description.Descriptions.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.junit.Test;

import com.asakusafw.lang.compiler.model.graph.CoreOperator;
import com.asakusafw.lang.compiler.model.graph.CoreOperator.CoreOperatorKind;
import com.asakusafw.lang.compiler.model.graph.UserOperator;
import com.asakusafw.lang.compiler.model.testing.OperatorExtractor;
import com.asakusafw.vocabulary.operator.MasterBranch;
import com.asakusafw.vocabulary.operator.MasterCheck;
import com.asakusafw.vocabulary.operator.MasterJoin;
import com.asakusafw.vocabulary.operator.MasterJoinUpdate;
import com.asakusafw.vocabulary.operator.MasterSelection;
import com.asakusafw.vocabulary.operator.Update;

/**
 * Test for {@link MasterJoinOperatorUtil}.
 */
public class MasterJoinOperatorUtilTest {

    private final ClassLoader cl = getClass().getClassLoader();

    /**
     * simple case.
     * @throws Exception if failed
     */
    @Test
    public void simple() throws Exception {
        UserOperator operator = extract(MasterJoin.class, Simple.class, "m0");
        assertThat(MasterJoinOperatorUtil.isSupported(operator), is(true));
        assertThat(MasterJoinOperatorUtil.getSelection(cl, operator), is(nullValue()));
    }

    /**
     * check supports.
     * @throws Exception if failed
     */
    @Test
    public void support() throws Exception {
        UserOperator m0 = extract(MasterJoin.class, Support.class, "m0");
        UserOperator m1 = extract(MasterCheck.class, Support.class, "m1");
        UserOperator m2 = extract(MasterBranch.class, Support.class, "m2");
        UserOperator m3 = extract(MasterJoinUpdate.class, Support.class, "m3");
        UserOperator m4 = extract(Update.class, Support.class, "m4");
        CoreOperator m5 = CoreOperator.builder(CoreOperatorKind.CHECKPOINT)
                .input("in", typeOf(String.class))
                .output("out", typeOf(String.class))
                .build();

        assertThat(MasterJoinOperatorUtil.isSupported(m0), is(true));
        assertThat(MasterJoinOperatorUtil.isSupported(m1), is(true));
        assertThat(MasterJoinOperatorUtil.isSupported(m2), is(true));
        assertThat(MasterJoinOperatorUtil.isSupported(m3), is(true));
        assertThat(MasterJoinOperatorUtil.isSupported(m4), is(false));
        assertThat(MasterJoinOperatorUtil.isSupported(m5), is(false));
    }

    /**
     * w/ selection.
     * @throws Exception if failed
     */
    @Test
    public void with_selection() throws Exception {
        UserOperator m0 = extract(MasterJoin.class, WithSelection.class, "m0");
        UserOperator m1 = extract(MasterJoin.class, WithSelection.class, "m1");
        UserOperator m2 = extract(MasterJoin.class, WithSelection.class, "m2");
        UserOperator m3 = extract(MasterJoin.class, WithSelection.class, "m3");

        Method s0 = MasterJoinOperatorUtil.getSelection(cl, m0);
        assertThat(s0, is(nullValue()));

        Method s1 = MasterJoinOperatorUtil.getSelection(cl, m1);
        assertThat(s1, is(notNullValue()));
        assertThat(s1.getDeclaringClass(), is((Object) WithSelection.class));
        assertThat(s1.getName(), is("s1"));

        try {
            MasterJoinOperatorUtil.getSelection(cl, m2);
            fail();
        } catch (ReflectiveOperationException e) {
            // ok.
        }

        try {
            MasterJoinOperatorUtil.getSelection(cl, m3);
            fail();
        } catch (ReflectiveOperationException e) {
            // ok.
        }
    }

    /**
     * unsupported operator.
     * @throws Exception if failed
     */
    @Test(expected = RuntimeException.class)
    public void invalid_unsupported() throws Exception {
        MasterJoinOperatorUtil.getSelection(cl, CoreOperator.builder(CoreOperatorKind.CHECKPOINT)
                .input("in", typeOf(String.class))
                .output("out", typeOf(String.class))
                .build());
    }

    private UserOperator extract(
            Class<? extends Annotation> annotationType,
            Class<?> operatorClass,
            String methodName) {
        return OperatorExtractor.extract(annotationType, operatorClass, methodName)
                .input("mst", typeOf(String.class))
                .input("tx", typeOf(String.class))
                .output("joined", typeOf(String.class))
                .output("missed", typeOf(String.class))
                .build();
    }

    @SuppressWarnings("javadoc")
    public static abstract class Simple {

        @MasterJoin
        public abstract void m0();
    }

    @SuppressWarnings("javadoc")
    public static abstract class Support {

        @MasterJoin
        public abstract void m0();

        @MasterCheck
        public abstract void m1();

        @MasterBranch
        public abstract void m2();

        @MasterJoinUpdate
        public abstract void m3();

        @Update
        public abstract void m4();
    }

    @SuppressWarnings("javadoc")
    public static abstract class WithSelection {

        @MasterJoin()
        public abstract void m0();

        @MasterJoin(selection = "s1")
        public abstract void m1();

        @MasterJoin(selection = "s2")
        public abstract void m2();

        @MasterJoin(selection = "s3")
        public abstract void m3();

        @MasterSelection
        public abstract void s1();

        public abstract void s2();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using BlueSheep.Common.Protocol.Types;
using BlueSheep.Common.IO;
using BlueSheep.Engine.Types;

namespace BlueSheep.Common.Protocol.Messages
{
    public class EmotePlayAbstractMessage : Message
    {
        public new const uint ID =5690;
        public override uint ProtocolID
        {
            get { return ID; }
        }

        public byte emoteId;
        public double emoteStartTime;

        public EmotePlayAbstractMessage()
        {
        }

        public EmotePlayAbstractMessage(byte emoteId, double emoteStartTime)
        {
            this.emoteId = emoteId;
            this.emoteStartTime = emoteStartTime;
        }

        public override void Serialize(BigEndianWriter writer)
        {
            writer.WriteByte(emoteId);
            writer.WriteDouble(emoteStartTime);
        }

        public override void Deserialize(BigEndianReader reader)
        {
            emoteId = reader.ReadByte();
            if (emoteId < 0 || emoteId > 255)
                throw new Exception("Forbidden value on emoteId = " + emoteId + ", it doesn't respect the following condition : emoteId < 0 || emoteId > 255");
            emoteStartTime = reader.ReadDouble();
            if (emoteStartTime < -9.007199254740992E15 || emoteStartTime > 9.007199254740992E15)
                throw new Exception("Forbidden value on emoteStartTime = " + emoteStartTime + ", it doesn't respect the following condition : emoteStartTime < -9.007199254740992E15 || emoteStartTime > 9.007199254740992E15");
        }

    }

}


text:
Anonymize a field using by replacing values with a consistent HMAC function.

## Anonymize Options
| Name | Required | Default | Description |
|------|----------|---------|-------------|
|`field`|yes|-|The field to anonymize. The field in the document can be a string or an array.|
|`target_field`|no|`field`|The field to assign the anonymize value to. If not defined `field` will be overwritten.|
|`key`|no|supersecrethere|The key value used for the `HMAC`.|
|`method`|no|HmacSHA1|`HMAC` algorithm to use. See [here](https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#Mac) for a complete list.|
|`ignore_missing`|no|true|If `true` and `field` does not exist, the processor quietly exits without modifying the document|

## Usage

```
PUT _ingest/pipeline/anonymize-pipeline
{
  "description": "A pipeline to do whatever",
  "processors": [
    {
      "anonymize" : {
        "field"          : "my_field",
        "target_field"   : "hash",
        "key"            : "testkey",
        "method"         : "HmacSHA256",
        "ignore_missing" : true
      }
    }
  ]
}

PUT /my-index/_doc/1?pipeline=anonymize-pipeline
{
  "my_field" : ["my_value1", "my_value2","my_value3"]
}

GET /my-index/_doc/1
{
  "_index": "my-index",
  "_type": "_doc",
  "_id": "1",
  "_version": 1,
  "found": true,
  "_source": {
    "my_field": [
      "my_value1",
      "my_value2",
      "my_value3"
    ],
    "hash": [
      "a4b12fddb3fd1389dec57010bd7b8c68c0f613d07115b8a5b1fd166a981c93fa",
      "a9b22cef4d3cbd2dbb80f6209faa637d7d7ef96dbeb06bf10fac47eb23813859",
      "33510269cdd2ac8b819a85cc12cbd1a7948fa5abf695944c0250488334d2ce61"
    ]
  }
}

PUT _ingest/pipeline/anonymize-pipeline
{
  "description": "A pipeline to do whatever",
  "processors": [
    {
      "anonymize" : {
        "field" : "my_field"
      }
    }
  ]
}

PUT /my-index/_doc/2?pipeline=anonymize-pipeline
{
  "my_field" : "Some content"
}

GET /my-index/_doc/2
{
  "_index": "my-index",
  "_type": "_doc",
  "_id": "2",
  "_version": 1,
  "found": true,
  "_source": {
    "my_field": "5e7dc9df6c9bd2503167c70afbf1b52cb8a1c095",
  }
}
```

## Configuration
No configuration required.

## Setup
Remember to set the `elasticsearchVersion` parameter in your `gradle.properties` file.

First you need to create a zip distribution by running:

```bash
gradle clean check
```
This will produce a zip file in `build/distributions`.

After building the zip file, you can install it:

```bash
bin/elasticsearch-plugin install file:///path/to/ingest-anonymize/build/distribution/ingest-anonymize-x.y.z.zip
```

## Java
Starting from `elasticsearch 7.x`, developers must use Java 14.

## Bugs & TODO

* There are always bugs
* and todos...

## Acknowledgements
Thanks to [Alexander Reelsen](https://github.com/spinscale) for the project
https://github.com/spinscale/cookiecutter-elasticsearch-ingest-processor.


text:
#pragma once

#include <iostream>

#include <boost/mpl/bool.hpp>
#include <boost/numeric/mtl/utility/is_distributed.hpp>

#include "Timer.hpp"
#include "solver/MatrixStreams.hpp"

#ifdef HAVE_PARALLEL_MTL4
#include <boost/numeric/mtl/par/distribution.hpp>
#endif

namespace AMDiS
{

  namespace tag
  {
    struct distributed {};
    struct non_distributed {};
  }

  namespace traits
  {
    template<class T>
    struct distributed_tag : boost::mpl::if_<
      mtl::traits::is_distributed<T>,
      tag::distributed,
      tag::non_distributed
      > {};
  }

  namespace dispatch
  {
    /// init matrix
    template<typename MatrixOut, typename M>
    void initMatrix(MatrixOut& /*m*/, MapperBase<M>& /*mapper*/) {}

    /// init vector
    template<typename VectorOut, typename MatrixT>
    void initVector(VectorOut& /*v*/, const MatrixT& /*source*/) {}

    /// init systemmatrix depending on Mapper parameters.
    template<typename M>
    void initMatrix(MTLTypes::MTLMatrix& m, MapperBase<M>& mapper)
    {
      m.change_dim(mapper.getNumRows(), mapper.getNumCols());
      set_to_zero(m);
    }

    template<typename MatrixOut, typename MatrixIn, typename M>
    void fillMatrix(MatrixOut& m, const MatrixIn& source, MapperBase<M>& mapper)
    {
      MatMap<const MatrixIn, M> matMap{source, mapper.self()};
      m << matMap;
    }

#ifdef HAVE_PARALLEL_MTL4
    /// init systemmatrix depending on Mapper parameters,
    /// specialized for distributed matrices
    template<typename M>
    void initMatrix(MTLTypes::PMTLMatrix& m, MapperBase<M>& mapper)
    {
      mtl::par::block_distribution dist(mapper.getNumRows());
      dist.setup_from_local_size(mapper.getMap().getLocalDofs());
      m.change_dim(0, 0);
      m.init_distribution(dist, dist, mapper.getNumRows(), mapper.getNumRows());
      set_to_zero(m);
    }

    /// init MTL-vector depending on Mapper parameters,
    /// specialized for distributed matrices
    template<typename MatrixT>
    void initVector(MTLTypes::PMTLVector& v, const MatrixT& matrix)
    {
      v.init_distribution(row_distribution(matrix), num_rows(matrix));
      set_to_zero(v);
    }
#endif

    /// init MTL-vector depending on Mapper parameters.
    template<typename MatrixT>
    void initVector(MTLTypes::MTLVector& v, const MatrixT& matrix)
    {
      v.change_dim(num_rows(matrix));
      set_to_zero(v);
    }

    /// fill MTL-vector
    template<typename VectorOut, typename VectorIn, typename M>
    void fillVector(VectorOut& v, const VectorIn& source, MapperBase<M>& mapper)
    {
      VecMap<const VectorIn, M> srcVecMap{source, mapper.self()};
      v << srcVecMap;
    }

  } // end namespace dispatch
} // end namespace AMDiS


text:
'use strict';

/**
 * display has an optional output port
 */

module.exports = function display() {
  var inport = this.openInputPort('IN');
  var outport = this.openOutputPort('OUT', 'OPTIONAL');
  while (true) {
    var ip = inport.receive();
    if (ip === null) {
      break;
    }
    var data = ip.contents;
    if (ip.type == this.IPTypes.OPEN)
      console.log('OPEN: ' + data);
    else if (ip.type == this.IPTypes.CLOSE)
      console.log('CLOSE: ' + data);
    else
      console.log('data: ' + data);
    outport.send(ip);
  }
};


text:
ActiveRecord::Base.connection.execute("DROP TABLE IF EXISTS 'cases'")
ActiveRecord::Base.connection.create_table(:cases) do |t|
  t.string :name
end

class Case < ActiveRecord::Base
  include SettingCrazy
  use_setting_template ExampleTemplate
  has_many :notes
end


text:
use strict;
use warnings;
use Getopt::Std;
our ($opt_f);
my ($line);
getopt('f:n:c:');
die "Please enter a file to process using -f <filename>\n" unless (defined $opt_f);
die "Unable to open input file " unless (open my $infile, "<", $opt_f);
die "Unable to open output file " unless (open my $oufile, ">", $opt_f . ".out");
while (<$infile>) {
    chomp;
    $line = $_;
    print $oufile $line;
}
close $infile;
print $oufile "\n";
close $oufile;


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('trains', '0002_trainclass_fare'),
    ]

    operations = [
        migrations.CreateModel(
            name='Bogey',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('className', models.CharField(max_length=255, verbose_name='Seat Class')),
                ('seatQuota', models.CharField(max_length=255, verbose_name='Seat Quota')),
                ('fare', models.PositiveIntegerField(default=0, verbose_name='Fare')),
            ],
        ),
        migrations.RemoveField(
            model_name='trainclass',
            name='className',
        ),
        migrations.RemoveField(
            model_name='trainclass',
            name='fare',
        ),
        migrations.RemoveField(
            model_name='trainclass',
            name='seatQuota',
        ),
        migrations.AddField(
            model_name='trainclass',
            name='bogey',
            field=models.ForeignKey(default=1, to='trains.Bogey'),
            preserve_default=False,
        ),
    ]


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.LanguageServices
{
    internal interface ISemanticFactsService : ILanguageService
    {
        /// <summary>
        /// True if this language supports implementing an interface by signature only. If false,
        /// implementations must specific explicitly which symbol they're implementing.
        /// </summary>
        bool SupportsImplicitInterfaceImplementation { get; }

        bool SupportsParameterizedProperties { get; }

        /// <summary>
        /// True if anonymous functions in this language have signatures that include named
        /// parameters that can be referenced later on when the function is invoked.  Or, if the
        /// anonymous function is simply a signature that will be assigned to a delegate, and the
        /// delegate's parameter names are used when invoking.
        ///
        /// For example, in VB one can do this:
        ///
        /// dim v = Sub(x as Integer) Blah()
        /// v(x:=4)
        ///
        /// However, in C# that would need to be:
        ///
        /// Action<int> v = (int x) => Blah();
        /// v(obj:=4)
        ///
        /// Note that in VB one can access 'x' outside of the declaration of the anonymous type.
        /// While in C# 'x' can only be accessed within the anonymous type.
        /// </summary>
        bool ExposesAnonymousFunctionParameterNames { get; }

        bool IsExpressionContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken);
        bool IsStatementContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken);
        bool IsTypeContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken);
        bool IsNamespaceContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken);
        bool IsNamespaceDeclarationNameContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken);
        bool IsTypeDeclarationContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken);
        bool IsMemberDeclarationContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken);
        bool IsPreProcessorDirectiveContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken);
        bool IsGlobalStatementContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken);
        bool IsLabelContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken);
        bool IsAttributeNameContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken);
        bool IsNameOfContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken);

        /// <summary>
        /// True if a write is performed to the given expression.  Note: reads may also be performed
        /// to the expression as well.  For example, "++a".  In this expression 'a' is both read from
        /// and written to.
        /// </summary>
        bool IsWrittenTo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken);

        /// <summary>
        /// True if a write is performed to the given expression.  Note: unlike IsWrittenTo, this
        /// will not return true if reads are performed on the expression as well.  For example,
        /// "++a" will return 'false'.  However, 'a' in "out a" or "a = 1" will return true.
        /// </summary>
        bool IsOnlyWrittenTo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken);
        bool IsInOutContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken);
        bool IsInRefContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken);

        bool CanReplaceWithRValue(SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken);

        string GenerateNameForExpression(SemanticModel semanticModel, SyntaxNode expression, bool capitalize = false);

        ISymbol GetDeclaredSymbol(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken);

        bool LastEnumValueHasInitializer(INamedTypeSymbol namedTypeSymbol);

        bool SupportsParameterizedEvents { get; }

        /// <summary>
        /// return speculative semantic model for supported node. otherwise, it will return null
        /// </summary>
        bool TryGetSpeculativeSemanticModel(SemanticModel oldSemanticModel, SyntaxNode oldNode, SyntaxNode newNode, out SemanticModel speculativeModel);

        /// <summary>
        /// get all alias names defined in the semantic model
        /// </summary>
        ImmutableHashSet<string> GetAliasNameSet(SemanticModel model, CancellationToken cancellationToken);

        ForEachSymbols GetForEachSymbols(SemanticModel semanticModel, SyntaxNode forEachStatement);

        bool IsAssignableTo(ITypeSymbol fromSymbol, ITypeSymbol toSymbol, Compilation compilation);
    }
}


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

#import <Cocoa/Cocoa.h>

@interface NSBitmapImageRep (CSIconViewExtras)

/* Returns TRUE if the specified rectangle, in image coordinates, intersects
   with the non-transparent section of the image.  This function only supports
   8-bit, 16-bit or floating point sample data (i.e. it expects truecolor data
   as opposed to the older---and nastier---formats). */
- (BOOL)rectIntersectsWithImage:(NSRect)rect;
- (BOOL)rectIntersectsWithImage:(NSRect)rect withAlphaThreshold:(float)thresh;

@end

/*
 * Local Variables:
 * mode: ObjC
 * End:
 *
 */


text:
namespace TestCases.HSSF.UserModel
{
    using System;

    using NPOI.HSSF;
    using NPOI.SS.Formula;
    using TestCases.SS.Formula;
    using TestCases.HSSF;
    using NUnit.Framework;
    using NPOI.SS.UserModel;

    /**
     * Tests Setting and Evaluating user-defined functions in HSSF
     */
    [TestFixture]
    public class TestHSSFExternalFunctions
    {
        /* This test is a copy of BaseTestExternalFunctions.BaseTestInvokeATP(String testFile)
         * If we made this test class derived from BaseTestExternalFunctions,
         * the test BaseTestExternalFunctions.TestExternalFunctions would run twice,
         * the fist passed and the second failed.
         *
         */
        [Test]
        public void TestATP()
        {
            //baseTestInvokeATP("atp.xls");
            IWorkbook wb = HSSFITestDataProvider.Instance.OpenSampleWorkbook("atp.xls");
            IFormulaEvaluator Evaluator = wb.GetCreationHelper().CreateFormulaEvaluator();

            ISheet sh = wb.GetSheetAt(0);
            // these two are not imlemented in r
            Assert.AreEqual("DELTA(1.3,1.5)", sh.GetRow(0).GetCell(1).CellFormula);
            Assert.AreEqual("COMPLEX(2,4)", sh.GetRow(1).GetCell(1).CellFormula);

            ICell cell2 = sh.GetRow(2).GetCell(1);
            Assert.AreEqual("ISODD(2)", cell2.CellFormula);
            Assert.AreEqual(false, Evaluator.Evaluate(cell2).BooleanValue);
            Assert.AreEqual(CellType.Boolean, Evaluator.EvaluateFormulaCell(cell2));

            ICell cell3 = sh.GetRow(3).GetCell(1);
            Assert.AreEqual("ISEVEN(2)", cell3.CellFormula);
            Assert.AreEqual(true, Evaluator.Evaluate(cell3).BooleanValue);
            Assert.AreEqual(CellType.Boolean, Evaluator.EvaluateFormulaCell(cell3));
        }

    }

}


text:
package com.huawei.esdk.fusionmanager.local.impl.autogen.common;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="return" type="{http://response.model.user.soap.business.common.north.galaxmanager.com/xsd}ListUserResp" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "_return"
})
@XmlRootElement(name = "listUserInfoResponse")
public class ListUserInfoResponse {

    @XmlElement(name = "return")
    protected ListUserResp _return;

    /**
     * Gets the value of the return property.
     *
     * @return
     *     possible object is
     *     {@link ListUserResp }
     *
     */
    public ListUserResp getReturn() {
        return _return;
    }

    /**
     * Sets the value of the return property.
     *
     * @param value
     *     allowed object is
     *     {@link ListUserResp }
     *
     */
    public void setReturn(ListUserResp value) {
        this._return = value;
    }

}


text:
require 'spec_helper'

describe["_.unshift"] = function()
	before = function()
		input = { 1,2 }
		result = _.unshift(input, 3)
	end

	it["should add the item onto the beginning of the array"] = function()
		expect(result).should_equal {3,1,2}
	end

	it["should return the input array"] = function()
		expect(result).should_be(input)
	end
end

spec:report(true)


text:
package jodd.http;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class HttpBrowserOfflineTest {

	@Test
	public void testDefaultParameters() {
		HttpBrowser httpBrowser = new HttpBrowser();
		httpBrowser.setDefaultHeader("aaa", "123");

		HttpRequest request = HttpRequest.get("foo.com");
		request.header("bbb", "987");

		httpBrowser.addDefaultHeaders(request);

		assertEquals(3, request.headers().size());
		assertEquals("123", request.header("aaa"));
		assertEquals("987", request.header("bbb"));
	}

	@Test
	public void testDefaultParametersOverwrite() {
		HttpBrowser httpBrowser = new HttpBrowser();
		httpBrowser.setDefaultHeader("aaa", "123");

		HttpRequest request = HttpRequest.get("foo.com");
		request.header("aaa", "987");

		httpBrowser.addDefaultHeaders(request);

		assertEquals(2, request.headers().size());
		assertEquals("987", request.header("aaa"));
	}
}


text:
title: 'Create a Poll'
taxonomy:
    category:
        - docs
---

**How to Use the NEM Voting Module**

You will find two options on the services tab on NanoWallet: See Polls and Create Poll. Let's walk through their features.

**Creating a Poll**

Example of a poll creation form on the testnet:
![](1-5ehVC2Lx2tsVEglO-4kGfg.png)

On the Create poll option you will find a form with all the information needed for a poll to be created. There is a small description for each field.

The fields that define a poll are:

* Title: This is a short title people will see on the poll index and when opening the poll.
* Description: The description's purpose is to explain what the poll is about and to include relevant information. The description field is not required but it is strongly encouraged so people know exactly what they are voting on.
* Poll Index: The address of the index account to send the poll. By default a public one is set.
* Date of Ending: The date and time the poll will end and no more votes will be counted.
* Multiple: you can choose whether or not the vote will allow multiple options. In this case vote weights will be split between the different options a voter chooses.
* Type: The type of vote counting (details below.)
* Options: The options voters will be able to choose from.
* Whitelist: This is only used for white list polls, where only votes from the specified addresses will be accepted.

When creating a poll the user can specify the way votes will be weighted. Currently there are two options:
* POI: Proof of Importance is a great tool for weighing the votes on polls, especially those that affect the NEM community. In the voting platform we make it possible to use the importance score, intrinsic to NEM, to weight votes in a simple way.
* White List: On simple polls every vote counts the same. A whitelist is required for this type since anybody can create as many NEM accounts as they want.


text:
SpecBegin(Braintree)

__block Braintree *braintree;

beforeEach(^{
    NSString *clientToken = [BTClient offlineTestClientTokenWithAdditionalParameters:nil];
    braintree = [Braintree braintreeWithClientToken:clientToken];

});

describe(@"tokenizeCardWithNumber:expirationMonth:expirationYear:completion:", ^{
    it(@"tokenizes a valid card", ^AsyncBlock{
        [braintree tokenizeCardWithNumber:@"4111111111111111"
                           expirationMonth:@"12"
                           expirationYear:@"2020"
                               completion:^(NSString *nonce, NSError *error) {
                                   expect(nonce).to.beKindOf([NSString class]);
                                   expect(nonce).notTo.equal(@"");
                                   done();
                               }];
    });

    it(@"tokenizes an invalid card", ^AsyncBlock{
        [braintree tokenizeCardWithNumber:@"bad-card"
                           expirationMonth:@"12"
                           expirationYear:@"2020"
                               completion:^(NSString *nonce, NSError *error) {
                                   expect(nonce).to.beKindOf([NSString class]);
                                   expect(nonce).notTo.equal(@"");
                                   done();
                               }];
    });
});

describe(@"dropInViewControllerWithCustomization:completion: Drop-In factory method", ^{
    it(@"constructs a Drop-In view controller", ^{
        UIViewController *dropIn = [braintree dropInViewControllerWithDelegate:nil];

        expect(dropIn).to.beKindOf([UIViewController class]);
        expect([dropIn view]).to.beKindOf([UIView class]);
    });

    it(@"returns a new instance each time", ^{
        UIViewController *dropIn1 = [braintree dropInViewControllerWithDelegate:nil];
        UIViewController *dropIn2 = [braintree dropInViewControllerWithDelegate:nil];

        expect(dropIn1).notTo.beIdenticalTo(dropIn2);
    });
});

describe(@"payPalButtonWithCompletion:", ^{
    __block Braintree *braintreeWithPayPalEnabled;

    describe(@"with PayPal enabled", ^{
        beforeEach(^{
            NSString *clientToken = [BTClient offlineTestClientTokenWithAdditionalParameters:@{BTClientTokenKeyPayPalEnabled: @YES}];
            braintreeWithPayPalEnabled = [Braintree braintreeWithClientToken:clientToken];

        });
        it(@"should return a payPalButton", ^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            BTPayPalButton *control = [braintreeWithPayPalEnabled payPalButtonWithDelegate:nil];
#pragma clang diagnostic pop
            expect(control).to.beKindOf([BTPayPalButton class]);
        });
    });

    describe(@"with PayPal disabled", ^{
        it(@"should not return a payPalButton", ^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            UIControl *control = [braintree payPalButtonWithDelegate:nil];
#pragma clang diagnostic pop
            expect(control).to.beNil;
        });
    });
});

describe(@"paymentButtonWithDelegate:paymentProviderTypes:", ^{
    it(@"returns a PaymentButton with specified payment providers", ^{
        id enabledPaymentProviderTypes = [NSOrderedSet orderedSetWithObjects:@(BTPaymentProviderTypePayPal), nil];
        BTPaymentButton *button = [braintree paymentButtonWithDelegate:nil paymentProviderTypes:enabledPaymentProviderTypes];

        expect(button).to.beKindOf([BTPaymentButton class]);
        expect(button.enabledPaymentProviderTypes).to.equal(enabledPaymentProviderTypes);
    });
});

describe(@"paymentProviderWithDelegate", ^{
    it(@"provides a configured BTPaymentProvider", ^{
        id delegate = [OCMockObject niceMockForProtocol:@protocol(BTPaymentMethodCreationDelegate)];

        BTPaymentProvider *provider = [braintree paymentProviderWithDelegate:delegate];
        expect(provider.client).to.equal(braintree.client);
        expect(provider.delegate).to.equal(delegate);
    });
});

describe(@"libraryVersion", ^{
    it(@"returns the current version number based on the podspec", ^{
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\A\\d+\\.\\d+\\.\\d+\\Z"
                                                                               options:0
                                                                                error:NULL];
        NSString *version = [Braintree libraryVersion];

        expect([regex numberOfMatchesInString:version
                                      options:0
                                        range:NSMakeRange(0, [version length])]).to.equal(1);
    });
});

SpecEnd


text:
if (typeof process !== "undefined" && process.title === "node") {
    module.exports = require("./lib/" + "server")
} else if (typeof window !== "undefined") {
    module.exports = require("./lib/client")
}


text:
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /* HAVE_CONFIG_H */

#include <stdlib.h>
#include <string.h>

#include "hashset.h"

typedef struct entry {
  unsigned hash;
  char* data;
  struct entry* next;
} entry;

struct hashset {
  /* Array of head entries.
   * An entry is unused if entry.data == NULL.
   * The set is defunct if entries == NULL.
   */
  entry* entries;
  /* The length of the above array. This must be a power of two. */
  unsigned table_size;
  /* The bitmask to convert hashes to indices. */
  unsigned mask;
  /* The total number of entries (including links). */
  unsigned num_entries;
  /* The threshhold at which to become defunct. */
  unsigned defunct_thresh;
};

/* Calculates the Jenkins One-at-a-Time hash function for the
 * given string.
 * See: http://en.wikipedia.org/wiki/Jenkins_hash_function
 */
static unsigned hs_hash(char* str) {
  unsigned hash = 0;
  while (*str) {
    hash += *str++;
    hash += (hash << 10);
    hash ^= (hash >> 6);
  }
  hash += (hash << 3);
  hash ^= (hash >> 11);
  hash += (hash << 15);
  return hash;
}

hashset hs_create(void) {
  hashset ret = malloc(sizeof(struct hashset));
  if (!ret) return ret;

  ret->table_size = 16;
  ret->mask = ret->table_size - 1;
  /* If this fails, entries is NULL, which just marks the table as defunct,
   * which is exactly what we want anyway.
   */
  ret->entries = malloc(ret->table_size*sizeof(entry));
  if (ret->entries)
    memset(ret->entries, 0, ret->table_size*sizeof(entry));
  ret->num_entries = 0;
  ret->defunct_thresh = ~0u;
  return ret;
}

static void hs_free_entries(hashset hs) {
  unsigned i;
  entry* curr, * next;
  for (i = 0; i < hs->table_size; ++i) {
    if (hs->entries[i].data) {
      /* Entry exists, free its data. */
      free(hs->entries[i].data);
      /* Now free any links it may have and their data */
      for (curr = hs->entries[i].next; curr; curr = next) {
        next = curr->next;
        free(curr->data);
        free(curr);
      }
    }
  }

  hs->entries = NULL;
}

void hs_free(hashset hs) {
  if (!hs) return;

  if (hs->entries)
    hs_free_entries(hs);

  free(hs);
}

void hs_defunct_at(hashset hs, unsigned thresh) {
  if (!hs) return;

  hs->defunct_thresh = thresh;
}

int hs_test(hashset hs, char* data) {
  unsigned hash, ix;
  entry* curr;

  /* Consider a null hashset defunct */
  if (!hs || !hs->entries) return 1;

  hash = hs_hash(data);
  ix = hash & hs->mask;

  /* If the entry does not exist, the rest of the entry struct should be
   * considered uninitialised, so return now.
   */
  if (!hs->entries[ix].data) return 0;
  /* Search each item in the chain until a match is found or the end is
   * reached. */
  for (curr = &hs->entries[ix]; curr; curr = curr->next)
    if (hash == curr->hash && 0 == strcmp(data, curr->data))
      return 1;
  return 0;
}

static void hs_put_one(hashset hs, char* data, unsigned hash) {
  unsigned ix;
  entry* new_entry;

  if (!hs || !hs->entries) return;

  /* Make a copy of the data for the table to own */
  data = strdup(data);
  if (!data) {
    /* Allocation failed, make defunct */
    hs_free_entries(hs);
    return;
  }

  ix = hash & hs->mask;
  if (!hs->entries[ix].data) {
    /* No collision, can insert directly. */
    hs->entries[ix].data = data;
    hs->entries[ix].hash = hash;
    hs->entries[ix].next = NULL;
    return;
  }

  /* Collision, must create link. */
  new_entry = malloc(sizeof(entry));
  if (!new_entry) {
    /* Allocation failed, make defunct */
    hs_free_entries(hs);
    return;
  }

  /* OK, set the new entry up and insert it. */
  new_entry->data = data;
  new_entry->hash = hash;
  new_entry->next = hs->entries[ix].next;
  hs->entries[ix].next = new_entry;
}

void hs_put(hashset hs, char* data) {
  struct hashset old;
  unsigned i;
  entry* curr;

  if (!hs || !hs->entries) return;

  /* Make defunct if will exceed limit */
  if (hs->num_entries+1 >= hs->defunct_thresh) {
    hs_free_entries(hs);
    return;
  }

  /* If this would bring the load average above 50%, double size. */
  if (hs->num_entries*2 >= hs->table_size) {
    /* Move hashset data to temporary */
    old = *hs;
    /* Double size and allocate */
    hs->table_size *= 2;
    hs->mask = hs->table_size-1;
    hs->entries = malloc(hs->table_size * sizeof(entry));
    if (hs->entries) {
      /* This part could be made more efficient by reusing the strings and even
       * some of the dynamically-allocated entries. However, this would
       * significantly complicate the code for what would not be a huge
       * performance benefit in most cases.
       */
      /* Initialise entries to zero */
      memset(hs->entries, 0, hs->table_size * sizeof(entry));
      /* Insert old entries into new table */
      for (i = 0; i < old.table_size; ++i)
        if (old.entries[i].data)
          for (curr = &old.entries[i]; curr; curr = curr->next)
            hs_put_one(hs, curr->data, curr->hash);
    }
    /* Free old data */
    hs_free_entries(&old);

    /* Return now if became defunct */
    if (!hs->entries) return;
  }

  /* OK, add single datum */
  hs_put_one(hs, data, hs_hash(data));
}


text:
package org.socialsignin.spring.data.dynamodb.repository.query;

import java.io.Serializable;

import org.socialsignin.spring.data.dynamodb.core.DynamoDBOperations;
import org.socialsignin.spring.data.dynamodb.query.Query;
import org.socialsignin.spring.data.dynamodb.repository.support.DynamoDBEntityInformation;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.query.ParameterAccessor;
import org.springframework.data.repository.query.parser.PartTree;

public class DynamoDBQueryCreator<T,ID extends Serializable> extends AbstractDynamoDBQueryCreator<T, ID,T> {

	public DynamoDBQueryCreator(PartTree tree,
			DynamoDBEntityInformation<T, ID> entityMetadata,
			DynamoDBOperations dynamoDBOperations) {
		super(tree, entityMetadata, dynamoDBOperations);
	}

	public DynamoDBQueryCreator(PartTree tree,
			ParameterAccessor parameterAccessor,
			DynamoDBEntityInformation<T, ID> entityMetadata,
			DynamoDBOperations dynamoDBOperations) {
		super(tree, parameterAccessor, entityMetadata, dynamoDBOperations);
	}

	@Override
	protected Query<T> complete(DynamoDBQueryCriteria<T, ID> criteria, Sort sort) {
		if (sort != null) {
			criteria.withSort(sort);
		}

		return criteria.buildQuery(dynamoDBOperations);

	}

}


text:
"use strict";

var util = require('util');

function SerialContext() {

};

SerialContext.init = function (lgr, adptr) {
	this.logger = lgr;
	this.adapter = adptr;
};

function CircularArray(size) {
	this.buffer = [];
	this.maxSize = size;
};

CircularArray.prototype.push = function (data) {
	if (this.maxSize <= this.buffer.length) {
		this.buffer.shift();
	}
	this.buffer.push(data);
};

CircularArray.prototype.clear = function (data) {
	this.buffer = [];
};

CircularArray.prototype.length = function (data) {
	return this.buffer.length;
};

function SerialLogger() {
	this.logBuffer = null;
};

SerialLogger.prototype.init = function (size) {
	this.logBuffer = new CircularArray(size);
};

SerialLogger.prototype.log = function (args) {
    var msg = util.format.apply(null, args);
	this.logBuffer.push({ ts: new Date(), msg: msg });
	console.log(msg);
};

module.exports.SerialContext = SerialContext;
module.exports.SerialLogger = SerialLogger;
module.exports.CircularArray = CircularArray;


text:
#include "gm.h"

#include "SkBitmap.h"
#include "SkPaint.h"
#include "SkPicture.h"
#include "SkPictureRecorder.h"
#include "SkShader.h"

static struct {
    SkShader::TileMode tmx;
    SkShader::TileMode tmy;
} kTileConfigs[] = {
    { SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode },
    { SkShader::kRepeat_TileMode, SkShader::kClamp_TileMode  },
    { SkShader::kMirror_TileMode, SkShader::kRepeat_TileMode },
};

class PictureShaderGM : public skiagm::GM {
public:
    PictureShaderGM(SkScalar tileSize, SkScalar sceneSize)
        : fTileSize(tileSize)
        , fSceneSize(sceneSize) {

        // Build the picture.
        SkPictureRecorder recorder;
        SkCanvas* pictureCanvas = recorder.beginRecording(tileSize, tileSize, NULL, 0);
        this->drawTile(pictureCanvas);
        fPicture.reset(recorder.endRecording());

        // Build a reference bitmap.
        fBitmap.allocN32Pixels(SkScalarCeilToInt(tileSize), SkScalarCeilToInt(tileSize));
        fBitmap.eraseColor(SK_ColorTRANSPARENT);
        SkCanvas bitmapCanvas(fBitmap);
        this->drawTile(&bitmapCanvas);
    }

protected:
    virtual uint32_t onGetFlags() const SK_OVERRIDE {
        return kSkipTiled_Flag;
    }

    virtual SkString onShortName() SK_OVERRIDE {
        return SkString("pictureshader");
    }

    virtual SkISize onISize() SK_OVERRIDE {
        return SkISize::Make(1400, 1250);
    }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        this->drawSceneColumn(canvas, SkPoint::Make(0, 0), 1, 1, 0);
        this->drawSceneColumn(canvas, SkPoint::Make(0, fSceneSize * 6.4f), 1, 2, 0);
        this->drawSceneColumn(canvas, SkPoint::Make(fSceneSize * 2.4f, 0), 1, 1, 1);
        this->drawSceneColumn(canvas, SkPoint::Make(fSceneSize * 2.4f, fSceneSize * 6.4f), 1, 1, 2);
        this->drawSceneColumn(canvas, SkPoint::Make(fSceneSize * 4.8f, 0), 2, 1, 0);
        this->drawSceneColumn(canvas, SkPoint::Make(fSceneSize * 9.6f, 0), 2, 2, 0);
    }

private:
    void drawSceneColumn(SkCanvas* canvas, const SkPoint& pos, SkScalar scale, SkScalar localScale,
                         unsigned tileMode) {
        SkMatrix ctm, localMatrix;

        ctm.setTranslate(pos.x(), pos.y());
        ctm.preScale(scale, scale);
        localMatrix.setScale(localScale, localScale);
        this->drawScene(canvas, ctm, localMatrix, tileMode);

        ctm.setTranslate(pos.x(), pos.y() + fSceneSize * 1.2f * scale);
        ctm.preScale(scale, scale);
        localMatrix.setTranslate(fTileSize / 4, fTileSize / 4);
        localMatrix.preScale(localScale, localScale);
        this->drawScene(canvas, ctm, localMatrix, tileMode);

        ctm.setTranslate(pos.x(), pos.y() + fSceneSize * 2.4f * scale);
        ctm.preScale(scale, scale);
        localMatrix.setRotate(45);
        localMatrix.preScale(localScale, localScale);
        this->drawScene(canvas, ctm, localMatrix, tileMode);

        ctm.setTranslate(pos.x(), pos.y() + fSceneSize * 3.6f * scale);
        ctm.preScale(scale, scale);
        localMatrix.setSkew(1, 0);
        localMatrix.preScale(localScale, localScale);
        this->drawScene(canvas, ctm, localMatrix, tileMode);

        ctm.setTranslate(pos.x(), pos.y() + fSceneSize * 4.8f * scale);
        ctm.preScale(scale, scale);
        localMatrix.setTranslate(fTileSize / 4, fTileSize / 4);
        localMatrix.preRotate(45);
        localMatrix.preScale(localScale, localScale);
        this->drawScene(canvas, ctm, localMatrix, tileMode);
    }

    void drawTile(SkCanvas* canvas) {
        SkPaint paint;
        paint.setColor(SK_ColorGREEN);
        paint.setStyle(SkPaint::kFill_Style);
        paint.setAntiAlias(true);

        canvas->drawCircle(fTileSize / 4, fTileSize / 4, fTileSize / 4, paint);
        canvas->drawRect(SkRect::MakeXYWH(fTileSize / 2, fTileSize / 2,
                                          fTileSize / 2, fTileSize / 2), paint);

        paint.setColor(SK_ColorRED);
        canvas->drawLine(fTileSize / 2, fTileSize * 1 / 3,
                         fTileSize / 2, fTileSize * 2 / 3, paint);
        canvas->drawLine(fTileSize * 1 / 3, fTileSize / 2,
                         fTileSize * 2 / 3, fTileSize / 2, paint);
    }

    void drawScene(SkCanvas* canvas, const SkMatrix& matrix, const SkMatrix& localMatrix,
                   unsigned tileMode) {
        SkASSERT(tileMode < SK_ARRAY_COUNT(kTileConfigs));

        SkPaint paint;
        paint.setStyle(SkPaint::kFill_Style);
        paint.setColor(SK_ColorLTGRAY);

        canvas->save();
        canvas->concat(matrix);
        canvas->drawRect(SkRect::MakeWH(fSceneSize, fSceneSize), paint);
        canvas->drawRect(SkRect::MakeXYWH(fSceneSize * 1.1f, 0, fSceneSize, fSceneSize), paint);

        SkAutoTUnref<SkShader> pictureShader(SkShader::CreatePictureShader(
                    fPicture,
                    kTileConfigs[tileMode].tmx,
                    kTileConfigs[tileMode].tmy,
                    &localMatrix,
                    NULL));
        paint.setShader(pictureShader.get());
        canvas->drawRect(SkRect::MakeWH(fSceneSize, fSceneSize), paint);

        canvas->translate(fSceneSize * 1.1f, 0);

        SkAutoTUnref<SkShader> bitmapShader(SkShader::CreateBitmapShader(
                    fBitmap,
                    kTileConfigs[tileMode].tmx,
                    kTileConfigs[tileMode].tmy,
                    &localMatrix));
        paint.setShader(bitmapShader.get());
        canvas->drawRect(SkRect::MakeWH(fSceneSize, fSceneSize), paint);

        canvas->restore();
    }

    SkScalar    fTileSize;
    SkScalar    fSceneSize;

    SkAutoTUnref<SkPicture> fPicture;
    SkBitmap fBitmap;

    typedef GM INHERITED;
};

DEF_GM( return SkNEW_ARGS(PictureShaderGM, (50, 100)); )


text:
A Ruby wrapper for Project Noah API
visit http://beta.noah.dost.gov.ph/apidocs/

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'project_noah'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install project_noah

## Usage

```ruby
data_response = ProjectNoah::Api.doppler
@doppler = JSON.parse(data_response)
```

Endpoint list
* doppler
* mtsat
* latest_contour
* cumulative_rainfall
* stations
* four_day_forecast
* four_hour_forecast
* flood_maps
* landslide_maps
* storm_surge_maps
* muncities
* provinces
* regions

## Contributing

1. Fork it ( https://github.com/nadflores/project_noah/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
package org.etower.core.domain;

import java.util.List;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.etower.common.jpa.entity.IdEntity;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity
@Table(name = "et_role")
//默认的缓存策略.
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class EtRole extends IdEntity {
	private static final long serialVersionUID = 1L;

	private boolean isSuper;
	private int priority;
	private String remark;
	private String roleName;

	private EtSite etSite;
	private List<EtUser> etUsers;
	private Set<EtRolePermission> etRolePerm;

	public EtRole() {
	}

	public boolean getIsSuper() {
		return isSuper;
	}

	public void setIsSuper(boolean isSuper) {
		this.isSuper = isSuper;
	}

	public int getPriority() {
		return priority;
	}

	public void setPriority(int priority) {
		this.priority = priority;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public String getRoleName() {
		return roleName;
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	@ManyToOne(fetch=FetchType.LAZY, optional=false)
	@JoinColumn(name = "SITE_ID")
	public EtSite getEtSite() {
		return etSite;
	}

	public void setEtSite(EtSite etSite) {
		this.etSite = etSite;
	}

	@ManyToMany
	@JoinTable(name = "et_user_role", joinColumns = { @JoinColumn(name = "ROLE_ID") }, inverseJoinColumns = { @JoinColumn(name = "USER_ID") })
	public List<EtUser> getEtUsers() {
		return etUsers;
	}

	public void setEtUsers(List<EtUser> etUsers) {
		this.etUsers = etUsers;
	}

	@OneToMany(fetch=FetchType.LAZY, mappedBy = "etRole")
	public Set<EtRolePermission> getEtRolePerm() {
		return etRolePerm;
	}

	public void setEtRolePerm(Set<EtRolePermission> etRolePerm) {
		this.etRolePerm = etRolePerm;
	}

}


text:
LAPPS Schema Compiler
============================

**NOTE** This is still a work in progress and likely contains misleading and/or
downright false information...

### Build Status
[![Master build status](http://grid.anc.org:9080/travis/svg/oanc/org.anc.json.schema-compiler?branch=master)](https://travis-ci.org/oanc/org.anc.lapps.schema-compiler)
[![Develop build status](http://grid.anc.org:9080/travis/svg/oanc/org.anc.json.schema-compiler?branch=develop)](https://travis-ci.org/oanc/org.anc.lapps.schema-compiler)

The LAPPS (Language Application Grid) Schema compiler generates a
[JSON Schema](http://json-schema.org) from the LAPPS alternate syntax. The alternate
syntax is **not** a new schema language, it is simply a simplified syntax for
representing the objects that make up a JSON schema.

## Maven

```xml
<dependency>
    <groupId>org.anc.json</groupId>
    <artifactId>compiler</artifactId>
    <version>${see below}</version>
</dependency>
```

[![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.anc.json/compiler/badge.svg?style=plastic)](https://maven-badges.herokuapp.com/maven-central/org.anc.json/compiler)

## Examples

Example schemata can be found at:

1. [http://vocab.lappsgrid.org/schema/lif.schema](http://vocab.lappsgrid.org/schema/lif.schema)
1. [http://vocab.lappsgrid.org/schema/metadata.schema](http://vocab.lappsgrid.org/schema/metadata.schema)

# Alternate Syntax

Since a schema using the alternate syntax is really just a [Groovy](http://groovy.codehaus.org) script a basic
understanding of the Groovy language is recommended, but not required.

The same set of JSON Schema keywords and constructs is used so the alternate syntax looks
almost exactly the same as the Javascript version; except with far fewer double
quotes, colons, and braces. Please refer to the [JSON Schema specification](http://json-schema.org) for a description
of the JSON Schema syntax.

### Built in variables

The following variables are declared automatically and made available by the compiler:

* object
* array
* number
* integer
* string
* nil *(since null is already a keyword in Groovy)*

Using a built in variable is exactly the same as using the variable name
 surrounded by double quotes.

    type object
    // is exactly the same as
    type "object"

## Name/Value pairs

In the alternate syntax the *name* in a name/value pair does not need to be enclosed in
double quotes, unless it contains characters that are not allowed in a Groovy (Java)
variable name:

In Javascript:

    {
        "type": "integer",
        "minimum": 1
    }

in the alternate syntax:

    type integer
    minimum 1

**NOTE**

1. The outer braces are not required.
1. No double quotes around the keywords *type*, *integer*, or *minimum*.
1. No colon between the name and the value.
1. No comma required to separate statements (see comments below).

Multiple statements can be combined on a single line by separating them with
semi-colons.

    type integer; minimum 1

## JSON Objects

In the alternate syntax a JSON object is simply a name/value pair where the value
 is another sequence of name/value pairs wrapped in curly braces.

     properties {
         name {
             type string
         }
         age {
             type integer
             minimum 0
         }
     }

## JSON Arrays

In the alternate syntax any comma separated list of values is converted into a JSON
array object

    type object, string, number

This is equivalent to the Javascript

    "type":["object", "string", "number"]

To create an array with containing a single element the array syntax must be used
explicitly. In addition, since the Groovy parser will attempt to parse

    type [ object ]

as an array access we also need to include the array in parenthesis:

    type([ object ])

The exception to this is the *required* keyword, which will always parse the value
as an array regardless of the number of items in the list.

## JSON Values

JSON values are represented in exactly the same way as they are in Javascript.

**NOTE** Due to possible differences in Groovy/Javascript floating point representations
and other issues there may be some differences in some types.

# Programming Constructs

One important factor to keep in mind is that under the hood the LAPPS alternate syntax
is just a Groovy script (Java program).  It is the execution of the script that
generates the Groovy (Java) object that is serialized into JSON using the the
[Jackson](http://wiki.fasterxml.com/JacksonHome) library. This means it is possible to
use arbitrary Groovy/Java programming constructs in schema definition.

## Variables

New variables can be defined at any point in an alternate syntax schemsa. New variable
definitions do not need to specify a type.

    root = 'http://json.example.com'

    title 'Variables example.'
    id root
    properties {
        firstName { type string; id "$root/firstName" }
        lastName { type string; id "$root/lastName }
    }

**Groovy Note** Variable substitution does not happen in strings enclosed in single
quotes. For the above to work double quotes MUST be used.

## Flow of Control

Any Groovy flow of control structure can be used in an alternate syntax schema

    root = 'http://json.example.com'
    hasAge = true
    props = [ 'firstName', 'lastName', 'address' ]
    id root
    properties {
        props.each {
            myId = "$root/$it"
            "$it" { type string; id myId }
        }
        if (hasAge) {
            age { type integer; minimum 0; id "$root/age" }
        }
    }

This generates the schema:

    {
        "id": "http://json.example.com",
        "properties": {
            "firstName": {
                "type": "string",
                "id": "http://json.example.com/firstName"
            },
            "lastName": {
                "type": "string",
                "id": "http://json.example.com/lastName"
            },
            "address": {
                "type": "string",
                "id": "http://json.example.com/address"
            },
            "age": {
                "type": "integer",
                "minimum": 0,
                "id": "http://json.example.com/age"
            }
        }
    }

**Groovy Note** The variable *it* is the default name used by Groovy when passing
parameters to closures.

## Imports and @Grab

Give examples that import other Groovy/Java modules and use @Grab to fetch a
dependency from a Maven repository.

While I can not imagine a use-case where these features would be useful (and they might
actually be harmful) I try to not let my lack of imagination limit what others mighht
do.

# Caveats

List known limitations and problems here:

- the current implementation accepts any input and generates output. If the output
is not a valid JSON schema... que sera sera...
- multipleOf, anyOf, oneOf, et al. need work.

# Command Line

Show how to run the standalone jar file.

# As a Library

Provide code that shows how to use the SchemaCompiler class.

    String schema = """
        type object
        properties {
            firstName { type string }
            lastName { type string }
            age {
                type integer
                minimum 0
            }
        }
        required 'firstName', 'lastName'
    """

    SchemaCompiler compiler = new SchemaCompiler()
    println compiler.compile(schema)


text:
Trabalhos práticos da disciplina de Análise e projetos de algoritmos.

trabalho_01: Algoritmos de ordenação