text:
immutable MatchEnv
  # sizes of the full size patches
  size_src::NTuple{2, Int64}
  size_dst::NTuple{2, Int64}

  # blockmatch scale
  scale::Float64
  # bandpass values
  bandpass

  # bandpass filter for xcorr
  kernel::Array{Float64, 2}

  # tforms for scaling
  tform_src::Array{Float64, 2}
  tform_dst::Array{Float64, 2}

  # locations for the full size patches
  src_patch_full::Array{Float64, 2}
  dst_patch_full::Array{Float64, 2}

  # locations for the scaled patches
  src_patch::Array{Float64, 2}
  dst_patch::Array{Float64, 2}
end

global MATCH_ENVS = Dict{Symbol, MatchEnv}()

function clear_matchenvs()
    for key in keys(MATCH_ENVS)
        MATCH_ENVS[key] = MatchEnv(0:0,0:0)
    end
    gc();
    global MATCH_ENVS = Dict{Symbol, MatchEnv}()
end

function register_matchenv(me::MatchEnv)
    MATCH_ENVS[Symbol(me.size_src, me.size_dst, me.scale, me.bandpass)] = me
end

function get_matchenv(src_range, dst_range; scale = 1.0, bandpass = (0,0))
  if haskey(MATCH_ENVS, Symbol(map(length, src_range), map(length, dst_range), scale, bandpass))
    return MATCH_ENVS[Symbol(map(length, src_range), map(length, dst_range), scale, bandpass)]
  end

  me = MatchEnv(src_range, dst_range; scale = scale, bandpass = bandpass)
  register_matchenv(me)

  return me
end

function MatchEnv(src_range, dst_range; scale = 1.0, bandpass = (0,0))
  size_src = map(length, src_range)
  size_dst = map(length, dst_range)

  src_patch_full = zeros(Float64, size_src...)
  dst_patch_full = zeros(Float64, size_dst...)

  if scale == 1.0
    src_patch = zeros(Float64, size_src...)
    dst_patch = zeros(Float64, size_dst...)
    tform_src = zeros(Float64, 0, 0)
    tform_dst = zeros(Float64, 0, 0)
  else
    tform = [scale 0 0; 0 scale 0; 0 0 1]

    bb_src = BoundingBox{Float64}(0,0, size_src...)
    wbb_src = tform_bb(bb_src, tform)
    tbb_src = snap_bb(wbb_src)
    src_patch = zeros(Float64, tbb_src.h, tbb_src.w)
    tform_src = [tbb_src.h/size_src[1] - eps 0 0; 0 tbb_src.w/size_src[2] - eps 0; 0 0 1]

    bb_dst = BoundingBox{Float64}(0,0, size_dst...)
    wbb_dst = tform_bb(bb_dst, tform)
    tbb_dst = snap_bb(wbb_dst)
    dst_patch = zeros(Float64, tbb_dst.h, tbb_dst.w)
    tform_dst = [tbb_dst.h/size_dst[1] - eps 0 0; 0 tbb_dst.w/size_dst[2] - eps 0; 0 0 1]
  end

  if bandpass == (0, 0)
    kernel = zeros(Float64, 0, 0)
  else
    kernel = make_bandpass_kernel(bandpass...)
  end

    return MatchEnv(
  size_src::NTuple{2, Int64},
  size_dst::NTuple{2, Int64},

  scale::Float64,
  bandpass,

  kernel::Array{Float64, 2},

  tform_src::Array{Float64, 2},
  tform_dst::Array{Float64, 2},

  src_patch_full::Array{Float64, 2},
  dst_patch_full::Array{Float64, 2},

  src_patch::Array{Float64, 2},
  dst_patch::Array{Float64, 2}
    )
end

function clean!(me::MatchEnv)
  @inbounds begin
    me.src_patch_full[:] = Float64(0)
    me.dst_patch_full[:] = Float64(0)
    me.src_patch[:] = Float64(0)
    me.dst_patch[:] = Float64(0)
  end
end

function init_Match()

global SRC_PATCH_FULL = Array{Float64, 2}(1,1);
global SRC_PATCH_FULL_H = Array{Float64, 2}(1,1);
global SRC_PATCH = Array{Float64, 2}(1,1);
#global SRC_PATCH_G_H = Array{Float64, 2}(1,1);
#global SRC_PATCH_G_L = Array{Float64, 2}(1,1);
global DST_PATCH_FULL = Array{Float64, 2}(1,1);
global DST_PATCH_FULL_H = Array{Float64, 2}(1,1);
global DST_PATCH = Array{Float64, 2}(1,1);
#global DST_PATCH_G_H = Array{Float64, 2}(1,1);
#global DST_PATCH_G_L = Array{Float64, 2}(1,1);

end

init_Match();

struct Match{T} <: AbstractMatch
  src_index          # source mesh index
  dst_index          # destination mesh index
  src_points::Points{T}     # source point coordinate in image
  dst_points::Points{T}        # destination point coordinate in image
  correspondence_properties    # in the same array order as points, contains properties of correspondences

  filters                       # Array of filters
  properties::Dict{Symbol, Any}
end

function Base.deepcopy(m::Match; src_index=m.src_index, dst_index=m.dst_index,
                        src_points=m.src_points, dst_points=m.dst_points,
                        correspondence_properties=m.correspondence_properties,
                        filters=m.filters, properties=m.properties)
  return Match(src_index, dst_index, deepcopy(src_points), deepcopy(dst_points),
                        deepcopy(correspondence_properties), deepcopy(filters),
                        deepcopy(properties))
end

