text:
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from time import time
from time import localtime
import glob
from os import remove

# upload every files inside local input folder. (Delete them (locally) after the upload - not at the moment)
def upload_input_data(s3_name, conn=S3Connection()):

    # select the input directory to upload files. At the moment it is in stand-by
    # input_directory = select_input_directory(s3_name)

    # conn = S3Connection()
    bucket = conn.get_bucket(s3_name)

    # all files from local data folder
    path = 'data/*/'
    localfolders = glob.glob(path)

    op = -1
    while op != str(0):
        count = 1
        print "\nUpload input files to S3 Bucket:"
        # It selects and shows the local folders inside 'data' folder (1st level only)
        for localfolder in localfolders:
            print "\t%d.\t%s" % (count, localfolder[5:-1])
            count += 1
        print "\t0.\tPrevious Menu"
        op = raw_input("Please select the folder to upload your input data to MapReduce operation: ")

        try:
            int(op)
        except ValueError:
            print "Invalid operation. Try again..."
        else:
            if 0 < int(op) < count:
                # upload all the files inside the selected localfolder to the selected S3 bucket
                selectedfolder = glob.glob(localfolders[int(op)-1]+ "input/*")
                upcount = 1
                for files in selectedfolder:
                   # in order to avoid the windows-style
                    if '\\' in files:
                        files = files.replace('\\', '/')

                    lastpositonofslash = files.rfind('/')
                    bucketfile = "input/" + localfolders[int(op)-1][5:-1] + files[lastpositonofslash:]

                    k = bucket.new_key(bucketfile)
                    print "uploading %s to %s..." % (files, bucketfile)
                    k.set_contents_from_filename(files)
                    upcount += 1
                    break

                    print "%d files uploaded to %s bucket!" % (upcount-1, s3_name)
                else:
                    break

# todo: ainda nao tem qualquer proteccao
# todo: diferenciar melhor o map do reduce
# action = mapper OR reducer
def upload_map_reduce(s3_name, conn=S3Connection()):

    # print "\n------Connecting to S3 (Bucket: %s)...-----" % s3_name
    bucket = conn.get_bucket(s3_name)

    # all files from local folder
    path = 'data/*/'
    files = glob.glob(path)

    data = {}
    op = -1
    while op not in data:
        count = 1
        print "\nUpload MapReduce scripts to S3 Bucket:"
        # It selects and shows the local folders inside 'data' folder (1st level only)
        for file in files:
            print "\t%d.\t%s" % (count, file[5:-1])
            count += 1
        print "\t0.\tPrevious Menu"

        op = raw_input("Please select the folder to upload your MapReduce scripts: ")

        try:
            int(op)
        except ValueError:
            print "Invalid operation. Try again..."
        else:
            if 0 < int(op) < count:
                # upload all the files inside the selected localfolder to the selected S3 bucket
                selectedfolder = glob.glob(files[int(op)-1] + "scripts/*")
                upcount = 1
                for file in selectedfolder:
                    # in order to avoid the windows-style
                    if '\\' in file:
                        file = file.replace('\\', '/')

                    lastpositonofslash = file.rfind('/')
                    bucketfile = "scripts/" + files[int(op)-1][5:-1] + file[lastpositonofslash:]

                    k = bucket.new_key(bucketfile)
                    print "uploading %s to %s..." % (file, bucketfile)
                    k.set_contents_from_filename(file)
                    upcount += 1
                break
                print "%d scripts uploaded to %s bucket!" % (upcount-1, s3_name)
            else:
                break

# todo: sem proteccoes e sem retorno sem um bucket definido atm
def select_s3_bucket(conn=S3Connection()):
    buckets = conn.get_all_buckets()

    data = {}
    op = 1
    while op != str(0):
        count = 1
        print "\nAvailable buckets in your account"
        for bucket in buckets:
            data[str(count)] = bucket.name
            print "\t%d.\t%s" % (count, bucket.name)
            count += 1
        print "\t%d.\tCreate new bucket (name must be unique)" % count
        print "\t0.\tMain Menu"

        op = raw_input("Your option: ")
        op = op.strip()

        if op in data:          # return a existing bucket
            return data[op]
        elif op == str(count):
            return create_new_bucket(conn)
        elif op != str(0):
            print 'Invalid option! Please, try again...'

def select_s3_bucket2(conn=S3Connection()):
    buckets = conn.get_all_buckets()

    data = {}
    op = 1
    while op != str(0):
        count = 1
        print "\nAvailable buckets in your account"
        for bucket in buckets:
            data[str(count)] = bucket.name
            print "\t%d.\t%s" % (count, bucket.name)
            count += 1
        print "\t%d.\tCreate new bucket (name must be unique)" % count
        print "\t0.\tMain Menu"

        op = raw_input("Your option: ")
        op = op.strip()

        if op in data:          # return a existing bucket
            return buckets[int(op)-1]
        elif op == str(count):
            return create_new_bucket(conn)
        elif op != str(0):
            print 'Invalid option! Please, try again...'

def create_new_bucket(conn=S3Connection()):
    # the new bucket will include a timestamp to try to assure a unique name to the new s3 bucket
    t = localtime(time())
    atm_date = str(t.tm_year) + str(t.tm_mon) + str(t.tm_mday) + str(t.tm_hour) + str(t.tm_min) + str(t.tm_sec)

    bucket_name = raw_input("Give a name to your bucket [it appends date of creation to assure a unique name]: ")
    conn.create_bucket(bucket_name + "-" + atm_date)

    return bucket_name + "-" + atm_date

def create_new_directory(folders):

    op = 1
    while op == 1:
        new_folder = raw_input("Give a name to your new directory (name must be unique): ")

        if new_folder not in folders.values():
            op = 0
        else:
            print 'Invalid name! Please, try again...'

    return new_folder

def select_input_directory(bucket_name, conn=S3Connection()):

    bucket = conn.get_bucket(bucket_name)

    # just select the files inside the input folder
    folders = list(bucket.list('input/', '/'))
    # it assumes that the bucket has only one level of folders inside input folder
    folders = [f.name for f in folders if f.name.count('/') == 2]

    data = {}
    op = 1
    while op not in data:
        count = 1
        print "\nAvailable input themes in your bucket"
        for folder in folders:
            data[str(count)] = folder[6:-1]
            print "\t%d.\t%s" % (count, folder[6:-1])
            count += 1
        print "\t0.\tCreate new folder (name must be unique)"

        op = raw_input("Your option: ")

        if op in data:          # return a existing folder
            return data[op]
        elif op == str(0):
            return create_new_directory(data)
        else:
            print 'Invalid option! Please, try again...'


text:
"""Upload index files for BWA-MEM2 aligner."""
import shutil
from pathlib import Path

from resolwe.process import (
    Cmd,
    DirField,
    FileField,
    Process,
    SchedulingClass,
    StringField,
)

class ImportBWA2Index(Process):
    """Import BWA-MEM2 index files."""

    slug = "upload-bwamem2-index"
    name = "BWA-MEM2 index files"
    process_type = "data:index:bwamem2"
    version = "1.1.0"
    category = "Import"
    scheduling_class = SchedulingClass.BATCH
    requirements = {
        "expression-engine": "jinja",
        "executor": {
            "docker": {"image": "public.ecr.aws/genialis/resolwebio/dnaseq:6.3.1"},
        },
    }
    data_name = '{{ ref_seq.file|default("?") }}'
    version = "1.0.0"

    class Input:
        """Input fields to process Import BWA-MEM2 index."""

        ref_seq = FileField(label="Reference sequence (nucleotide FASTA)")
        index_name = FileField(label="BWA-MEM2 index files")
        species = StringField(
            label="Species",
            description="Select a species name from the dropdown menu "
            "or write a custom species name in the species "
            "field. For sequences that are not related to "
            "any particular species (e.g. adapters file), "
            "you can select the value Other.",
            allow_custom_choice=True,
            choices=[
                ("Homo sapiens", "Homo sapiens"),
                ("Mus musculus", "Mus musculus"),
                ("Rattus norvegicus", "Rattus norvegicus"),
                ("Macaca mulatta", "Macaca mulatta"),
                ("Dictyostelium discoideum", "Dictyostelium discoideum"),
                ("Other", "Other"),
            ],
        )

        build = StringField(
            label="Genome build",
        )

    class Output:
        """Output fields to process BWAMEM2Index."""

        index = DirField(label="BWA-MEM2 index")
        fastagz = FileField(label="FASTA file (compressed)")
        fasta = FileField(label="FASTA file")
        fai = FileField(label="FASTA file index")
        species = StringField(label="Species")
        build = StringField(label="Build")

    def run(self, inputs, outputs):
        """Run the analysis."""
        index_dir = Path("BWAMEM2_index")
        if not index_dir.exists():
            index_dir.mkdir()

        index_file = inputs.index_name.import_file(imported_format="compressed")
        shutil.unpack_archive(index_file, index_dir)

        fasta_path = inputs.ref_seq.import_file(imported_format="extracted")

        supported_extensions = (".fa", ".fasta", ".faa", ".fna", ".ffn", ".frn")
        if not fasta_path.endswith(supported_extensions):
            self.error(
                f"The imported file has unsupported file name extension. "
                f"The supported extensions are {supported_extensions}."
            )

        fasta_path = Path(fasta_path)
        output_fasta = fasta_path.with_suffix(".fasta")
        fasta_path.rename(output_fasta)

        Cmd["pigz"]["-k", output_fasta]()
        Cmd["samtools"]["faidx", output_fasta]()

        outputs.index = index_dir.name
        outputs.fasta = output_fasta.name
        outputs.fastagz = f"{output_fasta}.gz"
        outputs.fai = f"{output_fasta}.fai"
        outputs.species = inputs.species
        outputs.build = inputs.build

redpajama_set_name: RedPajamaGithub


text:
//
//  TFTableViewSection.h
//  TFTableViewManagerDemo
//
//  Created by Summer on 16/8/24.
//  Copyright © 2016年 Summer. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@class TFTableViewManager;
@class ASDisplayNode;
@class TFTableViewItem;
@class TFTableViewSection;

typedef void(^TFTableViewSectionReloadHeaderFooterViewBlock)(TFTableViewSection *section,__kindof UIView * headerFooterView, NSInteger sectionIndex);

/**
 *  the table view section handler.
 */
@interface TFTableViewSection : NSObject

///-----------------------------
/// @name TFTableViewSection Properties.
///-----------------------------

/**
 *  @brief An array of section items (rows).
 */
@property (strong, readonly, nonatomic) NSArray<__kindof TFTableViewItem *> *items;

/**
 *  @brief The title of the header of the specified section of the table view.
 */
@property (copy, nonatomic) NSString *headerTitle;

/**
 *  @brief The title of the footer of the specified section of the table view.
 */
@property (copy, nonatomic) NSString *footerTitle;

/**
 *  @brief The height of the header of the specified section of the table view.
 */
@property (assign, nonatomic) CGFloat headerHeight;

/**
 *  @brief The height of the footer of the specified section of the table view.
 */
@property (assign, nonatomic) CGFloat footerHeight;

/**
 *  @brief A view object to display in the header of the specified section of the table view, when set this value headerview is not reuseable,if you want to reuse, set 'reuseHeaderViewClass' property instead and update headerView UI in reloadHeaderViewBlock.
 */
@property (strong, nonatomic) UIView *headerView;

