text:
using MetroOverhaul.NEXT;
using MetroOverhaul.NEXT.Extensions;
using MetroOverhaul.NEXT.Texturing;

namespace MetroOverhaul.InitializationSteps
{
    public static partial class SetupSteelTexture
    {
        public static void Setup19mSteelTexture(NetInfo info, NetInfoVersion version)
        {
            switch (version)
            {
                case NetInfoVersion.Ground:
                    {
                        foreach (var segment in info.m_segments)
                        {
                            if (segment.m_mesh.name.Contains("Pavement") || (segment.m_mesh.name.Contains("Fence_Steel")))
                            {
                                segment.SetTextures(
                                    new TextureSet
                                        (@"Textures\Ground_Segment_Pavement_Steel_Small__MainTex.png",
                                            @"Textures\Ground_Segment_Pavement_Island__AlphaMap.png",
                                            @"Textures\Ground_Segment_Pavement_Small__XYSMap.png"),
                                    new LODTextureSet
                                        (@"Textures\Ground_Segment_Pavement_Steel_Small__MainTex_LOD.png",
                                            @"Textures\Ground_Segment_Pavement_Steel__AlphaMap_LOD.png",
                                            @"Textures\Ground_Segment_Pavement_Steel__XYSMap_LOD.png"));
                            }
                            else if (segment.m_mesh.name.Contains("ThirdRail"))
                            {
                                segment.SetTextures(
                                    new TextureSet
                                        (@"Textures\ThirdRail__MainTex.png",
                                            @"Textures\ThirdRail__AlphaMap.png",
                                            @"Textures\ThirdRail__XYSMap.png"),
                                    new LODTextureSet
                                        (@"Textures\ThirdRail__MainTex_LOD.png",
                                            @"Textures\ThirdRail__AlphaMap_LOD.png",
                                            @"Textures\ThirdRail__XYSMap_LOD.png"));
                            }
                            else
                            {
                                segment.SetTextures(
                                    new TextureSet
                                        (@"Textures\Ground_Segment_Rail__MainTex.png",
                                            @"Textures\Ground_Segment_Rail__AlphaMap.png",
                                            @"Textures\Ground_Segment_Rail__XYSMap.png"));
                            }
                        }
                        foreach (var node in info.m_nodes)
                        {
                            if (node.m_mesh.name.Contains("LevelCrossing_Pavement"))
                            {
                                node.SetTextures(
                                    new TextureSet
                                        (@"Textures\Ground_Level_Crossing__MainTex.png",
                                            @"Textures\Ground_Level_Crossing__AlphaMap.png",
                                            @"Textures\Ground_Segment_Rail__XYSMap.png"),
                                    new LODTextureSet
                                        (@"Textures\Ground_Level_Crossing__MainTex_LOD.png",
                                            @"Textures\Ground_Level_Crossing__AlphaMap_LOD.png",
                                            @"Textures\Ground_Segment_Pavement__XYSMap_LOD.png"));
                            }

                            else if (node.m_mesh.name.Contains("Level_Crossing_Rail"))
                            {
                                node.SetTextures(
                                    new TextureSet
                                        (@"Textures\Ground_Level_Crossing_Rail__MainTex.png",
                                            @"Textures\Ground_Segment_Rail__AlphaMap.png",
                                            @"Textures\Ground_Level_Crossing_Rail__XYSMap.png"));
                            }
                            else if (node.m_mesh.name.Contains("Pavement") || (node.m_mesh.name.Contains("Fence_Steel")))
                            {
                                node.SetTextures(
                                    new TextureSet
                                        (@"Textures\Ground_Node_Pavement_Small__MainTex.png",
                                            @"Textures\Ground_Node_Pavement_Island__AlphaMap.png",
                                            @"Textures\Ground_Segment_Pavement_Steel__XYSMap.png"),
                                    new LODTextureSet
                                        (@"Textures\Ground_Node_Pavement_Steel__MainTex_LOD.png",
                                            @"Textures\Ground_Node_Pavement_Steel__AlphaMap_LOD.png",
                                            @"Textures\Ground_Segment_Pavement_Steel__XYSMap_LOD.png"));
                            }
                            else if (node.m_mesh.name.Contains("ThirdRail"))
                            {
                                node.SetTextures(
                                    new TextureSet
                                        (@"Textures\ThirdRail__MainTex.png",
                                            @"Textures\ThirdRail__AlphaMap.png",
                                            @"Textures\ThirdRail__XYSMap.png"),
                                    new LODTextureSet
                                        (@"Textures\ThirdRail__MainTex_LOD.png",
                                            @"Textures\ThirdRail_Node__AlphaMap_LOD.png",
                                            @"Textures\ThirdRail__XYSMap_LOD.png"));
                            }
                            else
                            {
                                node.SetTextures(
                                    new TextureSet
                                        (@"Textures\Ground_Segment_Rail_Steel__MainTex.png",
                                            @"Textures\Ground_Segment_Rail__AlphaMap.png",
                                            @"Textures\Ground_Segment_Rail_Steel__XYSMap.png"));
                            }
                        }
                        break;
                    }
                case NetInfoVersion.Elevated:
                case NetInfoVersion.Bridge:
                    {
                        var elevatedBridge = version == NetInfoVersion.Elevated ? "Elevated" : "Bridge";
                        foreach (var segment in info.m_segments)
                        {

                            if (segment.m_mesh.name.Contains("Station_Pavement"))
                            {

                                segment.SetTextures(
                                    new TextureSet
                                        ($@"Textures\{elevatedBridge}_Station_Segment_Pavement_Steel__MainTex.png",
                                            $@"Textures\{elevatedBridge}_Segment_Pavement_Steel__AlphaMap.png",
                                            $@"Textures\{elevatedBridge}_Segment_Pavement_Steel__XYSMap.png"),
                                    new LODTextureSet
                                        ($@"Textures\{elevatedBridge}_Station_Segment_Pavement_Steel__MainTex_LOD.png",
                                            $@"Textures\{elevatedBridge}_Segment_Pavement_Steel__AlphaMap_LOD.png",
                                            $@"Textures\{elevatedBridge}_Segment_Pavement_Steel__XYSMap_LOD.png"));
                            }
                            else if (segment.m_mesh.name.Contains("Pavement") || (segment.m_mesh.name.Contains("Fence")))
                            {
                                segment.SetTextures(
                                    new TextureSet
                                        ($@"Textures\{elevatedBridge}_Segment_Pavement_Steel__MainTex.png",
                                            $@"Textures\{elevatedBridge}_Segment_Pavement_Steel__AlphaMap.png",
                                            $@"Textures\{elevatedBridge}_Segment_Pavement_Steel__XYSMap.png"),
                                    new LODTextureSet
                                        ($@"Textures\{elevatedBridge}_Segment_Pavement_Steel__MainTex_LOD.png",
                                            $@"Textures\{elevatedBridge}_Segment_Pavement_Steel__AlphaMap_LOD.png",
                                            $@"Textures\{elevatedBridge}_Segment_Pavement_Steel__XYSMap_LOD.png"));
                            }
                            else if (segment.m_mesh.name.Contains("ThirdRail"))
                            {
                                segment.SetTextures(
                                    new TextureSet
                                        (@"Textures\ThirdRail__MainTex.png",
                                            @"Textures\ThirdRail__AlphaMap.png",
                                            @"Textures\ThirdRail__XYSMap.png"),
                                    new LODTextureSet
                                        (@"Textures\ThirdRail__MainTex_LOD.png",
                                            @"Textures\ThirdRail__AlphaMap_LOD.png",
                                            @"Textures\ThirdRail__XYSMap_LOD.png"));
                            }
                            else
                            {
                                segment.SetTextures(
                                    new TextureSet
                                        (@"Textures\Ground_Segment_Rail__MainTex.png",
                                            @"Textures\Ground_Segment_Rail__AlphaMap.png",
                                            @"Textures\Ground_Segment_Rail__XYSMap.png"));
                            }
                        }
                        foreach (var node in info.m_nodes)
                        {
                            if (node.m_mesh.name.Contains("Pavement") || (node.m_mesh.name.Contains("Fence")))
                            {
                                if (node.m_mesh.name.Contains("Elevated"))
                                {
                                    node.SetTextures(
                                        new TextureSet
                                            (@"Textures\Elevated_Node_Pavement_Steel__MainTex.png",
                                                @"Textures\Elevated_Node_Pavement_Steel__AlphaMap.png",
                                                @"Textures\Ground_Segment_Pavement_Steel__XYSMap.png"),
                                        new LODTextureSet
                                            (@"Textures\Elevated_Segment_Pavement_Steel__MainTex_LOD.png",
                                                @"Textures\Elevated_Segment_Pavement_Steel__AlphaMap_LOD.png",
                                                @"Textures\Ground_Segment_Pavement_Steel__XYSMap_LOD.png"));
                                }
                                else if (node.m_mesh.name.Contains("Bridge"))
                                {
                                    node.SetTextures(
                                        new TextureSet
                                            (@"Textures\Bridge_Segment_Pavement_Steel__MainTex.png",
                                                @"Textures\Bridge_Segment_Pavement_Steel__AlphaMap.png",
                                                @"Textures\Bridge_Segment_Pavement_Steel__XYSMap.png"),
                                        new LODTextureSet
                                            (@"Textures\Bridge_Segment_Pavement_Steel__MainTex_LOD.png",
                                                @"Textures\Bridge_Segment_Pavement_Steel__AlphaMap_LOD.png",
                                                @"Textures\Bridge_Segment_Pavement_Steel__XYSMap_LOD.png"));
                                }
                            }
                            else if (node.m_mesh.name.Contains("ThirdRail"))
                            {
                                node.SetTextures(
                                    new TextureSet
                                        (@"Textures\ThirdRail__MainTex.png",
                                            @"Textures\ThirdRail__AlphaMap.png",
                                            @"Textures\ThirdRail__XYSMap.png"),
                                    new LODTextureSet
                                        (@"Textures\ThirdRail__MainTex_LOD.png",
                                            @"Textures\ThirdRail_Node__AlphaMap_LOD.png",
                                            @"Textures\ThirdRail__XYSMap_LOD.png"));
                            }
                            else if (node.m_mesh.name.Contains("Boosted") || (node.m_mesh.name.Contains("Insert")))
                            {
                                node.SetTextures(
                                    new TextureSet
                                        (@"Textures\Elevated_Segment_Steel_Rail__MainTex.png",
                                            @"Textures\Ground_Segment_Rail__AlphaMap.png",
                                            @"Textures\Elevated_Segment_Steel_Rail__XYSMap.png"),
                                    new LODTextureSet
                                        (@"Textures\Elevated_Segment_Steel_Rail__MainTex_LOD.png",
                                            @"Textures\Ground_Segment_Rail__AlphaMap_LOD.png",
                                            @"Textures\Elevated_Segment_Steel_Rail__XYSMap_LOD.png"));
                            }
                            else
                            {
                                node.SetTextures(
                                    new TextureSet
                                        (@"Textures\Ground_Segment_Rail_Steel__MainTex.png",
                                            @"Textures\Ground_Segment_Rail__AlphaMap.png",
                                            @"Textures\Ground_Segment_Rail_Steel__XYSMap.png"));
                            }
                        }
                        break;
                    }
                case NetInfoVersion.Slope:
                    //case NetInfoVersion.Tunnel:
                    {
                        foreach (var segment in info.m_segments)
                        {
                            if (segment.m_mesh.name.Contains("Pavement_Steel") || (segment.m_mesh.name.Contains("Fence_Steel")))
                            {
                                segment.SetTextures(
                                    new TextureSet
                                        (@"Textures\Tunnel_Segment_Pavement_Steel__MainTex.png",
                                            @"Textures\Elevated_Segment_Pavement_Steel__AlphaMap.png",
                                            @"Textures\Tunnel_Segment_Pavement_Steel__XYSMap.png"),
                                    new LODTextureSet
                                        (@"Textures\Tunnel_Segment_Pavement_Steel__MainTex_LOD.png",
                                            @"Textures\Elevated_Segment_Pavement_Steel__AlphaMap_LOD.png",
                                            @"Textures\Tunnel_Segment_Pavement_Steel__XYSMap_LOD.png"));
                            }
                            else if (segment.m_mesh.name.Contains("ThirdRail"))
                            {
                                segment.SetTextures(
                                    new TextureSet
                                        (@"Textures\ThirdRail__MainTex.png",
                                            @"Textures\ThirdRail__AlphaMap.png",
                                            @"Textures\ThirdRail__XYSMap.png"),
                                    new LODTextureSet
                                        (@"Textures\ThirdRail__MainTex_LOD.png",
                                            @"Textures\ThirdRail__AlphaMap_LOD.png",
                                            @"Textures\ThirdRail__XYSMap_LOD.png"));
                            }
                            else
                            {
                                segment.SetTextures(
                                    new TextureSet
                                        (@"Textures\Ground_Segment_Rail__MainTex.png",
                                            @"Textures\Ground_Segment_Rail__AlphaMap.png",
                                            @"Textures\Ground_Segment_Rail__XYSMap.png"));
                            }
                        }
                        foreach (var node in info.m_nodes)
                        {
                            if (node.m_mesh.name.Contains("Node_Pavement_Steel") || (node.m_mesh.name.Contains("Fence_Steel")))
                            {
                                node.SetTextures(
                                    new TextureSet
                                        (@"Textures\Tunnel_Node_Pavement_Steel__MainTex.png",
                                            @"Textures\Elevated_Node_Pavement_Steel__AlphaMap.png",
                                            @"Textures\Tunnel_Segment_Pavement_Steel__XYSMap.png"),
                                    new LODTextureSet
                                        (@"Textures\Tunnel_Node_Pavement_Steel__MainTex_LOD.png",
                                            @"Textures\Elevated_Node_Pavement_Steel__AlphaMap_LOD.png",
                                            @"Textures\Tunnel_Segment_Pavement_Steel__XYSMap_LOD.png"));
                            }
                            else if (node.m_mesh.name.Contains("ThirdRail"))
                            {
                                node.SetTextures(
                                    new TextureSet
                                        (@"Textures\ThirdRail__MainTex.png",
                                            @"Textures\ThirdRail__AlphaMap.png",
                                            @"Textures\ThirdRail__XYSMap.png"),
                                    new LODTextureSet
                                        (@"Textures\ThirdRail__MainTex_LOD.png",
                                            @"Textures\ThirdRail_Node__AlphaMap_LOD.png",
                                            @"Textures\ThirdRail__XYSMap_LOD.png"));
                            }
                            else
                            {
                                node.SetTextures(
                                    new TextureSet
                                        (@"Textures\Ground_Segment_Rail__MainTex.png",
                                            @"Textures\Ground_Segment_Rail__AlphaMap.png",
                                            @"Textures\Ground_Segment_Rail__XYSMap.png"));
                            }
                        }
                        break;
                    }
            }
        }
    }
}