## IO
function get_correspondences_df(match::Match; globalized=true, manual_only=true)
    pre, post, filter = get_correspondences(match, globalized=globalized, manual_only=manual_only)
    pre_z, post_z = get_index(match)
    n = length(filter)
    df = DataFrame(vcat(pre, ones(n)'*pre_z, post, ones(n)'*post_z, filter')')
    names!(df, [:pre_x, :pre_y, :pre_z, :post_x, :post_y, :post_z, :filter])
    return df
end

function to_dataframe(match::Match; manual_only=true)
    return hcat(get_correspondences_df(match, manual_only=manual_only), match.correspondence_properties)
end

function to_csv(match::Match; manual_only=true)
    check_local_dir(:match)
    fn = joinpath(get_local_path(:match), get_name(match))
    println("Writing correspondences to $fn")
    # writetable(fn, to_dataframe(match, manual_only=manual_only), separator=',')
    CSV.write(fn, to_dataframe(match, manual_only=manual_only))
end

function load_manual_filters!(match::Match)
    fn = joinpath(get_local_path(:match), get_name(match))
    println("Loading manual inspection filters from $fn")
    # df = readtable(fn)
    df = CSV.read(fn)
    match.filters[:manual] = .~convert(Array{Bool,1}, df[:filter])
end

### index related
function get_src_index(match::Match)
  return match.src_index
end
function get_dst_index(match::Match)
  return match.dst_index
end
function get_index(match::Match)
    return get_src_and_dst_indices(match::Match)
end
function get_src_and_dst_indices(match::Match)
  return match.src_index, match.dst_index
end

### counting
function count_correspondences(match::Match) return size(match.src_points, 2);  end
function count_filtered_correspondences(match::Match; manual_only=false) return sum(get_filtered_indices(match, manual_only=manual_only)); end
function count_rejected_correspondences(match::Match; manual_only=false) return sum(get_rejected_indices(match, manual_only=manual_only)); end

function count_filters(match::Match) return size(match.filters, 2); end
function count_filtered_properties(match::Match, property_name, compare, threshold)
    return sum(compare(get_correspondence_properties(match::Match, property_name; filtered = true), threshold))
end

### correspondences related
function get_filtered_indices(match::Match; manual_only=false)
    return map(!, get_rejected_indices(match; manual_only=manual_only))
end
function get_rejected_indices(match::Match; manual_only=false)
    ret = fill(false, count_correspondences(match));
    if manual_only
      if :manual in names(match.filters)
        ret = match.filters[:manual]
      end
    else
      for j in 1:count_filters(match)
        dfcol::Array{Bool, 1} = match.filters.columns[j]
        for i in 1:length(dfcol)
          @inbounds ret[i] = ret[i] || dfcol[i]
        end
      end
    end
    return ret
end
#=
function (match::Match)
    return match.correspondence_properties[get_filtered_indices(match), :]
end
=#

function get_correspondences(match::Match; globalized::Bool=false, filtered::Bool=false, use_post::Bool=false, src_mesh = nothing, dst_mesh = nothing, manual_only=false)
    if filtered
      src_pts = match.src_points[:, get_filtered_indices(match, manual_only=manual_only)]; dst_pts = match.dst_points[:, get_filtered_indices(match, manual_only=manual_only)];
    else
      src_pts = copy(match.src_points); dst_pts = copy(match.dst_points);
    end
    if use_post
      src_pts = deform(src_pts, src_mesh);
      dst_pts = deform(dst_pts, dst_mesh);
    end
    if globalized
      globalize!(src_pts, get_offset(:match_image));
      globalize!(dst_pts, get_offset(:match_image));
    end
    filtered ? ret = (src_pts, dst_pts) : ret = (src_pts, dst_pts, get_filtered_indices(match, manual_only=manual_only));
    return ret;
end

### property handling
function get_dfs(dict::Dict, keytofetch)
    for key in keys(dict)
        if key == keytofetch
          return Base.get(dict, key, nothing)
        elseif typeof(Base.get(dict, key, nothing)) <: Dict
          if get_dfs(Base.get(dict, key, nothing), keytofetch) != nothing
            return get_dfs(Base.get(dict, key, nothing), keytofetch)
          end
        end
    end
    return nothing
end

function get_correspondence_properties(match::Match, property_name; filtered = false)
    if length(match.correspondence_properties) > 0
        ret = match.correspondence_properties[property_name];
        if length(ret) != 0
            ret = Array{typeof(ret[1])}(ret);
        end
        return filtered ? ret[get_filtered_indices(match)] : ret
    else
        return []
    end
end

function get_correspondence_properties(match::Match, fn::Function, args...; filtered = false)
    return filtered ? fn(match, args...)[get_filtered_indices(match)] : fn(match, args...)
end

### reviewing
function set_reviewed!(match::Match)
    match.properties[:review][:author] = author();
    return;
end

function is_reviewed(match::Match)
    return match.properties[:review][:author] == null_author()
end

function get_author(match::Match)
    author = match.properties[:review][:author]
    return author
end

function is_flagged(match::Match, filter_name = nothing)
    if filter_name == nothing return match.properties[:review][:flagged];
    else
    return haskey(match.properties[:review][:flags], filter_name); end
end

function flag!(match::Match, crit = nothing)
    match.properties[:review][:flagged] = true;
    if crit != nothing
    match.properties[:review][:flags][crit[1]] = crit[2:end];
      end
end

"""
Flag a match based on property criteria
"""
function flag!(match::Match, property_name, compare, threshold)
    attributes = get_correspondence_properties(match, property_name; filtered = true)
    inds_to_filter = find(i -> compare(i, threshold), attributes)
    if length(inds_to_filter) > 0
        flag!(match, (property_name, compare, threshold))
    end
end

function unflag!(match::Match, filter_name = nothing)
    if filter_name == nothing
    match.properties[:review][:flagged] = false;
    for key in keys(match.properties[:review][:flags])
      pop!(match.properties[:review][:flags], key);
    end
      else
      if haskey(match.properties[:review][:flags], filter_name)
      pop!(match.properties[:review][:flags], filter_name);
    end
      if length(match.properties[:review][:flags]) == 0
      match.properties[:review][:flagged] = false;
    end
      end
end

### helper methods
function get_ranges(pt, src_index, src_offset, src_image_size, dst_index, dst_offset, dst_image_size)
    get_ranges(pt, src_index, dst_index, PARAMS[:match][:block_r], PARAMS[:match][:search_r]);
end

function get_ranges(pt, src_index, src_offset, src_image_size, dst_index, dst_offset, dst_image_size, block_r::Int64, search_r::Int64)
    # convert to local coordinates in both src / dst images, and then round up to an integer
    src_pt = ceil.(Int64, pt);
    # if global_offsets
    rel_offset = src_offset - dst_offset;
    # else
    #   rel_offset = src_offset
    # end
    dst_pt = src_pt + rel_offset
    dst_pt = ceil.(Int64, dst_pt);

    block_range = -block_r:block_r;
    search_range = -(block_r+search_r):(block_r+search_r);

    src_range_full = src_pt[1] + block_range, src_pt[2] + block_range;
    dst_range_full = dst_pt[1] + search_range, dst_pt[2] + search_range;

    range_in_src = intersect(src_range_full[1], 1:src_image_size[1]), intersect(src_range_full[2], 1:src_image_size[2]);
    if length(range_in_src[1]) % 2 != 1
      range_in_src = range_in_src[1][1:end-1], range_in_src[2];
    end
    if length(range_in_src[2]) % 2 != 1
      range_in_src = range_in_src[1], range_in_src[2][1:end-1];
    end
    range_in_dst = intersect(dst_range_full[1], 1:dst_image_size[1]), intersect(dst_range_full[2], 1:dst_image_size[2]);

    src_pt_locs = findfirst(range_in_src[1] .== src_pt[1]), findfirst(range_in_src[2] .== src_pt[2]);
    dst_pt_locs = findfirst(range_in_dst[1] .== dst_pt[1]), findfirst(range_in_dst[2] .== dst_pt[2]);
    dst_pt_locs_full = findfirst(dst_range_full[1] .== dst_pt[1]), findfirst(dst_range_full[2] .== dst_pt[2]);

    if src_pt_locs[1] == 0 || src_pt_locs[2] == 0 || dst_pt_locs[1] == 0 || dst_pt_locs[2] == 0
    return nothing
    end

    return src_index, range_in_src, [src_pt_locs[1], src_pt_locs[2]], dst_index, range_in_dst, dst_range_full, [dst_pt_locs[1], dst_pt_locs[2]], [dst_pt_locs_full[1], dst_pt_locs_full[2]], rel_offset;
end

function meanpad!(img, val)
  @fastmath avg = mean(img)
  @fastmath zero_entries = img .== val
  @inbounds img[zero_entries] = avg
  #=
  running_sum = 0.0;
  count = 0;
  zero_entries = Array{Int64, 1}();
    @simd for i in 1:length(img)
      @inbounds px = img[i];
      if px != 0
        @fastmath running_sum += px;
        @fastmath count += 1;
      end
      if px == 0
        push!(zero_entries, i)
      end
    end
    if length(zero_entries) == 0 return end
    @fastmath nonzero_mean = running_sum / count
    if eltype(img) != Float64
        @fastmath nonzero_mean = round(eltype(img), nonzero_mean)
    end
    for i in zero_entries
      @inbounds px = img[i];
      if px == 0
        @fastmath @inbounds img[i] = nonzero_mean;
#=      if i%2 != 0
        @fastmath @inbounds img[i] = nonzero_mean;
      else
        @fastmath @inbounds img[i] = nonzero_mean + eps::Float64;
        end =#
      end
    end
    =#
end

# if from_disk src_image / dst_image are indices
# function prepare_patches(src_image, dst_image, src_range, dst_range, dst_range_full, scale, highpass_sigma; from_disk = false)
function prepare_patches(src_image, dst_image, src_range, dst_range, dst_range_full, bandpass_sigmas; me = get_matchenv(src_range, dst_range_full, bandpass = bandpass_sigmas), meanpad = true, meanpad_val=0)
    clean!(me)
    indices_within_range = findin(dst_range_full[1], dst_range[1]), findin(dst_range_full[2], dst_range[2])
    @fastmath @inbounds me.src_patch_full[:] = view(src_image, src_range...)
    @fastmath @inbounds me.dst_patch_full[indices_within_range...] = view(dst_image, dst_range...)

    if meanpad
        meanpad!(me.src_patch_full, meanpad_val)
        meanpad!(me.dst_patch_full, meanpad_val)
    end

    if (bandpass_sigmas != (0,0)) & (bandpass_sigmas != [0,0])
        @inbounds me.src_patch_full[:] = convolve_Float64_planned(me.src_patch_full, me.kernel; crop = :same, padding = :mean)
        @inbounds me.dst_patch_full[:] = convolve_Float64_planned(me.dst_patch_full, me.kernel; crop = :same, padding = :mean)
    end

    return me.src_patch_full, me.dst_patch_full
end

function make_bandpass_kernel(lowpass_sigma, highpass_sigma)
    kernel_l = Images.Kernel.gaussian(lowpass_sigma)
    kernel_h = Images.Kernel.gaussian(highpass_sigma)
    oset = kernel_l.offsets[1]+1

    for j in oset:-oset
      for i in oset:-oset
        kernel_h[i, j] -= kernel_l[i,j]
      end
    end
    kernel = -kernel_h.parent
    return kernel
end

"""
Template match two image patches to produce point pair correspondence
"""
function get_match(pt, ranges, src_image, dst_image, scale = 1.0, bandpass_sigmas = (0, 0), full = false, meanpad = true, meanpad_val = 0)
    src_index, src_range, src_pt_loc, dst_index, dst_range, dst_range_full, dst_pt_loc, dst_pt_loc_full, rel_offset = ranges;
#=  if sum(src_image[src_range[1], first(src_range[2])]) == 0 && sum(src_image[src_range[1], last(src_range[2])]) == 0 &&
            sum(src_image[first(src_range[1]), src_range[2]]) == 0 && sum(src_image[last(src_range[1]), src_range[2]]) == 0 return nothing end
    if sum(dst_image[dst_range[1], first(dst_range[2])]) == 0 && sum(dst_image[dst_range[1], last(dst_range[2])]) == 0 &&
            sum(dst_image[first(dst_range[1]), dst_range[2]]) == 0 && sum(dst_image[last(dst_range[1]), dst_range[2]]) == 0 return nothing end=#

    #see if any of the edges in the template are fully padded
    if sum(src_image[src_range[1], first(src_range[2])]) == 0 return nothing end
    if sum(src_image[src_range[1], last(src_range[2])]) == 0 return nothing end
    if sum(src_image[first(src_range[1]), src_range[2]]) == 0 return nothing end
    if sum(src_image[last(src_range[1]), src_range[2]]) == 0 return nothing end

    if sum(src_image[src_range[1], round(Int64,median(src_range[2]))]) == 0 return nothing end
    if sum(src_image[round(Int64,median(src_range[1])), src_range[2]]) == 0 return nothing end
    dst_quart_range_i = linspace(dst_range[1][1], dst_range[1][end], 5)
    dst_quart_range_j = linspace(dst_range[2][1], dst_range[2][end], 5)
    cent_sum = 0;
    cent_sum += sum(dst_image[round(Int64, dst_quart_range_i[2]):round(Int64, dst_quart_range_i[4]), round(Int64, dst_quart_range_j[2])]);
    cent_sum += sum(dst_image[round(Int64, dst_quart_range_i[2]):round(Int64, dst_quart_range_i[4]), round(Int64, dst_quart_range_j[4])]);
    cent_sum += sum(dst_image[round(Int64, dst_quart_range_i[2]), round(Int64, dst_quart_range_j[2]):round(Int64, dst_quart_range_j[4])]);
    cent_sum += sum(dst_image[round(Int64, dst_quart_range_i[4]), round(Int64, dst_quart_range_j[2]):round(Int64, dst_quart_range_j[4])]);
    if cent_sum == 0 return nothing end

#   if sum(dst_image[dst_range[1], round(Int64,linspace(dst_range[2][1], dst_range[2][end], 5)[2])]) == 0 return nothing end
#   if sum(dst_image[dst_range[1], round(Int64,linspace(dst_range[2][1], dst_range[2][end], 5)[4])]) == 0 return nothing end
#   if sum(dst_image[round(Int64,linspace(dst_range[1][1], dst_range[1][end], 5)[2]), dst_range[2]]) == 0 return nothing end
#   if sum(dst_image[round(Int64,linspace(dst_range[1][1], dst_range[1][end], 5)[4]), dst_range[2]]) == 0 return nothing end

    correspondence_properties = DataFrame();
    correspondence_properties[:ranges_src_pt_loc] = [src_pt_loc];
    correspondence_properties[:ranges_src_range] = src_range;
    correspondence_properties[:ranges_dst_pt_loc] = [dst_pt_loc];
    correspondence_properties[:ranges_dst_range] = dst_range;
    correspondence_properties[:ranges_dst_range_full] = dst_range_full;
    correspondence_properties[:ranges_scale] = scale;

#=
    src_range = ceil(Int64, scale * first(src_range[1])) : ceil(Int64, scale * last(src_range[1])), ceil(Int64, scale * first(src_range[2])) : ceil(Int64, scale * last(src_range[2]))
    dst_range = ceil(Int64, scale * first(dst_range[1])) : ceil(Int64, scale * last(dst_range[1])), ceil(Int64, scale * first(dst_range[2])) : ceil(Int64, scale * last(dst_range[2]))
    dst_range_full = ceil(Int64, scale * first(dst_range_full[1])) : ceil(Int64, scale * last(dst_range_full[1])), ceil(Int64, scale * first(dst_range_full[2])) : ceil(Int64, scale * last(dst_range_full[2]))
    src_pt_loc = ceil(Int64, scale * src_pt_loc);
    dst_pt_loc = ceil(Int64, scale * dst_pt_loc);
    dst_pt_loc_full = ceil(Int64, scale * dst_pt_loc_full);

    # padding
    if dst_range != dst_range_full
        indices_within_range = findin(dst_range_full[1], dst_range[1]), findin(dst_range_full[2], dst_range[2])
        intersect_img = dst_image[dst_range...];
        avg = mean(intersect_img);
        if isnan(avg) return nothing; end
        avg = round(eltype(dst_image), avg);
        padded_img = fill(avg, length(dst_range_full[1]), length(dst_range_full[2]));
        padded_img[indices_within_range...] = intersect_img;
        xc = normxcorr2_preallocated(src_image[src_range[1], src_range[2]], padded_img);
    else
    xc = normxcorr2_preallocated(src_image[src_range[1], src_range[2]], dst_image[dst_range[1], dst_range[2]]);
    end
    =#
    #tic()
    src_patch, dst_patch = prepare_patches(src_image, dst_image, src_range, dst_range, dst_range_full, bandpass_sigmas, meanpad = meanpad, meanpad_val = meanpad_val)
    inputs_have_zeros = (0 in src_patch) | (0 in dst_patch)

    #if (pp == nothing) return nothing end;
    #   prepare_patches(src_image, dst_image, src_range, dst_range, dst_range_full, scale, highpass_sigma)
    xc::Array{Float64,2} = normxcorr2_preallocated(src_patch, dst_patch; shape = full ? "full" : "valid");

    r_max = maximum(xc)
    if isnan(r_max)
        return nothing
    end;

    function compute_dv(xc, r_val)
        #   if r_max > 1.0 println("rounding error") end
        ind = findfirst(r_max .== xc)
        i_max, j_max = ind2sub(xc, ind)
        if i_max == 0
            i_max = size(xc, 1)
        end

        i_max_int = i_max
        j_max_int = j_max

        if 2 < i_max < size(xc, 1) - 1 && 2 < j_max < size(xc, 2) - 1
            xc_w = sum(xc[i_max-2:i_max+2, j_max-2:j_max+2])
            xc_i = sum(xc[i_max+2, j_max-2:j_max+2]) * 2 + sum(xc[i_max+1, j_max-2:j_max+2]) - sum(xc[i_max-1, j_max-2:j_max+2]) - sum(xc[i_max-2, j_max-2:j_max+2]) * 2
            xc_j = sum(xc[i_max-1:i_max+1, j_max+1]) - sum(xc[i_max-1:i_max+1, j_max-1])
            i_max += xc_i / xc_w
            j_max += xc_j / xc_w
            if isnan(i_max) || isnan(j_max)
              println(xc_i)
              println(xc_j)
              println(xc_w)
              return nothing
            end
        end

        @fastmath @inbounds begin
        if scale != 1.0
            #length of the dst_range_full is always odd, so only need to care about the oddity / evenness of the source to decide the size of the xc in full
            if full
              xc_i_len = length(dst_range_full[1]) + length(src_range[1]) - 1
              xc_j_len = length(dst_range_full[2]) + length(src_range[2]) - 1
            else
                if isodd(length(src_range[1]))
                  xc_i_len = length(dst_range_full[1]) - length(src_range[1]) + 1
                else
                  xc_i_len = length(dst_range_full[1]) - length(src_range[1])
                end
                if isodd(length(src_range[2]))
                  xc_j_len = length(dst_range_full[2]) - length(src_range[2]) + 1
                else
                  xc_j_len = length(dst_range_full[2]) - length(src_range[2])
                end
            end
            xc_i_locs = linspace(1, xc_i_len, size(xc, 1))
            xc_j_locs = linspace(1, xc_j_len, size(xc, 2))
            i_max = (i_max - 1) * step(xc_i_locs) + 1
            j_max = (j_max - 1) * step(xc_j_locs) + 1
        end
        if full
            di = Float64(i_max + src_pt_loc[1] - dst_pt_loc_full[1] - length(src_range[1]))
            dj = Float64(j_max + src_pt_loc[2] - dst_pt_loc_full[2] - length(src_range[2]))
        else
            di = Float64(i_max - 1 + src_pt_loc[1] - dst_pt_loc_full[1])
            dj = Float64(j_max - 1 + src_pt_loc[2] - dst_pt_loc_full[2])
        end
        end
        return di, dj, i_max_int, j_max_int
    end

    di, dj, i_max, j_max = compute_dv(xc, r_max)

    function recompute_r_without_zeros(src_patch, dst_patch, di, dj)
        dst_bbox = BoundingBox(1, 1, size(dst_patch)...)
        src_offset = dst_pt_loc_full[1] - src_pt_loc[1] + di,
                        dst_pt_loc_full[2] - src_pt_loc[2] + dj
        src_bbox = BoundingBox(src_offset..., size(src_patch)...)
        dst_slice = bb_to_slice(dst_bbox - src_bbox)

        src_bbox = BoundingBox(1, 1, size(src_patch)...)
        dst_offset = src_pt_loc[1] - dst_pt_loc_full[1] - di,
                        src_pt_loc[2] - dst_pt_loc_full[2] - dj
        dst_bbox = BoundingBox(dst_offset..., size(dst_patch)...)
        src_slice = bb_to_slice(dst_bbox - src_bbox)
        src_sub = src_patch[src_slice...]
        dst_sub = dst_patch[dst_slice...]
        mask = (src_sub .!= 0) & (dst_sub .!= 0)
        return cor(src_sub[mask], dst_sub[mask])
    end

    if inputs_have_zeros
        r_max = recompute_r_without_zeros(src_patch, dst_patch, di, dj)
    end

    correspondence_properties[:patches_src_normalized_dyn_range] = (maximum(view(src_image, src_range...)) - minimum(view(src_image, src_range...))) / typemax(eltype(src_image));
    correspondence_properties[:patches_src_kurtosis] = kurtosis(view(src_image, src_range...));
    correspondence_properties[:patches_dst_kurtosis] = kurtosis(view(dst_image, dst_range...));
    correspondence_properties[:xcorr_r_max] = r_max;

    function compute_r_diff(xc_orig, rad, r_max_original, i_max, j_max)
        xc = copy(xc_orig)
        range_i = intersect(1:size(xc, 1), (-rad:rad) + i_max)
        range_j = intersect(1:size(xc, 2), (-rad:rad) + j_max)
        @inbounds xc[range_i, range_j] = -Inf
        r_max_new = maximum(xc)
        if inputs_have_zeros
            di, dj, i_max, j_max = compute_dv(xc_orig, r_max_new)
            r_max_new = recompute_r_without_zeros(src_patch, dst_patch, di, dj)
        end
        return r_max_original - r_max_new
    end

    for rad in [5, 10, 15]
        correspondence_properties[Symbol(string("xcorr_delta_", rad))] = compute_r_diff(xc, rad, r_max, i_max, j_max)
    end
    for beta in [0.5, 0.75, 0.95]
        correspondence_properties[Symbol(string("xcorr_sigma_", beta))] = sigma(xc, beta) / scale;
    end
    correspondence_properties[:vects_dv] = [[di, dj]];
    correspondence_properties[:vects_norm] = norm([di, dj]);
    #correspondence_properties[:posts] = Dict{Any, Any}();

    return vcat(pt + rel_offset + [di, dj], correspondence_properties);
end

function Base.filter!(match::Match, priority, function_name, compare, threshold, vars...)
    # attributes = get_correspondence_properties(match, property_name)
    attributes = eval(function_name)(match, vars...)
    compare = eval(compare)
    filter_col = fill(false, count_correspondences(match))
    @inbounds for i in 1:length(attributes)
      filter_col[i] = compare(attributes[i], threshold)
    end
    match.filters[Symbol(tuple(priority, function_name, compare, threshold, vars...))] = filter_col;
    return sum(filter_col)
    #=
    if attributes == nothing return 0; end
    inds_to_filter = find(i -> compare(i, threshold), attributes);
    type_name = function_name
    if length(vars) > 0
        type_name = vars[1]
    end
    push!(match.filters, Dict{Any, Any}(
                :author => author(),
                :type     => type_name,
                :threshold => threshold,
                :rejected  => inds_to_filter,
                :function => function_name
                  ));
    #println("$(length(inds_to_filter)) / $(count_correspondences(match)) rejected.");
    return length(inds_to_filter);
    =#
end

function Base.filter!(match::Match, filter::Tuple)
    return filter!(match, filter...)
end

function get_residual_norms_post(match, ms)
    src_pts_after, dst_pts_after, filtered = get_globalized_correspondences_post(ms, findfirst(match_in_ms -> match_in_ms.src_index == match.src_index && match_in_ms.dst_index == match.dst_index, ms.matches));
    norms = zeros(eltype(dst_pts_after), size(dst_pts_after, 2))
    @fastmath @inbounds begin
      @simd for i in 1:size(dst_pts_after, 2)
      d1 = dst_pts_after[1,i] - src_pts_after[1,i]
      d2 = dst_pts_after[2,i] - src_pts_after[2,i]
      norms[i] = sqrt(d1^2+d2^2)
    end
        end
    return norms
end

function check(match::Match, function_name, compare, threshold, vars...)
     return eval(compare)(eval(function_name)(match, vars...), threshold)
end

function check!(match::Match, crits)
    unflag!(match);
    for crit in crits
        if check(match, crit...)
            flag!(match, crit);
        end
    end
    return is_flagged(match);
end

### ADD MANUAL FILTER
# function filter_manual!(match::Match, inds_to_filter; filtertype="manual")
#   push!(match.filters, Dict{Symbol, Any}(
#               :author   => author(),
#               :type     => filtertype,
#               :rejected  => inds_to_filter
#                 ));
#   return;
# end

function clear_filters!(match::Match; filtertype=nothing)
    # match.filters = match.filters[setdiff(1:length(match.filters), find(filter -> filter==filtertype, MeshSet(match.filters)))]
    if filtertype == nothing
        delete!(match.filters, 1:size(match.filters,2))
    end
end

function undo_filter!(match::Match)
    if length(match.filters) > 0
        pop!(match.filters);
    end
end

"""
Create matches between two meshes

Args:
    * src_mesh (source image)
    * dst_mesh (destination image)

Output:
    * List of Match objects for each pair of src & dst mask components

Description:
    * Load mesh images & associated masks (indexed image)
    * Calculate the number of mask components for both src & dst
    * Create Match object for each pair of mask components
"""
function get_matches{T}(src_mesh::Mesh{T}, dst_mesh::Mesh{T})
    src_index = get_index(src_mesh);
    dst_index = get_index(dst_mesh);
    src_image = get_image(src_index, :match_image, mip=get_mip(:match_image));
    dst_image = get_image(dst_index, :match_image, mip=get_mip(:match_image));
    if use_roi_mask()
        src_roi = get_image(src_index, :roi_mask, mip=get_mip(:match_image), input_mip=get_mip(:roi_mask));
        dst_roi = get_image(dst_index, :roi_mask, mip=get_mip(:match_image), input_mip=get_mip(:roi_mask));
        roi_value = get_mask_value(:roi_mask)
        unsafe_mask_image!(src_image, src_roi, roi_value, src_image, keep_id=true)
        unsafe_mask_image!(dst_image, dst_roi, roi_value, dst_image, keep_id=true)
    end
    matches = Array{Match,1}()
    if use_defect_split()
      src_image_sub = deepcopy(src_image)
      dst_image_sub = deepcopy(dst_image)
      println("Getting masks for $(src_index) & $(dst_index):")
      src_mask = get_image(src_index, :defect_split, mip=get_mip(:match_image), input_mip=get_mip(:defect_split));
      dst_mask = get_image(dst_index, :defect_split, mip=get_mip(:match_image), input_mip=get_mip(:defect_split));
      println("Compiling mask components")
      src_subsections = Array{IMG_ELTYPE, 1}(unique(src_mask))
      dst_subsections = Array{IMG_ELTYPE,1}(unique(dst_mask))
      defect_value = get_mask_value(:defect_split)
      src_subsections = filter!(x -> x != defect_value, src_subsections)
      dst_subsections = filter!(x -> x != defect_value, dst_subsections)
      src_mesh.properties[:subsections] = src_subsections / SPLIT_MESH_BASIS
      dst_mesh.properties[:subsections] = dst_subsections / SPLIT_MESH_BASIS
      println("src_subsections: $src_subsections")
      println("dst_subsections: $dst_subsections")
      for ss in src_subsections
        for ds in dst_subsections
          src_id = src_index + ss/SPLIT_MESH_BASIS
          dst_id = dst_index + ds/SPLIT_MESH_BASIS
          unsafe_copy_image!(src_image, src_image_sub)
          unsafe_mask_image!(src_image, src_mask, ss, src_image_sub, keep_id=true)
          unsafe_copy_image!(dst_image, dst_image_sub)
          unsafe_mask_image!(dst_image, dst_mask, ds, dst_image_sub, keep_id=true)
          push!(matches, Match(src_mesh, dst_mesh,
                                          src_id, dst_id,
                                          src_image_sub,
                                          dst_image_sub))
        end
      end
      src_image_sub = 0
      src_image_sub = 0
      dst_image_sub = 0
      dst_image_sub = 0
    else
      push!(matches, Match(src_mesh, dst_mesh, src_index, dst_index,
                                                  src_image, dst_image))
    end
    gc();
    gc();
    return matches
end

function Match{T}(src_mesh::Mesh{T}, dst_mesh::Mesh{T},
                src_index=get_index(src_mesh), dst_index=get_index(dst_mesh),
                src_image=get_image(src_mesh), dst_image=get_image(dst_mesh))
    println("Matching $(src_index) -> $(dst_index):")
    image_size = get_image_size(src_mesh);
    image_offset = get_offset(src_mesh);

    print("computing ranges:")
    @time ranges = map(get_ranges, columnviews(src_mesh.src_nodes), repeated(src_index), repeated(image_offset), repeated(image_size), repeated(dst_index), repeated(image_offset), repeated(image_size), repeated(PARAMS[:match][:block_r]), repeated(PARAMS[:match][:search_r]));
    ranged_inds = find(i -> i != nothing, ranges);
    ranges = ranges[ranged_inds];
    print("    ")

    println("$(length(ranged_inds)) / $(size(src_mesh.src_nodes, 2)) nodes to check.")

    if length(ranged_inds) != 0
        ranges = Array{typeof(ranges[1]), 1}(ranges);
    end

    print("computing matches:")
    print("    ")
    use_full_conv = false
    meanpad = true
    @time dst_allpoints = pmap(get_match, columnviews(src_mesh.src_nodes[:,ranged_inds]),
                                    ranges,
                                    repeated(src_image),
                                    repeated(dst_image),
                                    repeated(get_scale(:match_image)),
                                    repeated(PARAMS[:match][:bandpass_sigmas]),
                                    repeated(use_full_conv),
                                    repeated(meanpad),
                                    repeated(get_mask_value(:match_image)))

    matched_inds = find(i -> i != nothing, dst_allpoints);

    #=for ap in dst_allpoints
      if typeof(ap) == RemoteException
        println(ap)
      end
    end=#

    src_points = copy(src_mesh.src_nodes[:,ranged_inds[matched_inds]]);
    dst_points = similar(src_points)
    for j in 1:size(dst_points, 2)
      @inbounds dst_points[1,j] = dst_allpoints[matched_inds[j]][1]
      @inbounds dst_points[2,j] = dst_allpoints[matched_inds[j]][2]
    end
    correspondence_properties = vcat([dst_allpoints[ind][3] for ind in matched_inds]...)

    filters = DataFrame();
    properties = Dict{Symbol, Any}(
        :params => PARAMS,
        :review => Dict{Symbol, Any}(
                :flagged => false,
                :flags => Dict{Symbol, Any}(),
                :author => null_author()
                )
            );

#   @everywhere init_Match();
    @everywhere gc();

    return Match{T}(src_index, dst_index, src_points, dst_points, correspondence_properties, filters, properties);
end


text:
#include "Tiano.h"
#include EFI_PROTOCOL_DEFINITION (FirmwareVolumeBlock)

EFI_GUID  gFramerworkEfiFirmwareVolumeBlockProtocolGuid = FRAMEWORK_EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL_GUID;
EFI_GUID  gEfiFirmwareVolumeBlockProtocolGuid = EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL_GUID;
EFI_GUID  gEfiFirmwareVolumeBlock2ProtocolGuid = EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL_GUID;

EFI_GUID_STRING(&gFramerworkEfiFirmwareVolumeBlockProtocolGuid, "FirmwareVolumeBlock Protocol", "Framework Firmware Volume Block protocol");
EFI_GUID_STRING(&gEfiFirmwareVolumeBlockProtocolGuid, "FirmwareVolumeBlock Protocol", "Firmware Volume Block protocol");
EFI_GUID_STRING(&gEfiFirmwareVolumeBlock2ProtocolGuid, "FirmwareVolumeBlock2 Protocol", "Firmware Volume Block2 protocol");

redpajama_set_name: RedPajamaGithub


text:
title: Deconstructing
date: 2015-06-25
slug: /2015/06/25/deconstructing/
tags: DevOps, apache kafka, aws, docker, kinesis, mesos

[][1]If you haven’t heard about [Apache Kafka][2], or his little brother Amazon Kinesis, go and read about [why they are so great][3].

I was chatting with a friend last night and he told me “I get containers now. I needed some give it some thought, but I get them now”. If I had to describe him with one word I would use “smart” without any doubt… still he had to think about why containers are so great.

We carried on talking and after two more beers and few pork ribs I managed to make him understand why we are about to change we build applications. It’s not only because of containers (or systems like Mesos or Kubernetes), but because with containers, we have seen the light of deconstructing the monoliths into microservices.

But, there’s another key element on this Game of Thrones: The Log, systems like Apache kafka are going to help to change completely the landscape of what we build, and ship and run. Like with Microservices, the Log overlord brings a blessing in disguise: it’s not what it does, it’s what allows others to do.

It is not about its responsibility, it’s about delegating that responsibility in who really has it. Let’s look at what happens today. We have a system, that system gets some data, compute that data and stores that data in a database. Easy!

Then someone comes along and asks to get that same data and put it somewhere else, so our system now gets some data, compute that data and stores that data in two different places.

As we can see, this does not scale very well, so people get smart, and start doing things like database triggers and a whole bunch of things that are totally correct in itself, but over time, it creates a big mess of “dirty integrations”. These are the things that will break when we want to move our system. These are the future nightmares of our microservices journey.

Then, we have The LOG… a dumb system that guess what: it does not care about what do you do with that data. The Log Overlord will keep your data for a while, and it’s up to you, the consumers, to use it.

A bit like how the TV has been broadcasting for a few years… with a twist, because, as we do now, this TV system allows you to consume the programs when you want it.

Ok, so, basically, we have a place where we put all that data (for a while) and we have a bunch of people consuming that data? So what?

Well, not much, but as with microservices, what the LOG overlord provides is the ability of your consumers to consume the way they want (once per hour, once per day… in real time), and even more, the people who create the TV shows do not care about the broadcasting anymore.

Think about it. Microservices decouple your business logic. With microservices you can write very business specific services without having to worry about all the other business rules, use cases and (oh yes) those terrible exceptions.

Apache Kafka or Amazon Kinesis decouple your data. How you read that data is up to the readers and the writers have nothing to do with that. It’s like a writer writing a book, and people reading that book: when they want, how they want… as opposed to the writer writing and reading aloud to certain audience.

I’m not sure if the creators of Kafka chose that name because it’s a system that allows writers and readers to focus and enjoy what they want to do.

As I said, we are living very exciting times with a lot of change. Let me finish with a song… or my own version of a song by [Elvis Presley][4]:

  Treat me like a fool,
 Treat me mean and cruel,
 But LOG me.

  Wring my faithful heart,
 Tear it all apart,
 But LOG me.

 [1]: http://ivan.pedrazas.me/wp-content/uploads/2015/06/kafka_logo.png
 [2]: http://kafka.apache.org/
 [3]: http://www.oreilly.com/pub/e/3098
 [4]: https://www.youtube.com/watch?v=f8PMqLHF1jU


text:
package com.lbadvisor.AgeGroup.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

import com.lbadvisor.AgeGroup.R;
import com.lbadvisor.AgeGroup.utils.UIUtils;

/**
 * 自定义带边框的textview
 * Created by likun on 15/10/20.
 */
public class BorderTextView extends TextView {
    public BorderTextView(Context context) {
        super(context);
    }
    public BorderTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    private int sroke_width = 1;
    @Override
    protected void onDraw(Canvas canvas) {
        Paint paint = new Paint();
        paint.setStrokeWidth(5);
        //  将边框设为绿色
        paint.setColor(UIUtils.getResource().getColor(R.color.GREEN));
        //  画TextView的4个边
        canvas.drawLine(0, 0, this.getWidth() - sroke_width, 0, paint);
        canvas.drawLine(0, 0, 0, this.getHeight() - sroke_width, paint);
        canvas.drawLine(this.getWidth() - sroke_width, 0, this.getWidth() - sroke_width, this.getHeight() - sroke_width, paint);
        canvas.drawLine(0, this.getHeight() - sroke_width, this.getWidth() - sroke_width, this.getHeight() - sroke_width, paint);
        super.onDraw(canvas);
    }
}


text:
using System;
using System.Reflection.Emit;
using CodeBuilder.Context;

namespace CodeBuilder.Helpers
{
    public static class EmitHelper
    {
        private static readonly Type[] _bigIntTypes = new[] { typeof(uint), typeof(long), typeof(ulong) };
        public static void ConvertToNativeInt(IBuildContext ctx, Type fromType)
        {
            ctx.Generator.Emit(IsBiggerThanInt(fromType) ? OpCodes.Conv_Ovf_I : OpCodes.Conv_I);
        }

        public static bool IsBiggerThanInt(Type type)
        {
            return CollectionHelper.Contains(_bigIntTypes, type);
        }
    }
}


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit5c6425025f9d278d70661629cc19eec4::getLoader();


text:
<?php

/**
 * Products grid for urlrewrites
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Adminhtml_Block_Urlrewrite_Product_Grid extends Mage_Adminhtml_Block_Catalog_Product_Grid
{
    /**
     * Disable massaction
     *
     * @return Mage_Adminhtml_Block_Urlrewrite_Product_Grid
     */
    protected function _prepareMassaction()
    {
        return $this;
    }

    /**
     * Prepare columns layout
     *
     * @return Mage_Adminhtml_Block_Urlrewrite_Product_Grid
     */
    protected function _prepareColumns()
    {
        $this->addColumn('entity_id',
            array(
                'header'=> Mage::helper('adminhtml')->__('ID'),
                'width' => 50,
                'index' => 'entity_id',
        ));

        $this->addColumn('name',
            array(
                'header'=> Mage::helper('adminhtml')->__('Name'),
                'index' => 'name',
        ));

        $this->addColumn('sku',
            array(
                'header'=> Mage::helper('adminhtml')->__('SKU'),
                'width' => 80,
                'index' => 'sku',
        ));
        $this->addColumn('status',
            array(
                'header'=> Mage::helper('adminhtml')->__('Status'),
                'width' => 50,
                'index' => 'status',
                'type'  => 'options',
                'options' => Mage::getSingleton('catalog/product_status')->getOptionArray(),
        ));
        return $this;
    }

    /**
     * Get url for dispatching grid ajax requests
     *
     * @return string
     */
    public function getGridUrl()
    {
        return $this->getUrl('*/*/productGrid', array('_current' => true));
    }

    /**
     * Get row url
     *
     * @return string
     */
    public function getRowUrl($row)
    {
        return $this->getUrl('*/*/edit', array('product' => $row->getId())) . 'category';
    }
}