/**
 *  @brief The class of headerView to be display in tableView. When set is value header view is reuseable, it is not neccessary to set headerReuseIdentifier, if not set 'headerReuseIdentifier', header view reuseable identifier is name of header view class .
 */
@property (nonatomic, strong) Class reuseHeaderViewClass;

/**
 *  @brief A node object to display in the header of the specified section of the table view.
 */
@property (strong, nonatomic) ASDisplayNode *headerNode;

/**
 *  @brief The reuse identifier when you use UITableViewHeaderFooterView to create a headerView.
 */
@property (strong, nonatomic) NSString *headerReuseIdentifier;

/**
 *  @brief when header view is reuse, use this block to refresh the UI of your header view.
 */
@property (nonatomic, copy) TFTableViewSectionReloadHeaderFooterViewBlock reuseHeaderViewReloadBlock;

/**
 *  @brief A view object to display in the footer of the specified section of the table view, when set this value footerView is not reuseable,if you want to reuse, set 'reuseFooterViewClass' property instead and update footerView UI in reloadFooterViewBlock.
 */
@property (strong, nonatomic) UIView *footerView;

/**
 *  @brief The class of footerView to be display in tableView. When set is value footer view is reuseable, it is not neccessary to set 'footerReuseIdentifier', if not set 'footerReuseIdentifier', footer view reuseable identifier is name of footer view class .
 */
@property (nonatomic, strong) Class reuseFooterViewClass;

/**
 *  @brief A node object to display in the footer of the specified section of the table view.
 */
@property (strong, nonatomic) ASDisplayNode *footerNode;
/**
 *  @brief The reuse identifier when you use UITableViewHeaderFooterView to create a footerView.
 */
@property (strong, nonatomic) NSString *footerReuseIdentifier;

/**
 *  @brief when footer view is reuse, use this block to refresh the UI of your footer view.
 */
@property (nonatomic, copy) TFTableViewSectionReloadHeaderFooterViewBlock reuseFooterViewReloadBlock;

/**
 *  @brief The table view manager of this section.
 */
@property (weak, nonatomic) TFTableViewManager *tableViewManager;

/**
 *  @brief Section index in table View.
 */
@property (assign, readonly, nonatomic) NSUInteger index;

/**
 *  @brief Section index title.
 */
@property (copy, nonatomic) NSString *indexTitle;

/**
 *  @brief tell table which section corresponds to section title/index.
 */
@property (assign, nonatomic) NSUInteger sectionIndex;

///-----------------------------
/// @name Creating and Initializing a TFTableViewSection.
///-----------------------------

/**
 *  Initializes a newly allocated section and sets header title.
 *
 *  @param headerTitle A header title.
 *
 *  @return A new section initialized with a header title.
 */
- (instancetype)initWithHeaderTitle:(NSString *)headerTitle;

/**
 *  Initializes a newly allocated section and sets footer title.
 *
 *  @param footerTitle A footer title.
 *
 *  @return A new section initialized with a footer title.
 */
- (instancetype)initWithFooterTitle:(NSString *)footerTitle;

/**
 *  Initializes a newly allocated section with header and footer titles.
 *
 *  @param headerTitle A header title.
 *  @param footerTitle A footer title.
 *
 *  @return A new section initialized with header and footer titles.
 */
- (instancetype)initWithHeaderTitle:(NSString *)headerTitle footerTitle:(NSString *)footerTitle;

/**
 *  Initializes a newly allocated section containing a header view.
 *
 *  @param headerView A header view.
 *
 *  @return A new section initialized containing a header view.
 */
- (instancetype)initWithHeaderView:(UIView *)headerView;

/**
 *  Initializes a newly allocated section containing a footer view.
 *
 *  @param footerView A footer view.
 *
 *  @return A new section initialized containing a footer view.
 */
- (instancetype)initWithFooterView:(UIView *)footerView;

/**
 *  Initializes a newly allocated section containing header and footer views.
 *
 *  @param headerView A header view.
 *  @param footerView A footer view.
 *
 *  @return A new section initialized with header and footer views.
 */
- (instancetype)initWithHeaderView:(UIView *)headerView footerView:(UIView *)footerView;

/**
 *  Creates and returns a new section.
 *
 *  @return A new section.
 */
+ (instancetype)section;

/**
 *  Creates and returns a new section with predefined header title.
 *
 *  @param headerTitle A header title.
 *
 *  @return A new section with defined header title.
 */
+ (instancetype)sectionWithHeaderTitle:(NSString *)headerTitle;

/**
 *  Creates and returns a new section with predefined footer title.
 *
 *  @param footerTitle A footer title.
 *
 *  @return A new section with defined footer title.
 */
+ (instancetype)sectionWithFooterTitle:(NSString *)footerTitle;

/**
 *  Creates and returns a new section with predefined header and footer titles.
 *
 *  @param headerTitle A header title.
 *  @param footerTitle A footer title.
 *
 *  @return A new section with header and footer titles.
 */
+ (instancetype)sectionWithHeaderTitle:(NSString *)headerTitle footerTitle:(NSString *)footerTitle;

/**
 *  Creates and returns a new section containing a header view.
 *
 *  @param headerView A header view.
 *
 *  @return A new section containing a header view.
 */
+ (instancetype)sectionWithHeaderView:(UIView *)headerView;

/**
 *  Creates and returns a new section containing a footer view.
 *
 *  @param footerView A footer view.
 *
 *  @return A new section containing a footer view.
 */
+ (instancetype)sectionWithFooterView:(UIView *)footerView;

/**
 *  Creates and returns a new section containing header and footer views.
 *
 *  @param headerView A header view.
 *  @param footerView A footer view.
 *
 *  @return A new section containing header and footer views.
 */
+ (instancetype)sectionWithHeaderView:(UIView *)headerView footerView:(UIView *)footerView;

///-----------------------------
/// @name Add and insert Items.
///-----------------------------

/**
 *  Adds a given item at the end of the section.
 *
 *  @param item The item to add to the end of the section. This value must not be `nil`.
 */
- (void)addItem:(__kindof TFTableViewItem *)item;

/**
 *  Adds the items contained in another given array to the end of the section.
 *
 *  @param array An array of items to add to the end of the section.
 */
- (void)addItemsFromArray:(NSArray<__kindof TFTableViewItem *> *)array;

/**
 *  Inserts a given item into the section at a given index.
 *
 *  @param item  The item to add to the section. This value must not be `nil`.
 *  @param index The index in the section at which to insert item. This value must not be greater than the count of items in the section.
 */
- (void)insertItem:(__kindof TFTableViewItem *)item atIndex:(NSUInteger)index;

/**
 *  Inserts the items in the provided items array into the section at the specified indexes.
 *
 *  @param items   An array of items to insert into the section.
 *  @param indexes The indexes at which the items should be inserted.
 */
- (void)insertItems:(NSArray<__kindof TFTableViewItem *> *)items atIndexes:(NSIndexSet *)indexes;

///-----------------------------
/// @name Removing Items.
///-----------------------------

/**
 *  Removes all occurrences in the section of a given item.
 *
 *  @param item The item to remove from the section.
 */
- (void)removeItem:(__kindof TFTableViewItem *)item;

/**
 *  Removes the item with the highest-valued index in the section.
 */
- (void)removeLastItem;

/**
 *  Removes the item at index.
 *
 *  @param index The index from which to remove the item in the section. The value must not exceed the bounds of the section.
 */
- (void)removeItemAtIndex:(NSUInteger)index;

/**
 *  Removes the items at the specified indexes from the section.
 *
 *  @param indexes The indexes of the items to remove from the section. The locations specified by indexes must lie within the bounds of the section.
 */
- (void)removeItemsAtIndexes:(NSIndexSet *)indexes;

/**
 *  Removes from the section the items in another given array.
 *
 *  @param array An array containing the items to be removed from the section.
 */
- (void)removeItemsInArray:(NSArray<TFTableViewItem *> *)array;

/**
 *  Removes from the section each of the items within a given range.
 *
 *  @param range The range of the items to remove from the section.
 */
- (void)removeItemsInRange:(NSRange)range;

/**
 *  Removes all occurrences within a specified range in the section of a given item.
 *
 *  @param item  The item to remove from the section.
 *  @param range The range from which to remove item.
 */
- (void)removeItem:(__kindof TFTableViewItem *)item inRange:(NSRange)range;

/**
 *  Empties the section of all its items.
 */
- (void)removeAllItems;

///-----------------------------
/// @name Replacing Items
///-----------------------------

/**
 *  Replaces the item at index with another item.
 *
 *  @param index The index of the item to be replaced. This value must not exceed the bounds of the section.
 *  @param item  The item with which to replace the item at index index in the section. This value must not be `nil`.
 */
- (void)replaceItemAtIndex:(NSUInteger)index withItem:(__kindof TFTableViewItem *)item;

/**
 *  Replaces the items in the section with all of the items from a given array.
 *
 *  @param array The array of items from which to select replacements for the items.
 */
- (void)replaceItemsWithItemsFromArray:(NSArray<__kindof TFTableViewItem *> *)array;

/**
 *  Replaces the items in the section at specified locations specified with the items from a given array.
 *
 *  @param indexes The indexes of the items to be replaced.
 *  @param items   The items with which to replace the items in the section at the indexes specified by `indexes`. The count of locations in indexes must equal the count of items.
 */
- (void)replaceItemsAtIndexes:(NSIndexSet *)indexes withItems:(NSArray<__kindof TFTableViewItem *> *)items;

/**
 *  Replaces the items in the section specified by a given range with all of the items from a given array.
 *
 *  @param range The range of items to replace in (or remove from) the section.
 *  @param array The array of items from which to select replacements for the items in range.
 */
- (void)replaceItemsInRange:(NSRange)range withItemsFromArray:(NSArray<__kindof TFTableViewItem *> *)array;

///-----------------------------
/// @name Rearranging Items
///-----------------------------

/**
 *  Exchanges the items in the section at given indices.
 *
 *  @param idx1 The index of the item with which to replace the item at index idx2.
 *  @param idx2 The index of the item with which to replace the item at index idx1.
 */
- (void)exchangeItemAtIndex:(NSUInteger)idx1 withItemAtIndex:(NSUInteger)idx2;

/**
 *  Sorts the items in ascending order as defined by the comparison function compare.
 *
 *  @param compare The comparison function to use to compare two items at a time.
 *  @param context The context argument to pass to the compare function.
 */
- (void)sortItemsUsingFunction:(NSInteger (*)(id, id, void *))compare context:(void *)context;
- (void)sortItemsUsingSelector:(SEL)comparator;

///-----------------------------
/// @name TFTableViewSection handle tableView section actions.
///-----------------------------

/**
 *  Reloads the `section` using a given animation effect.
 *
 *  @param animation A constant that indicates how the reloading is to be animated.
 */
- (void)reloadSectionWithAnimation:(UITableViewRowAnimation)animation;

/**
 *  Delete the `section` using a given animation effect.
 *
 *  @param animation A constant that indicates how the reloading is to be animated.
 */
- (void)deleteSectionWithAnimation:(UITableViewRowAnimation)animation;

/**
 *  Reload rows at index set.
 *
 *  @param indexSet the index set of reload rows.
 */
- (void)reloadRowsAtIndexes:(NSIndexSet *)indexSet withAnimation:(UITableViewRowAnimation)animation;

