text:
//
//  FolderView.m
//  tianmao
//
//  Created by dengwei on 16/1/16.
//  Copyright (c) 2016年 dengwei. All rights reserved.
//

#import "FolderView.h"
#import "ShopTypeCell.h"
#import "ShopListViewController.h"

#define kProductCellHeight 80
#define kSubViewHeight 200

typedef CGRect(^newFrame)(CGFloat up, CGFloat down, NSIndexPath *path, UITableViewCell *cell);

@interface FolderView ()

/**
 *  动画的表格行
 */
@property (nonatomic, strong) NSMutableArray *animationRows;

/**
 *  子类店铺的视图控制器
 */
@property (nonatomic, strong) ShopListViewController *shopListController;

@end

@implementation FolderView

-(instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style{
    self = [super initWithFrame:frame style:style];
    if (self) {
        //1.设置背景图片
        UIImage *image = [UIImage imageNamed:@"tmall_bg_furley.png"];
        //使用图片屏幕背景
        [self setBackgroundColor:[UIColor colorWithPatternImage:image]];

        //2.设置表格行高
        self.rowHeight = kProductCellHeight;

        //3.取消垂直滚动条
        self.showsVerticalScrollIndicator = NO;

        //4.取消弹簧效果
        [self setBounces:NO];

        //5.顶部多滚出部分区域
        //self.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);

        //6.实例化子类视图控制器
        self.shopListController = [[ShopListViewController alloc] init];
    }
    return self;
}

#pragma mark 抽屉操作
-(void)operateFolderAtIndexPath:(NSIndexPath *)indexPath shopList:(NSArray *)shopList{
    /**
     *  选中某一行表格后,将下方的表格向下移动kSubViewHeight的高度
     *  可以通过tableView的indexPathsForVisibleRows获取到当前屏幕上所有显示的行
     */

    //处理关闭抽屉,释放掉animationRows
    /**
     *  如果animationRows数组不存在,说明没有打开抽屉,做打开抽屉的操作。
     如果animationRows数组已经存在,说明抽屉已经打开,做关闭抽屉操作。
     */
    if ([self.animationRows count] != 0) {
        [self closeFolder];
        return;
    }

    //打开抽屉前需要填充商店列表中的数据
    [self.shopListController setShopList:shopList];
    //刷新数据
    [self.shopListController.tableView reloadData];

    //新建一个数组,可以把所有可能动画的表格行的iindexPath全部记录下来
    NSMutableArray *array = [NSMutableArray arrayWithArray:[self indexPathsForVisibleRows]];
    self.animationRows = array;
    /**
     *  1.下方的空间足够大,只要挪动选中行下方的表格即可
     *  2.下方的空间不够大,上面的要挪多少,下边要挪多少?
     */

    UITableViewCell *cell = [self cellForRowAtIndexPath:indexPath];
    //1)选中单元格的y
    CGFloat cellY = cell.frame.origin.y;
    //2)选中单元格的行高
    CGFloat cellHeight = cell.frame.size.height;
    //3)准备插入子视图的Y
    CGFloat subViewY = cellY + cellHeight;
    //4)屏幕的高度
    CGFloat tableHeight = self.frame.size.height;
    //5)表格的偏移
    CGFloat offsetY = self.contentOffset.y;

    //判断空间是否足够
    if (tableHeight - subViewY + offsetY < kSubViewHeight) {
        NSLog(@"空间不足");
        CGFloat up = tableHeight + offsetY - kSubViewHeight - subViewY;
        subViewY = tableHeight + offsetY - kSubViewHeight;
        CGFloat down = kSubViewHeight + up;

        [self openFolderFromIndexPath:indexPath up:up down:down newFrame:^CGRect(CGFloat up, CGFloat down, NSIndexPath *path, UITableViewCell *cell) {
            CGRect newFrame = cell.frame;
            //小于或等于选中行的向上挪
            if (path.row <= indexPath.row) {
                newFrame.origin.y += up;
            }else{
                //大于的向下
                newFrame.origin.y += down;
            }
            return newFrame;
        }];
    }else{
        NSLog(@"空间足够");
        [self openFolderFromIndexPath:indexPath up:0 down:self.shopListController.view.frame.size.height newFrame:^CGRect(CGFloat up, CGFloat down, NSIndexPath *path, UITableViewCell *cell) {
            CGRect frame = cell.frame;
            if (path.row > indexPath.row) {
                //2.挪动表格行,挪动位置:frame,center
                frame.origin.y += down;
            }
            return frame;
        }];
    }
    //设置子视图
    CGRect subViewFrame = self.shopListController.view.frame;
    subViewFrame.origin.y = subViewY;
    [self.shopListController.view setFrame:subViewFrame];

    [self insertSubview:self.shopListController.view atIndex:0];
}

#pragma mark 打开抽屉
-(void)openFolderFromIndexPath:(NSIndexPath *)indexPath up:(CGFloat)up down:(CGFloat)down newFrame:(newFrame)newFrame {
    [UIView animateWithDuration:1.0f animations:^{
        for (NSIndexPath *path in self.animationRows) {
            //1.取出要挪动的表格行
            ShopTypeCell *cell = (ShopTypeCell *)[self cellForRowAtIndexPath:path];
            //记录初始Y值
            cell.originY = cell.frame.origin.y;
            //当前的frame,使用block
            CGRect frame = newFrame(up, down, path, cell);

            [cell setFrame:frame];
        }
    }];
}

#pragma mark 关闭抽屉
-(void)closeFolder{
    /**
     关闭抽屉,就是把所有动画行复位
     要复位,需要知道动画行的初始位置
     要在挪动表格行之前纪录对应的初始位置Y值
     注意:tag是整数,Y值是浮点数,因此不能用tag记录
     */

    [UIView animateWithDuration:1.0f animations:^{
        //1)遍历数组,还原所有动画行的Y值
        for (NSIndexPath *path in self.animationRows) {
            ShopTypeCell *cell = (ShopTypeCell *)[self cellForRowAtIndexPath:path];
            CGRect frame = cell.frame;
            frame.origin.y = cell.originY;
            [cell setFrame:frame];
        }
    } completion:^(BOOL finished) {
        //2)删除animationRows
        [self.animationRows removeAllObjects];
        //3)从主视图中移除子视图
        [self.shopListController.view removeFromSuperview];
    }];
}

@end


text:
package org.apache.nutch.crawl;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;
import org.apache.nutch.net.URLFilters;
import org.apache.nutch.net.URLNormalizers;

/**
 * This class provides a way to separate the URL normalization
 * and filtering steps from the rest of CrawlDb manipulation code.
 *
 * @author Andrzej Bialecki
 */
public class CrawlDbFilter implements Mapper<Text, CrawlDatum, Text, CrawlDatum> {
  public static final String URL_FILTERING = "crawldb.url.filters";

  public static final String URL_NORMALIZING = "crawldb.url.normalizers";

  public static final String URL_NORMALIZING_SCOPE = "crawldb.url.normalizers.scope";

  private boolean urlFiltering;

  private boolean urlNormalizers;

  private boolean url404Purging;

  private URLFilters filters;

  private URLNormalizers normalizers;

  private String scope;

  public static final Logger LOG = LoggerFactory.getLogger(CrawlDbFilter.class);

  public void configure(JobConf job) {
    urlFiltering = job.getBoolean(URL_FILTERING, false);
    urlNormalizers = job.getBoolean(URL_NORMALIZING, false);
    url404Purging = job.getBoolean(CrawlDb.CRAWLDB_PURGE_404, false);

    if (urlFiltering) {
      filters = new URLFilters(job);
    }
    if (urlNormalizers) {
      scope = job.get(URL_NORMALIZING_SCOPE, URLNormalizers.SCOPE_CRAWLDB);
      normalizers = new URLNormalizers(job, scope);
    }
  }

  public void close() {}

  private Text newKey = new Text();

  public void map(Text key, CrawlDatum value,
      OutputCollector<Text, CrawlDatum> output,
      Reporter reporter) throws IOException {

    String url = key.toString();

    // https://issues.apache.org/jira/browse/NUTCH-1101 check status first, cheaper than normalizing or filtering
    if (url404Purging && CrawlDatum.STATUS_DB_GONE == value.getStatus()) {
      url = null;
    }
    if (urlNormalizers) {
      try {
        url = normalizers.normalize(url, scope); // normalize the url
      } catch (Exception e) {
        LOG.warn("Skipping " + url + ":" + e);
        url = null;
      }
    }
    if (url != null && urlFiltering) {
      try {
        url = filters.filter(url); // filter the url
      } catch (Exception e) {
        LOG.warn("Skipping " + url + ":" + e);
        url = null;
      }
    }
    if (url != null) { // if it passes
      newKey.set(url); // collect it
      output.collect(newKey, value);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
pub enum MessageAttribute {
    MappedAddress = 0,
    ResponseAddress,
    ChangeRequest,
    SourceAddress,
    ChangedAddress,
    Username,
    Password,
    MessageIntegrity,
    ErrorCode,
    UnknownAttributes,
    ReflectedFrom,
    ChannelNumber,
    Lifetime,
    AlternateServer,
    MagicCookie,
    Bandwidth,
    DestinationAddress,
    XorPeerAddress,
    Data,
    Realm,
    Nonce,
    XorRelayedAddress,
    RequestedAddressType,
    EvenPort,
    RequestedTransport,
    DontFragment,
    XorMappedAddress,
    ReservationToken,
    Priority,
    UseCandidate,
    Padding,
    ResponsePort,
    XorReflectedFrom,
    Icmp,
    XVovidaXorMappedAddress,
    XVovidaXorOnly,
    Software,
    CacheTimeout,
    Fingerprint,
    IceControlled,
    IceControlling,
    ResponseOrigin,
    OtherAddress,
    XVovidaSecondaryAddress,
    ConnectionRequestBinding,
    BindingChange
}

impl MessageAttribute {
    pub fn from_u16(i: u16) -> MessageAttribute {
        match i {
            0x0001 => MessageAttribute::MappedAddress,
            0x0002 => MessageAttribute::ResponseAddress,
            0x0003 => MessageAttribute::ChangeRequest,
            0x0004 => MessageAttribute::SourceAddress,
            0x0005 => MessageAttribute::ChangedAddress,
            0x0006 => MessageAttribute::Username,
            0x0007 => MessageAttribute::Password,
            0x0008 => MessageAttribute::MessageIntegrity,
            0x0009 => MessageAttribute::ErrorCode,
            0x000A => MessageAttribute::UnknownAttributes,
            0x000B => MessageAttribute::ReflectedFrom,
            0x000c => MessageAttribute::ChannelNumber,
            0x000D => MessageAttribute::Lifetime,
            0x000E => MessageAttribute::AlternateServer,
            0x000F => MessageAttribute::MagicCookie,
            0x0010 => MessageAttribute::Bandwidth,
            0x0011 => MessageAttribute::DestinationAddress,
            0x0012 => MessageAttribute::XorPeerAddress,
            0x0013 => MessageAttribute::Data,
            0x0014 => MessageAttribute::Realm,
            0x0015 => MessageAttribute::Nonce,
            0x0016 => MessageAttribute::XorRelayedAddress,
            0x0017 => MessageAttribute::RequestedAddressType,
            0x0018 => MessageAttribute::EvenPort,
            0x0019 => MessageAttribute::RequestedTransport,
            0x001a => MessageAttribute::DontFragment,
            0x0020 => MessageAttribute::XorMappedAddress,
            0x0022 => MessageAttribute::ReservationToken,
            0x0024 => MessageAttribute::Priority,
            0x0025 => MessageAttribute::UseCandidate,
            0x0026 => MessageAttribute::Padding,
            0x0027 => MessageAttribute::ResponsePort,
            0x0028 => MessageAttribute::XorReflectedFrom,
            0x0030 => MessageAttribute::Icmp,
            0x8020 => MessageAttribute::XVovidaXorMappedAddress,
            0x8021 => MessageAttribute::XVovidaXorOnly,
            0x8022 => MessageAttribute::Software,
            0x8023 => MessageAttribute::AlternateServer,
            0x8027 => MessageAttribute::CacheTimeout,
            0x8028 => MessageAttribute::Fingerprint,
            0x8029 => MessageAttribute::IceControlled,
            0x802A => MessageAttribute::IceControlling,
            0x802B => MessageAttribute::ResponseOrigin,
            0x802C => MessageAttribute::OtherAddress,
            0x8050 => MessageAttribute::XVovidaSecondaryAddress,
            0xC001 => MessageAttribute::ConnectionRequestBinding,
            0xC002 => MessageAttribute::BindingChange,
            _      => panic!("Unknown message attribute")
        }
    }

    pub fn to_u16(self) -> u16 {
        match self {
            MessageAttribute::MappedAddress => 0x0001,
            MessageAttribute::ResponseAddress => 0x0002,
            MessageAttribute::ChangeRequest => 0x0003,
            MessageAttribute::SourceAddress => 0x0004,
            MessageAttribute::ChangedAddress => 0x0005,
            MessageAttribute::Username => 0x0006,
            MessageAttribute::Password => 0x0007,
            MessageAttribute::MessageIntegrity => 0x0008,
            MessageAttribute::ErrorCode => 0x0009,
            MessageAttribute::UnknownAttributes => 0x000A,
            MessageAttribute::ReflectedFrom => 0x000B,
            MessageAttribute::ChannelNumber => 0x000c,
            MessageAttribute::Lifetime => 0x000D,
            MessageAttribute::MagicCookie => 0x000F,
            MessageAttribute::Bandwidth => 0x0010,
            MessageAttribute::DestinationAddress => 0x0011,
            MessageAttribute::XorPeerAddress => 0x0012,
            MessageAttribute::Data => 0x0013,
            MessageAttribute::Realm => 0x0014,
            MessageAttribute::Nonce => 0x0015,
            MessageAttribute::XorRelayedAddress => 0x0016,
            MessageAttribute::RequestedAddressType => 0x0017,
            MessageAttribute::EvenPort => 0x0018,
            MessageAttribute::RequestedTransport => 0x0019,
            MessageAttribute::DontFragment => 0x001a,
            MessageAttribute::XorMappedAddress => 0x0020,
            MessageAttribute::ReservationToken => 0x0022,
            MessageAttribute::Priority => 0x0024,
            MessageAttribute::UseCandidate => 0x0025,
            MessageAttribute::Padding => 0x0026,
            MessageAttribute::ResponsePort => 0x0027,
            MessageAttribute::XorReflectedFrom => 0x0028,
            MessageAttribute::Icmp => 0x0030,
            MessageAttribute::XVovidaXorMappedAddress => 0x8020,
            MessageAttribute::XVovidaXorOnly => 0x8021,
            MessageAttribute::Software => 0x8022,
            MessageAttribute::AlternateServer => 0x8023,
            MessageAttribute::CacheTimeout => 0x8027,
            MessageAttribute::Fingerprint => 0x8028,
            MessageAttribute::IceControlled => 0x8029,
            MessageAttribute::IceControlling => 0x802A,
            MessageAttribute::ResponseOrigin => 0x802B,
            MessageAttribute::OtherAddress => 0x802C,
            MessageAttribute::XVovidaSecondaryAddress => 0x8050,
            MessageAttribute::ConnectionRequestBinding => 0xC001,
            MessageAttribute::BindingChange => 0xC002,
        }
    }
}


text:
package gw.fs.physical;

import gw.fs.ResourcePath;
import gw.lang.UnstableAPI;

@UnstableAPI
public abstract class AbstractCachingPhysicalFileSystem implements IPhysicalFileSystem {

  protected final IPhysicalFileSystem _delegate;

  public AbstractCachingPhysicalFileSystem(IPhysicalFileSystem delegate) {
    _delegate = delegate;
  }

  @Override
  public boolean exists(ResourcePath resourcePath) {
    return getFileMetadata(resourcePath) != null;
  }

  @Override
  public boolean delete(ResourcePath filePath) {
    return _delegate.delete(filePath);
  }

  @Override
  public boolean mkdir(ResourcePath dirPath) {
    return _delegate.mkdir(dirPath);
  }
}


text:
Ti=MODEL PATENT LICENSE AGREEMENT

0.sec=The owner of the {_Licensed_Patent_Rights}, as defined below (the "{Def.Licensor.sec}"), grants a license on the terms and conditions set forth in this Patent License Agreement (the "{Def.Agreement.sec}") to the person or entity accepting this {_Agreement} (the "{Def.Licensee.sec}").

xlist=

{Def.Sec}
{Grant.Sec}
{Fee.Sec}
{Report.Sec}
{Term.Sec}
{Rep.Sec}
{Indemnify.Sec}
{Trademark.Sec}
{Misc.Sec}

Def.=[G/CreativeCommons/Model_Patent_License/Sec/Def/0.md]

Grant.=[G/CreativeCommons/Model_Patent_License/Sec/Grant/0.md]

Fee.=[G/CreativeCommons/Model_Patent_License/Sec/Fee/0.md]

Report.=[G/CreativeCommons/Model_Patent_License/Sec/Report/0.md]

Term.=[G/CreativeCommons/Model_Patent_License/Sec/Term/0.md]

Rep.=[G/CreativeCommons/Model_Patent_License/Sec/Rep/0.md]

Indemnify.=[G/CreativeCommons/Model_Patent_License/Sec/Indemnify/0.md]

Trademark.=[G/CreativeCommons/Model_Patent_License/Sec/Trademark/0.md]

Misc.=[G/CreativeCommons/Model_Patent_License/Sec/Misc/0.md]

00.sec=Annexes

{Annex.1.Sec}
{Annex.2.Doc}

=[G/Z/ol/Base]

Annex.1.Ti=Addendum A

Annex.1.1.sec=The purpose of this Addendum is to provide guidelines for a {_License_Data_Record}, which may be either in paper or electronic form. This {_License_Data_Record} is unique to each transaction and must specify a minimum information set in order to give effect to the Patent License Agreement.

Annex.1.2.0.sec=To constitute an agreement that incorporates the terms of the Patent License Agreement, a {_License_Data_Record} must:

Annex.1.2.1.sec=reference this {_Agreement} by linking to the URL of the Patent License Agreement deed or legal code, attaching a copy of it, referencing it by name, or by any other means that uniquely and unambiguously identifies it; AND

Annex.1.2.2.0.sec=provide the following information:

Annex.1.2.2.1.sec=Name of {_Licensor}: the name of the person or entities offering this license,

Annex.1.2.2.2.sec={_Licensor} Contact Information: address, contact person, phone number, fax, and/or email,

Annex.1.2.2.3.sec=Name of {_Licensee}: the name of the person or entities accepting this license,

Annex.1.2.2.4.sec={_Licensee} Contact Information: address, contact person, phone number, fax, and/or email,

Annex.1.2.2.5.Alt1.sec={_Licensed_Patent_Rights}: a list of patents and patent applications to be licensed

Annex.1.2.2.5.Alt2.sec={_Specification}: a written specification of the invention or technology to be licensed.

Annex.1.2.2.5.=[G/Z/Alt/2]

Annex.1.2.2.5.SecName=Annex.1.2.2.5

Annex.1.2.2.6.sec=License Fees and Royalties (optional):

Annex.1.2.2.7.sec={_Field_of_Use} (optional): a description of any scope of use limitations associated with the license,

Annex.1.2.2.8.sec="Have Made" Limitations (optional): any limitations to the license to "have made"

Annex.1.2.2.9.sec=Choice of Law (optional): jurisdiction for choice of law,

Annex.1.2.2.10.sec=Choice of Venue (optional) jurisdiction for legal venue,

Annex.1.2.2.11.sec={_Territory} (optional): geographic limitations of the license,

Annex.1.2.2.12.sec=Offer Limitations (optional): any limitations associated with the offer

Annex.1.2.2.=[G/Z/ol-a/s12]

Annex.1.2.=[G/Z/ol/s2]

Annex.1.=[G/Z/ol/s2]

Annex.2.DocTi=''Sample {_License_Data_Record}'''

Annex.2.0.sec=This {_License_Data_Record} references and incorporates the GX Model Patent License Agreement (located at URL: _________)

Annex.2.1.Ti=Parties

Annex.2.1.sec=

{Licensor.US.Notice.Block}
{Licensee.US.Notice.Block}

Licensor Name

Licensor Contact
Address:     _____________________________
             _____________________________
             _____________________________

Phone:       _____________________________

Fax:         _____________________________

Email:       _____________________________

Licensee Name
Licensee Contact
Address:     _____________________________
             _____________________________
             _____________________________
Phone:       _____________________________
Fax:         _____________________________
Email:       _____________________________

Annex.2.2.Ti=Licensed Patents Rights:

Annex.2.2.1.sec=Patent No.   ____________________________

Annex.2.2.2.sec=Patent Application No.__________________
…

'''OR'''

{_Specification} (attached a detailed specification or provide a URL):

Annex.2.2.3.Ti=License Fees & Royalties (optional)

Annex.2.2.3.sec=a description of any required fees, royalties, or other monetary consideration

Annex.2.2.4.Ti={_Field_of_Use} (optional):

Annex.2.2.5.Ti=Have Made Limitations (optional):

Annex.2.2.6.Ti=Choice of Law (optional)

Annex.2.2.6.sec=City_____________, State_____________

Annex.2.2.7.Ti=Choice of Venue (optional)

Annex.2.2.7.sec=City_____________, State_____________

Annex.2.2.8.Ti={_Territory} (Optional)

Annex.2.2.8.Ti=Offer Limitations (Optional)

Annex.2.2.=[G/Z/ol/8]

Annex.2.=[G/AgtForm/US/Frame/Licensor-Licensee/0.md]

Annex.2.=[G/Z/ol/2]

_Agreement=Agreement

_Field_of_Use=Field of Use

_License_Data_Record=License Data Record

_Licensed_Patent_Right=Licensed Patent Right

_Licensed_Patent_Rights=Licensed Patent Rights

_Licensed_Process=Licensed Process

_Licensed_Processes=Licensed Processes

_Licensed_Product=Licensed Product

_Licensed_Products=Licensed Products

_Licensee=Licensee

_Licensor=Licensor

_Mark=Mark

_Marks=Marks

_Necessary_Patent_Claim=Necessary Patent Claim

_Necessary_Patent_Claims=Necessary Patent Claims

_Specification=Specification

_Term=Term

_Territory=Territory

Def.Agreement.sec={_Agreement}

Def.Licensee.sec={_Licensee}

Def.Licensor.sec={_Licensor}

Def.Mark.sec={_Mark}

Grant.2.Xnum={Grant.Xnum}.2

Grant.Xnum=2

Fee.Xnum=3

Report.Xnum=4

Term.Xnum=5

Rep.Xnum=6

Indemnify.Xnum=7

Trademark.Xnum=8

Misc.Xnum=9


text:
=begin

Copyright 2012-2013 inBloom, Inc. and its affiliates.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=end

require 'mongo'
require_relative '../../utils/sli_utils.rb'

Given /^Another user has authenticated to SLI previously$/ do
  # This should be done as part of the Rake task config
end

When /^I access the API resource "([^"]*)" with no authorization headers present$/ do |arg1|
  url = Property['api_server_url']+"/api/rest"+arg1
  @res = RestClient.get(url){|response, request, result| response }
end

Then /^I should see a message that I am forbidden$/ do
  assertWithWait("Could not find Not Authorized in page title")  {@driver.page_source.index("error")!= nil}
end

Then /^I should see a message that I am an invalid user$/ do
  assertWithWait("Could not find Invalid Username or password in page title")  {@driver.page_source.index("error")!= nil}
end

When /^I have a _tla cookie set to an expired session$/ do

    #Need to be at a page in the domain before we can set a cookie.  Should take us to a 404 page within the db
    url = Property['databrowser_server_url']+"/sadfasdf/sadfadsfa"

    @driver.get(url)
    @driver.manage.add_cookie(:name => '_tla', :value => 'badbada5-9d81-8c1f-f91a-1fc23a1e6a79')
    @driver.manage.all_cookies.each { |cookie| puts "#{cookie[:name]} => #{cookie[:value]}" }
end

When /^I remember the _tla cookie value$/ do
  @user_sessions ||= []
  @driver.manage.all_cookies.select {|cookie| cookie[:name] == '_tla' }.each { |tla_cookie| @user_sessions << tla_cookie[:value] }
end

When /^I clear all session cookies$/ do
  @driver.manage.delete_all_cookies
end

When /^I logout of the databrowser$/ do
  url = Property['databrowser_server_url'] + "/entities/system/session/logout"
  @driver.get(url)
end

Then /^I should see that both sessions have been removed from the userSession collection$/ do
  assert(!@user_sessions.nil? && @user_sessions.size != 0, "Need user sessions to actually look up: #{@user_sessions}.")
  conn = Mongo::Connection.new("localhost", 27017)
  sli  = conn.db("sli")
  sessions = sli.collection('userSession').find({"_id" => {"$in" => @user_sessions}})
  assert(sessions.count == 0, "User sessions weren't cleared. Expected: 0, received: #{sessions.count} from #{@user_sessions}.")
end


text:
namespace SpirvNet.Spirv.Ops.Primitive
{
    public abstract class PrimitiveInstruction : Instruction
    {
        // intentionally empty
    }
}


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

<TITLE>
NotFilter
</TITLE>

<META NAME="date" CONTENT="2013-01-10">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.ivy.osgi.obr.filter

Class NotFilter

java.lang.Object
  org.apache.ivy.osgi.obr.xml.RequirementFilter
      org.apache.ivy.osgi.obr.filter.UniOperatorFilter
          org.apache.ivy.osgi.obr.filter.NotFilter

public class NotFilter
extends UniOperatorFilter

Constructor Summary

NotFilter(RequirementFilter subFilter)

Method Summary

protected  char
operator()

Methods inherited from class org.apache.ivy.osgi.obr.filter.UniOperatorFilter

append, equals, getSubFilter, hashCode

Methods inherited from class org.apache.ivy.osgi.obr.xml.RequirementFilter

toString

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

NotFilter

public NotFilter(RequirementFilter subFilter)

Method Detail

operator

protected char operator()

Specified by:
operator in class UniOperatorFilter

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
/**
 * Created by xiangwang on 12/9/16.
 */
(function () {
    'use strict';

    angular
        .module('studentDiscount')
        .service('MapService', MapService);

    MapService.$inject = ['NYU_CENTER', 'WINDOW_SIZE'];

    /* @ngInject */
    function MapService(NYU_CENTER, WINDOW_SIZE) {
        var MapService = this;
        var centerData = {
            nyuCenter: {
                pos: new google.maps.LatLng(NYU_CENTER.latitude, NYU_CENTER.longitude),
                name: "NYU Center"
            },

            userCenter: {
                pos: new google.maps.LatLng(NYU_CENTER.latitude, NYU_CENTER.longitude),
                name: "User Center"
            }
        };

        MapService.centerData = centerData;

        MapService.getCachedMap = getCachedMap;
        MapService.initPlaceMarkers = initPlaceMarkers;

        MapService.filterPlaceMarkers = filterPlaceMarkers;
        MapService.setCenter = setCenter;
        MapService.updateUserPosition = updateUserPosition;
        MapService.triggerMarker = triggerMarker;

        ////////////////
        var cached_map;
        var infoWindow;
        var markerMap = {};
        var userMarker;

        function getCachedMap() {
            if (!cached_map) {
                var mapCover = angular.element(document.getElementById("google-map"))[0];
                mapCover.style.height = 0.85 * WINDOW_SIZE.height + "px";
                mapCover.style.width = 0.9 * WINDOW_SIZE.width + "px";
                var mapProp = {
                    center: centerData.nyuCenter.pos,
                    zoom: 15,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    scaleControl: true
                };
                cached_map = new google.maps.Map(document.getElementById("google-map"), mapProp);
                // User marker
                var userImage = {
                    url: 'images/bluebubble.png', // This marker is 20 pixels wide by 32 pixels high.
                    size: new google.maps.Size(64, 64), // The origin for this image is (0, 0).
                    origin: new google.maps.Point(0, 0), // The anchor for this image is the base of the flagpole at (0, 32).
                    anchor: new google.maps.Point(0, 32), scaledSize: new google.maps.Size(45, 45)
                };
                userMarker = new google.maps.Marker({
                    position: centerData.userCenter.pos, icon: userImage
                });
                userMarker.setMap(cached_map);
                google.maps.event.addListener(cached_map, 'click', function () {
                    if (infoWindow != null) {
                        infoWindow.close();
                    }
                });
            }
            return cached_map;
        }

        function initPlaceMarkers(placeList) {
            for (var id in markerMap) {
                markerMap[id].setMap(null);
            }
            for (var i in placeList) {
                var place = placeList[i];
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(parseFloat(place.latitude), parseFloat(place.longitude)),
                    data: place,
                    icon: 'images/map/' + place.category + '.png'
                });
                marker.setMap(cached_map);
                google.maps.event.addListener(marker, 'click', function () {
                    if (infoWindow) {
                        infoWindow.close();
                    }
                    cached_map.setZoom(17);
                    cached_map.panTo(this.getPosition());
                    infoWindow = new google.maps.InfoWindow({
                        content: ''
                        + '
'
                        + '
'
                        + '         ' + this.data.place_name + ''
                        + '
'
                        + '
'
                        + '         '
                        + '
Discount :  ' + this.data.discount_percent + '
'
                        + '
Require :  ' + this.data.discount_detail + '
'
                        + '
Category :  ' + this.data.category + '
'
                        + '
Address :  ' + this.data.address + '
'
                        + (this.data.google_place_url ? ('
To Google Place
') : '')
                        + (this.data.web_url ? ('
To Website
') : '')
                        + '
'

                        + '
',
                        maxWidth: 1000
                    });
                    infoWindow.open(cached_map, this);
                });
                google.maps.event.addListener(marker, 'visible_changed', function () {
                });
                markerMap[marker.data.place_id] = marker;
            }
        }

        function triggerMarker(idFilter) {
            if (markerMap[idFilter]) {
                google.maps.event.trigger(markerMap[idFilter], 'click');
            }
        }

        function filterPlaceMarkers(categoryFilter, searchFilter) {
            for (var key in markerMap) {
                if (
                    (categoryFilter && (markerMap[key].data.category != categoryFilter))
                    || (searchFilter && (JSON.stringify(markerMap[key].data).indexOf(searchFilter) == -1))
                ) {
                    markerMap[key].setVisible(false);
                } else {
                    markerMap[key].setVisible(true);
                }
            }
        }

        function setCenter(centerPosistion) {
            cached_map.panTo(centerPosistion);
            cached_map.setZoom(15);
        }

        function updateUserPosition(pos) {
            centerData.userCenter.pos = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
            userMarker.setPosition(centerData.userCenter.pos);
        }
    }

})();


text:
package br.mil.mar.casnav.mclm.misc;

import br.mil.mar.casnav.mclm.persistence.entity.DataLayer;
import br.mil.mar.casnav.mclm.persistence.entity.Feicao;
import br.mil.mar.casnav.mclm.persistence.entity.SceneryNode;
import br.mil.mar.casnav.mclm.persistence.services.DataLayerService;

/*
 * Se mexer nesta estrutura, altere tamb�m
 * em TreeNode
 *
 */
public class SceneryTreeNode {
	// Especifico do TreePanel
	private String id;
	private boolean leaf;
	private String Cls;
	private boolean checked;
	private String text;
	private String iconCls;
	// -----------------------

	private int idSceneryNode;
	private int idNodeParent;
	private int indexOrder;
	private int idNodeData;
	private int idDataWindow;
	private String layerType;
	private String serviceUrl;
	private String originalServiceUrl;
	private String description;
	private String institute;
	private String layerName;
	private String layerAlias;
	private String serialId;
	private String referenceLayerSerial;
	private boolean readOnly;
	private boolean selected;
	private int layerStackIndex;
	private int transparency;
	private DataLayer dataLayer;
	private Feicao feicao;

	public SceneryTreeNode( SceneryNode sn, DataLayerService dss ) {
		this.idSceneryNode = sn.getIdSceneryNode();
		this.idNodeParent = sn.getIdNodeParent();
		this.indexOrder = sn.getIndexOrder();
		this.layerType = sn.getLayerType().toString();
		this.layerAlias = sn.getLayerAlias();
		this.readOnly = false;
		this.layerStackIndex = sn.getLayerStackIndex();
		this.transparency = sn.getTransparency();
		this.checked = sn.isSelected();
		this.selected = sn.isSelected();

		if ( sn.getLayer() != null ) {
			this.serviceUrl = sn.getLayer().getServiceUrl();
			this.originalServiceUrl = sn.getLayer().getOriginalServiceUrl();
			this.description = sn.getLayer().getDescription();
			this.institute = sn.getLayer().getInstitute();
			this.layerName = sn.getLayer().getLayerName();
			this.serialId = sn.getLayer().getSerialId();
			this.idNodeData = sn.getLayer().getIdNodeData();

			try {
				this.idDataWindow = sn.getLayer().getDataWindow().getIdDataWindow();
			} catch ( Exception ignored ) {
				this.idDataWindow = -1;
			}

		} else {
			// Não pode ser "null" porque a conversão para JSON vai omitir o atributo.
			this.serviceUrl = "";
			this.originalServiceUrl = "";
			this.description = "";
			this.institute = "";
			this.layerName = "";
			this.serialId = "";
		}

		// Precisa para ser compativel com o TreeNode do ExtJS
		this.id = String.valueOf( sn.getId() );
		this.text = this.layerAlias;

		if ( ( this.layerName == null || this.layerName.equals("") ) && ( !this.layerType.equals("TXT") ) ) {
			this.leaf = false;
		} else {
			this.leaf = true;
			if ( this.layerType.equals("KML") ) this.iconCls = "kml-icon";
			if ( this.layerType.equals("WMS") ) this.iconCls = "wms-icon";
			if ( this.layerType.equals("SHP") ) this.iconCls = "shp-icon";
			if ( this.layerType.equals("TIF") ) this.iconCls = "tif-icon";
			if ( this.layerType.equals("TXT") ) this.iconCls = "text-icon";

			if ( this.layerType.equals("FEI") ) {
				try {
					this.feicao = sn.getLayer().getFeicao();
				} catch ( Exception e ) {
					e.printStackTrace();
				}
				this.iconCls = "fei-icon";
			}

			if ( this.layerType.equals("DTA") ) {

				try {
					dss.newTransaction();
					String[] dssData = this.layerName.split(":");
					Integer idDataLayer = Integer.valueOf( dssData[1] );
					this.dataLayer = dss.getDataLayer( idDataLayer );
				} catch ( Exception e ) {
					//
				}
				this.iconCls = "cube-icon";

			}

		}

	}

	public int getIdSceneryNode() {
		return idSceneryNode;
	}

	public int getIdNodeParent() {
		return idNodeParent;
	}

	public int getIndexOrder() {
		return indexOrder;
	}

	public String getLayerType() {
		return layerType;
	}

	public String getServiceUrl() {
		return serviceUrl;
	}

	public String getOriginalServiceUrl() {
		return originalServiceUrl;
	}

	public String getDescription() {
		return description;
	}

	public String getInstitute() {
		return institute;
	}

	public String getLayerName() {
		return layerName;
	}

	public String getLayerAlias() {
		return layerAlias;
	}

	public String getSerialId() {
		return serialId;
	}

	public String getReferenceLayerSerial() {
		return referenceLayerSerial;
	}

	public boolean isReadOnly() {
		return readOnly;
	}

	public int getLayerStackIndex() {
		return layerStackIndex;
	}

	public int getTransparency() {
		return transparency;
	}

	public String getId() {
		return id;
	}

	public boolean isLeaf() {
		return leaf;
	}

	public String getCls() {
		return Cls;
	}

	public boolean isChecked() {
		return checked;
	}

	public String getText() {
		return text;
	}

	public String getIconCls() {
		return iconCls;
	}

	public boolean isSelected() {
		return selected;
	}

	public DataLayer getDataLayer() {
		return dataLayer;
	}

	public Feicao getFeicao() {
		return feicao;
	}

	public int getIdNodeData() {
		return idNodeData;
	}

	public int getIdDataWindow() {
		return idDataWindow;
	}

}


text:
set -v
phpdoc -p on -t doc -d Auth,admin/tutorials -ti "JanRain OpenID Library" \
    --ignore \*~,BigMath.php,Discover.php,CryptUtil.php,DiffieHellman.php,HMACSHA1.php,KVForm.php,Parse.php,TrustRoot.php,HTTPFetcher.php,ParanoidHTTPFetcher.php,PlainHTTPFetcher.php,ParseHTML.php,URINorm.php,XRI.php,XRIRes.php,Misc.php \
    -dn "OpenID" -o "HTML:frames:phphtmllib"


text:
local crypto       =  require("crypto")
local crypto_hmac  =  require("crypto.hmac")

-- obtain a copy of enc() here: http://lua-users.org/wiki/BaseSixtyFour
function enc(data)
    -- character table string
    local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    return ((data:gsub('.', function(x)
        local r,b='',x:byte()
        for i=8,1,-1 do
            r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0')
        end
        return r;
    end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
        if (#x < 6) then return '' end
        local c=0
        for i=1,6 do
            c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0)
        end
        return b:sub(c+1,c+1)
    end)..({ '', '==', '=' })[#data%3+1])
end

local ok, new_tab = pcall(require, "table.new")
if not ok then
    new_tab = function (narr, nrec) return {} end
end

local _M = new_tab(0, 155)
_M._VERSION = '0.01'

local hash_algorithms = {
    md5 = 1, md4 = 1, md2 = 1, sha1 = 1, sha = 1, mdc2 = 1, ripemd160 = 1
}

local months = {Jan = 1,Feb = 2,Mar = 3,Apr = 4, May = 5, Jun = 6,
                Jul = 7,Aug = 8,Sep = 9,Oct = 10,Nov = 11,Dec = 12}

local mt = { __index = _M }

function _M.new(self, secret)
    local secret = secret
    if not secret then
        return nil, "must provide secret"
    end
    return setmetatable({ secret = secret }, mt)
end

function _M.generate_signature(self, dtype, message, delimiter)
    local secret = self.secret
    if not secret then
        return nil, "not initialized"
    end

    if type(dtype) ~= "string" or not hash_algorithms[dtype] then
        dtype = "sha1"
    end

    if type(delimiter) ~= "string" then
        delimiter = string.char(10)
    end

    local StringToSign = ""

    if type(message) == "table" then
        for k, v in pairs(message) do
            StringToSign = StringToSign..v..(k ~= #message and delimiter or "")
        end
    elseif type(message) == "string" then
        StringToSign = message
    else
        return nil, "invalid message"
    end

    local sig_hmac  =  crypto_hmac.digest(dtype, StringToSign, secret, true)
    local signature  =  enc(sig_hmac)

    self.StringToSign = StringToSign
    self.sig_hmac = sig_hmac
    self.signature = signature

    return signature
end

function _M.check_signature(self, dtype, message, delimiter, signature)
    local secret = self.secret
    if not secret then
        return nil, "not initialized"
    end

    local new_signature, err = self:generate_signature(dtype, message, delimiter)
    if not new_signature then
        return new_signature, err
    end

    local correct = (new_signature == signature)

    return correct, (correct and "signature matches" or "not a match")
end

function _M.generate_headers(self, service, id, dtype, message, delimiter)
    local secret = self.secret
    if not secret then
        return nil, "not initialized"
    end

    local signature = self.signature
    if not signature then
        signature, err = self:generate_signature(dtype, message, delimiter)
        if signature then
            self.signature = signature
        else
            return nil, err
        end
    end

    if type(service) ~= "string" then
        service = "AWS"
    end

    if type(id) ~= "string" then
        return nil, "no id provided"
    end

    local date = os.date("!%a, %d %b %Y %H:%M:%S +0000")
    local auth = service.." "..id..":"..signature

    self.date = date
    self.auth = auth

    return {date = date, auth = auth}
end

function _M.check_headers(self, service, id, dtype, message, delimiter, max_time_diff)
    local request_headers = ngx.req.get_headers()
    local authorization = request_headers.authorization
    local date2 = request_headers.date

    if not authorization or not date2 then
        return nil, "missing headers"
    end

    local req_service,req_id,req_signature = authorization:match("(%S+) (%S+):(%S+)")

    if req_service ~= service or req_id ~= id then
        return nil, "incorrect authorization"
    end

    local day, month, year, hour, minute, second =
          date2:match("%a+, (%d+) (%a+) (%d+) (%d+):(%d+):(%d+)")
    month = months[month]

    local date1 = os.date("!*t")
    date1.isdst = nil
    local timestamp1 = os.time(date1)
    local timestamp2 = os.time({month = month,   year = year,
                                day   = day,     hour = hour,
                                min   = minute,  sec  = second})

    if type(max_time_diff) ~= "number" then
        max_time_diff  =  300 -- 5 minutes
    end

    if (timestamp2 - timestamp1) > max_time_diff then
        return nil, "time difference too great"
    end

    signature, err = self:check_signature(dtype, message, delimiter, req_signature)
    if not signature then
        return signature, err
    end

    return true
end

return _M


text:
using System.Threading.Tasks;

namespace AsyncConverter.Tests.Test.Data.FixReturnValueToTaskTests
{
    public class Class
    {
        public async Task TestAsync()
        {
            await Foo().ConfigureAwait(false);
            async Task Foo() => {caret}await Task.Delay(1000).ConfigureAwait(false);
        }
    }
}


text:
{-# LANGUAGE DeriveAnyClass  #-}
{-# LANGUAGE RecordWildCards #-}

{-# OPTIONS_GHC -Wno-redundant-constraints #-} -- for the Getter instances

module Pos.Chain.Block.Header
       ( BlockHeader (..)
       , blockHeaderProtocolMagicId
       , blockHeaderHash
       , choosingBlockHeader
       , _BlockHeaderGenesis
       , _BlockHeaderMain
       , verifyBlockHeader
       , headerLeaderKey
       , headerLastSlotInfo

       , HeaderHash
       , headerHashF
       , headerHashG

       , HasHeaderHash (..)

       , BlockSignature (..)

       , GenericBlockHeader
       , mkGenericBlockHeaderUnsafe
       , gbhProtocolMagicId
       , gbhPrevBlock
       , gbhBodyProof
       , gbhConsensus
       , gbhExtra

       , GenesisBlockHeader
       , mkGenesisHeader
       , genHeaderPrevBlock
       , genHeaderProof
       , genHeaderEpoch
       , genHeaderDifficulty
       , genHeaderAttributes

       , MainBlockHeader
       , mkMainHeader
       , mkMainHeaderExplicit
       , mainHeaderPrevBlock
       , mainHeaderProof
       , mainHeaderSlot
       , mainHeaderLeaderKey
       , mainHeaderDifficulty
       , mainHeaderSignature
       , mainHeaderBlockVersion
       , mainHeaderSoftwareVersion
       , mainHeaderAttributes
       , mainHeaderEBDataProof
       , verifyMainBlockHeader

       , MainToSign (..)
       , msHeaderHash
       , msBodyProof
       , msSlot
       , msChainDiff
       , msExtraHeader

       , MainConsensusData (..)
       , mcdSlot
       , mcdLeaderKey
       , mcdDifficulty
       , mcdSignature
       , verifyMainConsensusData
       ) where

import           Universum

import           Codec.CBOR.Decoding (decodeWordCanonical)
import           Codec.CBOR.Encoding (encodeWord)
import           Control.Lens (Getter, LensLike', makeLenses, makePrisms, to)
import           Control.Monad.Except (MonadError (throwError))
import           Data.SafeCopy (SafeCopy (..), contain, safeGet, safePut)
import qualified Data.Serialize as Cereal
import           Formatting (Format, bprint, build, int, (%))
import qualified Formatting.Buildable as Buildable

import           Pos.Binary.Class (Bi (..), decodeListLenCanonicalOf,
                     encodeListLen, enforceSize)
import           Pos.Chain.Block.Genesis (GenesisBody,
                     GenesisConsensusData (..), GenesisExtraHeaderData (..),
                     GenesisHeaderAttributes, GenesisProof (..), gcdDifficulty,
                     gcdEpoch, gehAttributes, mkGenesisProof)
import           Pos.Chain.Block.Main (BlockHeaderAttributes, MainBody,
                     MainExtraBodyData, MainExtraHeaderData, MainProof (..),
                     mehAttributes, mehBlockVersion, mehEBDataProof,
                     mehSoftwareVersion, mkMainProof,
                     verifyMainExtraHeaderData)
import           Pos.Chain.Delegation.HeavyDlgIndex (ProxySKBlockInfo,
                     ProxySigHeavy)
import           Pos.Chain.Delegation.LightDlgIndices (LightDlgIndices (..),
                     ProxySigLight)
import           Pos.Chain.Genesis.Hash (GenesisHash (..))
import           Pos.Chain.Update.BlockVersion (BlockVersion,
                     HasBlockVersion (..))
import           Pos.Chain.Update.SoftwareVersion (HasSoftwareVersion (..),
                     SoftwareVersion)
import           Pos.Core.Attributes (mkAttributes)
import           Pos.Core.Common (ChainDifficulty, HasDifficulty (..),
                     addressHash)
import           Pos.Core.Slotting (EpochIndex (..), EpochOrSlot (..),
                     HasEpochIndex (..), HasEpochOrSlot (..), SlotCount (..),
                     SlotId (..), flattenSlotId, slotIdF)
import           Pos.Crypto (Hash, ProtocolMagic (..), ProtocolMagicId (..),
                     PublicKey, SecretKey, SignTag (..), Signature, checkSig,
                     hashHexF, isSelfSignedPsk, proxySign, proxyVerify,
                     psigPsk, sign, toPublic, unsafeHash)
import           Pos.Util.Some (Some, applySome)
import           Pos.Util.Util (cborError, cerealError)

import           Pos.Chain.Block.Slog.Types (LastSlotInfo (..))

--------------------------------------------------------------------------------
-- GenesisBlock ∪ MainBlock
--------------------------------------------------------------------------------

-- | Either header of ordinary main block or genesis block.
data BlockHeader
    = BlockHeaderGenesis GenesisBlockHeader
    | BlockHeaderMain MainBlockHeader
    deriving (Eq, Show, Generic, NFData)

instance Buildable BlockHeader where
    build = \case
        BlockHeaderGenesis bhg -> Buildable.build bhg
        BlockHeaderMain    bhm -> Buildable.build bhm

instance HasDifficulty BlockHeader where
    difficultyL = choosingBlockHeader difficultyL difficultyL

instance HasEpochIndex BlockHeader where
    epochIndexL = choosingBlockHeader epochIndexL epochIndexL

instance HasEpochOrSlot BlockHeader where
    getEpochOrSlot = view (choosingBlockHeader (to getEpochOrSlot) (to getEpochOrSlot))

choosingBlockHeader
    :: Functor f
    => LensLike' f GenesisBlockHeader r
    -> LensLike' f MainBlockHeader r
    -> LensLike' f BlockHeader r
choosingBlockHeader onGenesis onMain f = \case
    BlockHeaderGenesis bh -> BlockHeaderGenesis <$> onGenesis f bh
    BlockHeaderMain bh -> BlockHeaderMain <$> onMain f bh

instance Bi BlockHeader where
   encode x = encodeListLen 2 <> encodeWord tag <> body
     where
       (tag, body) = case x of
         BlockHeaderGenesis bh -> (0, encode bh)
         BlockHeaderMain bh    -> (1, encode bh)

   decode = do
       decodeListLenCanonicalOf 2
       t <- decodeWordCanonical
       case t of
           0 -> BlockHeaderGenesis <$!> decode
           1 -> BlockHeaderMain <$!> decode
           _ -> cborError $ "decode@BlockHeader: unknown tag " <> pretty t

-- | The 'ProtocolMagic' in a 'BlockHeader'.
blockHeaderProtocolMagicId :: BlockHeader -> ProtocolMagicId
blockHeaderProtocolMagicId (BlockHeaderGenesis gbh) = _gbhProtocolMagicId gbh
blockHeaderProtocolMagicId (BlockHeaderMain mbh)    = _gbhProtocolMagicId mbh

-- | Verify a BlockHeader in isolation. There is nothing to be done for
-- genesis headers.
verifyBlockHeader
    :: MonadError Text m
    => ProtocolMagic
    -> BlockHeader
    -> m ()
verifyBlockHeader _ (BlockHeaderGenesis _) = pure ()
verifyBlockHeader pm (BlockHeaderMain bhm) = verifyMainBlockHeader pm bhm

headerLastSlotInfo :: SlotCount -> BlockHeader -> Maybe LastSlotInfo
headerLastSlotInfo slotCount = \case
    BlockHeaderGenesis _ -> Nothing
    BlockHeaderMain mbh -> Just $ convert mbh
  where
    convert :: MainBlockHeader -> LastSlotInfo
    convert bh =
        LastSlotInfo
            (flattenSlotId slotCount . _mcdSlot $ _gbhConsensus bh)
            -- Since _mcdLeaderKey is confirmed (see comment in function
            -- `mkMainHeaderExplicit`) to be the delegator's key, we will be
            -- enforcing block-minting-count thresholds by the delegator's key,
            -- which is the desired behavior.
            (addressHash . _mcdLeaderKey $ _gbhConsensus bh)

--------------------------------------------------------------------------------
-- HeaderHash
--------------------------------------------------------------------------------

-- | 'Hash' of block header.
type HeaderHash = Hash BlockHeader

-- | Specialized formatter for 'HeaderHash'.
headerHashF :: Format r (HeaderHash -> r)
headerHashF = build

-- HasHeaderHash
class HasHeaderHash a where
    headerHash :: a -> HeaderHash

instance HasHeaderHash HeaderHash where
    headerHash = identity

instance HasHeaderHash (Some HasHeaderHash) where
    headerHash = applySome headerHash

instance HasHeaderHash BlockHeader where
    headerHash = blockHeaderHash

instance HasHeaderHash GenesisBlockHeader where
    headerHash = blockHeaderHash . BlockHeaderGenesis

instance HasHeaderHash MainBlockHeader where
    headerHash = blockHeaderHash . BlockHeaderMain

headerHashG :: HasHeaderHash a => Getter a HeaderHash
headerHashG = to headerHash

-- | This function is required because type inference fails in attempts to
-- hash only @Right@ or @Left@.
--
-- Perhaps, it shouldn't be here, but I decided not to create a module
-- for only this function.
blockHeaderHash :: BlockHeader -> HeaderHash
blockHeaderHash = unsafeHash

--------------------------------------------------------------------------------
-- GenericBlockHeader
--------------------------------------------------------------------------------

-- | Header of block contains some kind of summary. There are various
-- benefits which people get by separating header from other data.
--
-- The constructor has `Unsafe' prefix in its name, because there in
-- general there may be some invariants which must hold for the
-- contents of header.
data GenericBlockHeader bodyProof consensus extra = GenericBlockHeader
    { _gbhProtocolMagicId :: !ProtocolMagicId
      -- | Pointer to the header of the previous block.
    , _gbhPrevBlock       :: !HeaderHash
    , -- | Proof of body.
      _gbhBodyProof       :: !bodyProof
    , -- | Consensus data to verify consensus algorithm.
      _gbhConsensus       :: !consensus
    , -- | Any extra data.
      _gbhExtra           :: !extra
    } deriving (Eq, Show, Generic, NFData)

instance
    (Bi bodyProof, Bi consensus, Bi extra)
    => Bi (GenericBlockHeader bodyProof consensus extra)
  where
    encode bh =  encodeListLen 5
              <> encode (unProtocolMagicId (_gbhProtocolMagicId bh))
              <> encode (_gbhPrevBlock bh)
              <> encode (_gbhBodyProof bh)
              <> encode (_gbhConsensus bh)
              <> encode (_gbhExtra bh)
    decode = do
        enforceSize "GenericBlockHeader b" 5
        _gbhProtocolMagicId <- ProtocolMagicId <$> decode
        _gbhPrevBlock <- decode
        _gbhBodyProof <- decode
        _gbhConsensus <- decode
        _gbhExtra     <- decode
        pure GenericBlockHeader {..}

instance
    (SafeCopy bodyProof, SafeCopy consensus, SafeCopy extra)
    => SafeCopy (GenericBlockHeader bodyProof consensus extra)
  where
    getCopy =
        contain $
        do _gbhProtocolMagicId <- safeGet
           _gbhPrevBlock <- safeGet
           _gbhBodyProof <- safeGet
           _gbhConsensus <- safeGet
           _gbhExtra <- safeGet
           return $! GenericBlockHeader {..}
    putCopy GenericBlockHeader {..} =
        contain $
        do safePut _gbhProtocolMagicId
           safePut _gbhPrevBlock
           safePut _gbhBodyProof
           safePut _gbhConsensus
           safePut _gbhExtra

-- | Export the @GenericBlockHeader@ constructor as an unsafe function for tests
mkGenericBlockHeaderUnsafe
    :: ProtocolMagic
    -> HeaderHash
    -> bodyProof
    -> consensus
    -> extra
    -> GenericBlockHeader bodyProof consensus extra
mkGenericBlockHeaderUnsafe pm = GenericBlockHeader pmi
  where
    pmi = getProtocolMagicId pm

--------------------------------------------------------------------------------
-- GenesisBlockHeader
--------------------------------------------------------------------------------

-- | Header of Genesis block.
type GenesisBlockHeader = GenericBlockHeader
    GenesisProof
    GenesisConsensusData
    GenesisExtraHeaderData

instance Buildable GenesisBlockHeader where
    build gbh@GenericBlockHeader {..} =
        bprint
            ("GenesisBlockHeader:\n"%
             "    hash: "%hashHexF%"\n"%
             "    previous block: "%hashHexF%"\n"%
             "    epoch: "%build%"\n"%
             "    difficulty: "%int%"\n"
            )
            gbhHeaderHash
            _gbhPrevBlock
            _gcdEpoch
            _gcdDifficulty
      where
        gbhHeaderHash :: HeaderHash
        gbhHeaderHash = blockHeaderHash $ BlockHeaderGenesis gbh
        GenesisConsensusData {..} = _gbhConsensus

instance HasEpochOrSlot GenesisBlockHeader where
    getEpochOrSlot = EpochOrSlot . Left . _gcdEpoch . _gbhConsensus

-- | Smart constructor for 'GenesisBlockHeader'
mkGenesisHeader
    :: ProtocolMagic
    -> Either GenesisHash BlockHeader
    -> EpochIndex
    -> GenesisBody
    -> GenesisBlockHeader
mkGenesisHeader pm prevHeader epoch body =
    GenericBlockHeader
        pmi
        (either getGenesisHash headerHash prevHeader)
        (mkGenesisProof body)
        consensus
        (GenesisExtraHeaderData $ mkAttributes ())
  where
    pmi = getProtocolMagicId pm
    difficulty = either (const 0) (view difficultyL) prevHeader
    consensus = GenesisConsensusData {_gcdEpoch = epoch, _gcdDifficulty = difficulty}

--------------------------------------------------------------------------------
-- MainBlockHeader
--------------------------------------------------------------------------------

-- | Header of generic main block.
type MainBlockHeader =
    GenericBlockHeader MainProof MainConsensusData MainExtraHeaderData

instance Buildable MainBlockHeader where
    build gbh@GenericBlockHeader {..} =
        bprint
            ("MainBlockHeader:\n"%
             "    hash: "%hashHexF%"\n"%
             "    previous block: "%hashHexF%"\n"%
             "    slot: "%slotIdF%"\n"%
             "    difficulty: "%int%"\n"%
             "    leader: "%build%"\n"%
             "    signature: "%build%"\n"%
             build
            )
            gbhHeaderHash
            _gbhPrevBlock
            _mcdSlot
            _mcdDifficulty
            _mcdLeaderKey
            _mcdSignature
            _gbhExtra
      where
        gbhHeaderHash :: HeaderHash
        gbhHeaderHash = blockHeaderHash $ BlockHeaderMain gbh
        MainConsensusData {..} = _gbhConsensus

-- | Smart constructor for 'MainBlockHeader'.
mkMainHeader
    :: ProtocolMagic
    -> Either GenesisHash BlockHeader
    -> SlotId
    -> SecretKey
    -> ProxySKBlockInfo
    -> MainBody
    -> MainExtraHeaderData
    -> MainBlockHeader
mkMainHeader pm prevHeader =
    mkMainHeaderExplicit pm prevHash difficulty
  where
    prevHash = either getGenesisHash headerHash prevHeader
    difficulty = either (const 0) (succ . view difficultyL) prevHeader

-- | Make a 'MainBlockHeader' for a given slot, with a given body, parent hash,
-- and difficulty. This takes care of some signing and consensus data.
mkMainHeaderExplicit
    :: ProtocolMagic
    -> HeaderHash -- ^ Parent
    -> ChainDifficulty
    -> SlotId
    -> SecretKey
    -> ProxySKBlockInfo
    -> MainBody
    -> MainExtraHeaderData
    -> MainBlockHeader
mkMainHeaderExplicit pm prevHash difficulty slotId sk pske body extra =
    GenericBlockHeader pmi prevHash proof consensus extra
  where
    pmi = getProtocolMagicId pm
    proof = mkMainProof body
    makeSignature toSign (psk,_) =
        BlockPSignatureHeavy $ proxySign pm SignMainBlockHeavy sk psk toSign
    signature =
        let toSign = MainToSign prevHash proof slotId difficulty extra
        in maybe
               (BlockSignature $ sign pm SignMainBlock sk toSign)
               (makeSignature toSign)
               pske
    -- If `pske :: ProxySKBlockInfo` is Just, indicating delegation, we use
    -- the PublicKey of the delegator (in Original era, this is the Stakeholder
    -- whose stake was selected by FTS. In OBFT era, this is the Genesis
    -- Stakeholder, selected via round-robin. In both cases, the delegator is
    -- delegating the right to mint a block to the delegatee).
    --
    -- If `pske :: ProxySKBlockInfo` is Nothing, we use `toPublic` of the `sk`
    -- provided, which should be provided by the node issuing the block who was
    -- thus selected themselves. See `db/src/Pos/DB/Block/Logic/Creation.hs`
    -- for the top of the function call chain which provides the `sk` which
    -- makes its way down to here.
    leaderPk = maybe (toPublic sk) snd pske
    consensus =
        MainConsensusData
        { _mcdSlot = slotId
        , _mcdLeaderKey = leaderPk
        , _mcdDifficulty = difficulty
        , _mcdSignature = signature
        }

-- | Verify a main block header in isolation.
verifyMainBlockHeader
    :: MonadError Text m
    => ProtocolMagic
    -> MainBlockHeader
    -> m ()
verifyMainBlockHeader pm GenericBlockHeader {..} = do
    -- Previous header hash is always valid.
    -- Body proof is just a bunch of hashes, which is always valid (although
    -- must be checked against the actual body, in verifyMainBlock.
    -- Consensus data and extra header data require validation.
    verifyMainConsensusData _gbhConsensus
    verifyMainExtraHeaderData _gbhExtra
    -- Internal consistency: is the signature in the consensus data really for
    -- this block?
    unless (verifyBlockSignature _mcdSignature) $
        throwError "can't verify signature"

  where

    verifyBlockSignature (BlockSignature sig) =
        checkSig pm SignMainBlock leaderPk signature sig
    verifyBlockSignature (BlockPSignatureLight proxySig) =
        proxyVerify
            pm
            SignMainBlockLight
            proxySig
            (\(LightDlgIndices (epochLow, epochHigh)) ->
                 epochLow <= epochId && epochId <= epochHigh)
            signature
    verifyBlockSignature (BlockPSignatureHeavy proxySig) =
        proxyVerify pm SignMainBlockHeavy proxySig (const True) signature
    signature = MainToSign _gbhPrevBlock _gbhBodyProof slotId difficulty _gbhExtra
    epochId = siEpoch slotId
    MainConsensusData
        { _mcdLeaderKey = leaderPk
        , _mcdSlot = slotId
        , _mcdDifficulty = difficulty
        , ..
        } = _gbhConsensus

--------------------------------------------------------------------------------
-- BlockSignature
--------------------------------------------------------------------------------

-- | Signature of the block. Can be either regular signature from the
-- issuer or delegated signature having a constraint on epoch indices
-- (it means the signature is valid only if block's slot id has epoch
-- inside the constrained interval).
data BlockSignature
    = BlockSignature (Signature MainToSign)
    | BlockPSignatureLight (ProxySigLight MainToSign)
    | BlockPSignatureHeavy (ProxySigHeavy MainToSign)
    deriving (Show, Eq, Generic)

instance NFData BlockSignature

instance Buildable BlockSignature where
    build (BlockSignature s)       = bprint ("BlockSignature: "%build) s
    build (BlockPSignatureLight s) = bprint ("BlockPSignatureLight: "%build) s
    build (BlockPSignatureHeavy s) = bprint ("BlockPSignatureHeavy: "%build) s

instance Bi BlockSignature where
    encode input = case input of
        BlockSignature sig       -> encodeListLen 2 <> encode (0 :: Word8) <> encode sig
        BlockPSignatureLight pxy -> encodeListLen 2 <> encode (1 :: Word8) <> encode pxy
        BlockPSignatureHeavy pxy -> encodeListLen 2 <> encode (2 :: Word8) <> encode pxy
    decode = do
        enforceSize "BlockSignature" 2
        tag <- decode @Word8
        case tag of
          0 -> BlockSignature <$> decode
          1 -> BlockPSignatureLight <$> decode
          2 -> BlockPSignatureHeavy <$> decode
          _ -> cborError $ "decode@BlockSignature: unknown tag: " <> show tag

instance SafeCopy BlockSignature where
    getCopy = contain $ Cereal.getWord8 >>= \case
        0 -> BlockSignature <$> safeGet
        1 -> BlockPSignatureLight <$> safeGet
        2 -> BlockPSignatureHeavy <$> safeGet
        t -> cerealError $ "getCopy@BlockSignature: couldn't read tag: " <> show t
    putCopy (BlockSignature sig)            = contain $ Cereal.putWord8 0 >> safePut sig
    putCopy (BlockPSignatureLight proxySig) = contain $ Cereal.putWord8 1 >> safePut proxySig
    putCopy (BlockPSignatureHeavy proxySig) = contain $ Cereal.putWord8 2 >> safePut proxySig

-- | Data to be signed in main block.
data MainToSign
    = MainToSign
    { _msHeaderHash  :: !HeaderHash  -- ^ Hash of previous header
                                     --    in the chain
    , _msBodyProof   :: !MainProof
    , _msSlot        :: !SlotId
    , _msChainDiff   :: !ChainDifficulty
    , _msExtraHeader :: !MainExtraHeaderData
    } deriving Generic

deriving instance Show MainToSign
deriving instance Eq MainToSign

instance Bi MainToSign where
    encode mts = encodeListLen 5
               <> encode (_msHeaderHash mts)
               <> encode (_msBodyProof mts)
               <> encode (_msSlot mts)
               <> encode (_msChainDiff mts)
               <> encode (_msExtraHeader mts)
    decode = do
        enforceSize "MainToSign" 5
        MainToSign <$> decode <*>
                          decode <*>
                          decode <*>
                          decode <*>
                          decode

--------------------------------------------------------------------------------
-- MainConsensusData
--------------------------------------------------------------------------------

data MainConsensusData = MainConsensusData
    { -- | Id of the slot for which this block was generated.
      _mcdSlot       :: !SlotId
    , -- | Public key of the slot leader. It's essential to have it here,
      -- because FTS gives us only hash of public key (aka 'StakeholderId').
      _mcdLeaderKey  :: !PublicKey
    , -- | Difficulty of chain ending in this block.
      _mcdDifficulty :: !ChainDifficulty
    , -- | Signature given by slot leader.
      _mcdSignature  :: !BlockSignature
    } deriving (Generic, Show, Eq)

instance NFData MainConsensusData

instance Bi MainConsensusData where
    encode cd =  encodeListLen 4
              <> encode (_mcdSlot cd)
              <> encode (_mcdLeaderKey cd)
              <> encode (_mcdDifficulty cd)
              <> encode (_mcdSignature cd)
    decode = do
        enforceSize "ConsensusData MainBlockchain)" 4
        MainConsensusData <$> decode <*>
                                 decode <*>
                                 decode <*>
                                 decode

instance SafeCopy MainConsensusData where
    getCopy =
        contain $
        do _mcdSlot <- safeGet
           _mcdLeaderKey <- safeGet
           _mcdDifficulty <- safeGet
           _mcdSignature <- safeGet
           return $! MainConsensusData {..}
    putCopy MainConsensusData {..} =
        contain $
        do safePut _mcdSlot
           safePut _mcdLeaderKey
           safePut _mcdDifficulty
           safePut _mcdSignature

-- | Verify the consensus data in isolation.
verifyMainConsensusData
    :: ( MonadError Text m )
    => MainConsensusData
    -> m ()
verifyMainConsensusData MainConsensusData {..} = do
    when (selfSignedProxy _mcdSignature) $
        throwError "can't use self-signed psk to issue the block"
  where
    selfSignedProxy (BlockSignature _)                      = False
    selfSignedProxy (BlockPSignatureLight (psigPsk -> psk)) = isSelfSignedPsk psk
    selfSignedProxy (BlockPSignatureHeavy (psigPsk -> psk)) = isSelfSignedPsk psk

--------------------------------------------------------------------------------
-- BlockHeaderGenesis prisms
--------------------------------------------------------------------------------

makePrisms 'BlockHeaderGenesis

--------------------------------------------------------------------------------
-- GenericBlockHeader Lenses
--------------------------------------------------------------------------------

makeLenses ''GenericBlockHeader

instance HasDifficulty GenesisBlockHeader where
    difficultyL = gbhConsensus . difficultyL

instance HasEpochIndex GenesisBlockHeader where
    epochIndexL = gbhConsensus . gcdEpoch

--------------------------------------------------------------------------------
-- MainConsensusData lenses
--------------------------------------------------------------------------------

makeLenses 'MainConsensusData

instance HasDifficulty MainConsensusData where
    difficultyL = mcdDifficulty

----------------------------------------------------------------------------
-- GenesisBlockHeader lenses
----------------------------------------------------------------------------

-- | Lens from 'GenesisBlockHeader' to 'HeaderHash' of its parent.
genHeaderPrevBlock :: Lens' GenesisBlockHeader HeaderHash
genHeaderPrevBlock = gbhPrevBlock

-- | Lens from 'GenesisBlockHeader' to 'GenesisProof'.
genHeaderProof :: Lens' GenesisBlockHeader GenesisProof
genHeaderProof = gbhBodyProof

-- | Lens from 'GenesisBlockHeader' to 'EpochIndex'.
genHeaderEpoch :: Lens' GenesisBlockHeader EpochIndex
genHeaderEpoch = gbhConsensus . gcdEpoch

-- | Lens from 'GenesisBlockHeader' to 'ChainDifficulty'.
genHeaderDifficulty :: Lens' GenesisBlockHeader ChainDifficulty
genHeaderDifficulty = gbhConsensus . gcdDifficulty

-- | Lens from 'GenesisBlockHeader' to 'GenesisHeaderAttributes'.
genHeaderAttributes :: Lens' GenesisBlockHeader GenesisHeaderAttributes
genHeaderAttributes = gbhExtra . gehAttributes

--------------------------------------------------------------------------------
-- MainBlockHeader lenses
--------------------------------------------------------------------------------

-- | Lens from 'MainBlockHeader' to 'HeaderHash' of its parent.
mainHeaderPrevBlock :: Lens' MainBlockHeader HeaderHash
mainHeaderPrevBlock = gbhPrevBlock

-- | Lens from 'MainBlockHeader' to 'MainProof'.
mainHeaderProof :: Lens' MainBlockHeader MainProof
mainHeaderProof = gbhBodyProof

-- | Lens from 'MainBlockHeader' to 'SlotId'.
mainHeaderSlot :: Lens' MainBlockHeader SlotId
mainHeaderSlot = gbhConsensus . mcdSlot

-- | Lens from 'MainBlockHeader' to 'PublicKey'.
mainHeaderLeaderKey :: Lens' MainBlockHeader PublicKey
mainHeaderLeaderKey = gbhConsensus . mcdLeaderKey

headerLeaderKey :: BlockHeader -> Maybe PublicKey
headerLeaderKey = \case
    BlockHeaderGenesis _ -> Nothing
    BlockHeaderMain mbh -> Just $ view mainHeaderLeaderKey mbh

-- | Lens from 'MainBlockHeader' to 'ChainDifficulty'.
mainHeaderDifficulty :: Lens' MainBlockHeader ChainDifficulty
mainHeaderDifficulty = gbhConsensus . mcdDifficulty

-- | Lens from 'MainBlockHeader' to 'Signature'.
mainHeaderSignature :: Lens' MainBlockHeader BlockSignature
mainHeaderSignature = gbhConsensus . mcdSignature

-- | Lens from 'MainBlockHeader' to 'BlockVersion'.
mainHeaderBlockVersion :: Lens' MainBlockHeader BlockVersion
mainHeaderBlockVersion = gbhExtra . mehBlockVersion

-- | Lens from 'MainBlockHeader' to 'SoftwareVersion'.
mainHeaderSoftwareVersion :: Lens' MainBlockHeader SoftwareVersion
mainHeaderSoftwareVersion = gbhExtra . mehSoftwareVersion

-- | Lens from 'MainBlockHeader' to 'BlockHeaderAttributes'.
mainHeaderAttributes :: Lens' MainBlockHeader BlockHeaderAttributes
mainHeaderAttributes = gbhExtra . mehAttributes

-- | Lens from 'MainBlockHeader' to 'MainExtraBodyData'
mainHeaderEBDataProof :: Lens' MainBlockHeader (Hash MainExtraBodyData)
mainHeaderEBDataProof = gbhExtra . mehEBDataProof

instance HasDifficulty MainBlockHeader where
    difficultyL = mainHeaderDifficulty

instance HasEpochOrSlot MainBlockHeader where
    getEpochOrSlot = EpochOrSlot . Right . view mainHeaderSlot

instance HasEpochIndex MainBlockHeader where
    epochIndexL = mainHeaderSlot . epochIndexL

instance HasBlockVersion MainBlockHeader where
    blockVersionL = mainHeaderBlockVersion

instance HasSoftwareVersion MainBlockHeader where
    softwareVersionL = mainHeaderSoftwareVersion

----------------------------------------------------------------------------
-- MainToSign lenses
----------------------------------------------------------------------------

makeLenses ''MainToSign


text:
from django.contrib import admin

from user.models import UserProfile

admin.site.register(UserProfile)


text:
SYNONYM

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

#### Published in
Lejeunia, n. s. 62: 13 (1972)

#### Original name
Lycoperdon lambinonii var. lambinonii Demoulin, 1972

### Remarks
null


text:
<%inherit file="_base.html"/>

<%block name="form">
	<form class="container" method="post" action="/cms/events/record" enctype="multipart/form-data">

События

					Фотография только JPG-файлы 750×420
					<input type="file" class="form-control" id="inputPhoto" name="photo" accept="image/jpg">

					Заголовок
					<input type="text" class="form-control form-control-lg" id="inputTitle" name="title" value="${event.title if event else ''}" required>

					Текст
					<textarea class="form-control" id="inputText" name="text" rows="8" required>${event.text if event else ''}</textarea>

					Дата
					<input type="text" class="form-control form-control-lg" id="inputDate" name="date" value="${event.date if event else ''}" required>

						<input type="checkbox" class="custom-control-input" id="inputEnabled" name="enabled" value="1" ${'checked="checked"' if event and event.enabled else ''} >

						Использовать на сайте

			<input type="hidden" name="event_id" value="${event.event_id if event else ''}">

<button type="submit" class="btn btn-primary">Сохранить</button>

	</form>
</%block>

<%block name="javascript">

</%block>


text:
package aspen

import (
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"
	"text/template"
)

var (
	SiteIndexFilename   = ".aspen-go-index.json"
	DefaultGenPackage   = "aspen_go_gen"
	DefaultOutputGopath = ""
	genServerTemplate   = template.Must(template.New("aspen-genserver").Parse(`
package main
// GENERATED FILE - DO NOT EDIT
// Rebuild with aspen-go-build!

import (
    "github.com/gittip/aspen-go"
    _ "{{.GenPackage}}"
)

func main() {
    aspen.RunServerMain("{{.WwwRoot}}",
        "{{.GenServerBind}}", "{{.GenPackage}}",
        "{{.CharsetDynamic}}", "{{.CharsetStatic}}",
        "{{.IndicesString}}", {{.ListDirs}}, {{.Debug}})
}
`))
)

type siteBuilder struct {
	// also used as defaults in generated server binary
	WwwRoot        string
	GenPackage     string
	GenServerBind  string
	CharsetStatic  string
	CharsetDynamic string
	Indices        []string
	ListDirs       bool
	Debug          bool

	// used primarily for compile time
	OutputGopath string
	Format       bool
	Compile      bool

	goexe       string
	walker      *treeWalker
	packagePath string
	genServer   string
	index       *siteIndex
}

type SiteBuilderCfg struct {
	WwwRoot       string
	OutputGopath  string
	GenPackage    string
	GenServerBind string
	Format        bool
	MkOutDir      bool
	Compile       bool

	CharsetStatic  string
	CharsetDynamic string
	Indices        []string
	ListDirs       bool
	Debug          bool
}

type siteIndex struct {
	WwwRoot   string                      `json:"root_dir"`
	Simplates map[string]*simplateSummary `json:"simplates"`
}

type simplateSummary struct {
	Type        string `json:"type"`
	ContentType string `json:"content_type"`
}

func init() {
	*(&DefaultOutputGopath) = strings.Split(os.Getenv("GOPATH"), ":")[0]
}

func newSiteBuilder(cfg *SiteBuilderCfg) (*siteBuilder, error) {
	var (
		err   error
		goexe string
	)

	rootDir, err := filepath.Abs(cfg.WwwRoot)
	if err != nil {
		return nil, err
	}

	outPath, err := filepath.Abs(cfg.OutputGopath)
	if err != nil {
		return nil, err
	}

	genPkg := cfg.GenPackage
	if len(genPkg) == 0 {
		genPkg = DefaultGenPackage
	}

	if cfg.Compile || cfg.Format {
		goexe, err = exec.LookPath("go")
		if err != nil {
			return nil, err
		}
	}

	if cfg.MkOutDir {
		err = os.MkdirAll(outPath, os.ModeDir|(os.FileMode)(0755))
		if err != nil {
			return nil, err
		}
	} else {
		outPathFi, err := os.Stat(outPath)
		if err != nil {
			return nil, err
		}

		if !outPathFi.IsDir() {
			return nil, fmt.Errorf("Invalid build output directory specified: %v", outPath)
		}
	}

	debugf("Creating new tree walker with package name %q, root dir %q", genPkg, rootDir)
	walker, err := newTreeWalker(genPkg, rootDir)
	if err != nil {
		return nil, err
	}

	sb := &siteBuilder{
		WwwRoot:       rootDir,
		OutputGopath:  outPath,
		GenPackage:    genPkg,
		GenServerBind: cfg.GenServerBind,
		Format:        cfg.Format,
		Compile:       cfg.Compile,

		CharsetDynamic: cfg.CharsetDynamic,
		CharsetStatic:  cfg.CharsetStatic,
		Indices:        cfg.Indices,
		ListDirs:       cfg.ListDirs,
		Debug:          cfg.Debug,

		goexe:       goexe,
		walker:      walker,
		packagePath: path.Join(outPath, "src", genPkg),
		genServer:   fmt.Sprintf("%s/%s-http-server", genPkg, genPkg),
		index: &siteIndex{
			WwwRoot:   rootDir,
			Simplates: map[string]*simplateSummary{},
		},
	}

	debugf("Initialized site builder: %+v from cfg %+v", sb, cfg)

	return sb, nil
}

func (me *siteBuilder) writeOneSource(simplate *simplate) error {
	if simplate.Type == SimplateTypeStatic {
		debugf("Site builder skipping write of static simplate %q",
			simplate.Filename)
		return nil
	}

	outname := path.Join(me.packagePath, simplate.OutputName())
	debugf("Writing source for %v to %v\n", simplate.Filename, outname)

	outnameParent := path.Dir(outname)
	_, err := os.Stat(outnameParent)
	if err != nil {
		err = os.MkdirAll(outnameParent, os.ModeDir|(os.FileMode)(0755))
		if err != nil {
			return err
		}
	}

	outf, err := os.Create(outname)
	if err != nil {
		return err
	}

	debugf(" --> Executing simplate for %v\n", simplate.Filename)
	err = simplate.Execute(outf)
	if err != nil {
		return err
	}
	debugf(" --> Done executing simplate for %v\n", simplate.Filename)

	err = outf.Close()
	if err != nil {
		return err
	}

	debugf(" --> Returning nil after writing %v\n", outname)
	return nil
}

func (me *siteBuilder) writeGenServer() error {
	dirname := path.Join(me.OutputGopath, "src", me.genServer)
	err := os.MkdirAll(dirname, os.ModeDir|(os.FileMode)(0755))
	if err != nil {
		return err
	}

	mainGo := path.Join(dirname, "main.go")
	debugf("Site builder writing generated server to %q", mainGo)

	fd, err := os.Create(mainGo)
	if err != nil {
		return err
	}

	defer fd.Close()

	err = genServerTemplate.Execute(fd, me)
	if err != nil {
		return err
	}

	return nil
}

func (me *siteBuilder) writeSources() error {
	debugf("Site builder writing sources")

	simplates, err := me.walker.Simplates()
	if err != nil {
		return err
	}

	for simplate := range simplates {
		if simplate == nil {
			// assume `walker.Simplates()` assigned error to same address
			// as one above?
			return err
		}

		debugf("Site builder about to write source for %v simplate %q",
			simplate.Type, simplate.Filename)
		err := me.writeOneSource(simplate)
		if err != nil {
			return err
		}

		me.indexSimplate(simplate)
	}

	err = me.dumpSiteIndex()
	if err != nil {
		return err
	}

	err = me.writeGenServer()
	if err != nil {
		return err
	}

	return nil
}

func (me *siteBuilder) indexSimplate(simplate *simplate) {
	me.index.Simplates[fmt.Sprintf("/%v", simplate.Filename)] = &simplateSummary{
		Type:        simplate.Type,
		ContentType: simplate.ContentType,
	}
}

func (me *siteBuilder) dumpSiteIndex() error {
	idxPath := path.Join(me.WwwRoot, SiteIndexFilename)

	debugf("Site builder dumping site index to %q", idxPath)

	out, err := os.Create(idxPath)
	if err != nil {
		return err
	}

	encoded, err := json.MarshalIndent(me.index, "", "  ")
	if err != nil {
		return err
	}

	_, err = out.Write(encoded)
	if err != nil {
		return err
	}

	err = out.Close()
	if err != nil {
		return err
	}

	return nil
}

func (me *siteBuilder) compileSources() error {
	debugf("Site builder compiling sources")
	origGopath := os.Getenv("GOPATH")
	err := os.Setenv("GOPATH", fmt.Sprintf("%s:%s", me.OutputGopath, origGopath))
	if err != nil {
		return err
	}

	defer os.Setenv("GOPATH", origGopath)

	installPkgCmd := exec.Command(me.goexe, "install", me.GenPackage)
	installPkgCmd.Stdout = os.Stdout
	installPkgCmd.Stderr = os.Stderr

	err = installPkgCmd.Run()
	if err != nil {
		return err
	}

	installBinCmd := exec.Command(me.goexe, "install", me.genServer)
	installBinCmd.Stdout = os.Stdout
	installPkgCmd.Stderr = os.Stderr

	err = installBinCmd.Run()
	if err != nil {
		return err
	}

	return nil
}

func (me *siteBuilder) formatOneSource(sourceFile string) error {
	origGopath := os.Getenv("GOPATH")
	err := os.Setenv("GOPATH", me.OutputGopath)
	if err != nil {
		return err
	}

	defer os.Setenv("GOPATH", origGopath)

	formatCmd := exec.Command(me.goexe, "fmt", me.GenPackage)
	formatCmd.Stdout = os.Stdout
	formatCmd.Stderr = os.Stderr

	err = formatCmd.Run()
	if err != nil {
		return err
	}

	return nil
}

func (me *siteBuilder) formatSources(sources []string) error {
	debugf("Site builder formatting sources")
	for _, source := range sources {
		err := me.formatOneSource(source)
		if err != nil {
			return err
		}
	}

	return nil
}

func (me *siteBuilder) sourcesList() ([]string, error) {
	return filepath.Glob(path.Join(me.packagePath, "*.go"))
}

func (me *siteBuilder) ensureSourcesWritten() ([]string, error) {
	sources, err := me.sourcesList()
	if err != nil {
		return sources, err
	}

	if len(sources) == 0 {
		return sources, fmt.Errorf("No sources found in %q", me.packagePath)
	}

	return sources, nil
}

func (me *siteBuilder) Build() error {
	err := me.writeSources()
	if err != nil {
		return err
	}

	sources, err := me.ensureSourcesWritten()
	if err != nil {
		return err
	}

	if me.Format {
		err = me.formatSources(sources)
		if err != nil {
			return err
		}
	}

	if me.Compile {
		err = me.compileSources()
		if err != nil {
			return err
		}
	}

	return nil
}

func (me *siteBuilder) IndicesString() string {
	return strings.Join(me.Indices, ",")
}

/*
Build non-static simplates found in the given document root
(SiteBuilderCfg.WwwRoot) into Go sources written to the src dir of a given
GOPATH entry (SiteBuilderCfg.OutputGopath).  The generated package
(SiteBuilderCfg.GenPackage) will be used as the output source directory name
and written as the package declaration for each generated Go source file.  An
http server source will also be written to a directory nested within the
generated package.

Sources may be formatted via `gofmt` by setting the passed-in
SiteBuilderCfg.Format to true.  The generated package and http executable may
be automatically compiled by setting the passed-in SiteBuilderCfg.Compile to
true.

The generated server will support the following options, defaulted to the values
passed to BuildMain:

            --www_root, -w: Filesystem path of the document publishing root
     --network_address, -a: The IPv4 or IPv6 address to which the generated server
                            will bind by default
               --debug, -x: Print debugging output

*/
func BuildMain(cfg *SiteBuilderCfg) int {
	SetDebug(cfg.Debug)

	builder, err := newSiteBuilder(cfg)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
		return 1
	}

	err = builder.Build()
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
		return 2
	}

	return 0
}


text:
package org.opentosca.driver;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.reflect.ConstructorUtils;
import org.opentosca.driver.noop.NoopDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

final class DriverUtils
{
  private static Logger logger = LoggerFactory.getLogger(DriverUtils.class);

  private static Cache<String, Driver> cache = CacheBuilder.newBuilder().build();

  @SuppressWarnings("unchecked")
  static Driver forName(final String name)
  {
    // Load from cache
    logger.info("Loading driver \"{}\"...", name);
    Driver driver = cache.getIfPresent(name);
    if (driver != null)
    {
      logger.info("Found driver in cache");
      return driver;
    }
    // Instantiate a new one
    try
    {
      logger.info("Create new instance of driver \"{}\"", name);
      Class<Driver> clazz;
      try
      {
        clazz = (Class<Driver>) ClassUtils.getClass(name);
      }
      catch (ClassNotFoundException e)
      {
        logger.error("Driver \"{}\" not found, falling back to NoopDriver", name);
        clazz = (Class<Driver>) ClassUtils.getClass(NoopDriver.class.getCanonicalName());
      }
      driver = ConstructorUtils.invokeConstructor(clazz);
      cache.put(name, driver);
      return driver;
    }
    catch (Exception e)
    {
      throw new RuntimeException("Class \"" + name + "\" could not be instantiated", e);
    }
  }
}


text:
package alluxio.client.hadoop.contract;

import alluxio.conf.PropertyKey;
import alluxio.conf.ServerConfiguration;
import alluxio.hadoop.HadoopConfigurationUtils;
import alluxio.testutils.LocalAlluxioClusterResource;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.contract.AbstractContractRenameTest;
import org.apache.hadoop.fs.contract.AbstractFSContract;
import org.junit.Rule;

public class FileSystemContractRenameIntegrationTest extends AbstractContractRenameTest {
  @Rule
  public LocalAlluxioClusterResource mClusterResource =
      new LocalAlluxioClusterResource.Builder()
          // Adding this fixed an error in allocating enough space in seekBigFile and PosBulkRead
          .setProperty(PropertyKey.USER_FILE_BUFFER_BYTES, "1k")
          .build();

  @Override
  protected AbstractFSContract createContract(Configuration conf) {
    return new FileSystemContract(HadoopConfigurationUtils.mergeAlluxioConfiguration(conf,
        ServerConfiguration.global()), mClusterResource.get());
  }
}


text:
"use strict";

// eslint-disable-next-line no-restricted-modules
module.exports = require("../index").__internal;


text:
package com.google.android.apps.muzei.api;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Looper;
import android.provider.BaseColumns;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

/**
 * Contract between Muzei and applications, containing the definitions for all supported URIs and
 * columns as well as helper methods to make it easier to work with the provided data.
 */
public class MuzeiContract {
    /**
     * Base authority for this content provider
     */
    public static final String AUTHORITY = "com.google.android.apps.muzei";
    /**
     * The scheme part for this provider's URI
     */
    private static final String SCHEME = "content://";

    /**
     * This class cannot be instantiated
     */
    private MuzeiContract() {
    }

    /**
     * Constants and helper methods for the Artwork table, providing access to the current artwork.
     *
     *
The Artwork table contains the details of the artwork that has been loaded by Muzei.
     * It also provides direct access to the cached image already downloaded by Muzei,
     * ensuring that you do not need to do additional networks requests or have internet access
     * when retrieving previously loaded artwork.
     *
     *
Working with the Artwork table

     *
     * Querying {@link #CONTENT_URI} will return either zero rows (in cases where the user has never
     * activated Muzei before) or a row for each previously loaded artwork with all of the details needed to create an
     * {@link com.google.android.apps.muzei.api.Artwork Artwork} object. The helper method
     * {@link #getCurrentArtwork(Context)} does builds an Artwork object for the most recent artwork, although
     * you can certainly query the {@link #CONTENT_URI} directly and either use the columns directly or
     * use {@link com.google.android.apps.muzei.api.Artwork#fromCursor(android.database.Cursor) Artwork.fromCursor(Cursor)}
     * to parse the Cursor for you.
     *
     *
If instead you use {@link ContentResolver#openInputStream(Uri) ContentResolver.openInputStream(Uri)},
     * you'll get an InputStream for the cached image Bitmap. This can
     * then be passed to {@link BitmapFactory#decodeStream(java.io.InputStream) BitmapFactory.decodeStream(InputStream)} or
     * similar methods to retrieve the Bitmap itself. The helper method
     * {@link #getCurrentArtworkBitmap(Context)} does this operation, although note
     * that this may return a very large Bitmap so following the
     * Displaying Bitmaps Efficiently training
     * advice is highly suggested.
     *
     *
Listening for changes

     *
     * Just like any {@link android.content.ContentProvider ContentProvider}, listening for changes can be done by
     * implementing a {@link android.database.ContentObserver ContentObserver} on {@link #CONTENT_URI} or by using
     * any of the helper classes such as {@link android.content.CursorLoader CursorLoader} to listen for updates.
     *
     *
However, if you want to receive updates while in the background and do not want to maintain
     * a constantly running {@link android.database.ContentObserver ContentObserver}, you can instead listen for the
     * {@link #ACTION_ARTWORK_CHANGED} broadcast, sent out immediately after an update is made:
     *
     *

     * <receiver android:name=".ExampleArtworkUpdateReceiver">
     *     <intent-filter>
     *         <action android:name="com.google.android.apps.muzei.ACTION_ARTWORK_CHANGED" />
     *     </intent-filter>
     * </receiver>
     *

     *
     * No data is sent alongside the broadcast, but this can be used to kick off an
     * {@link android.app.IntentService IntentService} to retrieve the latest artwork or start
     * other processing.
     */
    public static final class Artwork implements BaseColumns {
        /**
         * Column name for the flattened {@link ComponentName} of the source that is providing
         * this wallpaper
         *
Type: TEXT in the format of {@link ComponentName#flattenToShortString()}
         */
        public static final String COLUMN_NAME_SOURCE_COMPONENT_NAME = "sourceComponentName";
        /**
         * Column name of the artwork image URI. In almost all cases you should use
         * {@link ContentResolver#openInputStream(Uri) ContentResolver.openInputStream(CONTENT_URI)}
         * to retrieve the already downloaded artwork.
         *
Type: TEXT (URI)
         */
        public static final String COLUMN_NAME_IMAGE_URI = "imageUri";
        /**
         * Column name for the artwork's title.
         *
Type: TEXT
         */
        public static final String COLUMN_NAME_TITLE = "title";
        /**
         * Column name for the artwork's byline (such as author and date).
         *
Type: TEXT
         */
        public static final String COLUMN_NAME_BYLINE = "byline";
        /**
         * Column name for the artwork's attribution info.
         *
Type: TEXT
         */
        public static final String COLUMN_NAME_ATTRIBUTION = "attribution";
        /**
         * Column name for the artwork's opaque application-specific identifier.
         *
Type: TEXT
         */
        public static final String COLUMN_NAME_TOKEN = "token";
        /**
         * Column name for the artwork's view Intent, encoded via
         * {@link android.content.Intent#toUri(int) Intent.toUri(Intent.URI_INTENT_SCHEME)} and can
         * be decoded via
         * {@link android.content.Intent#parseUri(String, int) Intent.parseUri(viewIntent, Intent.URI_INTENT_SCHEME)}
         *
Type: TEXT (Intent encoded URI)
         */
        public static final String COLUMN_NAME_VIEW_INTENT = "viewIntent";
        /**
         * Column name for the font type to use to display artwork meta info.
         *
Type: TEXT
         */
        public static final String COLUMN_NAME_META_FONT = "metaFont";
        /**
         * Column name for when this artwork was added.
         * This will be automatically added for you by Muzei.
         *
Type: LONG (in milliseconds)
         */
        public static final String COLUMN_NAME_DATE_ADDED = "date_added";
        /**
         * The MIME type of {@link #CONTENT_URI} providing artwork.
         */
        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.android.apps.muzei.artwork";
        /**
         * The MIME type of {@link #CONTENT_URI} providing a single piece of artwork.
         */
        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.android.apps.muzei.artwork";
        /**
         * The default sort order for this table
         */
        public static final String DEFAULT_SORT_ORDER = COLUMN_NAME_DATE_ADDED + " DESC";
        /**
         * The table name offered by this provider.
         */
        public static final String TABLE_NAME = "artwork";

        /**
         * This class cannot be instantiated
         */
        private Artwork() {
        }

        /**
         * The content:// style URL for this table. This is the main entry point for queries and for
         * opening an {@link java.io.InputStream InputStream} to the current artwork's image.
         */
        public static final Uri CONTENT_URI = Uri.parse(MuzeiContract.SCHEME + MuzeiContract.AUTHORITY
                + "/" + Artwork.TABLE_NAME);
        /**
         * Intent action that will be broadcast when the artwork is changed. This happens immediately after the
         * ContentProvider is updated with data and should be considered the signal that you can retrieve the new
         * artwork.
         */
        public static final String ACTION_ARTWORK_CHANGED = "com.google.android.apps.muzei.ACTION_ARTWORK_CHANGED";

        /**
         * Returns the current Muzei {@link com.google.android.apps.muzei.api.Artwork Artwork}
         * @param context Context to retrieve a ContentResolver
         * @return the current Artwork or null if one could not be found
         */
        public static com.google.android.apps.muzei.api.Artwork getCurrentArtwork(Context context) {
            ContentResolver contentResolver = context.getContentResolver();
            Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
            if (cursor == null) {
                return null;
            }
            try {
                if (!cursor.moveToFirst()) {
                    return null;
                }
                return com.google.android.apps.muzei.api.Artwork.fromCursor(cursor);
            } finally {
                cursor.close();
            }
        }

        /**
         * Naively gets the current artwork image without any subsampling or optimization for output size
         *
Note that this may return a very large Bitmap so following the
         * Displaying Bitmaps Efficiently training
         * is highly recommended.
         * @param context Context to retrieve a ContentResolver
         * @return A Bitmap of the current artwork or null if the image could not be decoded
         * @throws FileNotFoundException If no cached artwork image was found
         */
        public static Bitmap getCurrentArtworkBitmap(Context context) throws FileNotFoundException {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                throw new IllegalStateException("getCurrentArtworkBitmap cannot be called on the main thread");
            }
            ContentResolver contentResolver = context.getContentResolver();
            return BitmapFactory.decodeStream(contentResolver.openInputStream(CONTENT_URI));
        }
    }

    public static final class Sources implements BaseColumns {
        /**
         * Column name for the flattened {@link ComponentName} of this source
         *
Type: TEXT in the format of {@link ComponentName#flattenToShortString()}
         */
        public static final String COLUMN_NAME_COMPONENT_NAME = "component_name";
        /**
         * Column name for the flag indicating if the source is currently selected
         *
Type: INTEGER (boolean)
         */
        public static final String COLUMN_NAME_IS_SELECTED = "selected";
        /**
         * Column name for the source's description.
         *
Type: TEXT
         */
        public static final String COLUMN_NAME_DESCRIPTION = "description";
        /**
         * Column name for the flag indicating if the source wants callbacks for network connectivity changes
         *
Type: INTEGER (boolean)
         */
        public static final String COLUMN_NAME_WANTS_NETWORK_AVAILABLE = "network";
        /**
         * Column name for the flag indicating if the source supports a 'Next Artwork' action
         *
Type: INTEGER (boolean)
         */
        public static final String COLUMN_NAME_SUPPORTS_NEXT_ARTWORK_COMMAND = "supports_next_artwork";
        /**
         * Column name for the commands the source supports
         *
Type: TEXT
         */
        public static final String COLUMN_NAME_COMMANDS = "commands";
        /**
         * The MIME type of {@link #CONTENT_URI} providing sources.
         */
        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.android.apps.muzei.source";
        /**
         * The MIME type of {@link #CONTENT_URI} providing a single source.
         */
        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.android.apps.muzei.source";
        /**
         * The default sort order for this table
         */
        public static final String DEFAULT_SORT_ORDER = Sources.COLUMN_NAME_IS_SELECTED + " DESC," +
                Sources.COLUMN_NAME_COMPONENT_NAME;
        /**
         * The table name offered by this provider.
         */
        public static final String TABLE_NAME = "sources";

        /**
         * This class cannot be instantiated
         */
        private Sources() {
        }

        /**
         * The content:// style URL for this table.
         */
        public static final Uri CONTENT_URI = Uri.parse(MuzeiContract.SCHEME + MuzeiContract.AUTHORITY
                + "/" + Sources.TABLE_NAME);
        /**
         * Intent action that will be broadcast when the source info is changed. This happens immediately after the
         * ContentProvider is updated with data and should be considered the signal that you can retrieve the new
         * source info.
         */
        public static final String ACTION_SOURCE_CHANGED = "com.google.android.apps.muzei.ACTION_SOURCE_CHANGED";

        /**
         * Parse the commands found in the {@link #COLUMN_NAME_COMMANDS} field into a List of {@link UserCommand}s.
         * @param commandsString The serialized commands found in {@link #COLUMN_NAME_COMMANDS}
         * @return A deserialized List of {@link UserCommand}s
         */
        public static List<UserCommand> parseCommands(String commandsString) {
            ArrayList<UserCommand> commands = new ArrayList<>();
            if (commandsString == null) {
                return commands;
            }
            try {
                JSONArray commandArray = new JSONArray(commandsString);
                for (int h=0; h<commandArray.length(); h++) {
                    commands.add(UserCommand.deserialize(commandArray.getString(h)));
                }
            } catch (JSONException e) {
                Log.e(MuzeiContract.Sources.class.getSimpleName(), "Error parsing commands from " + commandsString, e);
            }
            return commands;
        }
    }
}


text:
package org.apache.twill.internal;

import org.apache.twill.api.TwillRunnableSpecification;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Straightforward implementation of {@link org.apache.twill.api.TwillRunnableSpecification}.
 */
public final class DefaultTwillRunnableSpecification implements TwillRunnableSpecification {

  private final String className;
  private final String name;
  private final Map<String, String> arguments;

  public DefaultTwillRunnableSpecification(String className, String name, Map<String, String> arguments) {
    this.className = className;
    this.name = name;
    this.arguments = Collections.unmodifiableMap(new HashMap<String, String>(arguments));
  }

  public DefaultTwillRunnableSpecification(String className, TwillRunnableSpecification other) {
    this.className = className;
    this.name = other.getName();
    this.arguments = Collections.unmodifiableMap(new HashMap<String, String>(other.getConfigs()));
  }

  @Override
  public String getClassName() {
    return className;
  }

  @Override
  public String getName() {
    return name;
  }

  @Override
  public Map<String, String> getConfigs() {
    return arguments;
  }
}