text:
require 'rails_helper'

RSpec.describe User, type: :model do # rubocop:disable Metrics/BlockLength
  let!(:user) { User.create(email: Rails.application.secrets.personal_email, password: 'password', name: 'User') }

  describe 'associations' do
    it { should have_many(:identities) }
  end

  describe 'validations' do
    it { should allow_value('change@me-4199297424-twitter.com').for(:email) }
    user = User.create(email: 'change@me-4199297425-twitter.com', password: 'password')
    it "shouldn't allow User::TEMP_EMAIL_REGEX formatted emails on update" do
      expect { user.update!(name: 'name') }.to raise_error(ActiveRecord::RecordInvalid)
    end
    it 'should allow non User::TEMP_EMAIL_REGEX formatted emails on update' do
      expect { user.update!(email: 'not.temp.email.regex@example.com', name: 'name') }.not_to raise_error
    end
  end

  describe 'callbacks' do
    describe 'set_gravatar_url' do
      user = User.create(email: 'change@me-4199297426-twitter.com', password: 'password')
      it 'sets the gravatar_url for newly created users' do
        expect(user.gravatar_url).not_to be_nil
      end
      it 'updates the gravatar_url for updated created users' do
        # The gravatar_url is updated before the new email is confirmed.
        # I may change that later.
        original_url = user.gravatar_url
        user.update(email: 'new.email@example.com')
        expect(user.gravatar_url).not_to eq(original_url)
      end
    end
  end

  describe 'find_or_create_by_oauth' do # rubocop:disable Metrics/BlockLength
    auth_params = { provider: 'provider', uid: 'uid' }
    auth_struct = OpenStruct.new(auth_params.merge(info:  OpenStruct.new,
                                                   extra: OpenStruct.new(raw_info: OpenStruct.new)))

    verified_auth_struct = OpenStruct.new(auth_params
                                            .merge(info:  OpenStruct.new(email:    'email123@example.com',
                                                                         verified: 'true'),
                                                   extra: OpenStruct.new(raw_info: OpenStruct.new)))

    context 'User exists' do # rubocop:disable Metrics/BlockLength
      context 'Identity exists' do # rubocop:disable Metrics/BlockLength
        context 'User still has a temp email' do
          it 'Returns the existing user for the existing identity' do
            user = User.create!(email: 'change@me-uid-provider.com', password: 'password')
            Identity.create!(auth_params.merge(user: user))
            expect(User.find_or_create_by_oauth(auth_struct)).to eq(user)
          end
        end
        context "User doesn't have a temp email" do
          it 'Returns the existing user for the existing identity' do
            user = User.create!(email: 'email123@example.com', password: 'password')
            Identity.create!(auth_params.merge(user: user))
            expect(User.find_or_create_by_oauth(auth_struct)).to eq(user)
          end
        end
      end

      context "Identity doesn't exist" do # rubocop:disable Metrics/BlockLength
        context 'User has the temp email for the identity' do
          it 'Returns the existing user and creates an identity for it' do
            user = User.create!(email: 'change@me-uid-provider.com', password: 'password')
            expect(User.find_or_create_by_oauth(auth_struct)).to eq(user)
            expect(Identity.count).to eq(1)
            expect(Identity.first).to eq(user.identities.first)
          end
        end
      end
    end

    context "User doesn't exist" do
      context 'auth email is not verified' do
        it 'creates an identity and a new user with a temp email' do
          new_user = User.find_or_create_by_oauth(auth_struct)
          expect(new_user.class).to eq(User)
          expect(new_user.persisted?).to be_truthy
          expect(new_user.email_verified?).to be_falsy
          expect(Identity.count).to eq(1)
          expect(Identity.first).to eq(new_user.identities.first)
        end
      end
      context 'auth email is verified' do
        it 'creates an identity and a new user with a the verified email' do
          new_user = User.find_or_create_by_oauth(verified_auth_struct)
          expect(new_user.class).to eq(User)
          expect(new_user.persisted?).to be_truthy
          expect(new_user.email_verified?).to be_truthy
          expect(Identity.count).to eq(1)
          expect(Identity.first).to eq(new_user.identities.first)
        end
      end
    end
  end

  describe 'email_verified?' do
    it 'returns false when the emails is nil' do
      user = User.new
      expect(user.email_verified?).to be_falsy
    end
    it 'returns false when the emails matches USER::TEMP_EMAIL_REGEX' do
      user = User.new(email: 'change@me-4199297423-twitter.com')
      expect(user.email_verified?).to be_falsy
    end
    it "returns true when the email doesn't match User::TEMP_EMAIL_REGEX" do
      user = User.new(email: 'email123@example.com')
      expect(user.email_verified?).to be_truthy
    end
  end

  describe 'display_name' do
    it 'returns User::UNKNOWN_DISPLAY_NAME name and user name are nil or empty' do
      user = User.new(email: 'email123@example.com')
      expect(user.display_name).to eq(User::UNKNOWN_DISPLAY_NAME)
      user.name = ''
      expect(user.display_name).to eq(User::UNKNOWN_DISPLAY_NAME)
      user.username = ''
      expect(user.display_name).to eq(User::UNKNOWN_DISPLAY_NAME)
    end
    it "returns name when it isn't nil or empty" do
      user = User.new(email: 'email123@example.com', name: 'Name')
      expect(user.display_name).to eq('Name')
    end
    it "returns username when it isn't nil or empty" do
      user = User.new(email: 'email123@example.com', username: 'UserName')
      expect(user.display_name).to eq('UserName')
    end
    it "returns name when both username and name aren't nil or empty" do
      user = User.new(email: 'email123@example.com', username: 'UserName', name: 'Name')
      expect(user.display_name).to eq('Name')
    end
  end

  describe 'owns' do
    context "'as' option is passed" do
      it 'returns true when resource.send(options[:as]) returns the user, and false otherwise' do
        user = User.new
        resource = OpenStruct.new(owner: user)
        expect(user.owns(resource, as: :owner)).to be_truthy
        expect(user.owns(resource, as: :user)).to be_falsy
      end
    end
    context "'as' option is not passed" do
      it 'returns true when resource.user returns the user, and false otherwise' do
        user = User.new
        resource = OpenStruct.new(user: user)
        expect(user.owns(resource)).to be_truthy
        expect(user.owns(OpenStruct.new)).to be_falsy
      end
    end
  end