/**
 *  Insert rows with items array and indexes.
 *
 *  @param rows      an array of items
 *  @param indexSet  index set.
 *  @param animation A constant that indicates how the delete is to be animated.
 */
- (void)insertRows:(NSArray<__kindof TFTableViewItem *> *)rows atIndexes:(NSIndexSet *)indexSet withRowAnimation:(UITableViewRowAnimation)animation;

- (void)addRows:(NSArray<TFTableViewItem *> *)rows withRowAnimation:(UITableViewRowAnimation)animation;
/**
 *  Delete rows with the indexes of rows and a given animation effect.
 *
 *  @param indexSet  the index set.
 *  @param animation A constant that indicates how the delete is to be animated.
 */
- (void)deleteRowsAtIndexes:(NSIndexSet *)indexSet withAnimation:(UITableViewRowAnimation)animation;

/**
 *  Delete rows with items of rows and a given animation effect.
 *
 *  @param items An array of delete items.
 *  @param animation A constant that indicates how the delete is to be animated.
 */
- (void)deleteRows:(NSArray<__kindof TFTableViewItem *> *)items withAnimation:(UITableViewRowAnimation)animation;

@end


text:
package org.robolectric.res;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ResBundle<T> {
  // Matches a version qualifier like "v14". Parentheses capture the numeric
  // part for easy retrieval with Matcher.group(1).
  private static final String VERSION_QUALIFIER_REGEX = "v([0-9]+)";
  private static final String PADDED_VERSION_QUALIFIER_REGEX
      = "-" + VERSION_QUALIFIER_REGEX + "-";
  private static final Pattern VERSION_QUALIFIER_PATTERN_WITH_LINE_END
      = Pattern.compile(VERSION_QUALIFIER_REGEX + "$");
  private static final Pattern VERSION_QUALIFIER_PATTERN_WITH_DASHES
      = Pattern.compile(PADDED_VERSION_QUALIFIER_REGEX);

  private final ResMap<T> valuesMap = new ResMap<>();
  private final ResMap<List<T>> valuesArrayMap = new ResMap<>();
  private String overrideNamespace;

  public void put(String attrType, String name, T value, XmlLoader.XmlContext xmlContext) {
    ResName resName = new ResName(maybeOverride(xmlContext.packageName), attrType, name);
    List<Value<T>> values = valuesMap.find(resName);
    values.add(new Value<>(xmlContext.getQualifiers(), value));
    Collections.sort(values);
  }

  public T get(ResName resName, String qualifiers) {
    Value<T> value = getValue(resName, qualifiers);
    return value == null ? null : value.value;
  }

  public Value<T> getValue(ResName resName, String qualifiers) {
    List<Value<T>> values = valuesMap.find(maybeOverride(resName));
    return values != null ? pick(values, qualifiers) : null;
  }

  public static int getVersionQualifierApiLevel(String qualifiers) {
    Matcher m = VERSION_QUALIFIER_PATTERN_WITH_LINE_END.matcher(qualifiers);
    if (m.find()) {
      return Integer.parseInt(m.group(1));
    }
    return -1;
  }

  public static <T> Value<T> pick(List<Value<T>> values, String qualifiers) {
    final int count = values.size();
    if (count == 0) return null;

    BitSet possibles = new BitSet(count);
    possibles.set(0, count);

    StringTokenizer st = new StringTokenizer(qualifiers, "-");
    while (st.hasMoreTokens()) {
      String qualifier = st.nextToken();
      String paddedQualifier = "-" + qualifier + "-";
      BitSet matches = new BitSet(count);

      for (int i = possibles.nextSetBit(0); i != -1; i = possibles.nextSetBit(i + 1)) {
        if (values.get(i).qualifiers.contains(paddedQualifier)) {
          matches.set(i);
        }
      }

      if (!matches.isEmpty()) {
        possibles.and(matches); // eliminate any that didn't match this qualifier
      }

      if (matches.cardinality() == 1) break;
    }

    /*
     * If any resources out of the possibles have version qualifiers, return the
     * closest match that doesn't go over. This is the last step because it's lowest
     * in the precedence table at:
     * https://developer.android.com/guide/topics/resources/providing-resources.html#table2
     */
    int targetApiLevel = getVersionQualifierApiLevel(qualifiers);
    if (qualifiers.length() > 0 && targetApiLevel != -1) {
      Value<T> bestMatch = null;
      int bestMatchDistance = Integer.MAX_VALUE;
      for (int i = possibles.nextSetBit(0); i != -1; i = possibles.nextSetBit(i + 1)) {
        Value<T> value = values.get(i);
        int distance = getDistance(value, targetApiLevel);
        // Remove the version part and see if they still match
        String paddedQualifier = "-" + qualifiers + "-";
        String valueWithoutVersion = VERSION_QUALIFIER_PATTERN_WITH_DASHES.matcher(value.qualifiers).replaceAll("--");
        String qualifierWithoutVersion = VERSION_QUALIFIER_PATTERN_WITH_DASHES.matcher(paddedQualifier).replaceAll("--");
        if (qualifierWithoutVersion.contains(valueWithoutVersion) && distance >= 0 && distance < bestMatchDistance) {
          bestMatch = value;
          bestMatchDistance = distance;
        }
      }
      if (bestMatch != null) {
        return bestMatch;
      }
    }

    int i = possibles.nextSetBit(0);
    if (i != -1) return values.get(i);

    throw new IllegalStateException("couldn't handle qualifiers \"" + qualifiers + "\"");
  }

  /*
   * Gets the difference between the version qualifier of val and targetApiLevel.
   *
   * Return value:
   * - Lower number is a better match (0 is a perfect match)
   * - Less than zero: val's version qualifier is greater than targetApiLevel,
   *   or val has no version qualifier
   */
  private static int getDistance(Value val, int targetApiLevel) {
    int distance = -1;
    Matcher m = VERSION_QUALIFIER_PATTERN_WITH_DASHES.matcher(val.qualifiers);
    if (m.find()) {
      String match = m.group(1);
      int resApiLevel = Integer.parseInt(match);
      distance = targetApiLevel - resApiLevel;

      if (m.find()) {
        throw new IllegalStateException("A resource file was found that had two API level qualifiers: " + val);
      }
    } else {
      if (val.qualifiers.equals("--")) {
        distance = targetApiLevel;
      }
    }
    return distance;
  }

  public int size() {
    return valuesMap.size() + valuesArrayMap.size();
  }

  public void makeImmutable() {
    valuesMap.makeImmutable();
    valuesArrayMap.makeImmutable();
  }

  public void overrideNamespace(String overrideNamespace) {
    this.overrideNamespace = overrideNamespace;
    if (size() > 0) throw new RuntimeException();
  }

  String maybeOverride(String namespace) {
    return overrideNamespace == null ? namespace : overrideNamespace;
  }

  ResName maybeOverride(ResName resName) {
    return overrideNamespace == null ? resName : new ResName(overrideNamespace, resName.type, resName.name);
  }

  public void mergeLibraryStyle(ResBundle<T> fromResBundle, String packageName) {
    valuesMap.merge(packageName, fromResBundle.valuesMap);
    valuesArrayMap.merge(packageName, fromResBundle.valuesArrayMap);
  }

  public static class Value<T> implements Comparable<Value<T>> {
    private final String qualifiers;
    private final T value;

    Value(String qualifiers, T value) {
      if (value == null) {
        throw new NullPointerException();
      }

      this.qualifiers = qualifiers == null ? "--" : "-" + qualifiers + "-";
      this.value = value;
    }

    public String getQualifiers() {
      return qualifiers;
    }

    public T getValue() {
      return value;
    }

    @Override
    public int compareTo(Value<T> o) {
      return qualifiers.compareTo(o.qualifiers);
    }

    @Override public String toString() {
      return "Value{" +
          "qualifiers='" + qualifiers + '\'' +
          ", value=" + value +
          '}';
    }
  }

  private static class ResMap<T> {
    private final Map<ResName, List<Value<T>>> map = new HashMap<>();
    private boolean immutable;

    public List<Value<T>> find(ResName resName) {
      List<Value<T>> values = map.get(resName);
      if (values == null) map.put(resName, values = new ArrayList<>());
      return values;
    }

    private void merge(String packageName, ResMap<T> sourceMap) {
      if (immutable) {
        throw new IllegalStateException("immutable!");
      }

      for (Map.Entry<ResName, List<Value<T>>> entry : sourceMap.map.entrySet()) {
        ResName resName = entry.getKey().withPackageName(packageName);
        find(resName).addAll(entry.getValue());
      }
    }

    public int size() {
      return map.size();
    }

    public void makeImmutable() {
      immutable = true;
    }
  }
}


text:
The Median Filter is used to reduce noise in an image, it preserves useful detail in the image.

Such noise reduction is a typical pre-processing step to improve the results of later processing.
Each pixel in the image is considered and every nearby neighbor looked at.
The pixel value is then replaced with the median of all surrounding neighbors.
The surrounding neighbors are sorted after their size and then the pixel value in the middle picked for the currently selected pixel.
If the number of neighbors is even, the average of the two pixels in the middle is used.

Surprise egg with no calculation on the left and with median filter set to "diamond" on the right.

![ ](images/median/mediannocalculation.png) ![ ](images/median/mediandiamond4.png)

The egg with median filter set to "cube" on the left and on the right set to "sphere".

![ ](images/median/mediancube4.png) ![ ](images/median/mediansphere4.png)

[Median Filter explained](https://homepages.inf.ed.ac.uk/rbf/HIPR2/median.htm)

[Package](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.median_filter.html)

## Parameters

The following list details which parameters are used by the filter.

### Range

Default Value: 1, Minimum Value 1

### Mode

3 different modes to select from:

- Diamond calculates the Manhattan distance
- Sphere calculates the Euclid distance
- Cube calculates the Chessboard distance

Diamond is the default selected mode.


text:
function mexall()
%
% mex cpp associated code
%

mex -O -largeArrayDims ChooseCoarseGreedy_mex.cpp


text:
/*
    There are times when it is necessary for us to control the access and context
        behind an object, and this is where the Proxy pattern can be useful.
    It can help us control when an expensive object should be instantiated,
        provide advanced ways to reference the object, or modify the object
        to function a particular way in specific contexts.
    In jQuery core, a jQuery.proxy() method exists that accepts as input a
        function and returns a new one that will always have a specific context.
        This ensures that the value of this within a function is the value we expect.
    There is a slight difference between bind and proxy, which can matter a lot if
        you are using jQuery. Function.prototype.bind always returns a new function
        pointer. jQuery.proxy only returns a new function if a proxy of the same
        args has not already been created.
*/

// Native bind() vs $.proxy()
$(elm).on('click', doStuff.bind(thing)); //adds event handler
$(elm).off('click', doStuff.bind(thing)); //does not remove event handler as
// 2nd call of doStuff.bind(thing) always returns a new/different function

$(elm).on('click', $.proxy(doStuff, thing)); //adds handler
$(elm).off('click', $.proxy(doStuff, thing)); //DOES remove handler, as a second
// call to $.proxy(doStuff, thing) is smart enough to know about similar use-cases

// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function(fn, context) {
    if (typeof context === "string") {
        var tmp = fn[context];
        context = fn;
        fn = tmp;
    }

    // Quick check to determine if target is callable, in the spec
    // this throws a TypeError, but we will just return undefined.
    if (!jQuery.isFunction(fn)) {
        return undefined;
    }

    // Simulated bind
    var args = slice.call(arguments, 2),
        proxy = function() {
            return fn.apply(context, args.concat(slice.call(arguments)));
        };

    // Set the guid of unique handler to the same of original handler,
    // so it can be removed
    proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
    return proxy;
}