text:
date: 2012-07-09T00:00:00Z
mac_app_desc: A puzzle game where you have to move your knight across a board to a target
  square using the same movements as a knight in chess.
mac_app_image: /icons/KnightsMove128.png
mac_app_name: A Knight's Move
tags:
- knight's move
- chess
- mac
title: A Knight's Move Released
---

**UPDATE:** September 2016 - A Knight's Move for iOS is no longer available.

[A Knight's Move for Mac][1] is still supported.

---

"A Knight's Move" is a fun, addictive and simple puzzle game based on the
movements of chess pieces. Your goal is to move your white knight across a board
to a target square using the same movements as a knight in chess. Pawns may
block your way, while enemy bishops, castles, knights and the queen may try to
stop you.

The game is available for iPad, iPhone and iPod Touch from the iTunes Store and
requires iOS 5.0 or later. The Mac version is available from the Mac App Store
and requires OS X 10.7 or later.

Perfect for when you have a few minutes to relax, like on the train to work,
during your lunch break or during a boring lecture or class (Kids: don't take
advice from randoms, but you can turn the sound FX off. Just sayin'), "A
Knight's Move" will keep you coming back for "Just One More Go"!

Once you have played the tutorial pack, you can move on to the other puzzle
packs. Each pack comes with 25 more puzzles and there are many different packs
allowing you to select easy puzzles, challenging puzzles or variety packs, some
with themes.

See more about "A Knight's Move" at the [Knight's Move web page][1]

Get the game from the
Mac
App Store.

Tutorial puzzle on iPhone

[][3]

Pesky Pawns - one of the more difficult puzzles on Mac.

[1]: /knightsmove/
[3]: /images/PeskyPawns.png

redpajama_set_name: RedPajamaGithub


text:
A ruby wrapper for TextMarketer API.

## Installation

Add this line to your application's Gemfile:

    gem 'textmarketer'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install textmarketer

## Usage

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package de.adito.annocat.api;

import java.lang.annotation.Annotation;

/**
 * @author PaL
 *         Date: 11.06.12
 *         Time: 00:20
 */
public class FixedCategoryFacilityFactory extends AbstractCategoryFacilityFactory
{
  public FixedCategoryFacilityFactory(Class<? extends Annotation> pAnnotation, final Object pFixedResult)
  {
    register(pAnnotation, new Creator<Annotation>()
    {
      @Override
      public Object create(Annotation pAnnotation)
      {
        return pFixedResult;
      }
    });
  }

}


text:
class AddContentToProjects < ActiveRecord::Migration
  def change
  	add_column :projects, :content, :text
  end
end


text:
package com.airbnb.airpal.presto.metadata;

import com.airbnb.airpal.core.BackgroundCacheLoader;
import com.airbnb.airpal.core.execution.QueryClient;
import com.airbnb.airpal.presto.QueryRunner;
import com.facebook.presto.client.QueryResults;
import com.facebook.presto.client.StatementClient;
import com.google.common.base.Function;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Nullable;

import java.io.Closeable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;

@Slf4j
public class SchemaCache
        implements Closeable
{
    private static final long RELOAD_TIME_MINUTES = 2;
    private static final Set<String> EXCLUDED_SCHEMAS = Sets.newHashSet("sys", "information_schema");

    private final ExecutorService executor;
    private final QueryRunner.QueryRunnerFactory queryRunnerFactory;
    private final LoadingCache<String, Map<String, List<String>>> schemaTableCache;

    public SchemaCache(final QueryRunner.QueryRunnerFactory queryRunnerFactory,
            final ExecutorService executor)
    {
        this.queryRunnerFactory = checkNotNull(queryRunnerFactory, "queryRunnerFactory session was null!");
        this.executor = checkNotNull(executor, "executor was null!");

        ListeningExecutorService listeningExecutor = MoreExecutors.listeningDecorator(executor);
        BackgroundCacheLoader<String, Map<String, List<String>>> loader =
                new BackgroundCacheLoader<String, Map<String, List<String>>>(listeningExecutor)
                {
                    @Override
                    public Map<String, List<String>> load(String catalogName)
                    {
                        return queryMetadata(format(
                                "SELECT table_catalog, table_schema, table_name " +
                                        "FROM %s.information_schema.tables ", catalogName));
                    }
                };

        schemaTableCache = CacheBuilder.newBuilder()
                .refreshAfterWrite(RELOAD_TIME_MINUTES, TimeUnit.MINUTES)
                .build(loader);
    }

    private Map<String, List<String>> queryMetadata(String query)
    {
        final Map<String, List<String>> cache = Maps.newHashMap();
        QueryRunner queryRunner = queryRunnerFactory.create();
        QueryClient queryClient = new QueryClient(queryRunner, io.dropwizard.util.Duration.seconds(60), query);

        try {
            queryClient.executeWith(new Function<StatementClient, Void>() {
                @Nullable
                @Override
                public Void apply(StatementClient client)
                {
                    QueryResults results = client.current();
                    if (results.getData() != null) {
                        for (List<Object> row : results.getData()) {
                            String schema = (String) row.get(1);
                            String table = (String) row.get(2);

                            if (EXCLUDED_SCHEMAS.contains(schema)) {
                                continue;
                            }

                            List<String> tables = cache.get(schema);

                            if (tables == null) {
                                tables = Lists.newArrayList();
                                cache.put(schema, tables);
                            }

                            tables.add(table);
                        }
                    }

                    return null;
                }
            });
        }
        catch (QueryClient.QueryTimeOutException e) {
            log.error("Caught timeout loading columns", e);
        }

        return ImmutableMap.copyOf(cache);
    }

    public void populateCache(final String catalog)
    {
        checkNotNull(catalog, "schemaName is null");
        executor.execute(new Runnable()
        {
            @Override
            public void run()
            {
                schemaTableCache.refresh(catalog);
            }
        });
    }

    public Set<String> getCatalogs()
    {
        return schemaTableCache.asMap().keySet();
    }

    public Map<String, List<String>> getSchemaMap(final String catalog)
    {
        try {
            return schemaTableCache.get(catalog);
        }
        catch (ExecutionException e) {
            e.printStackTrace();
            return Maps.newHashMap();
        }
    }

    @Override
    public void close()
    {
        executor.shutdownNow();
    }

    public static ThreadFactory daemonThreadsNamed(String nameFormat)
    {
        return new ThreadFactoryBuilder().setNameFormat(nameFormat).setDaemon(true).build();
    }
}


text:
package es.ringbinder.eaye.common;

import javax.persistence.*;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;

public class EntityListener implements Serializable {

  private Logger log = Logger.getLogger(EntityListener.class.getName());

  @PersistenceContext
  private EntityManager em;

  @PrePersist
  private void prePersist(Object entity) {
    log.log(Level.INFO, String.format("callback: %s, class: %s", "PrePersist", entity.getClass().getName()));
  }

  @PostPersist
  private void postPersist(Object entity) {
    log.log(Level.INFO, String.format("callback: %s, class: %s", "PostPersist", entity.getClass().getName()));
  }

  @PreRemove
  private void preRemove(Object entity) {
    log.log(Level.INFO, String.format("callback: %s, class: %s", "PreRemove", entity.getClass().getName()));
  }

  @PostRemove
  private void postRemove(Object entity) {
    log.log(Level.INFO, String.format("callback: %s, class: %s", "PostRemove", entity.getClass().getName()));
  }

  @PreUpdate
  private void preUpdate(Object entity) {
    log.log(Level.INFO, String.format("callback: %s, class: %s", "PreUpdate", entity.getClass().getName()));
  }

  @PostUpdate
  private void postUpdate(Object entity) {
    log.log(Level.INFO, String.format("callback: %s, class: %s", "PostUpdate", entity.getClass().getName()));
  }

  @PostLoad
  private void postLoad(Object entity) {
    //String sId = "";
    //Object id = em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(entity);
    //if (id != null) {
    //  sId = id.toString();
    //}
    //log.log(Level.INFO, String.format("callback: %s, class: %s, id: %s", "PostLoad", entity.getClass().getName(), sId));
    log.log(Level.INFO, String.format("callback: %s, class: %s", "PostLoad", entity.getClass().getName()));
  }
}


text:
@implementation User
+ (NSString*)getPrimaryKey
{
    return @"userId";
}
MJCodingImplementation;
@end


text:
module MagentoApiWrapper::Requests
  class AddTrackingToShipment

    attr_accessor :data

    def initialize(data = {})
      @data = data
    end

    def body
      shipment_request_hash
    end

    def shipment_request_hash
      {
        session_id: self.session_id,
        shipment_increment_id: self.shipment_id,
        track_number: self.tracking_number,
        carrier: self.carrier,
        title: self.title
      }
    end

    def session_id
      data[:session_id]
    end

    def shipment_id
      data[:shipment_id]
    end

    def tracking_number
      data[:tracking_number]
    end

    def carrier
      data[:carrier]
    end

    def title
      data[:title]
    end

  end
end


text:
module Tim
  class BaseImage < Tim::Base
    has_many :image_versions, :inverse_of => :base_image
    belongs_to :template, :inverse_of => :base_images

    belongs_to :user, :class_name => Tim.user_class

    accepts_nested_attributes_for :template
    accepts_nested_attributes_for :image_versions

    validates_presence_of :name
    validates_presence_of :template, :unless => :import

    attr_accessible :template, :name, :description, :import
    attr_accessible :template_attributes
    attr_accessible :image_versions_attributes, :as => :admin
    attr_protected :id
  end
end


text:
<!DOCTYPE html>

		<link rel="stylesheet" href="../../codebase/webix.css" type="text/css" media="screen" charset="utf-8">

        <link rel="stylesheet" href="data/myform.css" type="text/css" media="screen" charset="utf-8">
		<title>Initialization in Document Body</title>

Book title

<input type="text" name="title"  id="title" value="" placeholder="Title" />

Author

<input type="text" name="author" id="author" value="" placeholder="Author" />

                In store<input type="checkbox" name="in_store" id="in_store" checked />

            <fieldset>
                <legend>Genre</legend>

                    <input type="radio" name="genre" value="poetry" id="genre1" />Poetry

                    <input type="radio" name="genre" value="horror" id="genre2" checked />Horror

                    <input type="radio" name="genre" value="short_story" id="genre3" />Short Story

                    <input type="radio" name="genre" value="fantasy" id="genre4" />Fantasy

                    <input type="radio" name="genre" value="drama" id="genre5" />Drama

                    <input type="radio" name="genre" value="tragedy" id="genre6" />Tragedy

            </fieldset>

Rank

                <select name="rank" id="rank">
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                </select>

Annotation

                <textarea name="annotation" id="annotation">some book annotation is here</textarea>

choose an action and apply it to Form

Action:

                <select name="action" id="action">
                    <option value="set_form">Set data</option>
                    <option value="load_form">Load form</option>
                    <option value="get_form">Get data (console)</option>
                    <option value="clear_form">Clear form</option>
                    <option value="focus_form">Focus</option>
                </select>

                <input type="button" value="Apply" onclick="apply_action()"/>


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * A newly created object using the Object contructor has its [[Extensible]]
 * property set to true by default (15.2.2.1, step 8).
 *
 * @path ch15/15.2/15.2.3/15.2.3.13/15.2.3.13-0-3.js
 * @description Object.isExtensible is true for objects created using the Object constructor
 */

function testcase() {
  var o = new Object();

  if (Object.isExtensible(o) === true) {
    return true;
  }
 }
runTestCase(testcase);


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Ascochyta clianthi Tassi

### Remarks
null


text:
"""
Created on Thu Jun  4 11:30:53 2015

@author: ajaver
"""
from tierpsy.helper.misc import TimeCounter, print_flush, WLAB, TABLE_FILTERS, get_base_name
from tierpsy.analysis.ske_filt.getFilteredSkels import getValidIndexes
from tierpsy.analysis.feat_create.obtainFeaturesHelper import WormStats, WormFromTable
from tierpsy.helper.params import copy_unit_conversions, read_fps, min_num_skel_defaults

import tierpsy.features.open_worm_analysis_toolbox as mv

import os
import warnings
from functools import partial
import numpy as np
import pandas as pd
import tables

#openworm has a lot of warnings. I do not want to correct them...
warnings.filterwarnings('ignore', '.*empty slice*',)
warnings.filterwarnings('ignore', ".*Falling back to 'gelss' driver.",)
warnings.filterwarnings('ignore', category=np.VisibleDeprecationWarning)
warnings.simplefilter(action="ignore", category=RuntimeWarning)
warnings.simplefilter(action="ignore", category=UserWarning)

# (http://www.pytables.org/usersguide/parameter_files.html)
tables.parameters.MAX_COLUMNS = 1024

#%%%%%%%
def _n_percentile(n, q):
        if isinstance(n, (float, int)) or n.size>0:
            return np.percentile(n, q)
        else:
            return np.nan

FUNC_FOR_DIV = {'means':np.mean, 'medians':np.median,
    'P10th':partial(_n_percentile, q=10), 'P90th':partial(_n_percentile, q=90)}

def getFeatStats(worm, wStats):
    if not isinstance(wStats, WormStats):
        wStats = WormStats()

    worm_openworm = worm.to_open_worm()
    assert worm_openworm.skeleton.shape[1] == 2
    worm_features = mv.WormFeatures(worm_openworm)

    def _get_worm_stat(func):
        # calculate the mean value of each feature
        worm_stat = wStats.getWormStats(worm_features, func)
        for field in wStats.extra_fields:
            worm_stat[field] = getattr(worm, field)
        return worm_stat

    worm_stats = {stat: _get_worm_stat(FUNC_FOR_DIV[stat]) for stat in FUNC_FOR_DIV}
    return worm_features, worm_stats

def getOpenWormData(worm, wStats=[]):
    if not isinstance(wStats, WormStats):
        wStats = WormStats()

    #get the worm features at its stats
    worm_features, worm_stats = getFeatStats(worm, wStats)

    # convert the timeseries features into a recarray
    tot_frames = worm.timestamp.size
    timeseries_data = np.full(tot_frames, np.nan, wStats.feat_timeseries_dtype)

    timeseries_data['timestamp'] = worm.timestamp
    timeseries_data['worm_index'] = worm.worm_index
    timeseries_data['skeleton_id'] = worm.skeleton_id
    timeseries_data['motion_modes'] = worm_features._features[
        'locomotion.motion_mode'].value

    for feat in wStats.feat_timeseries:
        feat_obj = wStats.features_info.loc[feat, 'feat_name_obj']
        if feat_obj in worm_features._features:
            timeseries_data[feat] = worm_features._features[feat_obj].value

    # convert the events features into a dictionary
    events_data = {}
    for feat in wStats.feat_events:
        feat_obj = wStats.features_info.loc[feat, 'feat_name_obj']
        if feat_obj in worm_features._features:
            events_data[feat] = worm_features._features[feat_obj].value

    return timeseries_data, events_data, worm_stats

def hasManualJoin(skeletons_file):
    with tables.File(skeletons_file, 'r') as fid:
        return any(x in fid.get_node('/trajectories_data').colnames for x in ['worm_index_manual', 'worm_index_N'])

def getGoodTrajIndexes(skeletons_file,
        use_skel_filter = True,
        use_manual_join = False,
        is_single_worm = False,
        feat_filt_param = {'min_num_skel':100}):

    assert (use_skel_filter or use_manual_join) or feat_filt_param
    if use_manual_join:
        assert hasManualJoin(skeletons_file)

    with pd.HDFStore(skeletons_file, 'r') as table_fid:
        colnames = table_fid.get_node('/trajectories_data').colnames

    if use_manual_join:
        worm_index_type = 'worm_index_manual' if 'worm_index_manual' in colnames else 'worm_index_N'
    else:
        worm_index_type = 'worm_index_joined'

    with pd.HDFStore(skeletons_file, 'r') as table_fid:
        trajectories_data = table_fid['/trajectories_data']

    if not (use_manual_join or use_skel_filter):
        # filter the raw skeletons using the parameters in feat_filt_param
        dd = {
            x: feat_filt_param[x] for x in [
                'min_num_skel',
                'bad_seg_thresh',
                'min_displacement']}
        good_traj_index, _ = getValidIndexes(
            trajectories_data, **dd)
    else:

        if use_manual_join:
            # select tables that were manually labeled as worms
            good = trajectories_data['worm_label'] == WLAB['WORM']
            trajectories_data = trajectories_data[good]

        if use_skel_filter and 'is_good_skel' in trajectories_data:
            # select data that was labeld in FEAT_FILTER
            good = trajectories_data['is_good_skel'] == 1
            trajectories_data = trajectories_data[good]

        assert worm_index_type in trajectories_data

        #keep only the trajectories that have at least min_num_skel valid skeletons
        N = trajectories_data.groupby(worm_index_type).agg({'has_skeleton': np.nansum})
        N = N[N > feat_filt_param['min_num_skel']].dropna()
        good_traj_index = N.index
    return good_traj_index, worm_index_type

def getWormFeaturesFilt(
        skeletons_file,
        features_file,
        use_skel_filter,
        use_manual_join,
        is_single_worm,
        feat_filt_param,
        split_traj_time):

    feat_filt_param = min_num_skel_defaults(skeletons_file, **feat_filt_param)

    def _iniFileGroups():
        # initialize groups for the timeseries and event features
        header_timeseries = {
            feat: tables.Float32Col(
                pos=ii) for ii, (feat, _) in enumerate(
                wStats.feat_timeseries_dtype)}

        table_timeseries = features_fid.create_table(
            '/', 'features_timeseries', header_timeseries, filters=TABLE_FILTERS)

        # save some data used in the calculation as attributes
        fps, microns_per_pixel, _ = copy_unit_conversions(table_timeseries, skeletons_file)
        table_timeseries._v_attrs['worm_index_type'] = worm_index_type

        # node to save features events
        group_events = features_fid.create_group('/', 'features_events')

        # save the skeletons
        with tables.File(skeletons_file, 'r') as ske_file_id:
            skel_shape = ske_file_id.get_node('/skeleton').shape

        worm_coords_array = {}
        w_node = features_fid.create_group('/', 'coordinates')
        for  array_name in ['skeletons', 'dorsal_contours', 'ventral_contours']:
            worm_coords_array[array_name] = features_fid.create_earray(
                w_node,
                array_name,
                shape=(
                    0,
                    skel_shape[1],
                    skel_shape[2]),
                atom=tables.Float32Atom(
                    shape=()),
                filters=TABLE_FILTERS)

        # initialize rec array with the averaged features of each worm
        stats_features_df = {stat:np.full(tot_worms, np.nan, dtype=wStats.feat_avg_dtype) for stat in FUNC_FOR_DIV}

        return header_timeseries, table_timeseries, group_events, worm_coords_array, stats_features_df

    progress_timer = TimeCounter('')
    def _displayProgress(n):
            # display progress
        dd = " Extracting features. Worm %i of %i done." % (n, tot_worms)
        print_flush(
            base_name +
            dd +
            ' Total time:' +
            progress_timer.get_time_str())

    #get the valid number of worms
    good_traj_index, worm_index_type = getGoodTrajIndexes(skeletons_file,
        use_skel_filter,
        use_manual_join,
        is_single_worm,
        feat_filt_param)

    fps = read_fps(skeletons_file)
    split_traj_frames = int(np.round(split_traj_time*fps)) #the fps could be non integer

    # function to calculate the progress time. Useful to display progress
    base_name = get_base_name(skeletons_file)

    with tables.File(features_file, 'w') as features_fid:
        #check if the stage was not aligned correctly. Return empty features file otherwise.
        with tables.File(skeletons_file, 'r') as skel_fid:
            if '/experiment_info' in skel_fid:
                dd = skel_fid.get_node('/experiment_info').read()
                features_fid.create_array(
                    '/', 'experiment_info', obj=dd)

        #total number of worms
        tot_worms = len(good_traj_index)
        if tot_worms == 0:
            print_flush(base_name + ' No valid worms found to calculate features. Creating empty file.')
            return

        # initialize by getting the specs data subdivision
        wStats = WormStats()
        all_splitted_feats = {stat:[] for stat in FUNC_FOR_DIV}

        #initialize file
        header_timeseries, table_timeseries, group_events, \
        worm_coords_array, stats_features_df = _iniFileGroups()

        _displayProgress(0)
        # start to calculate features for each worm trajectory
        for ind_N, worm_index in enumerate(good_traj_index):
            # initialize worm object, and extract data from skeletons file
            worm = WormFromTable(
            skeletons_file,
            worm_index,
            use_skel_filter=use_skel_filter,
            worm_index_type=worm_index_type,
            smooth_window=5)

            if is_single_worm:
                #worm with the stage correction applied
                worm.correct_schafer_worm()
                if np.all(np.isnan(worm.skeleton[:, 0, 0])):
                    print_flush('{} Not valid skeletons found after stage correction. Skiping worm index {}'.format(base_name, worm_index))
                    return
            # calculate features
            timeseries_data, events_data, worm_stats = getOpenWormData(worm, wStats)

            #get splitted features
            splitted_worms = [x for x in worm.split(split_traj_frames)
            if x.n_valid_skel > feat_filt_param['min_num_skel'] and
            x.n_valid_skel/x.n_frames >= feat_filt_param['bad_seg_thresh']]

            dd = [getFeatStats(x, wStats)[1] for x in splitted_worms]
            splitted_feats = {stat:[x[stat] for x in dd] for stat in FUNC_FOR_DIV}

            #% add data to save
            # save timeseries data
            table_timeseries.append(timeseries_data)
            table_timeseries.flush()

            # save skeletons
            worm_coords_array['skeletons'].append(worm.skeleton)
            worm_coords_array['dorsal_contours'].append(worm.dorsal_contour)
            worm_coords_array['ventral_contours'].append(worm.ventral_contour)

            # save event data as a subgroup per worm
            worm_node = features_fid.create_group(
                group_events, 'worm_%i' % worm_index)
            worm_node._v_attrs['worm_index'] = worm_index
            worm_node._v_attrs['frame_range'] = np.array(
                (worm.first_frame, worm.last_frame))

            for feat in events_data:
                tmp_data = events_data[feat]
                # consider the cases where the output is a single number, empty
                # or None
                if isinstance(tmp_data, (float, int)):
                    tmp_data = np.array([tmp_data])
                if tmp_data is None or tmp_data.size == 0:
                    tmp_data = np.array([np.nan])
                features_fid.create_carray(
                    worm_node, feat, obj=tmp_data, filters=TABLE_FILTERS)

            # store the average for each worm feature
            for stat in FUNC_FOR_DIV:
                stats_features_df[stat][ind_N] = worm_stats[stat]

                #append the splitted traj features
                all_splitted_feats[stat] += splitted_feats[stat]
            # report progress
            _displayProgress(ind_N + 1)
        # create and save a table containing the averaged worm feature for each
        # worm

        f_node = features_fid.create_group('/', 'features_summary')
        for stat, stats_df in stats_features_df.items():
            splitted_feats = all_splitted_feats[stat]

            #check that the array is not empty
            if len(splitted_feats) > 0:
                splitted_feats_arr = np.array(splitted_feats)
            else:
                #return a row full of nan to indicate a fail
                splitted_feats_arr = np.full(1, np.nan, dtype=wStats.feat_avg_dtype)

            features_fid.create_table(
                f_node,
                stat,
                obj = stats_df,
                filters = TABLE_FILTERS
                )

            feat_stat_split = features_fid.create_table(
                f_node,
                stat + '_split',
                obj=splitted_feats_arr,
                filters=TABLE_FILTERS
                )
            feat_stat_split._v_attrs['split_traj_frames'] = split_traj_frames

            if stat == 'means':
                #FUTURE: I am duplicating this field for backward compatibility, I should remove it later on.
                features_fid.create_table(
                    '/',
                    'features_means',
                    obj = stats_df,
                    filters = TABLE_FILTERS
                    )

                features_fid.create_table(
                    '/',
                    'features_means_split',
                    obj=splitted_feats_arr,
                    filters=TABLE_FILTERS
                    )

    print_flush(
        base_name +
        ' Feature extraction finished: ' +
        progress_timer.get_time_str())

#%%
if __name__ == '__main__':
    skeletons_file = '/Users/ajaver/Tmp/Results/FirstRun_181016/HW_N1_Set2_Pos6_Ch1_18102016_140043_skeletons.hdf5'
    features_file = skeletons_file.replace('_skeletons.hdf5', '_features.hdf5')

    param = TrackerParams()
    is_single_worm = False
    use_manual_join = False
    use_skel_filter = True
    fps = 25

    good_traj_index, worm_index_type = getGoodTrajIndexes(skeletons_file,
        use_skel_filter,
        use_manual_join,
        is_single_worm,
        param.feat_filt_param)

    worm_index = good_traj_index[0]
    worm = WormFromTable(
                skeletons_file,
                worm_index,
                use_skel_filter=use_skel_filter,
                worm_index_type=worm_index_type,
                smooth_window=5)

    split_traj_frames = 300*fps
    splitted_worms = [x for x in worm.splitWormTraj(split_traj_frames)
            if x.n_valid_skel > 100]

    wStats = WormStats()
    dd = [getFeatStats(x, wStats)[1] for x in splitted_worms]
    splitted_feats = {stat:[x[stat] for x in dd] for stat in FUNC_FOR_DIV}
#    worm_openworm = copy.copy(worm)
#    worm_openworm.changeAxis()
#    assert worm_openworm.skeleton.shape[1] == 2
#    worm_features = mv.WormFeatures(worm_openworm)
#
#    wStats = WormStatsClass()
#    worm_stats = wStats.getWormStats(worm_features, np.mean)

#%%
#    getWormFeaturesFilt(
#        skeletons_file,
#        features_file,
#        use_skel_filter,
#        use_manual_join,
#        is_single_worm,
#        **param.feats_param)


text:
<dom-module id="s-menuicon">
    <link rel="stylesheet" href="s-menuicon.css">
    <link href="../jspm_packages/npm/font-awesome@4.3.0/css/font-awesome.min.css" rel="stylesheet">
    <template>

            <content></content>

    </template>
</dom-module>


text:
package net.glowstone.net.message.play.entity;

import com.flowpowered.network.Message;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.bukkit.util.Vector;

@Data
@RequiredArgsConstructor
public final class EntityVelocityMessage implements Message {

    private final int id;
    private final int velocityX;
    private final int velocityY;
    private final int velocityZ;

    public EntityVelocityMessage(int id, Vector velocity) {
        this(id, convert(velocity.getX()), convert(velocity.getY()), convert(velocity.getZ()));
    }

    private static int convert(double val) {
        return (int) (val * 8000);
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>activity/*.json API Test</title>

<link rel="stylesheet" href="./css/qunit-git.css">


text:
#pragma once

#include <QtCore/QHash>
#include <QtCore/QSet>

#include "kitBase/robotModel/configurationInterface.h"

#include "kitBase/kitBaseDeclSpec.h"

namespace kitBase {
namespace robotModel {

/// Provides current configuration (devices connected to ports and ready to work) and ability to manage it.
class ROBOTS_KIT_BASE_EXPORT Configuration : public ConfigurationInterface
{
	Q_OBJECT

public:
	~Configuration() override;

	void configureDevice(robotParts::Device * const device) override;

	void applyConfiguration() override;

	QList<robotParts::Device *> devices() const override;

	robotParts::Device *device(const PortInfo &port) const override;

	void clearDevice(const PortInfo &port) override;

signals:
	/// Emitted when all pending devices are configured (or failed to configure).
	void allDevicesConfigured();

private slots:
	/// Called when some device is finished configuring.
	/// @param success - true if configuration was successful.
	void onDeviceConfigured(bool success);

private:
	/// Check that there are no pending or "in progress" requests and emit allDevicesConfigured() if it is true.
	void checkAllDevicesConfigured();

	/// Contains currently configured and ready devices.
	QHash<PortInfo, robotParts::Device *> mConfiguredDevices;  // Has ownership.

	/// Contains devices that are not configured yet but are added for configuration and possibly already requested
	/// to configure themselves.
	QHash<PortInfo, robotParts::Device *> mPendingDevices;  // Has ownership.

	/// Contains ports on which device is already requested to configure itself and we are waiting a signal about
	/// result of configuration.
	QSet<PortInfo> mConfigurationInProgress;
};

}
}


text:
module Azure::MediaServices::Mgmt::V2020_05_01
  module Models
    #
    # Represents a policy option.
    #
    class ContentKeyPolicyOption

      include MsRestAzure

      # @return The legacy Policy Option ID.
      attr_accessor :policy_option_id

      # @return [String] The Policy Option description.
      attr_accessor :name

      # @return [ContentKeyPolicyConfiguration] The key delivery configuration.
      attr_accessor :configuration

      # @return [ContentKeyPolicyRestriction] The requirements that must be met
      # to deliver keys with this configuration
      attr_accessor :restriction

      #
      # Mapper for ContentKeyPolicyOption class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ContentKeyPolicyOption',
          type: {
            name: 'Composite',
            class_name: 'ContentKeyPolicyOption',
            model_properties: {
              policy_option_id: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'policyOptionId',
                type: {
                  name: 'String'
                }
              },
              name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'name',
                type: {
                  name: 'String'
                }
              },
              configuration: {
                client_side_validation: true,
                required: true,
                serialized_name: 'configuration',
                type: {
                  name: 'Composite',
                  polymorphic_discriminator: '@odata.type',
                  uber_parent: 'ContentKeyPolicyConfiguration',
                  class_name: 'ContentKeyPolicyConfiguration'
                }
              },
              restriction: {
                client_side_validation: true,
                required: true,
                serialized_name: 'restriction',
                type: {
                  name: 'Composite',
                  polymorphic_discriminator: '@odata.type',
                  uber_parent: 'ContentKeyPolicyRestriction',
                  class_name: 'ContentKeyPolicyRestriction'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
#region headers

// Copyright (c) 2018 Matthias Jansen
// See the LICENSE file in the project root for more information.

#endregion

#region imports

using ExceptionShield.Terminators;
using ExceptionShield.Test.Scaffolding;
using FluentAssertions;
using Xunit;

#endregion

namespace ExceptionShield.Test.Terminators
{
    public class TerminatorBaseTests
    {
        private class FaultyTerminator : TerminatorBase<AppleException>
        {
            /// <inheritdoc />
            protected override void TerminateInner(AppleException exception)
            {
                throw new CityException();
            }
        }

        [Fact]
        public void Terminate_ShouldNeverThrow()
        {
            var terminator = new FaultyTerminator();

            terminator.Invoking(_ => _.Terminate(new AppleException())).Should().NotThrow();
        }
    }
}


text:
from __future__ import (absolute_import, print_function, unicode_literals)

import hashlib
import io

from botocore.exceptions import ClientError

from acli.connections import get_client
from acli.errors import handle_boto_errors
from acli.output.s3 import (output_s3_list, output_s3_info)

@handle_boto_errors
def check_bucket_accessible(s3_client=None, bucket_name=None):
    try:
        s3_client.head_bucket(Bucket=bucket_name)
        return True
    except ClientError:
        exit("Unable to access bucket.")
    except Exception as unhandled:
        exit('Unhandled exception: {0}'.format(unhandled))

@handle_boto_errors
def get_s3_file_md5(s3_client=None, bucket_name=None, path=None):
    try:
        key_detail = s3_client.head_object(Bucket=bucket_name, Key=path)
        return key_detail.get('ETag')[1:-1]
    except ClientError:
        pass

def get_local_file_md5(path=None):
    try:
        with io.open(path, "rb") as local_file:
            return hashlib.md5(local_file.read()).hexdigest()
    except IOError:
        pass

@handle_boto_errors
def s3_list(aws_config=None, item=None):
    """
    @type aws_config: Config
    @type item: unicode
    """
    s3_client = get_client(client_type='s3', config=aws_config)
    buckets = s3_client.list_buckets()
    if not item:
        if buckets.get('Buckets'):
            output_s3_list(buckets=buckets.get('Buckets'))
        else:
            exit("No buckets found.")
    else:
        prefix = ''
        if item and '/' in item:
            path_elements = item.split('/')
            bucket_name = path_elements[0]
            prefix = "/".join(path_elements[1:])
        else:
            bucket_name = item
        check_bucket_accessible(s3_client=s3_client, bucket_name=bucket_name)
        try:
            objects = s3_client.list_objects(Bucket=bucket_name, Prefix=prefix, Delimiter='/')
            if not any((objects.get('CommonPrefixes'),
                        (objects.get('Contents')))):
                exit('Nothing found in: {0}'.format(item[:-1]))
            common_prefixes = objects.get('CommonPrefixes', list())
            folders = list()
            for first_bit in common_prefixes:
                folders.append(first_bit)
            output_s3_list(objects=objects, folders=folders, item=item, bucket_name=bucket_name)
        except ClientError as ce:
            if 'NoSuchBucket' in ce.response['Error']['Code']:
                exit('Bucket not found.')
            else:
                exit('Unhandled error: {0}'.format(ce.response['Error']['Code']))

@handle_boto_errors
def s3_info(aws_config=None, item=None):
    """
    @type aws_config: Config
    @type item: unicode
    """
    s3_client = get_client(client_type='s3', config=aws_config)
    prefix = ''
    if item and '/' in item:
        path_elements = item.split('/')
        bucket_name = path_elements[0]
        prefix = "/".join(path_elements[1:])
        if prefix.endswith('/'):
            prefix = prefix[:-1]
    else:
        bucket_name = item
    buckets = s3_client.list_buckets()
    owner = buckets.get('Owner')

    try:
        if bucket_name:
            check_bucket_accessible(s3_client=s3_client, bucket_name=bucket_name)
            s3_object = s3_client.get_object(Bucket=bucket_name, Key=prefix)
            output_s3_info(s3_object=s3_object, key=prefix, bucket=bucket_name)
        else:
            output_s3_info(owner=owner)
    except ClientError as ce:
        if 'NoSuchBucket' in ce.response['Error']['Code']:
            exit('Bucket not found.')
        elif 'NoSuchKey' in ce.response['Error']['Code']:
            exit('Key not found.')
        else:
            exit('Unhandled error: {0}'.format(ce.response['Error']['Code']))

@handle_boto_errors
def s3_cp(aws_config=None, source=None, dest=None):
    """
    @type aws_config: Config
    @type source: unicode
    @type dest: unicode
    """
    from acli.utils import (is_readable)
    from boto3.s3.transfer import S3Transfer, TransferConfig
    import os
    config = TransferConfig(
        multipart_threshold=200 * 1024 * 1024,
        max_concurrency=10,
        num_download_attempts=10,
    )
    s3_prefix = 's3://'
    s3_client = get_client(client_type='s3', config=aws_config)
    if source.startswith(s3_prefix) and not dest.startswith(s3_prefix):
        # COPYING FROM S3 TO LOCAL
        s3_location = source[5:].split('/')
        bucket_name = s3_location[0]
        s3_source = '/'.join(s3_location[1:])
        check_bucket_accessible(s3_client=s3_client, bucket_name=bucket_name)
        if dest == '/':
            dest = '{0}{1}'.format(os.path.abspath(dest), s3_location[-1])
        elif dest == '.' or dest.endswith('/'):
            dest = '{0}/{1}'.format(os.path.abspath(dest), s3_location[-1])
        elif os.path.isdir(os.path.abspath(dest)):
            dest = '{0}/{1}'.format(dest, s3_location[-1])
        s3_file_md5 = get_s3_file_md5(s3_client=s3_client,
                                      bucket_name=bucket_name,
                                      path=s3_source)
        if s3_file_md5:
            if s3_file_md5 == get_local_file_md5(dest):
                exit('Not transferring as identical file already exists.')
        else:
            exit('Cannot find: {0}/{1}'.format(bucket_name, s3_source))
        transfer = S3Transfer(s3_client, config)
        try:
            print('Transferring: {0} to: {1}'.format(source, dest))
            transfer.download_file(bucket_name, s3_source, dest)
        except BaseException as e:
            if hasattr(e, 'strerror') and e.strerror == 'Permission denied':
                exit('Permission denied.')
            else:
                print('Unhandled exception: {0}'.format(e))
    elif source.startswith(s3_prefix) and dest.startswith(s3_prefix):
        # COPYING FROM S3 TO S3
        print('Transferring: {0} to: {1}'.format(source, dest))
        exit('Not yet implemented.')
    elif not source.startswith(s3_prefix) and dest.startswith(s3_prefix):
        try:
            # COPYING ITEM(S) FROM LOCAL TO S3
            if os.path.isdir(source):
                exit('File transfers only for now.')
            else:
                # COPY LOCAL FILE TO S3
                if not is_readable(source):
                    exit('Cannot access: {0}'.format(source))
                s3_location = dest[5:].split('/')
                bucket_name = s3_location[0]
                s3_dest = '/'.join(s3_location[1:])
                # COPYING FILE TO A FOLDER
                if dest.endswith('/'):
                    file_name = source.split('/')[-1]
                    s3_dest += file_name
                check_bucket_accessible(s3_client=s3_client, bucket_name=bucket_name)
                # CHECK IF FILES ARE IDENTICAL
                s3_file_md5 = get_s3_file_md5(s3_client=s3_client,
                                              bucket_name=bucket_name,
                                              path=s3_dest)
                # If it's mulipart, then don't bother checking and just transfer
                if s3_file_md5 and '-' not in s3_file_md5:
                    local_file_md5 = get_local_file_md5(path=source)
                    if local_file_md5 == s3_file_md5:
                        exit('Not transferring as identical file already exists.')
                print('Transferring: {0} to: {1}'.format(source, dest))
                transfer = S3Transfer(s3_client, config)
                transfer.upload_file(source, bucket_name, s3_dest)
        except ClientError as ce:
            if 'AccessDenied' in ce.response['Error']['Code']:
                exit('Access denied. Please check permissions.')
        except Exception as e:
            print('Unhandled exception: {0}'.format(e))
    else:
        exit('Source or dest must be an S3 location defined with s3://.')
    exit()

@handle_boto_errors
def s3_rm(aws_config=None, item=None):
    """
    @type aws_config: Config
    @type item: unicode
    """
    s3_client = get_client(client_type='s3', config=aws_config)
    prefix = ''
    bucket_name = ''
    if item and '/' in item:
        path_elements = item.split('/')
        bucket_name = path_elements[0]
        prefix = "/".join(path_elements[1:])
        if prefix.endswith('/'):
            exit('Only keys can currently be removed.')
        check_bucket_accessible(s3_client=s3_client, bucket_name=bucket_name)
    else:
        exit('Invalid key.')
    try:
        s3_client.head_object(Bucket=bucket_name, Key=prefix)
    except ClientError:
        exit('Cannot access \'{0}\'.'.format(item))
    try:
        s3_client.delete_objects(Bucket=bucket_name, Delete={'Objects': [{'Key': prefix}, ]})
        exit('\'{0}\' deleted.'.format(item))
    except ClientError as error:
        if 'NoSuchBucket' in error.response['Error']['Code']:
            exit('Bucket not found.')
        elif 'NoSuchKey' in error.response['Error']['Code']:
            exit('Key not found.')
        else:
            exit('Unhandled error: {0}'.format(error.response['Error']['Code']))


text:
#include "val/include/sbsa_avs_val.h"
#include "val/include/val_interface.h"

#include "val/include/sbsa_avs_pe.h"
#include "val/include/sbsa_avs_smmu.h"
#include "val/include/sbsa_avs_pgt.h"
#include "val/include/sbsa_avs_iovirt.h"
#include "val/include/sbsa_avs_memory.h"
#include "val/include/sbsa_avs_pcie_enumeration.h"
#include "val/include/sbsa_avs_pcie.h"
#include "val/include/sbsa_avs_exerciser.h"

#define TEST_NUM   (AVS_EXERCISER_TEST_NUM_BASE + 11)
#define TEST_DESC  "ATS Functionality Check           "

#define TEST_DATA_NUM_PAGES  1
#define TEST_DATA 0xDE

static
void
write_test_data(void *buf, uint32_t size)
{

  uint32_t index;

  for (index = 0; index < size; index++) {
    *((char8_t *)buf + index) = TEST_DATA;
  }

  val_data_cache_ops_by_va((addr_t)buf, CLEAN_AND_INVALIDATE);
}

static
void
clear_dram_buf(void *buf, uint32_t size)
{

  uint32_t index;

  for (index = 0; index < size; index++) {
    *((char8_t *)buf + index) = 0;
  }

  val_data_cache_ops_by_va((addr_t)buf, CLEAN_AND_INVALIDATE);
}

static
void
payload(void)
{
  uint32_t pe_index;
  uint32_t dma_len;
  uint32_t instance;
  uint32_t e_bdf;
  uint32_t cap_base;
  void *dram_buf_in_virt;
  void *dram_buf_out_virt;
  uint64_t dram_buf_in_phys;
  uint64_t dram_buf_out_phys;
  uint64_t dram_buf_in_iova;
  uint64_t dram_buf_out_iova;
  uint64_t m_vir_addr;
  uint32_t num_exercisers, num_smmus;
  uint32_t device_id, its_id;
  uint32_t page_size = val_memory_page_size();
  memory_region_descriptor_t mem_desc_array[2], *mem_desc;
  pgt_descriptor_t pgt_desc;
  smmu_master_attributes_t master;
  uint64_t ttbr;
  uint32_t test_data_blk_size = page_size * TEST_DATA_NUM_PAGES;
  uint64_t *pgt_base_array;
  uint64_t translated_addr;
  uint32_t test_skip = 1;
  uint32_t reg_value = 0;

  /* Initialize DMA master and memory descriptors */
  val_memory_set(&master, sizeof(master), 0);
  val_memory_set(mem_desc_array, sizeof(mem_desc_array), 0);
  mem_desc = &mem_desc_array[0];
  dram_buf_in_phys = 0;

  pe_index = val_pe_get_index_mpid(val_pe_get_mpid());
  num_exercisers = val_exerciser_get_info(EXERCISER_NUM_CARDS, 0);
  num_smmus = val_iovirt_get_smmu_info(SMMU_NUM_CTRL, 0);

  /* Allocate an array to store base addresses of page tables allocated for
   * all exercisers
   */
  pgt_base_array = val_memory_alloc(sizeof(uint64_t) * num_exercisers);
  if (!pgt_base_array) {
      val_print(AVS_PRINT_ERR, "\n       mem alloc failure", 0);
      val_set_status(pe_index, RESULT_FAIL(g_sbsa_level, TEST_NUM, 02));
      return;
  }
  val_memory_set(pgt_base_array, sizeof(uint64_t) * num_exercisers, 0);

  /* Allocate a buffer to perform DMA tests on */
  dram_buf_in_virt = val_memory_alloc_pages(TEST_DATA_NUM_PAGES);
  if (!dram_buf_in_virt) {
      val_print(AVS_PRINT_ERR, "\n       Cacheable mem alloc failure", 0);
      val_memory_free(pgt_base_array);
      val_set_status(pe_index, RESULT_FAIL(g_sbsa_level, TEST_NUM, 03));
      return;
  }

  /* Set the virtual and physical addresses for test buffers */
  dram_buf_in_phys = (uint64_t)val_memory_virt_to_phys(dram_buf_in_virt);
  dram_buf_out_virt = dram_buf_in_virt + (test_data_blk_size / 2);
  dram_buf_out_phys = dram_buf_in_phys + (test_data_blk_size / 2);
  dma_len = test_data_blk_size / 2;

  /* Get translation attributes via TCR and translation table base via TTBR */
  if (val_pe_reg_read_tcr(0 /*for TTBR0*/,
                          &pgt_desc.tcr))
    goto test_fail;

  if (val_pe_reg_read_ttbr(0 /*for TTBR0*/,
                           &ttbr))
    goto test_fail;

  /* Enable all SMMUs */
  for (instance = 0; instance < num_smmus; ++instance)
     val_smmu_enable(instance);

  for (instance = 0; instance < num_exercisers; ++instance) {

    /* if init fail moves to next exerciser */
    if (val_exerciser_init(instance))
        continue;

    /* Get exerciser bdf */
    e_bdf = val_exerciser_get_bdf(instance);

    /* If ATS Capability Not Present, Skip. */
    if (val_pcie_find_capability(e_bdf, PCIE_ECAP, ECID_ATS, &cap_base) != PCIE_SUCCESS)
        continue;

    val_pcie_read_cfg(e_bdf, cap_base + ATS_CTRL, &reg_value);
    reg_value |= ATS_CACHING_EN;
    val_pcie_write_cfg(e_bdf, cap_base + ATS_CTRL, reg_value);

    pgt_desc.pgt_base = (ttbr & AARCH64_TTBR_ADDR_MASK);
    pgt_desc.mair = val_pe_reg_read(MAIR_ELx);
    pgt_desc.stage = PGT_STAGE1;

    /* Get memory attributes of the test buffer, we'll use the same attibutes to create
     * our own page table later.
     */
    if (val_pgt_get_attributes(pgt_desc, (uint64_t)dram_buf_in_virt, &mem_desc->attributes))
        goto test_fail;

    /* Get SMMU node index for this exerciser instance */
    master.smmu_index = val_iovirt_get_rc_smmu_index(PCIE_EXTRACT_BDF_SEG(e_bdf), PCIE_CREATE_BDF_PACKED(e_bdf));

    clear_dram_buf(dram_buf_in_virt, test_data_blk_size);

    dram_buf_in_iova = dram_buf_in_phys;
    dram_buf_out_iova = dram_buf_out_phys;
    if (master.smmu_index != AVS_INVALID_INDEX &&
        val_iovirt_get_smmu_info(SMMU_CTRL_ARCH_MAJOR_REV, master.smmu_index) == 3) {
        if (val_iovirt_get_device_info(PCIE_CREATE_BDF_PACKED(e_bdf),
                                       PCIE_EXTRACT_BDF_SEG(e_bdf),
                                       &device_id, &master.streamid,
                                       &its_id))
            continue;

        /* Each exerciser instance accesses a unique IOVA, which, because of SMMU translations,
         * will point to the same physical address. We create the requisite page tables and
         * configure the SMMU for each exerciser as such.
         */

        mem_desc->virtual_address = (uint64_t)dram_buf_in_virt + instance * test_data_blk_size;
        mem_desc->physical_address = dram_buf_in_phys;
        mem_desc->length = test_data_blk_size;
        mem_desc->attributes |= PGT_STAGE1_AP_RW;

        /* Need to know input and output address sizes before creating page table */
        if ((pgt_desc.ias = val_smmu_get_info(SMMU_IN_ADDR_SIZE, master.smmu_index)) == 0)
          goto test_fail;

        if ((pgt_desc.oas = val_smmu_get_info(SMMU_OUT_ADDR_SIZE, master.smmu_index)) == 0)
          goto test_fail;

        if (val_pgt_create(mem_desc, &pgt_desc))
          goto test_fail;

        pgt_base_array[instance] = pgt_desc.pgt_base;

        /* Configure the SMMU tables for this exerciser to use this page table for VA to PA translations*/
        if (val_smmu_map(master, pgt_desc))
        {
            val_print(AVS_PRINT_ERR, "\n       SMMU mapping failed (%x)     ", e_bdf);
            goto test_fail;
        }

        dram_buf_in_iova = mem_desc->virtual_address;
        dram_buf_out_iova = dram_buf_in_iova + (test_data_blk_size / 2);
    }

    test_skip = 0;

    val_exerciser_set_param(DMA_ATTRIBUTES, (uint64_t)dram_buf_in_virt + instance * test_data_blk_size, dma_len, instance);

    /* Send an ATS Translation Request for the VA */
    if (val_exerciser_ops(ATS_TXN_REQ, (uint64_t)dram_buf_in_virt + instance * test_data_blk_size, instance)) {
        val_print(AVS_PRINT_ERR, "\n       ATS Translation Req Failed exerciser %4x", instance);
        goto test_fail;
    }

    /* Get ATS Translation Response */
    m_vir_addr = (uint64_t)dram_buf_in_virt + instance * test_data_blk_size;
    if (val_exerciser_get_param(ATS_RES_ATTRIBUTES, &translated_addr, &m_vir_addr, instance)) {
        val_print(AVS_PRINT_ERR, "\n       ATS Response failure %4x", instance);
        goto test_fail;
    }

    /* Compare Translated Addr with Physical Address from the Mappings */
    if (translated_addr != dram_buf_in_phys) {
        val_print(AVS_PRINT_ERR, "\n       ATS Translation failure %4x", instance);
        goto test_fail;
    }

    /* Initialize the sender buffer with test specific data */
    write_test_data(dram_buf_in_virt, dma_len);

    /* Configure Exerciser to issue subsequent DMA transactions with AT(Address Translated) bit Set */
    val_exerciser_set_param(CFG_TXN_ATTRIBUTES, TXN_ADDR_TYPE, AT_TRANSLATED, instance);

    if (val_exerciser_set_param(DMA_ATTRIBUTES, dram_buf_in_phys, dma_len, instance)) {
        val_print(AVS_PRINT_ERR, "\n       DMA attributes setting failure %4x", instance);
        goto test_fail;
    }

    /* Trigger DMA from input buffer to exerciser memory */
    if (val_exerciser_ops(START_DMA, EDMA_TO_DEVICE, instance)) {
        val_print(AVS_PRINT_ERR, "\n       DMA write failure to exerciser %4x", instance);
        goto test_fail;
    }

    if (val_exerciser_set_param(DMA_ATTRIBUTES, dram_buf_out_iova, dma_len, instance)) {
        val_print(AVS_PRINT_ERR, "\n       DMA attributes setting failure %4x", instance);
        goto test_fail;
    }

    /* Trigger DMA from exerciser memory to output buffer*/
    if (val_exerciser_ops(START_DMA, EDMA_FROM_DEVICE, instance)) {
        val_print(AVS_PRINT_ERR, "\n       DMA read failure from exerciser %4x", instance);
        goto test_fail;
    }

    if (val_memory_compare(dram_buf_in_virt, dram_buf_out_virt, dma_len)) {
        val_print(AVS_PRINT_ERR, "\n       Data Comparasion failure for Exerciser %4x", instance);
        goto test_fail;
    }

    clear_dram_buf(dram_buf_in_virt, test_data_blk_size);

  }

  if (test_skip)
    val_set_status(pe_index, RESULT_SKIP(g_sbsa_level, TEST_NUM, 01));
  else
    val_set_status(pe_index, RESULT_PASS(g_sbsa_level, TEST_NUM, 01));

  goto test_clean;

test_fail:
  val_set_status(pe_index, RESULT_FAIL(g_sbsa_level, TEST_NUM, 01));

test_clean:
  /* Return the pages to the heap manager */
  val_memory_free_pages(dram_buf_in_virt, TEST_DATA_NUM_PAGES);

  /* Remove all address mappings for each exerciser */
  for (instance = 0; instance < num_exercisers; ++instance)
  {
    e_bdf = val_exerciser_get_bdf(instance);
    master.smmu_index = val_iovirt_get_rc_smmu_index(PCIE_EXTRACT_BDF_SEG(e_bdf), PCIE_CREATE_BDF_PACKED(e_bdf));
    if (val_iovirt_get_device_info(PCIE_CREATE_BDF_PACKED(e_bdf),
                                   PCIE_EXTRACT_BDF_SEG(e_bdf),
                                   &device_id, &master.streamid,
                                   &its_id))
        continue;

    val_smmu_unmap(master);

    if (pgt_base_array[instance] != 0) {
      pgt_desc.pgt_base = pgt_base_array[instance];
      val_pgt_destroy(pgt_desc);
    }

    if (val_pcie_find_capability(e_bdf, PCIE_ECAP, ECID_ATS, &cap_base) == PCIE_SUCCESS)
    {
        val_pcie_read_cfg(e_bdf, cap_base + ATS_CTRL, &reg_value);
        reg_value &= ATS_CACHING_DIS;
        val_pcie_write_cfg(e_bdf, cap_base + ATS_CTRL, reg_value);
    }

  }

  /* Disable all SMMUs */
  for (instance = 0; instance < num_smmus; ++instance)
     val_smmu_disable(instance);

  val_memory_free(pgt_base_array);
}

uint32_t
e011_entry(void)
{
  uint32_t num_pe = 1;
  uint32_t status = AVS_STATUS_FAIL;

  status = val_initialize_test(TEST_NUM, TEST_DESC, num_pe, g_sbsa_level);
  if (status != AVS_STATUS_SKIP)
      val_run_test_payload(TEST_NUM, num_pe, payload, 0);

  /* Get the result from all PE and check for failure */
  status = val_check_for_error(TEST_NUM, num_pe);

  val_report_status(0, SBSA_AVS_END(g_sbsa_level, TEST_NUM));

  return status;
}


text:
    data Ordering  where
      LT :: Ordering
      GT :: Ordering
      EQ :: Ordering

### Type Classes

![Prelude](images/Prelude.png)

    class Alternative f where
      empty :: forall a. f a
      (<|>) :: forall a. f a -> f a -> f a

    class (Apply f) <= Applicative f where
      pure :: forall a. a -> f a

    class (Functor f) <= Apply f where
      (<*>) :: forall a b. f (a -> b) -> f a -> f b

    class (Apply m) <= Bind m where
      (>>=) :: forall a b. m a -> (a -> m b) -> m b

    class Bits b where
      (&) :: b -> b -> b
      (|) :: b -> b -> b
      (^) :: b -> b -> b
      shl :: b -> Prim.Number -> b
      shr :: b -> Prim.Number -> b
      zshr :: b -> Prim.Number -> b
      complement :: b -> b

    class BoolLike b where
      (&&) :: b -> b -> b
      (||) :: b -> b -> b
      not :: b -> b

    class (Semigroupoid a) <= Category a where
      id :: forall t. a t t

    class Eq a where
      (==) :: a -> a -> Prim.Boolean
      (/=) :: a -> a -> Prim.Boolean

    class Functor f where
      (<$>) :: forall a b. (a -> b) -> f a -> f b

    class (Applicative m, Bind m) <= Monad m where

    class Num a where
      (+) :: a -> a -> a
      (-) :: a -> a -> a
      (*) :: a -> a -> a
      (/) :: a -> a -> a
      (%) :: a -> a -> a
      negate :: a -> a

    class (Eq a) <= Ord a where
      compare :: a -> a -> Ordering

    class Semigroup a where
      (<>) :: a -> a -> a

    class Semigroupoid a where
      (<<<) :: forall b c d. a c d -> a b c -> a b d

    class Show a where
      show :: a -> Prim.String

### Type Class Instances

    instance bitsNumber :: Bits Prim.Number

    instance boolLikeBoolean :: BoolLike Prim.Boolean

    instance categoryArr :: Category Prim.Function

    instance eqArray :: (Eq a) => Eq [a]

    instance eqBoolean :: Eq Prim.Boolean

    instance eqNumber :: Eq Prim.Number

    instance eqOrdering :: Eq Ordering

    instance eqString :: Eq Prim.String

    instance numNumber :: Num Prim.Number

    instance ordNumber :: Ord Prim.Number

    instance semigroupString :: Semigroup Prim.String

    instance semigroupoidArr :: Semigroupoid Prim.Function

    instance showArray :: (Show a) => Show [a]

    instance showBoolean :: Show Prim.Boolean

    instance showNumber :: Show Prim.Number

    instance showOrdering :: Show Ordering

    instance showString :: Show Prim.String

### Values

    (#) :: forall a b. a -> (a -> b) -> b

    ($) :: forall a b. (a -> b) -> a -> b

    (++) :: forall s. (Semigroup s) => s -> s -> s

    (:) :: forall a. a -> [a] -> [a]

    (<) :: forall a. (Ord a) => a -> a -> Prim.Boolean

    (<=) :: forall a. (Ord a) => a -> a -> Prim.Boolean

    (>) :: forall a. (Ord a) => a -> a -> Prim.Boolean

    (>=) :: forall a. (Ord a) => a -> a -> Prim.Boolean

    (>>>) :: forall a b c d. (Semigroupoid a) => a b c -> a c d -> a b d

    ap :: forall m a b. (Monad m) => m (a -> b) -> m a -> m b

    asTypeOf :: forall a. a -> a -> a

    boolAnd :: Prim.Boolean -> Prim.Boolean -> Prim.Boolean

    boolNot :: Prim.Boolean -> Prim.Boolean

    boolOr :: Prim.Boolean -> Prim.Boolean -> Prim.Boolean

    concatString :: Prim.String -> Prim.String -> Prim.String

    cons :: forall a. a -> [a] -> [a]

    const :: forall a b. a -> b -> a

    flip :: forall a b c. (a -> b -> c) -> b -> a -> c

    liftA1 :: forall f a b. (Applicative f) => (a -> b) -> f a -> f b

    liftM1 :: forall m a b. (Monad m) => (a -> b) -> m a -> m b

    numAdd :: Prim.Number -> Prim.Number -> Prim.Number

    numAnd :: Prim.Number -> Prim.Number -> Prim.Number

    numCompare :: Prim.Number -> Prim.Number -> Ordering

    numComplement :: Prim.Number -> Prim.Number

    numDiv :: Prim.Number -> Prim.Number -> Prim.Number

    numMod :: Prim.Number -> Prim.Number -> Prim.Number

    numMul :: Prim.Number -> Prim.Number -> Prim.Number

    numNegate :: Prim.Number -> Prim.Number

    numOr :: Prim.Number -> Prim.Number -> Prim.Number

    numShl :: Prim.Number -> Prim.Number -> Prim.Number

    numShr :: Prim.Number -> Prim.Number -> Prim.Number

    numSub :: Prim.Number -> Prim.Number -> Prim.Number

    numXor :: Prim.Number -> Prim.Number -> Prim.Number

    numZshr :: Prim.Number -> Prim.Number -> Prim.Number

    refEq :: forall a. a -> a -> Prim.Boolean

    refIneq :: forall a. a -> a -> Prim.Boolean

    return :: forall m a. (Monad m) => a -> m a

    showArrayImpl :: forall a. (a -> Prim.String) -> [a] -> Prim.String

    showNumberImpl :: Prim.Number -> Prim.String

    showStringImpl :: Prim.String -> Prim.String

## Module Data.Function

### Values

    on :: forall a b c. (b -> b -> c) -> (a -> b) -> a -> a -> c

## Module Data.Eq

### Types

    data Ref a where
      Ref :: a -> Ref a

### Type Class Instances

    instance eqRef :: Eq (Ref a)

### Values

    liftRef :: forall a b. (a -> a -> b) -> Ref a -> Ref a -> b

## Module Prelude.Unsafe

### Values

    unsafeIndex :: forall a. [a] -> Prim.Number -> a

## Module Control.Monad.Eff

### Types

    data Eff :: # ! -> * -> *

    type Pure a = forall e. Eff e a

### Type Class Instances

    instance applicativeEff :: Applicative (Eff e)

    instance applyEff :: Apply (Eff e)

    instance bindEff :: Bind (Eff e)

    instance functorEff :: Functor (Eff e)

    instance monadEff :: Monad (Eff e)

### Values

    bindE :: forall e a b. Eff e a -> (a -> Eff e b) -> Eff e b

    forE :: forall e. Prim.Number -> Prim.Number -> (Prim.Number -> Eff e {  }) -> Eff e {  }

    foreachE :: forall e a. [a] -> (a -> Eff e {  }) -> Eff e {  }

    returnE :: forall e a. a -> Eff e a

    runPure :: forall a. Pure a -> a

    untilE :: forall e. Eff e Prim.Boolean -> Eff e {  }

    whileE :: forall e a. Eff e Prim.Boolean -> Eff e a -> Eff e {  }

## Module Control.Monad.Eff.Unsafe

### Values

    unsafeInterleaveEff :: forall eff1 eff2 a. Eff eff1 a -> Eff eff2 a

## Module Debug.Trace

### Types

    data Trace :: !

### Values

    print :: forall a r. (Show a) => a -> Eff (trace :: Trace | r) {  }

    trace :: forall r. Prim.String -> Eff (trace :: Trace | r) {  }

## Module Control.Monad.ST

### Types

    data ST :: * -> !

    data STArray :: * -> * -> *

    data STRef :: * -> * -> *

### Values

    modifySTRef :: forall a h r. STRef h a -> (a -> a) -> Eff (st :: ST h | r) a

    newSTArray :: forall a h r. Prim.Number -> a -> Eff (st :: ST h | r) (STArray h a)

    newSTRef :: forall a h r. a -> Eff (st :: ST h | r) (STRef h a)

    peekSTArray :: forall a h r. STArray h a -> Eff (st :: ST h | r) a

    pokeSTArray :: forall a h r. STArray h a -> Prim.Number -> a -> Eff (st :: ST h | r) a

    readSTRef :: forall a h r. STRef h a -> Eff (st :: ST h | r) a

    runST :: forall a r. (forall h. Eff (st :: ST h | r) a) -> Eff r a

    runSTArray :: forall a r. (forall h. Eff (st :: ST h | r) (STArray h a)) -> Eff r [a]

    writeSTRef :: forall a h r. STRef h a -> a -> Eff (st :: ST h | r) a


text:
The SHIELD Web UI - Developer Notes
===================================

This document contains notes for the initiate SHIELD Web UI
Developer, that curious creature who has decided to forego the
trappings of _modern Javascript development_ and live closer to
the land.  Or something.

A Note on Namespacing
---------------------

Not polluting the global namespace is all the rage these days.  We
took it a step too far, and put all of the definitions that we
need in a single namespace, `S.H.I.E.L.D`; yes -- that's a nested
structure 4 or 5 levels deep.  You're welcome.

The Data Structures At Play
---------------------------

The core engine of the SHIELD Web UI is the `Database` object.  Or
maybe we're calling it the `Engine` class, or just plain old `UI`.
Who can even keep up with the furious change of pace here??

Anyway, it's the only class we have, and it's pretty central to
the UI.  It governs how the templates are drawn, how data gets
pulled down via WebSocket and XMLHttpRequests, aggregates and
composites data elements, and more.

To keep things straight, this magical class maintains local state,
via variables that are publicly accessible, and made available
explicitly to template code.

To keep all of this straight, we present the Utmostly Correct and
One True Way of Accessing Data.

- `.shield` - Metadata about the SHIELD Core, including things set
  by the operator, like the environment name, color, motd.  Also
  includes version and IP information.

  Note: this element is always set, and it rarely changes.

- `.user` - A User object.  If the viewer is not authenticated,
  this will be _undefined_ (but present), and the reset of the
  elements are probably missing.

- `.tenant` - The UUID of the currently targeted tenant.  If the
  authenticated user has zero grants, this will be _undefined_.

- `.tenants` - A map of UUID → Tenant object, for all tenants
  the authenticated user belongs to.   Each Tenant object
  contains:

  - `.tenants[uuid].targets` - The target data systems defined for
    this tenant.

  - `.tenants[uuid].stores` - The storage systems defined for this
    tenant.  This _DOES NOT_ include global storage systems.

  - `.tenants[uuid].jobs` - Scheduled backup jobs for this tenant.
  - `.tenants[uuid].archives` - Backup archives for this tenant.

  - `.tenants[uuid].role` - The name of the role that this user
    has been granted, on this tenant (a string).

  - `.tenants[uuid].grants[right]` - A set of booleans, one for
    each tenant right, that translates roles like "admin" into
    answers to questions like "is this user an engineer on this
    tenant?"

    Currently recognized rights are: `admin`, `engineer`, and
    `operator`.

- `.system.grants[right]` - A set of booleans, one for each system
  right, that translate roles like "engineer" into answers to
  questions like "is this user an admin?"

  Currently recognized rights are: `admin`, `manager`, and
  `engineer`.

- `.global.stores` - A map of UUID → Store object, for all
   globally defined stores.  Admin accounts will have access to
   more (sensitive) attributes on each storage system.

- `.global.tenants` - A map of UUID → Tenant object, for all
  tenants.  This is only available for admins.

Some of this data is duplicated.  That is unfortunate, but the
structure described above serves the purposes of the web UI,
without burdening the frontend developer with too many performance
optimization shenanigans.

As data comes across the WebSocket, or via XMLHttpRequests, the
attributes will be merged in an overriding fashion.  Additional
fields not specified in an update are strictly to be left alone.
This allows the web UI to store additional metadata, or cache
calculated attributes, without fear of losing them later because
of a refresh or update.


text:
import { Cryptology } from '../utilities/cryptology';
import { ECPair, HDNode } from 'bitcoinjs-lib';

export class Identity {

	private cryptology: Cryptology;

	constructor() {
		this.cryptology = new Cryptology();
	}

	// public publicKey;
	// public privateKey;
	// public masterKey;
	// public publicKeyFingerprint;
	// public signingKey;
	// public verifyKey;
	// public verifyKeyFingerprint;
	public id: number;
	public type = 'Identity';
	public label: string;

	public key: CryptoKey;
	public seed: CryptoKey;

	public root: HDNode;
	public account: HDNode;
	// public pair: ECPair;

	public address: string;
	public identifier: string;

	// get id() {
	// 	return this.cryptology.uint8ArrayToHex(this.publicKeyFingerprint);
	// }

	// get displayName() {
	// 	return this.cryptology.uint8ArrayToHex(this.publicKeyFingerprint);
	// }
}


text:
@tailwind base;

@tailwind components;

html {
  font-size: 10px;
}

@tailwind utilities;


text:
$(".datepicker").pickadate({
    selectMonths: true,
    selectYears: 15,
    today: "Hoje",
    clear: "Limpar",
    close: "Ok",
    closeOnSelect: false
});

$(".timepicker").pickatime({
    default: "Atual",
    fromnow: 0,
    twelvehour: false,
    donetext: "OK",
    cleartext: "Limpar",
    canceltext: "Cancelar",
    autoclose: false,
    ampmclickable: true,
    aftershow: function(){}
});


text:
require 'spec_helper'

describe PowerResource::CollectionHelper do
  let(:post) { Post.create(title: 'Test post', content: 'Lorem ipsum dolor') }

  before :each do
    @controller = PostsController.new
    @controller.request = ActionDispatch::TestRequest.new
    @controller.instance_variable_set('@post', post)
  end

  describe '#collection_name' do
    it 'returns a name for a current collection' do
      expect(helper.collection_name).to eq('posts')
    end
  end

  describe '#collection_human_name' do
    it 'returns humanized name for a current collection' do
      expect(helper.collection_human_name).to eq('Posts')
    end
  end

  describe '#collection_title' do
    it 'returns a title for a current collection' do
      expect(helper.collection_title).to eq('Posts')
    end
  end

  ### Localization specs

  context 'when locale is set' do
    before :each do
      I18n.locale = :fi
    end

    after :each do
      I18n.locale = I18n.default_locale
    end

    describe '#collection_human_name' do
      it 'returns localized name for a current collection' do
        expect(helper.collection_human_name).to eq('Artikkelit')
      end
    end

    describe '#collection_title' do
      it 'returns localized title for a current collection' do
        expect(helper.collection_title).to eq('Lista artikkeleista')
      end
    end
  end
end


text:
published: true
tags:
  - databases
  - postgreSQL
  - windows
excerpt: >-
  The MIMIC II database is an excellent resource with thousands of de-identified
  ICU patients and their EMR data. Installation of the database for Windows is a
  bit sparse so here is some more information on how to get it working.
comments: true
---
## Installing MIMIC II Database on Windows

[MIMIC II](https://physionet.org/mimic2/), Multiparameter Intelligent Monitoring in Intensive Care, is a database with approxmiately 33,000 de-identified patients. It is available for public use (after submitting an application) and is free to use. This makes the MIMIC database an excellent resource for researchers and data analysts alike to use and build machine learning models or run statistical analyses for specific medical conditions that would otherwise be unaccessible.

A new version of the MIMIC database, MIMIC III, is [available online](https://mimic.physionet.org/tutorials/install-mimic-locally-windows/) and has thorough documentation on how to install the database for different systems.

Documentation for MIMIC II is also available, but it's not as thorough as it could be for Windows users. When you download MIMIC II, it comes with shell scripts to use on unix/linux/OS X machines, but fortunately there is a [python script to run in Windows](https://github.com/AndreaBravi/MIMIC2) available. A few extra steps are needed to clarify how to use this python script.

* Be sure you have already installed PostrgreSQL. I used version 9.6.1 without issue.
* Have python installed on your workstation. My machine already has Anaconda which installed Python.
* If you're planning on installing the entire database, you're supposed to have at least 75GB.
* **Most importantly, you must place the files files (the tar.gz files) into the MIMIC-Importer-2.6/tarballs directory. Include in this directory the mimic2cdb-2.6-Definitions.tar.gz file as well! **

1. Download the [python script](https://github.com/AndreaBravi/MIMIC2).
2. If you downloaded the script in your Downloads folder, then you will need to launch the Command Prompt window and type the following:

python.exe C:\Users\YOURUSERNAME\Downloads\MIMIC2-master\MIMIC2-master\mimic2_setup.py

3. If python.exe does not work, then you will need to set up your PATH variable to load Python, or point directly to the python executable.
4. The script will ask for **script to pg_env.bat:**. This is referring to the Postgres installation directory. For me I typed:

C\Program Files\PostgreSQL\9.6

5. Now you will be asked for **Provide Path to MIMIC Importer:**, which is the script that comes from MIMIC's website where you download the flat files (it is not included with the flat files). For me I saved it to my desktop:

 C:\Users\darene\Desktop\MIMIC\MIMIC-Importer-2.6

6. The script will ask for the database credentials you'd like to use.
7. Finally, it will untar the tarballed flat files which will take a few minutes, and then proceed with adding each subject to the database.

If you have any trouble, the included README.txt that's included with the flat file download is very thorough.


text:
#region Copyright

#endregion Copyright

using DataTables.AspNet.Core;
using DataTables.AspNet.Core.NameConvention;
using DataTables.AspNet.Mvc5.NameConvention;

namespace DataTables.AspNet.Mvc5
{
    /// <summary>
    /// Represents a configuration object for DataTables.AspNet.
    /// </summary>
    public class Options : IOptions
    {
        /// <summary>
        /// Gets default page length when parameter is not set.
        /// </summary>
        public int DefaultPageLength { get; private set; }
        /// <summary>
        /// Gets an indicator if draw parameter should be validated.
        /// </summary>
        public bool IsDrawValidationEnabled { get; private set; }
        /// <summary>
        /// Gets an indicator whether request parameters parsing is enabled or not.
        /// </summary>
        public bool IsRequestAdditionalParametersEnabled { get; private set; }
        /// <summary>
        /// Gets an indicator whether response parameters parsing is enabled or not.
        /// </summary>
        public bool IsResponseAdditionalParametersEnabled { get; private set; }

        /// <summary>
        /// Gets the request name convention to be used when resolving request parameters.
        /// </summary>
        public IRequestNameConvention RequestNameConvention { get; private set; }
        /// <summary>
        /// Gets the response name convention to be used when serializing response elements.
        /// </summary>
        public IResponseNameConvention ResponseNameConvention { get; private set; }

        /// <summary>
        /// Sets the default page length to be used when request parameter is not set.
        /// Page length is set to 10 by default.
        /// </summary>
        /// <param name="defaultPageLength">The new default page length to be used.</param>
        /// <returns></returns>
        public IOptions SetDefaultPageLength(int defaultPageLength) { DefaultPageLength = defaultPageLength; return this; }
        /// <summary>
        /// Enables draw validation.
        /// Draw validation is enabled by default.
        /// </summary>
        /// <returns></returns>
        public IOptions EnableDrawValidation() { IsDrawValidationEnabled = true; return this; }
        /// <summary>
        /// Disables draw validation.
        /// As stated by jQuery DataTables, draw validation should not be disabled unless explicitly required.
        /// </summary>
        /// <returns></returns>
        public IOptions DisableDrawValidation() { IsDrawValidationEnabled = false; return this; }
        /// <summary>
        /// Enables parsing request aditional parameters.
        /// You must provide your own function for parameter resolution on DataTables.AspNet registration.
        /// </summary>
        /// <returns></returns>
        public IOptions EnableRequestAdditionalParameters() { IsRequestAdditionalParametersEnabled = true; return this; }
        /// <summary>
        /// Disables parsing request aditional parameters.
        /// Aditional parameters are not resolved by default for security reasons.
        /// </summary>
        /// <returns></returns>
        public IOptions DisableRequestAdditionalParameters() { IsRequestAdditionalParametersEnabled = false; return this; }
        /// <summary>
        /// Enables parsing response aditional parameters.
        /// </summary>
        /// <returns></returns>
        public IOptions EnableResponseAdditionalParameters() { IsResponseAdditionalParametersEnabled = true; return this; }
        /// <summary>
        /// Disables parsing response aditional parameters.
        /// Aditional parameters are not resolved by default for security reasons.
        /// </summary>
        /// <returns></returns>
        public IOptions DisableResponseAdditionalParameters() { IsResponseAdditionalParametersEnabled = false; return this; }
        /// <summary>
        /// Forces DataTables to use CamelCase on request/respose parameter names.
        /// CamelCase is enabled by default and is available for DataTables 1.10 and above.
        /// </summary>
        /// <returns></returns>
        public IOptions UseCamelCase() { RequestNameConvention = new CamelCaseRequestNameConvention(); ResponseNameConvention = new CamelCaseResponseNameConvention(); return this; }
        /// <summary>
        /// Forces DataTables to use HungarianNotation on request/response parameter names.
        /// HungarianNotation is available for compatibility with older/legacy DataTables (prior to 1.10).
        /// </summary>
        /// <returns></returns>
        public IOptions UseHungarianNotation() { RequestNameConvention = new HungarianNotationRequestNameConvention(); ResponseNameConvention = new HungarianNotationResponseNameConvention(); return this; }

        /// <summary>
        /// Creates a new 'Option' instance.
        /// </summary>
        public Options()
            : this (10, true, false, false, new CamelCaseRequestNameConvention(), new CamelCaseResponseNameConvention())
        { }
        /// <summary>
        /// Creates a new 'Option' instance.
        /// </summary>
        /// <param name="defaultPageLength">Default page length to be used.</param>
        /// <param name="enableDrawValidation">Indicates if draw validation will be enabled by default or not.</param>
        /// <param name="enableRequestAdditionalParameters">Indicates whether request aditional parameters parsing is enabled or not.</param>
        /// <param name="enableResponseAdditionalParameters">Indicates whether response aditional parameters parsing is enabled or not.</param>
        /// <param name="requestNameConvention">Request naming convention to be used.</param>
        /// <param name="responseNameConvention">Response naming convention to be used.</param>
        public Options(int defaultPageLength, bool enableDrawValidation, bool enableRequestAdditionalParameters, bool enableResponseAdditionalParameters, IRequestNameConvention requestNameConvention, IResponseNameConvention responseNameConvention)
        {
            DefaultPageLength = defaultPageLength;
            IsDrawValidationEnabled = enableDrawValidation;
            IsRequestAdditionalParametersEnabled = enableRequestAdditionalParameters;
            IsResponseAdditionalParametersEnabled = enableResponseAdditionalParameters;

            RequestNameConvention = requestNameConvention;
            ResponseNameConvention = responseNameConvention;
        }
    }
}