end


text:
<?php
return array(
    'view_manager' => array(
        'strategies' => array(
            'ViewJsonStrategy',
        ),
    ),
    'service_manager' => array(
        'invokables' => array(
            'ldc-zfc-user-oauth2-authentication-adapter-db' => 'LdcZfcUserOAuth2\Authentication\Adapter\Db',
        ),
        'factories' => array(
            'ldc-zfc-user-oauth2-storage-pdo' => 'LdcZfcUserOAuth2\Storage\ZfcUserPdoFactory',
            'ldc-zfc-user-oauth2-storage-bridge' => 'LdcZfcUserOAuth2\Storage\ZfcUserStorageBridgeFactory',
        ),
    ),
);


text:
import { Express } from "express";
import authRouter from "./auth";
import userRouter from "./user";
import uploadRouter from "./upload";
import companyRouter from "./company";

function registerRouter(app: Express) {
  app.use("/api", [
    authRouter,
    userRouter,
    uploadRouter,
    companyRouter,
  ]);
}

export { registerRouter };


text:
<dom-module id="team-styles">
  <template>
    <style>
      .container{
        @apply(--layout-horizontal);
        @apply(--layout-around-justified);
        @apply(--layout-wrap);
        margin-left: auto;
        margin-right: auto;
      }

      .big {
        font-size: 22px;
        padding: 8px 16px 16px;
        color: var(--google-grey-500);
      }

      .team team-member ::content .colored {
        background-color: var(--paper-blue-grey-700);
      }

      .alumni team-member ::content .colored {
        background-color: var(--paper-red-700);
      }
    </style>
  </template>