// Usage:
$("button").on("click", function() {
    setTimeout($.proxy(function() {
        // "this" now refers to our element as we wanted
        $(this).addClass("active");
    }, this), 500);

    // the last "this" we're passing tells $.proxy() that our DOM element
    // is the value we want "this" to refer to.
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;

namespace aBlist
{
	public class MapActivity : Activity, pcl.IMap
	{
		protected GoogleMap map;
		protected CameraUpdate cameraUpdate;
		protected IList<Marker> listMarkers = new List<Marker>();

		// User values
		protected IList<pcl.Marker> ListMarkers = new List<pcl.Marker>();
		protected pcl.Marker markerForInitRegion;

		protected const int MAP_VIEW_ZOOM_INIT = 3;
		protected const int MAP_VIEW_ZOOM_MARK = 16;

		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			SetContentView (Resource.Layout.Map);
			// Init Map
			InitMap ();
		}

		protected override void OnStart ()
		{
			base.OnStart ();

			MapFragment mapFrag = (MapFragment) FragmentManager.FindFragmentById(Resource.Id.mapContainer);
			this.map = mapFrag.Map;
			if (this.map != null) {
				// The GoogleMap object is ready to go.
				if (this.cameraUpdate == null) {
					InitMapInRegion();
				}
				this.map.MarkerClick += OnMapMarkerClick;
				this.map.MapClick += OnMapClick;
				this.map.MapLongClick += MapLongClick;

				// Clean Map to ensure to load new items created at Tools
				ClearMap ();

				// Load Markers
				InitMarkers ();
			}
		}

		public void ClearMap ()
		{
			ClearMarkers ();
			this.map.Clear ();
		}

		public void InitMarkers ()
		{
			foreach (var element in ListMarkers) {
				MarkerOptions markerOptions = new MarkerOptions ();
				markerOptions.SetPosition (new LatLng (element.Coordinate.Latitude, element.Coordinate.Longitude));
				markerOptions.SetIcon(BitmapDescriptorFactory.DefaultMarker ());
				var marker = this.map.AddMarker (markerOptions);
				this.listMarkers.Add (marker);
			}
		}
		public void InitMap ()
		{
			// Maps
			var mapFragment = MapFragment.NewInstance ();
			FragmentTransaction fragmentTransaction = FragmentManager.BeginTransaction ();
			fragmentTransaction.Add (Resource.Id.mapContainer, mapFragment);
			fragmentTransaction.Commit ();
		}

		public void InitMapInRegion ()
		{
			ChangeRegionInMap (this.markerForInitRegion);
		}

		public void ChangeRegionInMap (pcl.Marker marker)
		{
			if (marker != null) {
				LatLng location = new LatLng(marker.Coordinate.Latitude, marker.Coordinate.Longitude);
				CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
				builder.Target(location);
				builder.Zoom(MAP_VIEW_ZOOM_INIT);
				CameraPosition cameraPosition = builder.Build();
				this.cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);
				this.map.MoveCamera (this.cameraUpdate);
			}
		}

		protected void OnMapMarkerClick(object sender, GoogleMap.MarkerClickEventArgs e)
		{

		}

		protected void OnMapClick(object sender, GoogleMap.MapClickEventArgs e)
		{

		}

		protected void MapLongClick(object sender, GoogleMap.MapLongClickEventArgs e)
		{

		}

		public void ClearMarkers ()
		{
			foreach (var element in listMarkers) {
				element.Remove ();
			}
		}
	}
}


text:
package com.github.oxo42.stateless4j;

public final class OutVar<T> {

    private T obj;

    public T get() {
        return obj;
    }

    public void set(T v) {
        this.obj = v;
    }

    @Override
    public String toString() {
        return String.valueOf(obj);
    }
}


text:
struct lpc_info_record {
  int id_nr;
  unsigned short udp_port;
  string mud_name;
  string channel;
  string request;
  string sender;
  string recipent;
  string data;
  string reply_type;
};

struct dns_record {
  unsigned long      ip_address;
  unsigned short     port;
  string             mud_name;
  string             mud_port;
  string             mud_version;
  string             intermud_version;
  int                mud_type;
  unsigned long      kb_in;
  unsigned long      kb_out;
  unsigned long      msg_in;
  unsigned long      msg_out;
  int                muted;
  long               services;
  string             last_connected;
};

#endif


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>EOF Gap-Filling Script Documentation — HABS Forecast Model 1.0 documentation</title>

    <link rel="stylesheet" href="_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="HABS Forecast Model 1.0 documentation" href="index.html" />
    <link rel="up" title="Satellite Data Processing" href="hab_project.html" />
    <link rel="next" title="EOF Gap-0Filling Script Code" href="step3_code.html" />
    <link rel="prev" title="NASA Download Script Code" href="step2_code.html" />

Navigation

          index

          modules |

          next |

          previous |

HABS Forecast Model 1.0 documentation »

Satellite Data Processing »

EOF Gap-Filling Script Documentation¶

EOF gap filling script for HABS satellite data

Description

Main script to process HABS satellite data for use in the HABS NowCast model.

The body of the script:

Imports the python and custom modules

Sets the directory paths

Sets the date objects

The main() function:

Assembles satellite data for the DINEOF runs

Runs DINEOF gap filling

Downsamples the filled data to ROMS resolution

Saves the data as netCDF4, puts a copy in a web-accessible location, and archives the data.

Usage

python filled_satellite_data DATA_DIR EOF_WORK_DIR EOF_DIR BIN_DIR EOF_DATA_DIR PYTHON_DIR LOG_DIR

Args

DATA_DIR: location of satellite data directory

EOF_WORK_DIR: location of work directory

EOF_DIR: location of DINEOF software

BIN_DIR: location of python and dineof scripts

EOF_DATA_DIR: location of

PYTHON_DIR LOG_DIR: location of python

Development software versions

Mac OSX, version 10.11.3

Python 2.7.11 :: Anaconda 2.4.0

Python module dependencies

datetime

time

numpy

os

pydap

sys

Python library dependencies

habs_lib_prenowcast.get_bands_4

habs_lib_prenowcast.geteofdata

habs_lib_prenowcast.downsample

habs_lib_prenowcast.write_filled_nc

habs_lib_prenowcast.netcdfwrite

Creator

Dale Robinson, CoastWatch WCRN

History

Modified Nov. 2015 from a script by Fred Barr (CeNCOOS)

Modified for new (mini) server March 2016

Added Sphinx documentation April 2016

filled_satellite_data.main()¶

Main function for EOF gap filling script

Description

The main function has 4 major steps:

Data Assembly: The script assembles chlorophyll, rf488, and rf555 data for the last 180 days and saves them into separate netCDF3 file along with a land mask.

DINEOF Gap Filling: A DINEOF is run on the chlorophyll, rf488, and rf555 data stored in the netCDF3 file and the filled data fields are added as new variables to the netCDF3 files.

Downsampling: The filled fields from the netCDF files are loaded, downsampled to ROMS resolution, and stored together in a new netCDF4 file.

Distribution:The netCDF4 file is make available online for further processing.

Outputs

final product - netCDF4 file with 180 days of filled chlorophyll, rf488, and rf555 data fields

intermediate products

L2b gridded daily files containing raw chlorophyll, rf488, and rf555 data

L3 gridded daily files for each band

netCFD3 file containing raw and filled chlorophyll, rf488, and rf555 data fields and land mask

Previous topic

NASA Download Script Code

Next topic

EOF Gap-0Filling Script Code

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

HABS Forecast Model 1.0 documentation »

Satellite Data Processing »

        © Copyright 2016, Dr. Dale Robinson.
      Created using Sphinx 1.3.5.


text:
function createObjectWrite() {
    const assignment = `obj[${JSON.stringify(key)}]=42`;
    return `(function(){${assignment}})` // NOT OK
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Phidgets; //Needed for the RFID class and the PhidgetException class
using Phidgets.Events; //Needed for the phidget event handling classes

namespace RFID_full
{
    public partial class Form1 : Form
    {
        private RFID rfid; //Declare an RFID object
        private ErrorEventBox errorBox;

        public Form1()
        {
            InitializeComponent();
            errorBox = new ErrorEventBox();
            this.Bounds = new Rectangle(this.Location, new Size(298, 433));
        }

        //initialize our Phidgets RFID reader and hook the event handlers
        private void Form1_Load(object sender, EventArgs e)
        {
            rfid = new RFID();

            rfid.Attach += new AttachEventHandler(rfid_Attach);
            rfid.Detach += new DetachEventHandler(rfid_Detach);
            rfid.Error += new ErrorEventHandler(rfid_Error);

            rfid.Tag += new TagEventHandler(rfid_Tag);
            rfid.TagLost += new TagEventHandler(rfid_TagLost);

            foreach (String proto in System.Enum.GetNames(typeof(RFID.RFIDTagProtocol)))
            {
                writeProtoCmb.Items.Add(proto);
            }
            writeProtoCmb.SelectedIndex = 0;

            //Disabled controls until Phidget is attached
            antennaChk.Enabled = false;
            ledChk.Enabled = false;
            output0Chk.Enabled = false;
            output1chk.Enabled = false;

            openCmdLine(rfid);

        }

        //attach event handler..populate the details fields as well as display the attached status.  enable the checkboxes to change
        //the values of the attributes of the RFID reader such as enable or disable the antenna and onboard led.
        void rfid_Attach(object sender, AttachEventArgs e)
        {
            RFID attached = (RFID)sender;
            //attachedTxt.Text = e.Device.Attached.ToString();
            attachedTxt.Text = attached.Attached.ToString();
            nameTxt.Text = attached.Name;
            serialTxt.Text = attached.SerialNumber.ToString();
            versionTxt.Text = attached.Version.ToString();
            outputsTxt.Text = attached.outputs.Count.ToString();

            switch (attached.ID)
            {
                case Phidget.PhidgetID.RFID_2OUTPUT_READ_WRITE:
                    this.Bounds = new Rectangle(this.Location, new Size(298, 545));
                    writeBox.Visible = true;
                    break;
                case Phidget.PhidgetID.RFID:
                case Phidget.PhidgetID.RFID_2OUTPUT:
                default:
                    this.Bounds = new Rectangle(this.Location, new Size(298, 433));
                    writeBox.Visible = false;
                    break;
            }

            if (rfid.outputs.Count > 0)
            {
                antennaChk.Checked = true;
                rfid.Antenna = true;
                antennaChk.Enabled = true;
                ledChk.Enabled = true;
                output0Chk.Enabled = true;
                output1chk.Enabled = true;
            }
        }

        //detach event handler...clear all the fields, display the attached status, and disable the checkboxes.
        void rfid_Detach(object sender, DetachEventArgs e)
        {
            RFID detached = (RFID)sender;
            attachedTxt.Text = detached.Attached.ToString();
            nameTxt.Text = "";
            serialTxt.Text = "";
            versionTxt.Text = "";
            outputsTxt.Text = "";

            this.Bounds = new Rectangle(this.Location, new Size(298, 433));
            writeBox.Visible = false;

            if (rfid.outputs.Count > 0)
            {
                antennaChk.Enabled = false;
                ledChk.Enabled = false;
                output0Chk.Enabled = false;
                output1chk.Enabled = false;
            }
        }

        void rfid_Error(object sender, ErrorEventArgs e)
        {
            Phidget phid = (Phidget)sender;
            DialogResult result;
            switch (e.Type)
            {
                case PhidgetException.ErrorType.PHIDGET_ERREVENT_BADPASSWORD:
                    phid.close();
                    TextInputBox dialog = new TextInputBox("Error Event",
                        "Authentication error: This server requires a password.", "Please enter the password, or cancel.");
                    result = dialog.ShowDialog();
                    if (result == DialogResult.OK)
                        openCmdLine(phid, dialog.password);
                    else
                        Environment.Exit(0);
                    break;
                default:
                    if (!errorBox.Visible)
                        errorBox.Show();
                    break;
            }
            errorBox.addMessage(DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + ": " + e.Description);
        }

        //Tag event handler...we'll display the tag code in the field on the GUI
        void rfid_Tag(object sender, TagEventArgs e)
        {
            tagTxt.Text = e.Tag;
            protoTxt.Text = e.protocol.ToString();

            //This sends the RFID tag and an enter to the active application
            if (keyboardCheckBox.Checked == true)
            {
                SendKeys.Send(e.Tag);
                SendKeys.Send("{ENTER}");
            }
        }

        //Tag lost event handler...here we simply want to clear our tag field in the GUI
        void rfid_TagLost(object sender, TagEventArgs e)
        {
            tagTxt.Text = "";
            protoTxt.Text = "";
        }

        //Enable or disable the RFID antenna by clicking the checkbox
        private void antennaChk_CheckedChanged(object sender, EventArgs e)
        {
            rfid.Antenna = antennaChk.Checked;
        }

        //turn on and off the onboard LED by clicking the checkox
        private void ledChk_CheckedChanged(object sender, EventArgs e)
        {
            rfid.LED = ledChk.Checked;
        }

        //turn on and off output 0, to light a LED for example
        private void output0Chk_CheckedChanged(object sender, EventArgs e)
        {
            rfid.outputs[0] = output0Chk.Checked;
        }

        //turn on and off output 1, to light a LED for example
        private void output1chk_CheckedChanged(object sender, EventArgs e)
        {
            rfid.outputs[1] = output1chk.Checked;
        }

        //When the application is being terminated, close the Phidget.
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            rfid.Attach -= new AttachEventHandler(rfid_Attach);
            rfid.Detach -= new DetachEventHandler(rfid_Detach);
            rfid.Tag -= new TagEventHandler(rfid_Tag);
            rfid.TagLost -= new TagEventHandler(rfid_TagLost);

            //run any events in the message queue - otherwise close will hang if there are any outstanding events
            Application.DoEvents();

            rfid.close();
        }

        private void writeBtn_Click(object sender, EventArgs e)
        {
            try
            {
                RFID.RFIDTagProtocol proto = (RFID.RFIDTagProtocol)Enum.Parse(typeof(RFID.RFIDTagProtocol), writeProtoCmb.SelectedItem.ToString());
                rfid.write(writeTagTxt.Text, proto, writeLockChk.Checked);
            }
            catch (PhidgetException ex)
            {
                MessageBox.Show("Error writing tag: " + ex.Message);
            }
        }

        //Parses command line arguments and calls the appropriate open
        #region Command line open functions
        private void openCmdLine(Phidget p)
        {
            openCmdLine(p, null);
        }
        private void openCmdLine(Phidget p, String pass)
        {
            int serial = -1;
            String logFile = null;
            int port = 5001;
            String host = null;
            bool remote = false, remoteIP = false;
            string[] args = Environment.GetCommandLineArgs();
            String appName = args[0];

            try
            { //Parse the flags
                for (int i = 1; i < args.Length; i++)
                {
                    if (args[i].StartsWith("-"))
                        switch (args[i].Remove(0, 1).ToLower())
                        {
                            case "l":
                                logFile = (args[++i]);
                                break;
                            case "n":
                                serial = int.Parse(args[++i]);
                                break;
                            case "r":
                                remote = true;
                                break;
                            case "s":
                                remote = true;
                                host = args[++i];
                                break;
                            case "p":
                                pass = args[++i];
                                break;
                            case "i":
                                remoteIP = true;
                                host = args[++i];
                                if (host.Contains(":"))
                                {
                                    port = int.Parse(host.Split(':')[1]);
                                    host = host.Split(':')[0];
                                }
                                break;
                            default:
                                goto usage;
                        }
                    else
                        goto usage;
                }
                if (logFile != null)
                    Phidget.enableLogging(Phidget.LogLevel.PHIDGET_LOG_INFO, logFile);
                if (remoteIP)
                    p.open(serial, host, port, pass);
                else if (remote)
                    p.open(serial, host, pass);
                else
                    p.open(serial);
                return; //success
            }
            catch { }
        usage:
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("Invalid Command line arguments." + Environment.NewLine);
            sb.AppendLine("Usage: " + appName + " [Flags...]");
            sb.AppendLine("Flags:\t-n   serialNumber\tSerial Number, omit for any serial");
            sb.AppendLine("\t-l   logFile\tEnable phidget21 logging to logFile.");
            sb.AppendLine("\t-r\t\tOpen remotely");
            sb.AppendLine("\t-s   serverID\tServer ID, omit for any server");
            sb.AppendLine("\t-i   ipAddress:port\tIp Address and Port. Port is optional, defaults to 5001");
            sb.AppendLine("\t-p   password\tPassword, omit for no password" + Environment.NewLine);
            sb.AppendLine("Examples: ");
            sb.AppendLine(appName + " -n 50098");
            sb.AppendLine(appName + " -r");
            sb.AppendLine(appName + " -s myphidgetserver");
            sb.AppendLine(appName + " -n 45670 -i 127.0.0.1:5001 -p paswrd");
            MessageBox.Show(sb.ToString(), "Argument Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            Application.Exit();
        }
        #endregion

    }
}


text:
package com.cloudera.framework.testing.server.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.IOException;
import java.util.Collections;

import com.cloudera.framework.testing.TestConstants;
import com.cloudera.framework.testing.server.DfsServer;
import com.cloudera.framework.testing.server.HiveServer;
import com.cloudera.framework.testing.server.HiveServer.Runtime;
import com.cloudera.framework.testing.server.MrServer;
import com.cloudera.framework.testing.server.SparkServer;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

public abstract class TestHiveServer implements TestConstants {

  public abstract HiveServer getHiveServer();

  @Test
  public void testGetHiveServer() {
    assertNotNull(getHiveServer());
    assertTrue(getHiveServer().isStarted());
  }

  @Test
  public void testImplicitDependencies() {
    assertTrue(DfsServer.getInstance().isStarted());
    assertTrue((getHiveServer().getRuntime().equals(Runtime.LOCAL_MR2) ? MrServer.getInstance() : SparkServer.getInstance()).isStarted());
  }

  @Test(expected = IOException.class)
  public void testHiveNullFile() throws Exception {
    getHiveServer().execute((File) null);
  }

  @Test(expected = IOException.class)
  public void testHiveNoFile() throws Exception {
    getHiveServer().execute(new File("/sql/some-non-existent-script.sql"));
  }

  /**
   * Test Hive
   */
  @SuppressWarnings("ResultOfMethodCallIgnored")
  @Test
  public void testHiveCreateSelect() throws Exception {
    new File(REL_DIR_DATA).mkdirs();
    File localDataFile = new File(REL_DIR_DATA + "/somedata.csv");
    FileUtils.writeStringToFile(localDataFile, "1,1\n2,2\n3,3\n");
    assertEquals(0, DfsServer.getInstance().listFilesDfs("/usr/hive", true).length);
    assertEquals(0, getHiveServer().execute("SHOW TABLES").size());
    assertEquals(1, getHiveServer().execute("SHOW DATABASES").size());
    assertEquals(2,
      getHiveServer()
        .execute(new File(getClass().getResource("/ddl/create.sql").getPath()),
          new ImmutableMap.Builder<String, String>().put("test.table.name", "somedata").put("test.table.field.delim", ",").build())
        .size());
    assertEquals(0,
      getHiveServer().execute("LOAD DATA LOCAL INPATH '" + localDataFile.toString() + "' OVERWRITE INTO TABLE somedata").size());
    assertEquals(1, DfsServer.getInstance().listFilesDfs("/usr/hive", true).length);
    assertEquals("3", getHiveServer().execute("SELECT count(1) AS cnt FROM somedata").get(0));
    assertEquals("2", getHiveServer().execute("SELECT col1 FROM somedata WHERE col2 = 2").get(0));
    assertEquals(2, getHiveServer()
      .execute("SELECT * FROM somedata", Collections.emptyMap(), Collections.emptyMap(), 2).size());
    assertEquals(1, getHiveServer().execute("SHOW TABLES").size());
    assertEquals(0, getHiveServer().execute("CREATE DATABASE somedb").size());
    assertEquals(0, getHiveServer().execute("USE somedb").size());
    assertEquals(0, getHiveServer()
      .execute("CREATE TABLE somedata (col1 INT, col2 INT) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE").size());
    assertEquals(0,
      getHiveServer()
        .execute("CREATE TABLE somedata_copy (col1 INT, col2 INT) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE")
        .size());
    assertEquals(2, getHiveServer().execute("SHOW TABLES").size());
    assertEquals(0, getHiveServer().execute("USE default").size());
    assertEquals(1, getHiveServer().execute("SHOW TABLES").size());
    assertEquals(2, getHiveServer().execute("SHOW DATABASES").size());
  }

  @Test
  public void testHiveCreateSelectAgain() throws Exception {
    testHiveCreateSelect();
  }

}


text:
UX

Information architecture

Functional prototyping

Usability analysis

Design

User interface design

Illustartions

Character & Game design

Multi-screen design

Software

Rich frontend development

Backend development

Game development

        	View our work
        	or
        	Get in touch

A bunch of talented and hard working developers, designers and, managers, with personality to match...Yes, we really do exist!

Our core team

Klaudyna

Marketing & Sales

Michał

Analysis Manager

Maciek

Art Director

Łukasz

Technical Leader

Maciek

Illustrator

					Join Us
					Contact us

+ our software development engineering gurus

We turn your ideas into reality - faster than you thought possible.

Hire us


text:
title: "TypeScript - размеченные объединения"
layout: post
categories: TypeScript
tags: [typescript, union types]
share: true
---

> Пользовательское объединение типов - что это и как можно использовать

Помимо объединения **примитивных** типов данных (например):

{% highlight typescript %}
type myType = number | string;
{% endhighlight %}

... в TypeScript можно делать и объединение **пользовательских** типов данных:

{% highlight typescript %}
interface Rectange {
  width: number,
  height: number
}

interface Circle {
  radius: number
}

type Shape = Rectange | Circle;
{% endhighlight %}

Более того, пользовательские типы можно **связать** между собой при помощи общего для всех типов поля:

{% highlight typescript %}
interface Rectange {
  width: number,
  height: number,
  type: 'rectange'
}

interface Circle {
  radius: number,
  type: 'circle'
}

type Shape = Rectange | Circle;
{% endhighlight %}

... здесь поле `type` - является таким связующим звеном; такое поле называется _дискриминантом_.

Прелесть такого объединения типов заключается в том, что можно проверять значение этого поля и в зависимости от результата - выполнять нужное действие. Например, можно создать такую функцию `calcArea`:

{% highlight typescript %}
function calcArea(shape: Shape): number {
  const { type } = shape;

  switch(type) {
    case 'rectange':
      return shape.width * shape.height;
    case 'circle':
      return Math.round(Math.PI * shape.radius ** 2);
  }
}
{% endhighlight %}

... и тогда пример использования этой функции и объединенного типа будет таким:

{% highlight typescript %}
interface Rectange {
  width: number,
  height: number,
  type: 'rectange'
}

interface Circle {
  radius: number,
  type: 'circle'
}

type Shape = Rectange | Circle;

function calcArea(shape: Shape): number {
  const { type } = shape;

  switch(type) {
    case 'rectange':
      return shape.width * shape.height;
    case 'circle':
      return Math.round(Math.PI * shape.radius ** 2);
  }
}

const rectangle: Rectange = { width: 10, height: 10, type: 'rectange' };
const circle: Circle = { radius: 20, type: 'circle' };

console.log(calcArea(rectangle)); // => 100
console.log(calcArea(circle)); // => 1257
{% endhighlight %}

---


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace com.akoimeexx.utilities.assemblyinformation.Dialogs {
    /// <summary>
    /// Interaction logic for Details.xaml
    /// </summary>
    public partial class Details : Window, INotifyPropertyChanged {
#region Properties
        public ViewModels.DetailsViewModel ViewModel {
            get { return _viewModel; }
            set {
                _viewModel = value;
                PropertyChanged?.Invoke(
                    this,
                    new PropertyChangedEventArgs("ViewModel")
                );
            }
        } private ViewModels.DetailsViewModel _viewModel =
            new ViewModels.DetailsViewModel();
#endregion Properties
    }
    public partial class Details {
#region Events
        public event PropertyChangedEventHandler PropertyChanged;
#endregion Events
    }
    public partial class Details {
#region Constructors & Destructor
        public Details(string assemblyPath) {
            try {
                if (!File.Exists(assemblyPath))
                    throw new FileNotFoundException(String.Format(
                        "Could not find the file specified at \"{0}\"",
                        assemblyPath
                    ));
                InitializeComponent();
                ViewModel.AssemblyDetails =
                        ReflectionAnalyzer.ExamineAssembly(assemblyPath);
                DataContext = ViewModel;
            } catch (Exception e) {
                MessageBox.Show(
                    String.Join(
                        Environment.NewLine,
                        "An error occured while loading assembly details:",
                        e.Message
                    ),
                    "Exception thrown",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error
                );
                Close();
            }
        }
#endregion Constructors & Destructor
    }
}


text:
package edu.cmu.hcii.whyline.ui.qa;

import java.awt.Color;
import java.awt.Graphics2D;

import edu.cmu.hcii.whyline.bytecode.Branch;
import edu.cmu.hcii.whyline.qa.BranchBlock;
import edu.cmu.hcii.whyline.ui.UI;

/**
 * @author Andrew J. Ko
 *
 */
public class BranchBlockView extends EventBlockView<BranchBlock> {

	private boolean isRedundantLoopBlock;

	public BranchBlockView(Visualization visualization, BranchBlock block) {

		super(visualization, block);

	}

	public boolean isFamiliarInitially() { return visualization.getTrace().hasUserSourceFileFor(visualization.getTrace().getInstruction(getEventID()).getClassfile()); }

	protected void setIsRedundantLoopBlock(boolean isRedundant) {

		this.isRedundantLoopBlock = isRedundant;
		// Don't do this! The user didn't ask us to!
//		setCollapsed(isRedundant);
		updateDescription();

	}

	public String determineFirstLine() {

		return ((Branch)visualization.getTrace().getInstruction(getExplanation().getEventID())).getKeyword();

	}

	public String determineSecondLine() { return null; }

	protected Color determineBorderColor() {

		if(isRedundantLoopBlock) return UI.CONTROL_COLOR;
		else return UI.CONTROL_COLOR;

	}

	protected void paintExpanded(Graphics2D g) {

		// Draw a vertical bar to represent the branch, distinguishing it from other types of blocks.
		g.setColor(determineBorderColor());
		int x = (int)(getVisibleLocalLeft() + widthOfLabel + UI.PADDING_WITHIN_EVENTS * 2);
		g.drawLine(x, (int)getVisibleLocalTop(), x, (int)getVisibleLocalBottom());

		super.paintExpanded(g);

	}

	public void drawSelection(Graphics2D g) {

		java.awt.Stroke stroke = g.getStroke();
		g.setStroke(UI.SELECTED_STROKE);
		g.setColor(UI.getHighlightColor());
		g.drawRoundRect((int)getLocalLeft(), (int)getLocalTop(), (int)widthOfLabel + UI.PADDING_WITHIN_EVENTS * 2, (int)getLocalHeight(), UI.getRoundedness(), UI.getRoundedness());
		g.setStroke(stroke);

	}

	protected void paintLabel(Graphics2D g) {

		g.drawGlyphVector(getFirstLineGlyphs(), (float)getVisibleLocalLeft() + UI.PADDING_WITHIN_EVENTS, (float)(getLocalTop() + heightOfLabel));

	}

}


text:
@interface UILabel (VerticalAlignment)

- (float)frameForSizeOfTextWithMaxHeight:(int)maxHeight;

@end


text:
package credentials

import (
	"encoding/xml"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"time"
)

// AssumeRoleWithWebIdentityResponse contains the result of successful AssumeRoleWithWebIdentity request.
type AssumeRoleWithWebIdentityResponse struct {
	XMLName          xml.Name          `xml:"https://sts.amazonaws.com/doc/2011-06-15/ AssumeRoleWithWebIdentityResponse" json:"-"`
	Result           WebIdentityResult `xml:"AssumeRoleWithWebIdentityResult"`
	ResponseMetadata struct {
		RequestID string `xml:"RequestId,omitempty"`
	} `xml:"ResponseMetadata,omitempty"`
}

// WebIdentityResult - Contains the response to a successful AssumeRoleWithWebIdentity
// request, including temporary credentials that can be used to make MinIO API requests.
type WebIdentityResult struct {
	AssumedRoleUser AssumedRoleUser `xml:",omitempty"`
	Audience        string          `xml:",omitempty"`
	Credentials     struct {
		AccessKey    string    `xml:"AccessKeyId" json:"accessKey,omitempty"`
		SecretKey    string    `xml:"SecretAccessKey" json:"secretKey,omitempty"`
		Expiration   time.Time `xml:"Expiration" json:"expiration,omitempty"`
		SessionToken string    `xml:"SessionToken" json:"sessionToken,omitempty"`
	} `xml:",omitempty"`
	PackedPolicySize            int    `xml:",omitempty"`
	Provider                    string `xml:",omitempty"`
	SubjectFromWebIdentityToken string `xml:",omitempty"`
}

// WebIdentityToken - web identity token with expiry.
type WebIdentityToken struct {
	Token  string
	Expiry int
}

// A STSWebIdentity retrieves credentials from MinIO service, and keeps track if
// those credentials are expired.
type STSWebIdentity struct {
	Expiry

	// Required http Client to use when connecting to MinIO STS service.
	Client *http.Client

	// MinIO endpoint to fetch STS credentials.
	stsEndpoint string

	// getWebIDTokenExpiry function which returns ID tokens
	// from IDP. This function should return two values one
	// is ID token which is a self contained ID token (JWT)
	// and second return value is the expiry associated with
	// this token.
	// This is a customer provided function and is mandatory.
	getWebIDTokenExpiry func() (*WebIdentityToken, error)
}

// NewSTSWebIdentity returns a pointer to a new
// Credentials object wrapping the STSWebIdentity.
func NewSTSWebIdentity(stsEndpoint string, getWebIDTokenExpiry func() (*WebIdentityToken, error)) (*Credentials, error) {
	if stsEndpoint == "" {
		return nil, errors.New("STS endpoint cannot be empty")
	}
	if getWebIDTokenExpiry == nil {
		return nil, errors.New("Web ID token and expiry retrieval function should be defined")
	}
	return New(&STSWebIdentity{
		Client: &http.Client{
			Transport: http.DefaultTransport,
		},
		stsEndpoint:         stsEndpoint,
		getWebIDTokenExpiry: getWebIDTokenExpiry,
	}), nil
}

func getWebIdentityCredentials(clnt *http.Client, endpoint string,
	getWebIDTokenExpiry func() (*WebIdentityToken, error)) (AssumeRoleWithWebIdentityResponse, error) {
	idToken, err := getWebIDTokenExpiry()
	if err != nil {
		return AssumeRoleWithWebIdentityResponse{}, err
	}

	v := url.Values{}
	v.Set("Action", "AssumeRoleWithWebIdentity")
	v.Set("WebIdentityToken", idToken.Token)
	v.Set("DurationSeconds", fmt.Sprintf("%d", idToken.Expiry))
	v.Set("Version", "2011-06-15")

	u, err := url.Parse(endpoint)
	if err != nil {
		return AssumeRoleWithWebIdentityResponse{}, err
	}

	u.RawQuery = v.Encode()

	req, err := http.NewRequest("POST", u.String(), nil)
	if err != nil {
		return AssumeRoleWithWebIdentityResponse{}, err
	}

	resp, err := clnt.Do(req)
	if err != nil {
		return AssumeRoleWithWebIdentityResponse{}, err
	}

	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return AssumeRoleWithWebIdentityResponse{}, errors.New(resp.Status)
	}

	a := AssumeRoleWithWebIdentityResponse{}
	if err = xml.NewDecoder(resp.Body).Decode(&a); err != nil {
		return AssumeRoleWithWebIdentityResponse{}, err
	}

	return a, nil
}