</dom-module>


text:
veboMaven
=========

Sistema desenvolvido em 2007 utilizando Java (Swing), Hibernate e Derby para a fabricação e vendas de perfumes.


text:
/* this comes from the `reuse' library. copy any changes back to the source */

#ifndef _ODE_ERROR_H_
#define _ODE_ERROR_H_

#include "config.h"

#ifdef __cplusplus
extern "C" {
#endif

/* all user defined error functions have this type. error and debug functions
 * should not return.
 */
typedef void dMessageFunction (int errnum, const char *msg, va_list ap);

/* set a new error, debug or warning handler. if fn is 0, the default handlers
 * are used.
 */
void dSetErrorHandler (dMessageFunction *fn);
void dSetDebugHandler (dMessageFunction *fn);
void dSetMessageHandler (dMessageFunction *fn);

/* return the current error, debug or warning handler. if the return value is
 * 0, the default handlers are in place.
 */
dMessageFunction *dGetErrorHandler();
dMessageFunction *dGetDebugHandler();
dMessageFunction *dGetMessageHandler();

/* generate a fatal error, debug trap or a message. */
void _cdecl dError (int num, const char *msg, ...);
void _cdecl dDebug (int num, const char *msg, ...);
void _cdecl dMessage (int num, const char *msg, ...);
//#define dError(a,b)
//#define dDebug(a,b)
//#define dMessage(a,b)

#ifdef __cplusplus
}
#endif

#endif


text:
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MigAz.Azure.Arm
{
    public class StorageAccountKey
    {
        private JToken _Key;
        private List<Subnet> _Subnets = new List<Subnet>();

        private StorageAccountKey() { }

        public StorageAccountKey(JToken key)
        {
            _Key = key;
        }

        public string Name
        {
            get { return (string)_Key["keyName"]; }
        }

        public string Permissions
        {
            get { return (string)_Key["permissions"]; }
        }

        public string Value
        {
            get { return (string)_Key["value"]; }
        }

    }
}


text:
<?php

namespace frontend\modules\doctors\controllers;

use Yii;
use frontend\modules\doctors\models\Doctors;
use frontend\modules\doctors\models\DoctorsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Json;
use yii\db\Query;
use yii\filters\AccessControl;
use yii\web\ForbiddenHttpException;
/**
 * DoctorsController implements the CRUD actions for Doctors model.
 */