// Retrieve retrieves credentials from the MinIO service.
// Error will be returned if the request fails.
func (m *STSWebIdentity) Retrieve() (Value, error) {
	a, err := getWebIdentityCredentials(m.Client, m.stsEndpoint, m.getWebIDTokenExpiry)
	if err != nil {
		return Value{}, err
	}

	// Expiry window is set to 10secs.
	m.SetExpiration(a.Result.Credentials.Expiration, DefaultExpiryWindow)

	return Value{
		AccessKeyID:     a.Result.Credentials.AccessKey,
		SecretAccessKey: a.Result.Credentials.SecretKey,
		SessionToken:    a.Result.Credentials.SessionToken,
		SignerType:      SignatureV4,
	}, nil
}


text:
export KUBERNETES_SERVICE_HOST=tsrv.devshift.net
export KUBERNETES_SERVICE_PORT=8443

echo "Using Kubernetes Master: ${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}"

[ -z "$KUBERNETES_SERVICE_HOST" ] && IFS=':' read KUBERNETES_SERVICE_HOST KUBERNETES_SERVICE_PORT <<< "$PARTS"
[ -z "$KUBERNETES_SERVICE_HOST" ] && echo "Need to set KUBERNETES_SERVICE_HOST" && exit 1;
[ -z "$KUBERNETES_SERVICE_PORT" ] && echo "Need to set KUBERNETES_SERVICE_PORT" && exit 1;

export OAUTH_AUTHORIZE_URI="https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}/oauth/authorize"
export OAUTH_LOGOUT_URI="https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}/connect/endsession?id_token={{id_token}}"
# This is devshift
export PROXIED_K8S_API_SERVER="${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}"
# This is our proxy that we will connect to
export K8S_API_SERVER="localhost:3000"

if [ -z "${OAUTH_ISSUER}" ]; then
  export OAUTH_ISSUER="https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}"
fi
if [ -z "${OAUTH_SCOPE}" ]; then
  export OAUTH_SCOPE="user:full"
fi
if [ -z "${OAUTH_CLIENT_ID}" ]; then
  export OAUTH_CLIENT_ID="fabric8"
fi
if [ -z "${K8S_API_SERVER_PROTOCOL}" ]; then
  export K8S_API_SERVER_PROTOCOL="http"
fi
if [ -z "${K8S_API_SERVER_BASE_PATH}" ]; then
  export K8S_API_SERVER_BASE_PATH="/_p/oso"
fi
if [ -z "${WS_K8S_API_SERVER}" ]; then
  export WS_K8S_API_SERVER=${PROXIED_K8S_API_SERVER}
fi
if [ -z "${FABRIC8_PIPELINES_NAMESPACE}" ]; then
  export FABRIC8_PIPELINES_NAMESPACE="-development"
fi

echo "Configured to connect to kubernetes cluster at https://${PROXIED_K8S_API_SERVER}/"

echo ""
echo "WS_K8S_API_SERVER:             ${WS_K8S_API_SERVER}"
echo "K8S_API_SERVER_PROTOCOL:       ${K8S_API_SERVER_PROTOCOL}"
echo "K8S_API_SERVER_BASE_PATH:      ${K8S_API_SERVER_BASE_PATH}"
echo "OAUTH_ISSUER:                  ${OAUTH_ISSUER}"
echo "OAUTH_CLIENT_ID:               ${OAUTH_CLIENT_ID}"
echo "OAUTH_SCOPE:                   ${OAUTH_SCOPE}"
echo "OAUTH_AUTHORIZE_URI            ${OAUTH_AUTHORIZE_URI}"
echo "OAUTH_LOGOUT_URI               ${OAUTH_LOGOUT_URI}"
echo "FABRIC8_PIPELINES_NAMESPACE    ${FABRIC8_PIPELINES_NAMESPACE}"
echo ""


text:
/*
    This file is part of the Blink open source project.
    This file has been auto-generated by CodeGeneratorV8.pm. DO NOT MODIFY!

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#ifndef V8TestMediaQueryListListener_h
#define V8TestMediaQueryListListener_h

#include "bindings/bindings/tests/idls/TestMediaQueryListListener.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8DOMWrapper.h"
#include "bindings/v8/WrapperTypeInfo.h"

namespace WebCore {

class V8TestMediaQueryListListener {
public:
    static bool HasInstance(v8::Handle<v8::Value>, v8::Isolate*, WrapperWorldType);
    static bool HasInstanceInAnyWorld(v8::Handle<v8::Value>, v8::Isolate*);
    static v8::Handle<v8::FunctionTemplate> GetTemplate(v8::Isolate*, WrapperWorldType);
    static TestMediaQueryListListener* toNative(v8::Handle<v8::Object> object)
    {
        return fromInternalPointer(object->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex));
    }
    static void derefObject(void*);
    static WrapperTypeInfo info;
    static const int internalFieldCount = v8DefaultWrapperInternalFieldCount + 0;
    static inline void* toInternalPointer(TestMediaQueryListListener* impl)
    {
        return impl;
    }

    static inline TestMediaQueryListListener* fromInternalPointer(void* object)
    {
        return static_cast<TestMediaQueryListListener*>(object);
    }
    static void installPerContextProperties(v8::Handle<v8::Object>, TestMediaQueryListListener*, v8::Isolate*) { }
    static void installPerContextPrototypeProperties(v8::Handle<v8::Object>, v8::Isolate*) { }
private:
    friend v8::Handle<v8::Object> wrap(TestMediaQueryListListener*, v8::Handle<v8::Object> creationContext, v8::Isolate*);
    static v8::Handle<v8::Object> createWrapper(PassRefPtr<TestMediaQueryListListener>, v8::Handle<v8::Object> creationContext, v8::Isolate*);
};

template<>
class WrapperTypeTraits<TestMediaQueryListListener > {
public:
    static WrapperTypeInfo* info() { return &V8TestMediaQueryListListener::info; }
};

inline v8::Handle<v8::Object> wrap(TestMediaQueryListListener* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
    ASSERT(impl);
    ASSERT(DOMDataStore::getWrapper<V8TestMediaQueryListListener>(impl, isolate).IsEmpty());
    return V8TestMediaQueryListListener::createWrapper(impl, creationContext, isolate);
}

inline v8::Handle<v8::Value> toV8(TestMediaQueryListListener* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
    if (UNLIKELY(!impl))
        return v8NullWithCheck(isolate);
    v8::Handle<v8::Value> wrapper = DOMDataStore::getWrapper<V8TestMediaQueryListListener>(impl, isolate);
    if (!wrapper.IsEmpty())
        return wrapper;
    return wrap(impl, creationContext, isolate);
}

inline v8::Handle<v8::Value> toV8ForMainWorld(TestMediaQueryListListener* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
    ASSERT(worldType(isolate) == MainWorld);
    if (UNLIKELY(!impl))
        return v8::Null(isolate);
    v8::Handle<v8::Value> wrapper = DOMDataStore::getWrapperForMainWorld<V8TestMediaQueryListListener>(impl);
    if (!wrapper.IsEmpty())
        return wrapper;
    return wrap(impl, creationContext, isolate);
}

template<class CallbackInfo, class Wrappable>
inline v8::Handle<v8::Value> toV8Fast(TestMediaQueryListListener* impl, const CallbackInfo& callbackInfo, Wrappable* wrappable)
{
    if (UNLIKELY(!impl))
        return v8::Null(callbackInfo.GetIsolate());
    v8::Handle<v8::Object> wrapper = DOMDataStore::getWrapperFast<V8TestMediaQueryListListener>(impl, callbackInfo, wrappable);
    if (!wrapper.IsEmpty())
        return wrapper;
    return wrap(impl, callbackInfo.Holder(), callbackInfo.GetIsolate());
}

inline v8::Handle<v8::Value> toV8ForMainWorld(PassRefPtr< TestMediaQueryListListener > impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
    return toV8ForMainWorld(impl.get(), creationContext, isolate);
}

template<class CallbackInfo, class Wrappable>
inline v8::Handle<v8::Value> toV8Fast(PassRefPtr< TestMediaQueryListListener > impl, const CallbackInfo& callbackInfo, Wrappable* wrappable)
{
    return toV8Fast(impl.get(), callbackInfo, wrappable);
}

inline v8::Handle<v8::Value> toV8(PassRefPtr< TestMediaQueryListListener > impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
    return toV8(impl.get(), creationContext, isolate);
}

}

#endif // V8TestMediaQueryListListener_h


text:
var _ = require('lodash');
var mixin = require('mixin-class');
var ko = require('knockout');
var peekObservable = ko.utils.peekObservable;

var Validator = require('./lib/validator')

var nullValidator = new Validator();
nullValidator.validate = function() {};

var Factory = mixin(
        function(model, config) {
            var self = this;
            var validatorsObject = this.validators = {};
            _.each(config, function(validators, key) {
                validatorsObject[key] = self[key] = new self.Validator(model, key, validators);
            });

            this.isValid = ko.computed(function() {
                var isValid = true;
                _.each(validatorsObject, function(validator) {
                    if (!validator.isValid()) {
                        isValid = false;
                    }
                });
                return isValid;
            });
        },
        {
            Validator: Validator,

            validate: function() {
                _.each(this.validators, function(validator) {
                    validator.validate();
                });
            },

            clear: function() {
                _.each(this.validators, function(validator) {
                    validator.clear();
                });
            }
        }
    )

Factory.nullValidator = nullValidator;
Factory.handler = require('./lib/validate-handlers')

module.exports = Factory;


text:
default['nexus3_resources_test']['api']['create']['default']['script_name'] = 'foo'
default['nexus3_resources_test']['api']['create']['default']['content'] = 'repository.createMavenHosted("foo")'
default['nexus3_resources_test']['api']['create']['default']['retries'] = 10
default['nexus3_resources_test']['api']['create']['default']['retry_delay'] = 10
# Test to update the script content
default['nexus3_resources_test']['api']['create']['update']['script_name'] = 'foo'
default['nexus3_resources_test']['api']['create']['update']['content'] = 'repository.createMavenHosted("bar")'
#  action: delete
default['nexus3_resources_test']['api']['delete']['default']['script_name'] = 'foo'


text:
package de.adesso.wickedforms.wicket7.components;

import de.adesso.wickedforms.model.Form;
import de.adesso.wickedforms.wicket7.DefaultPanelFactory;
import de.adesso.wickedforms.wicket7.PanelFactory;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.HeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.html.panel.GenericPanel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.request.resource.PackageResourceReference;

import java.util.ArrayList;
import java.util.List;

public abstract class FormPanel extends GenericPanel<Form> implements Submittable {

    private final PanelFactory panelFactory;

    public FormPanel(String id, final IModel<Form> model) {
        this(id, model, true);
    }

    /**
     * Constructor.
     *
     * @param id    the wicket id this panel should bind to.
     * @param model the form model that describes the contents of the form.
     */
    public FormPanel(final String id, final IModel<Form> model, boolean showSubmittable) {
        super(id, model);
        model.getObject().assignIds();
        this.panelFactory = new DefaultPanelFactory();
        add(new DynamicForm("form", model, panelFactory, this, showSubmittable));
        mountResources();
    }

    public FormPanel(final String id, final Form formModel) {
        this(id, formModel, true);
    }

    @SuppressWarnings("unchecked")
    public FormPanel(final String id, final Form formModel, boolean showSubmittable) {
        super(id, Model.of(formModel));
        formModel.assignIds();
        this.panelFactory = new DefaultPanelFactory();
        add(new DynamicForm("form", getModel(), panelFactory, this, showSubmittable));
        mountResources();
    }

    public FormPanel(final String id, final IModel<Form> model, final PanelFactory panelFactory) {
        this(id, model, panelFactory, true);
    }

    /**
     * Constructor defining a {@link PanelFactory}. The {@link PanelFactory} is
     * responsible for creating the sub panels that each contain an element of
     * the form (i.e. a text field, a checkbox, ...). By providing a custom
     * {@link PanelFactory}, you can define your own panels with their own HTML
     * markup to be used and thus override the default look & feel.
     *
     * @param id              the wicket id this panel should bind to.
     * @param model           the form model that describes the contents of the form.
     * @param panelFactory    the factory to use for creating the sub panels that each
     *                        contain a form element (text field, checkbox, ...).
     * @param showSubmittable tells the form to be submittable from outer form (without explicit submit-button) or can be submitted by itself.
     */
    public FormPanel(final String id, final IModel<Form> model,
                     final PanelFactory panelFactory, boolean showSubmittable) {
        super(id, model);
        model.getObject().assignIds();
        this.panelFactory = panelFactory;
        add(new DynamicForm("form", model, panelFactory, this, showSubmittable));
        mountResources();
    }

    /**
     * Retrieves all {@link HeaderItem}s like Javascript files and CSS files
     * that should be included in each page that contains a {@link FormPanel}.
     * Override this method to provide different CSS.
     *
     * @return all {@link HeaderItem}s to add to the page.
     */
    protected List<HeaderItem> getHeaderItems() {
        List<HeaderItem> headerItems = new ArrayList<HeaderItem>();
        headerItems.add(CssHeaderItem
                .forReference(new PackageResourceReference(FormPanel.class,
                        "FormPanel.css")));
        return headerItems;
    }

    private void mountResources() {
        WebApplication application = ((WebApplication) getApplication());
        application.mountResource("wickedforms/invalid.png",
                new PackageResourceReference(FormPanel.class, "invalid.png"));
        application.mountResource("wickedforms/red_asterisk.png",
                new PackageResourceReference(FormPanel.class,
                        "red_asterisk.png"));
        application.mountResource("wickedforms/valid.png",
                new PackageResourceReference(FormPanel.class, "valid.png"));
    }

    /**
     * Executed when the form is submitted.
     *
     * @param submittedData the {@link Form} object containing the state of the form
     *                      at submit time. If you have used Bindings and implemented
     *                      {@link de.adesso.wickedforms.model.elements.AbstractFormElement#onDiscard} to clean up after
     *                      discarded elements, the user input will be bound to the target
     *                      objects by now and you will not actually need to evaluate this
     *                      parameter.
     *                      <p/>
     *                      If you need to evaluate this parameter, be aware that elements
     *                      that were marked as "discarded" while the user worked with the
     *                      form, are still contained. Call
     *                      {@link de.adesso.wickedforms.model.elements.AbstractFormElement#isDiscarded()} on each element
     *                      before evaluating it.
     */
    @Override
    public abstract void onSubmit(final Form submittedData);

    @Override
    public void renderHead(final IHeaderResponse response) {
        for (HeaderItem headerItem : getHeaderItems()) {
            response.render(headerItem);
        }
    }

    public Form getWickedFormModel() {
        return (Form) getDefaultModelObject();
    }

}