class DefaultController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['create', 'update', 'delete', 'view', 'index'],
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['moder']
                    ],
                    [
                        'allow' => false,
                        'roles' => ['?']
                    ]
                ]
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Doctors models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new DoctorsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Doctors model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $this->changeTimeFormat($model); // форматируем время начала и конца работы

        return $this->render('view', [
            'model' => $model,
        ]);
    }

    /**
     * Creates a new Doctors model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Doctors();

        if (Yii::$app->user->can('moder') && $model->load(Yii::$app->request->post()) && !$this->actionIsDouble($model->name)) {
            if (count(explode(':', $model->start_time)) != 2)
            {
                throw new \yii\base\ErrorException('Неправильный формат времени приёма!');
            }
            $this->changeTimeFormat($model);
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Doctors model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if (Yii::$app->user->can('moder') && $model->load(Yii::$app->request->post())) {
            if (count(explode(':', $model->start_time)) != 2)
            {
                throw new \yii\base\ErrorException('Неправильный формат времени приёма! ');
            }
            $this->changeTimeFormat($model);
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Doctors model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        if (Yii::$app->user->can('moder'))
        {
            $this->findModel($id)->delete();
            return $this->redirect(['index']);
        }
        else
        {
            throw new ForbiddenHttpException();
        }

    }

    /**
     * Finds the Doctors model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return \frontend\modules\doctors\models\Doctors the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Doctors::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * Получение данных врача по его id
     * @param integer $id уникальный идентификатор в базе данных
     * @return mixed набор полей записи о враче
     */
    public static function actionGetData($id)
    {
        $doctor = Doctors::findOne($id);

        return Json::encode($doctor);
    }

    /**
     * Изменение формата времени у экземпляра класса Doctors
     * старый формат чч:мм
     * выходной формат - количество минут от полночи: часы * 60 + минуты
     * @param \frontend\modules\doctors\models\Doctors $model экземпляр класса Doctors
     */
    private function changeTimeFormat(&$model)
    {
        $start_time = explode(':', $model->start_time);
        if (count($start_time) == 2)
        {
            $model->start_time = Doctors::timeToInt($model->start_time);

            $model->end_time = Doctors::timeToInt($model->end_time);
        }
        else
        {
            $model->start_time = Doctors::timeToString($model->start_time);
            $model->end_time = Doctors::timeToString($model->end_time);
        }
    }

    /**
     * Преобразование числа минут во время в формате чч:мм
     * @param string $string
     * @return string время в формате чч:мм
     */
//    private function intToTime($string)
//    {
//        $minute = $string%60;
//        $hour = ($string - $minute)/60;
//        if ($minute < 10)
//        {
//            $minute = '0'.$minute;
//        }
//        if ($hour < 10)
//        {
//            $hour = '0'.$hour;
//        }
//        return $hour.':'.$minute;
//    }

    /**
     * Преобразование времени в формате чч:мм в число минут
     * @param string $string
     * @return int количество минут
     */
//    private function timeToInt($string)
//    {
//        $string = explode(':', $string);
//        $hour = $string[0];
//        $minute = $string[1];
//        return $hour*60+$minute;
//    }

    /**
     * Проверка на наличие совпадающих записей
     * @param type $name ФИО доктора
     * @return boolean
     */
    public function actionIsDouble($name)
    {
        $result = false;
        $model = Doctors::findOne(['name' => $name] );
        if($model)
        {
            $result = true;
        }
        return $result;
    }
}


text:
@echo off
echo this is inout description
set /p ip=输入本地IP:
set hosts="127.0.0.1"
echo %ip%
if %ip%==y (echo yes) else (echo not bad)

pause


text:
module CountriesRu
  VERSION = "0.1.0"
end


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/gkehub/v1alpha/configmanagement/configmanagement.proto

package com.google.cloud.gkehub.configmanagement.v1alpha;

public interface HierarchyControllerVersionOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.gkehub.configmanagement.v1alpha.HierarchyControllerVersion)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Version for open source HNC
   *

   *
   * string hnc = 1;
   *
   * @return The hnc.
   */
  java.lang.String getHnc();
  /**
   *
   *
   *

   * Version for open source HNC
   *

   *
   * string hnc = 1;
   *
   * @return The bytes for hnc.
   */
  com.google.protobuf.ByteString getHncBytes();

  /**
   *
   *
   *

   * Version for Hierarchy Controller extension
   *

   *
   * string extension = 2;
   *
   * @return The extension.
   */
  java.lang.String getExtension();
  /**
   *
   *
   *

   * Version for Hierarchy Controller extension
   *

   *
   * string extension = 2;
   *
   * @return The bytes for extension.
   */
  com.google.protobuf.ByteString getExtensionBytes();
}


text:
package org.netbeans.modeler.properties.nentity;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Column {

    private String name;
    private Integer width = -1;
    private boolean editable;
    private boolean hidden = false;
    private boolean autoIncrement = false;
    private String autoIncrementSufix = "";
    private Class clazz;
    private List<? extends Object> values = new LinkedList();

    public Column(String name, boolean editable, boolean hidden, Class clazz) {
        this(name, editable, clazz);
        this.hidden = hidden;
    }

    public Column(String name, boolean editable, boolean hidden, Class clazz, Integer width) {
        this(name, editable, hidden, clazz);
        this.width = width;

    }

    public Column(String name, boolean editable, Class clazz) {
        this.name = name;
        this.editable = editable;
        this.clazz = clazz;
    }

    public Column(String name, boolean editable, Class clazz, boolean autoIncrement, String autoIncrementSufix) {
        this.name = name;
        this.editable = editable;
        this.clazz = clazz;
        this.autoIncrement = autoIncrement;
        this.autoIncrementSufix = autoIncrementSufix;
    }

    public Column(String name, boolean editable, Class clazz, Integer width) {
        this(name, editable, clazz);
        this.width = width;
    }

    public Column(String name, boolean editable, Class clazz, List<? extends Object> values) {
        this.name = name;
        this.editable = editable;
        this.clazz = clazz;
        this.values = values;
    }

    public Column(String name, boolean editable, Class clazz, Object[] values) {
        this.name = name;
        this.editable = editable;
        this.clazz = clazz;
        this.values = Arrays.asList(values);
    }

    public Column(String name, boolean editable, Class clazz, Integer width, Object[] values) {
        this(name, editable, clazz, values);
        this.width = width;
    }

    public Column() {
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the editable
     */
    public boolean isEditable() {
        return editable;
    }

    /**
     * @param editable the editable to set
     */
    public void setEditable(boolean editable) {
        this.editable = editable;
    }

    /**
     * @return the clazz
     */
    public Class getClassType() {
        return clazz;
    }

    /**
     * @param clazz the clazz to set
     */
    public void setClassType(Class clazz) {
        this.clazz = clazz;
    }

    /**
     * @return the values
     */
    public List<? extends Object> getValues() {
        return values;
    }

    /**
     * @param values the values to set
     */
    public void setValues(List<? extends Object> values) {
        this.values = values;
    }

    /**
     * @return the hidden
     */
    public boolean isHidden() {
        return hidden;
    }

    /**
     * @param hidden the hidden to set
     */
    public void setHidden(boolean hidden) {
        this.hidden = hidden;
    }

    /**
     * @return the width
     */
    public Integer getWidth() {
        return width;
    }

    /**
     * @param width the width to set
     */
    public void setWidth(Integer width) {
        this.width = width;
    }

    /**
     * @return the autoIncrement
     */
    public boolean isAutoIncrement() {
        return autoIncrement;
    }

    /**
     * @param autoIncrement the autoIncrement to set
     */
    public void setAutoIncrement(boolean autoIncrement) {
        this.autoIncrement = autoIncrement;
    }

    /**
     * @return the autoIncrementSufix
     */
    public String getAutoIncrementSufix() {
        return autoIncrementSufix;
    }

    /**
     * @param autoIncrementSufix the autoIncrementSufix to set
     */
    public void setAutoIncrementSufix(String autoIncrementSufix) {
        this.autoIncrementSufix = autoIncrementSufix;
    }
}


text:
(function () {
   var fso = new ActiveXObject("Scripting.FileSystemObject");
   var searchPath = fso.GetFolder(".").Path.replace(/\\/g, "\\\\") + "\\\\searchText.txt";
   var file = fso.GetFile(searchPath);
   var stream = file.OpenAsTextStream(1,0);
   var searchString = stream.ReadAll();
   stream.Close();

   var replacementPath = fso.GetFolder(".").Path.replace(/\\/g, "\\\\") + "\\\\replaceText.txt";
   file = fso.GetFile(replacementPath);
   stream = file.OpenAsTextStream(1,0);
   var replacementString = stream.ReadAll();
   stream.Close();

   return  {

   process: function(path) {
      if (fso.FolderExists(path)) {
         return this.processDirectory(path);
      }
      else {
         return this.ProcessFile(path);
      }
   },

   processDirectory: function (path) {
     var folder = fso.GetFolder(path);
     if (folder.attributes&2) return; //don't process invisible folders
     var subfolderEnumerator = new Enumerator(folder.SubFolders);
     var filesEnumerator     = new Enumerator(folder.Files);

      for (;!filesEnumerator.atEnd();filesEnumerator.moveNext()) {
       this.processFile(filesEnumerator.item().Path);
       }

     for (;!subfolderEnumerator.atEnd();subfolderEnumerator.moveNext()) {
       this.processDirectory(subfolderEnumerator.item().Path);
       }
     },

   processFile:  function (path) {
      WScript.StdOut.WriteLine("Processing: "+path);
      var file = fso.GetFile(path);
      var stream = file.OpenAsTextStream(1,0);
      var content = stream.ReadAll();
      stream.Close();
      var newContent = content.replace(searchString, replacementString);
      if (content !== newContent) {
         stream = file.OpenAsTextStream(2,0);
         stream.Write(newContent);
         stream.Close();
         }
      }
   }
})().process(".\\..\\..\\TestCases");


text:
FROM java:8
WORKDIR /
COPY ./target/fhir-mediator-0.1.0-jar-with-dependencies.jar .
EXPOSE 8080
CMD java -jar fhir-mediator-0.1.0-jar-with-dependencies.jar


text:
package kg.apc.jmeter.jmxmon;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;

/**
 * This class store jmx connections
 * It is not a complete pool, it will not manage lease on connection
 * It only provide the same connection for the same jmx url
 *
 */
public class JMXMonConnectionPool {

	/**
	 * the logger
	 */
	private static final Logger log = LoggingManager.getLoggerForClass();

	/**
	 * Store {@link JMXMonConnection}
	 */
	private Map<String, JMXMonConnection> pool;

	/**
	 * The constructor
	 */
	public JMXMonConnectionPool() {
		super();
		pool = new HashMap<String, JMXMonConnection>();
	}

	/**
	 * Try to get a connection to the specified jmx url
	 * @param jmxUrl the jmx url
	 * @param attributes jmx connection attributes
	 * @return a jmx connection
	 */
	public MBeanServerConnection getConnection(String jmxUrl, Hashtable attributes)
	{
		return getConnection(jmxUrl, attributes, false);
	}

	/**
	 * Try to get a connection to the specified jmx url
	 * @param jmxUrl the jmx url
	 * @param attributes jmx connection attributes
	 * @param wait if true wait the current thread until the end of the connection attempt
	 * @return a jmx connection
	 */
	public MBeanServerConnection getConnection(String jmxUrl, Hashtable attributes, boolean wait)
	{
		JMXMonConnection connection = (JMXMonConnection)pool.get(jmxUrl);
		if (connection == null) {
			connection = new JMXMonConnection(jmxUrl);
			pool.put(jmxUrl, connection);
		}
		return connection.connect(attributes, wait);

	}

	/**
	 * Close all active connections by closing linked {@link JMXConnector}
	 */
	public void closeAll() {
		for (Object connection : pool.values()) {
			JMXMonConnection jmxcon = (JMXMonConnection)connection;
            if (jmxcon.connector != null) {
                try {
                	jmxcon.connector.close();
                    log.debug("jmx connector is closed");
                } catch (Exception ex) {
                    log.debug("Can't close jmx connector, but continue");
                }
            } else {
                log.debug("jmxConnector == null, don't try to close connection");
            }

            jmxcon.connector = null;
            jmxcon = null;

        }
		/* erase pool informations for this run but will be recreate for the next run */
		pool.clear();
	}

	/**
	 * This class store jmx connection data
	 * and ensure that only one connection attempt
	 * is made simultaneously
	 *
	 */
	private class JMXMonConnection {

		/**
		 * jmx url
		 */
		private String jmxUrl;

		/**
		 * jmx connector or null if not connected
		 */
		private JMXConnector connector;
		/**
		 * jmx connection or null if not connected
		 */
		private MBeanServerConnection connection;
		/**
		 * thread used to handle connection attempt
		 */
		private Thread connectionAttemptThread;
		/**
		 * semaphore : true if a connection attempt is running
		 */
		private boolean connectionAttemptFlag;

		/**Construtor
		 *
		 * @param jmxUrl jmx url
		 */
		private JMXMonConnection(String jmxUrl){
			this.jmxUrl = jmxUrl;
		}

		/**
		 * Empty URL denotes local connection
		 */
		private boolean isLocalConnection() {
			return jmxUrl.isEmpty();
		}

		/**
		 * Start a connection thread if none are running
		 * @param attributes jmx connection attributes
		 * @param wait if true wait the current thread until the end of the connection attempt
		 */
		protected synchronized void tryConnect(final Hashtable attributes, boolean wait)
		{
			if (isLocalConnection()) {
				log.debug("Using local PlatformMBeanServer connection");
				connection = ManagementFactory.getPlatformMBeanServer();
				return;
			}
			connectionAttemptFlag = true;

			connectionAttemptThread = new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						JMXServiceURL u = new JMXServiceURL(jmxUrl);
						log.debug("Create new connection url = " + jmxUrl);
			            connector = JMXConnectorFactory.connect(u, attributes);
			            connection = connector.getMBeanServerConnection();

		            } catch (MalformedURLException ex) {
		                //throw new RuntimeException(ex);
		                log.error("Malformed JMX url", ex);
		            } catch (IOException ex) {
		                log.error("IOException reading JMX", ex);
		            }
					finally {
						connectionAttemptFlag = false;
					}
				}
			});

			connectionAttemptThread.start();

			if (wait)
				try {
					connectionAttemptThread.join();
				} catch (InterruptedException e) {
					log.warn("Connection thread has been interrupted", e);
				}

		}

		/**
		 * Check if a connection already exists if true it will return the
		 * existing connection else it will attempt a new connection
		 * @param attributes jmx connection attributes
		 * @param wait if true wait the current thread until the end of the connection attempt
		 * @return a jmx connection or null
		 */
		protected MBeanServerConnection connect(Hashtable attributes, boolean wait) {

			if (connection != null){
				log.debug("Reused the same connection for url = " + (isLocalConnection()?"(local JVM)":jmxUrl));
				return connection;
			}

			if (!connectionAttemptFlag)
				tryConnect(attributes, wait);

			return connection;
		}

		/**
		 * Store a new jmx connection
		 * @param connector the jmx connector
		 * @param connection the jmx connection
		 */
		protected void setNewActiveConnection(JMXConnector connector, MBeanServerConnection connection)
		{
			this.connector = connector;
			this.connection = connection;
		}

	}

	/**
	 * Allow external class to notify the pool that the connection identified by the provided
	 * jmx url is closed/in error
	 * @param url the jmx url
	 */
	public void notifyConnectionDirty(String url) {
		JMXMonConnection connection = (JMXMonConnection)pool.get(url);

		if (connection != null){
			connection.setNewActiveConnection(null, null);
		}
	}

}