text:
function MDGamepad() {

    this.gamepad = null;
    this.gamepads = [];
    this.interval1 = null;
    this.interval2 = null;
    this.interval3 = null;
    this.eventsList = [];
    this.buttons = [];
    this.axises = [];
    this.gamepadtype = null;

    this.infoUpdateInterval = 1;
    this.gamepadId = 0;

    this.init = function() {
        if(this.interval1 != null) {
            clearInterval(this.interval1);
        }
        if(this.interval2 != null) {
            clearInterval(this.interval2);
        }
        if(this.interval3 != null) {
            clearInterval(this.interval3);
        }
        this.interval1 = setInterval(function() {
            mdg.gamepads = navigator.getGamepads();
            if(mdg.gamepads.length > 0) {
                if(typeof mdg.gamepads[mdg.gamepadId] != "undefined" && mdg.gamepads[mdg.gamepadId] != null) {
                    if(mdg.gamepad == null) {
                        mdg.gamepad = mdg.gamepads[mdg.gamepadId];
                        mdg.gamepadtype = mdg.gamepad.id;
                        for(var i in mdg.gamepad.axes) {
                            mdg.axises[i] = mdg.gamepad.axes[i];
                        }
                        MDGamepadDoEvent('connected', []);
                        for(var i in mdg.gamepad.buttons) {
                            if(mdg.gamepad.buttons[i] instanceof GamepadButton) {
                                mdg.buttons[i] = [];
                                mdg.buttons[i].pressed = false;
                            }
                        }
                    } else {
                        if(mdg.gamepad != mdg.gamepads[mdg.gamepadId]) {
                            MDGamepadDoEvent('disconnected', []);
                            mdg.buttons = [];
                            mdg.gamepad = null;
                            mdg.gamepadtype = null;

                            mdg.gamepad = mdg.gamepads[mdg.gamepadId];
                            mdg.gamepadtype = mdg.gamepad.id;
                            MDGamepadDoEvent('connected', []);
                            for(var i in mdg.gamepad.buttons) {
                                if(mdg.gamepad.buttons[i] instanceof GamepadButton) {
                                    mdg.buttons[i] = [];
                                    mdg.buttons[i].pressed = false;
                                }
                            }
                        } else {
                            mdg.gamepad = mdg.gamepads[mdg.gamepadId];
                        }
                    }
                } else {
                    if(mdg.gamepad != null && mdg.gamepad instanceof Gamepad) {
                        for(var i in mdg.buttons) {
                            if(mdg.buttons[i].pressed == true) {
                                MDGamepadDoEvent('buttonup', {'button': i});
                            }
                        }
                        MDGamepadDoEvent('disconnected', []);
                        mdg.buttons = [];
                        mdg.axises = [];
                        mdg.gamepad = null;
                        mdg.gamepadtype = null;
                    }
                }
            } else {
                if(mdg.gamepad != null && mdg.gamepad instanceof Gamepad) {
                    for(var i in mdg.buttons) {
                        if(mdg.buttons[i].pressed == true) {
                            MDGamepadDoEvent('buttonup', {'button': i});
                        }
                    }
                    MDGamepadDoEvent('disconnected', []);
                    mdg.buttons = [];
                    mdg.axises = [];
                    mdg.gamepad = null;
                    mdg.gamepadtype = null;
                }
            }
        }, this.infoUpdateInterval);

        this.interval2 = setInterval(function() {
            if(mdg.gamepad != null && mdg.gamepad instanceof Gamepad) {
                for(var i in mdg.gamepad.buttons) {
                    if(mdg.gamepad.buttons[i] instanceof GamepadButton) {
                        if(mdg.buttons[i].pressed == false && mdg.gamepad.buttons[i].pressed == true) {
                            MDGamepadDoEvent('buttondown', {'button': i});
                            mdg.buttons[i].pressed = true;
                        } else if(mdg.buttons[i].pressed == true && mdg.gamepad.buttons[i].pressed == false) {
                            MDGamepadDoEvent('buttonup', {'button': i});
                            mdg.buttons[i].pressed = false;
                        }
                    }
                }
            }
        }, this.infoUpdateInterval);

        this.interval3 = setInterval(function() {
            if(mdg.gamepad != null && mdg.gamepad instanceof Gamepad) {
                for(var i in mdg.gamepad.axes) {
                    if(mdg.axises[i] != mdg.gamepad.axes[i]) {
                        mdg.axises[i] = mdg.gamepad.axes[i];
                        MDGamepadDoEvent('newaxisposition', {'axis': i, 'position': mdg.gamepad.axes[i]});
                    }
                }
            }
        }, this.infoUpdateInterval);
    }

    this.init();

    var MDGamepadDoEvent = function(eventname, args) {
        if(typeof mdg.eventsList[eventname] != 'undefined') {
            mdg.eventsList[eventname](args);
        }
    }

    this.on = function(eventname, callback) {
        this.eventsList[eventname] = callback;
    }

    this.isGamepadConnected = function() {
        if(this.gamepad != null && this.gamepad instanceof Gamepad) {
            return true;
        } else {
            return false;
        }
    }

    this.getGamepadType = function() {
        return this.gamepadtype;
    }

    this.isButtonPressed = function(buttonIndex) {
        if(this.isGamepadConnected()) {
            if(typeof mdg.buttons[buttonIndex] != 'undefined') {
                return mdg.buttons[buttonIndex].pressed;
            }
        } else {
            return false;
        }
    }

    this.getAxises = function() {
        if(this.isGamepadConnected()) {
            return this.axises;
        } else {
            return false;
        }
    }
}


text:
namespace detail
{
	// Utility function to disambiguate from macro 'max'.
	template<typename T>
	inline T limit()
	{
		return (std::numeric_limits<T>::max)();
	}
}	// namespace detail

class FrameClock final
{
public:

	// Constructs a FrameClock object with sample depth 'depth'.
	explicit FrameClock(size_t depth = 100);

	// Resets all times to zero and discards accumulated samples.
	void clear();

	// Begin frame timing.
	// Should be called once at the start of each new frame.
	void beginFrame();

	// End frame timing.
	// Should be called once at the end of each frame.
	// Returns: Time elapsed since the matching FrameClock::beginFrame.
	sf::Time endFrame();

	// Sets the number of frames to be sampled for averaging.
	// 'depth' must be greater than or equal to 1.
	void setSampleDepth(size_t depth);

	// Returns: The number of frames to be sampled for averaging.
	size_t getSampleDepth() const;

	// Returns: The total accumulated frame time.
	sf::Time getTotalFrameTime() const;

	// Returns: The total accumulated number of frames.
	sf::Uint64 getTotalFrameCount() const;

	// Returns: Time elapsed during the last 'FrameClock::beginFrame/endFrame' pair.
	sf::Time getLastFrameTime() const;

	// Returns: The shortest measured frame time.
	sf::Time getMinFrameTime() const;

	// Returns: The longest measured frame time.
	sf::Time getMaxtFrameTime() const;

	// Returns: Average frame time over the last getSampleDepth() frames.
	sf::Time getAverageFrameTime() const;

	// Returns: Frames per second, considering the previous frame only.
	float getFramesPerSecond() const;

	// Returns: The lowest measured frames per second.
	float getMinFramesPerSecond() const;

	// Returns: The highest measured frames per second.
	float getMaxFramesPerSecond() const;

	// Returns: Average frames per second over the last getSampleDepth() frames.
	float getAverageFramesPerSecond() const;

	// Swaps the value of this FrameClock instance with 'other'.
	void swap(FrameClock& other);

private:

	template<typename T, typename U>
	struct Range
	{
		Range() :
			minimum(),
			maximum(),
			average(),
			current(),
			elapsed()
		{}

		void swap(Range& other)
		{
			std::swap(this->minimum, other.minimum);
			std::swap(this->maximum, other.maximum);
			std::swap(this->average, other.average);
			std::swap(this->current, other.current);
			std::swap(this->elapsed, other.elapsed);
		}

		T minimum;
		T maximum;
		T average;
		T current;
		U elapsed;
	};

	Range<sf::Time, sf::Time> time;
	Range<float, sf::Uint64>  freq;

	struct SampleData
	{
		SampleData() :
			accumulator(),
			data(),
			index()
		{}

		sf::Time accumulator;
		std::vector<sf::Time> data;
		std::vector<sf::Time>::size_type index;

		void swap(SampleData& other)
		{
			std::swap(this->accumulator, other.accumulator);
			std::swap(this->data, other.data);
			std::swap(this->index, other.index);
		}

	} sample;

	sf::Clock clock;
};

struct Stat
{
	sf::Color color;
	std::string str;
};

typedef std::vector<Stat> Stats;

class DiagnosticsHUD final : public sf::Drawable
{
public:
	DiagnosticsHUD(const FrameClock& clock, const sf::Font& font);

	sf::Color stat;
	sf::Color summaryFps;
	sf::Color summaryMilli;

protected:
	void draw(sf::RenderTarget& rt, sf::RenderStates states) const override;

private:
	template<typename T>
	static std::string format(std::string name, std::string resolution, T value)
	{
		std::ostringstream os;
		os.precision(4);
		os << std::left << std::setw(5);
		os << name << " : ";
		os << std::setw(5);
		os << value << " " << resolution;
		return os.str();
	}

	Stats build() const;

	const sf::Font* font;
	const FrameClock* clock;
};

#endif