text:
require 'helper'

class Test_TaxonifiLumperClump < Test::Unit::TestCase

  def setup
    @headers = ["family", "genus", "species", "author", "year"]
    @csv_string = CSV.generate() do |csv|
      csv <<  @headers
      csv << ["Fooidae", "Foo", "bar", "Smith", "1854"]
    end

    @csv = CSV.parse(@csv_string, headers: true)
  end

  def test_new_clump_without_params_can_be_created
    assert c = Taxonifi::Lumper::Clump.new
  end

  def test_new_clump_with_default_csv_can_be_created
    assert c = Taxonifi::Lumper::Clump.new(@csv)
  end

  def test_that_csv_can_be_added_to_clump_that_has_no_csv
    c = Taxonifi::Lumper::Clump.new
    assert c.add_csv(@csv)
  end

  def test_that_clump_with_csv_will_not_add_csv
    c = Taxonifi::Lumper::Clump.new
    c.add_csv(@csv)
    assert !c.add_csv(@csv)
  end

  def test_that_clump_with_csv_can_detach_csv
    c = Taxonifi::Lumper::Clump.new
    c.add_csv(@csv)
    assert c.remove_csv
  end

  def test_that_clump_without_csv_can_not_detach_csv
    c = Taxonifi::Lumper::Clump.new
    assert !c.remove_csv
  end

  def test_that_name_collection_can_be_derived_from_clump
    c = Taxonifi::Lumper::Clump.new
    c.add_csv(@csv)
    assert c.get_from_csv(:collection => :name)
    assert_equal ['collection0'], c.collections.keys
    assert_equal Taxonifi::Model::NameCollection, c.collections['collection0'].class
  end

  def test_that_ref_collection_can_be_derived_from_clump
    c = Taxonifi::Lumper::Clump.new
    c.add_csv(@csv)
    assert c.get_from_csv(:collection => :ref, :name => 'my_collection')
    assert_equal ['my_collection'], c.collections.keys
    assert_equal Taxonifi::Model::RefCollection, c.collections['my_collection'].class
  end

  def test_that_existing_named_collections_are_not_overwritten
    c = Taxonifi::Lumper::Clump.new
    c.add_csv(@csv)
    assert c.get_from_csv(:collection => :name, :name => 'my_collection')
    assert !c.get_from_csv(:collection => :name, :name => 'my_collection')
  end

  # name.ref ->

end


text:
@interface SignalDetailsViewController : UIViewController <CLLocationManagerDelegate, FSImageViewerViewControllerDelegate>

@property(strong, nonatomic) FSImageViewerViewController *imageViewController;
@property (weak, nonatomic) IBOutlet UIImageView *pictureView;

@property (strong, nonatomic) NSString *latitude;
@property (strong, nonatomic) NSString *longitude;
@property (strong, nonatomic) NSString *titleStr;
@property (strong, nonatomic) NSString *categoryStr;
@property (strong, nonatomic) NSString *authorStr;
@property (strong, nonatomic) NSString *addedOnStr;
@property (strong, nonatomic) NSString *descriptionStr;

@end


text:
package org.apache.camel.component.slack;

import org.apache.camel.EndpointInject;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.direct.DirectEndpoint;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;

import org.junit.Test;

public class SlackProducerTest extends CamelTestSupport {

    @EndpointInject(uri = "mock:errors")
    MockEndpoint errors;

    @EndpointInject(uri = "direct:test")
    DirectEndpoint test;

    @EndpointInject(uri = "direct:error")
    DirectEndpoint error;

    @Test
    public void testSlackMessage() throws Exception {
        errors.expectedMessageCount(0);

        template.sendBody(test, "Hello from Camel!");

        assertMockEndpointsSatisfied();
    }

    @Test
    public void testSlackError() throws Exception {
        errors.expectedMessageCount(1);

        template.sendBody(error, "Error from Camel!");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() {
                SlackComponent slack = new SlackComponent();
                slack.setWebhookUrl(System.getProperty("SLACK_HOOK", "https://hooks.slack.com/services/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"));
                context.addComponent("slack", slack);

                onException(Exception.class).handled(true).to(errors);

                final String slacUser =  System.getProperty("SLACK_USER", "CamelTest");
                from(test).to(String.format("slack:#general?iconEmoji=:camel:&username=%s", slacUser));

                from(error).to(String.format("slack:#badchannel?iconEmoji=:camel:&username=%s", slack));
            }
        };
    }
}


text:
<html>
<body>

Creates a new variable for the expression with type casting.
</body>
</html>


text:
/*
 * upclick(params)
 *
 *  parameters:
 *      element:        DOM object
 *      action:         Server script who receive file
 *      action_params:  Server script parameters. Array: key=value
 *      dataname:       File data name. Default: Filedata
 *      maxsize:        Maximum file size (in Bytes). 0 - unlimited
 *      target:         Response target name: '_new', '_blank',... Default: <Hidden frame name>
 *      zindex:         z-index listener
 *      onstart:        Callback function
 *                        onstart(filename).
 *                        Emited when file started upload
 *      oncomplete:      Callback function
 *                        oncomplete(server_response_data).
 *                        Emited when file successfully onloaded
 */
function upclick(params)
{
    // Parse params
    var defaults =
        {
            element: null,
            action: 'about:blank',
            action_params: {},
            maxsize: 0,
            onstart: null,
            oncomplete: null,
            dataname: 'Filedata',
            target: null,
            zindex: 'auto'
        };

    for(var key in defaults)
    {
        params[key] = params[key] ? params[key] : defaults[key];
    }

    var element = params['element'];
    if (typeof element == 'string')
        element = document.getElementById(element);

    var doc = element.ownerDocument;
    var input;

    // div
    var container = doc.createElement("div");

    // frame -> div
    var frame_name = 'frame' + new Date().getTime().toString().substr(8);

    // IE require such creation method
    container.innerHTML =
        '<iframe name="'+frame_name+'" src="about:blank" onload="this.onload_callback()"></iframe>';
    var frame = container.childNodes[0];

    // Callback for 'onload' event. Fired when form submited and data retrived
    frame.onload_callback =
        function()
        {
            // Phase 1. First 'onload' when element created
            // form -> div
            var form = doc.createElement('form');
            container.appendChild(form);
            form.method = 'post';
            form.enctype = 'multipart/form-data';
            form.encoding = 'multipart/form-data';
            if (params['target'])
            {
                form.target = params['target'];
                form.setAttribute('target', params['target']);
            }
            else
            {
                form.target = frame_name;
                form.setAttribute('target', frame_name);
            }
            form.action = params['action'];
            form.setAttribute('action', params['action']);
            form.style.margin = 0;
            form.style.padding = 0;
            form.style.height = '80px';
            form.style.width = '40px';
            form.runat = 'server';

            // MAX_FILESIZE. Maximum file size
            if (params['maxsize'])
            {
                var input_ms = doc.createElement('input');
                input_ms.type = 'hidden';
                input_ms.name = 'MAX_FILE_SIZE';
                input_ms.value = String(params['maxsize']);
                form.appendChild(input_ms);
            }

            // input -> form
            input = doc.createElement("input");
            input.name=params['dataname'];
            input.type='file';
            input.size='1';
            input.runat = 'server';
            form.appendChild(input);

            // input style
            input.style.position = 'absolute';
            input.style.display = 'block';
            input.style.top = 0;
            input.style.left = 0;
            input.style.height = form.style.height;
            input.style.width = '80px';
            input.style.opacity = 0;
            input.style.filter = 'alpha(opacity=0)';
            input.style.fontSize = 8;
            input.style.zIndex = 1;
            input.style.visiblity = 'hidden';
            input.style.marginLeft = '-40px'; // hide IE text field
            //input.style.cursor = 'pointer';

            // input click handler (enable container event listener)

            // 'change' event handler. Submit form
            var onchange_callback =
                function(e)
                {
                    // empty filename check
                    if (!input.value)
                        return;

                    // Action params
                    // clear old
                    for(var i=0; i < form.childNodes.length; i++) {
                        var param_input = form.childNodes[i];

                        if (param_input.is_action_params) {
                            form.removeChild(param_input);
                        }
                    }

                    // append params in form
                    var action_params = params['action_params'];

                    // if callable - get result
                    if (typeof(action_params) == "function") {
                        action_params = action_params();
                    }

                    for(var key in action_params)
                    {
                        var hidden = doc.createElement("input");
                        hidden.type = "hidden";
                        hidden.name = key;
                        hidden.value = String(action_params[key]);
                        hidden.is_action_params = true;
                        form.appendChild(hidden);
                    }

                    // Run onstart callback. When upload started
                    var onstart = params['onstart'];

                    if (onstart)
                        onstart(input.value);

                    form.submit();
                };

            // bind 'change' callback
            // DOM2: FF, Opera, Chrome
            if (input.addEventListener)
                input.addEventListener ('change', onchange_callback, false);

            // IE 5+
            else if (input.attachEvent)
            {
                input.attachEvent(
                    'onpropertychange',
                    function(e)
                    {
                        // Get event details for IE
                        if (!e)
                            e = window.event;

                        if (e.propertyName == 'value')
                            onchange_callback();
                    }
                    );
            }
            // IE 4
            else
                input.onpropertychange = onchange_callback;

            // Phase 2. Next 'onload' when data received from server
            frame.onload_callback =
                function()
                {
                    var ifwin = null;

                    // Get frame window
                    // IE5.5+, Mozilla, NN7
                    if (frame.contentWindow)
                        ifwin = frame.contentWindow;
                    // NN6, Konqueror
                    else if (frame.contentDocument)
                        ifwin = frame.contentDocument.defaultView;

                    // Run 'oncomplete' callback
                    var data = ifwin.document.body.innerHTML;
                    var oncomplete = params['oncomplete'];
                    if (oncomplete)
                        oncomplete(data);

                    // Clear filename
                    form.reset();
                }
        };

    // frame style
    frame.style.display = 'none';
    frame.width = 0;
    frame.height = 0;
    frame.marginHeight = 0;
    frame.marginWidth = 0;

    // container -> DOM
    doc.body.insertBefore(container, doc.body.firstChild);

    // container style
    container.style.position = 'absolute';
    container.style.overflow = 'hidden';
    container.style.padding = 0;
    container.style.margin = 0;
    container.style.visiblity = 'hidden';
    container.style.width = '0px';
    container.style.height = '0px';
    //container.style.cursor = 'pointer'; // FIXME flashed on IE

    // zindex detection
    if (params['zindex'] == 'auto')
    {
        var zi=0, ziparsed;
        var obj = element;
        var comp;

        while (obj.tagName != 'BODY')
        {
            comp = obj.currentStyle ? obj.currentStyle : getComputedStyle(obj, null);
            ziparsed = parseInt(comp.zIndex);
            ziparsed = isNaN(ziparsed) ? 0 : ziparsed;
            zi += ziparsed + 1;
            obj = obj.parentNode
        }

        container.style.zIndex = zi;
    }
    else
    {
        container.style.zIndex = params['zindex'];
    }

    // If cursor out of element => shitch off listener
    var onmouseout_callback =
    function(e)
    {
        if (!e)
            e = window.event;

        container.style.width = '0px';
        container.style.height = '0px';
        var receiver = doc.elementFromPoint(e.clientX, e.clientY);

        if (receiver === element)
        {
            container.style.width = '40px';
            container.style.height = '80px';
        }
    }
    // DOM2: FF, Chrome, Opera
    if (container.addEventListener)
        container.addEventListener('mousemove', onmouseout_callback, false);
     // IE 5+
    else if (container.attachEvent)
        container.attachEvent("onmousemove", onmouseout_callback);

    // Move the input with the mouse to make sure it get clicked!
    var onmousemove_callback =
        function(e)
        {
            // Get event details for IE
            if (!e)
                e = window.event;

            // find element position,
            var x = y = 0;

            if (e.pageX)
                x = e.pageX;
            else if (e.clientX)
               x = e.clientX +
                (doc.documentElement.scrollLeft ?
                    doc.documentElement.scrollLeft :
                    doc.body.scrollLeft);

            if (e.pageY)
                y = e.pageY;
            else if (e.clientY)
               y = e.clientY +
                    (doc.documentElement.scrollTop ?
                        doc.documentElement.scrollTop :
                        doc.body.scrollTop);

            // move listener
            container.style.left = x - 20 + 'px';
            container.style.top = y - 40 + 'px';
            container.style.width = '40px';
            container.style.height = '80px';

            // hover on element
            if( document.createEvent ) {
                var evt = document.createEvent('MouseEvents');
                evt.initEvent( 'mouseenter', true, false );
                element.dispatchEvent(evt);
                var evt2 = document.createEvent('MouseEvents');
                evt2.initEvent( 'mouseover', true, false );
                element.dispatchEvent(evt2);
            } else if( document.createEventObject ) {
                element.fireEvent('onmouseenter');
                element.fireEvent('onmouseover');
            }
        };

    // bind mousemove callback (for place button under cursor)
    // DOM2: FF, Chrome, Opera
    if (element.addEventListener)
        element.addEventListener('mousemove', onmousemove_callback, false);
     // IE 5+
    else if (element.attachEvent)
        element.attachEvent("onmousemove", onmousemove_callback);
}


text: nosetests -v --with-coverage --cover-package TileStache


text:
var fs = require('fs');
var path = require('path');
var merge = require('merge-stream');
var gulp = require('gulp');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');

function getFolders(dir) {
    return fs.readdirSync(dir)
      .filter(function(file) {
        return fs.statSync(path.join(dir, file)).isDirectory();
      });
}

/*
  Task percorre todas as pastas dentro de /cliente/modulos concatenando e minificando os arquivos .js
  Autor: André Silva

  Baseado em: https://github.com/gulpjs/gulp/blob/master/docs/recipes/running-task-steps-per-folder.md
*/
gulp.task('modulos', function() {
   var modulosPath = 'cliente/modulos';
   var modulosDestPath = 'cliente/build';

   var folders = getFolders(modulosPath);

   console.log('[gulp]: Iniciando a compactação dos módulos..');

   var tasks = folders.map(function(folder) {

      console.log('[gulp]: Compactando o módulo ' + folder + '..');

      return gulp.src(path.join(modulosPath, folder, '/**/*.js'))
        // Concatenar em "modulo".js
        .pipe(concat(folder + '.js'))
        // Escrever arquivo na pasta destino ("modulo".js)
        .pipe(gulp.dest(modulosDestPath))
        // Minificar
        .pipe(uglify())
        // Renomear para "modulo".min.js
        .pipe(rename(folder + '.min.js'))
        // Escrever arquivo na pasta destino ("modulo".min.js)
        .pipe(gulp.dest(modulosDestPath));
   });

   return merge(tasks);
});

gulp.task('default', function() {
  //Executar a task modulos
  gulp.start('modulos');
});


text:
package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/hersshel/hersshel/config"
	"github.com/hersshel/hersshel/store"
	"github.com/hersshel/hersshel/store/datastore"
)

// Store is a middleware function that initializes the Datastore and attaches to
// the context of every http.Request.
func Store(cfg *config.PostgreSQL) gin.HandlerFunc {
	db := datastore.New(cfg)

	return func(c *gin.Context) {
		store.ToContext(c, db)
		c.Next()
	}
}


text:
{-# LANGUAGE OverloadedStrings #-}

import qualified Aws
import qualified Aws.S3 as S3
import           Data.Conduit (($$+-))
import           Data.Conduit.Binary (sourceFile)
import qualified Data.Text as T
import           Network.HTTP.Conduit (withManager, responseBody)
import           System.Environment (getArgs)

main :: IO ()
main = do
  {- Set up AWS credentials and the default configuration. -}
  cfg <- Aws.dbgConfiguration
  let s3cfg = Aws.defServiceConfig :: S3.S3Configuration Aws.NormalQuery

  args <- getArgs

  let doUpload bucket obj file chunkSize =
        withManager $ \mgr -> do
          S3.multipartUpload cfg s3cfg mgr (T.pack bucket) (T.pack obj) (sourceFile file) (chunkSize*1024*1024)

  case args of
    [bucket,obj,file] ->
      doUpload bucket obj file 10
    [bucket,obj,file,chunkSize] ->
      doUpload bucket obj file (read chunkSize)
    _ -> do
      putStrLn "Usage: MultipartUpload bucket objectname filename (chunksize(MB)::optinal)"


text:
namespace Vidyano {
    "use strict";

    export namespace Actions {
        /* tslint:disable:class-name */
        export class viConfigurePO extends Action {
            constructor(service: Service, definition: ActionDefinition, owner: ServiceObjectWithActions) {
                super(service, definition, owner);

                this.isVisible = false;
            }
        }
        /* tslint:enable:class-name */
    }
}


text:
define([
    "intern!object",
    "intern/chai!assert",
    "tests/support/helper",
    "tests/support/commonRoutines"
], function ( registerSuite, assert, testHelper, commonRoutines ) {
    var comicWithStripWithImage;

    registerSuite({
        name: "Strip: list",

        setup: function () {
            /** Load fixtures. */
            comicWithStripWithImage = testHelper.loadFixtures( "ComicTest.Fixture.ComicWithStrips" );
        },

        teardown: function () {
            /** Unload fixtures. */
            testHelper.unloadFixtures( comicWithStripWithImage );
        },

        "Page cannot be change when strip is being edited.": function () {
            return testHelper.cleanupDashboardTest(
                commonRoutines.openStripList(
                    testHelper.getDashboardAuthorizedAsAdmin( this )
                )
                /** Open new entity for edit. */
                .findByCssSelector( ".create-strip" )
                    .click()
                    .end()
                /** Try to open existing entity for edit. */
                .setFindTimeout( testHelper.getTimeoutForPageAction() )
                .findByCssSelector( "[ng-controller=\"StripsController\"] .pagination li:not(.active) a:not(.ng-hide)" )
                    .click()
                    .end()
                .sleep( 1000 )
                /** Assert that the error has been shown. */
                .setFindTimeout( testHelper.getTimeoutForPageAction() )
                .findByCssSelector( ".noty_type_error .noty_text" )
                    .sleep( 1000 )
                    .getVisibleText()
                    .then( function ( visibleText ) {
                        assert.equal( visibleText, "Page cannot be change when strip is being edited. " +
                            "Save or discard changes first." );
                    })
            );
        }
    });
});


text:
package com.github.tomakehurst.wiremock.common;

public class InvalidInputException extends ClientError {

    public InvalidInputException(Errors errors) {
        super(errors);
    }

    protected InvalidInputException(Throwable cause, Errors errors) {
        super(cause, errors);
    }
}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.SecurityInsights.Models
{
    internal partial class UnknownEntityTimelineItem
    {
        internal static UnknownEntityTimelineItem DeserializeUnknownEntityTimelineItem(JsonElement element)
        {
            EntityTimelineKind kind = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("kind"))
                {
                    kind = new EntityTimelineKind(property.Value.GetString());
                    continue;
                }
            }
            return new UnknownEntityTimelineItem(kind);
        }
    }
}