text:
package org.supercsv.io;

import static org.junit.Assert.assertEquals;
import static org.supercsv.SuperCsvTestUtils.CSV_FILE;
import static org.supercsv.SuperCsvTestUtils.CUSTOMERS;
import static org.supercsv.SuperCsvTestUtils.HEADER;
import static org.supercsv.SuperCsvTestUtils.STRING_CUSTOMERS;
import static org.supercsv.SuperCsvTestUtils.WRITE_PROCESSORS;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.supercsv.mock.CustomerBean;
import org.supercsv.mock.CustomerStringBean;
import org.supercsv.prefs.CsvPreference;

/**
 * Tests the CsvListWriter class.
 *
 * @author James Bassett
 */
public class CsvListWriterTest {

	private static final CsvPreference PREFS = CsvPreference.STANDARD_PREFERENCE;

	private Writer writer;

	private CsvListWriter listWriter;

	/**
	 * Sets up the writer for the tests.
	 */
	@Before
	public void setUp() {
		writer = new StringWriter();
		listWriter = new CsvListWriter(writer, PREFS);
	}

	/**
	 * Closes the list writer after the test.
	 */
	@After
	public void tearDown() throws IOException {
		listWriter.close();
	}

	/**
	 * Tests the write() method with a List and array of CellProcessors.
	 */
	@Test
	public void testWriteListAndProcessors() throws IOException {
		listWriter.writeHeader(HEADER);
		for( CustomerBean customer : CUSTOMERS ) {
			final List<Object> customerList = Arrays.asList(new Object[] { customer.getCustomerNo(),
				customer.getFirstName(), customer.getLastName(), customer.getBirthDate(), customer.getMailingAddress(),
				customer.getMarried(), customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(),
				customer.getLoyaltyPoints() });
			listWriter.write(customerList, WRITE_PROCESSORS);
		}
		listWriter.flush();
		assertEquals(CSV_FILE, writer.toString());
	}

	/**
	 * Tests the write() method with a null List and array of CellProcessors.
	 */
	@Test(expected = NullPointerException.class)
	public void testWriteListAndProcessorsWithNullList() throws IOException {
		listWriter.write(null, WRITE_PROCESSORS);
	}

	/**
	 * Tests the write() method with a List and null array of CellProcessors.
	 */
	@Test(expected = NullPointerException.class)
	public void testWriteListAndProcessorsWithNullProcessors() throws IOException {
		listWriter.write(Arrays.asList(""), null);
	}

	/**
	 * Tests the write() method with a List.
	 */
	@Test
	public void testWriteList() throws IOException {
		listWriter.writeHeader(HEADER);
		for( CustomerStringBean customer : STRING_CUSTOMERS ) {
			final List<Object> customerList = Arrays.asList(new Object[] { customer.getCustomerNo(),
				customer.getFirstName(), customer.getLastName(), customer.getBirthDate(), customer.getMailingAddress(),
				customer.getMarried(), customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(),
				customer.getLoyaltyPoints() });
			listWriter.write(customerList);
		}
		listWriter.flush();
		assertEquals(CSV_FILE, writer.toString());
	}

	/**
	 * Tests the write() method with a null List.
	 */
	@Test(expected = NullPointerException.class)
	public void testWriteListWithNullList() throws IOException {
		listWriter.write((List<?>) null);
	}

	/**
	 * Tests the write() method with an Object array.
	 */
	@Test
	public void testWriteObjectArray() throws Exception {
		listWriter.writeHeader(HEADER);
		for( CustomerStringBean customer : STRING_CUSTOMERS ) {
			final Object[] customerArray = new Object[] { customer.getCustomerNo(), customer.getFirstName(),
				customer.getLastName(), customer.getBirthDate(), customer.getMailingAddress(), customer.getMarried(),
				customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(),
				customer.getLoyaltyPoints() };
			listWriter.write(customerArray);
		}
		listWriter.flush();
		assertEquals(CSV_FILE, writer.toString());
	}

	/**
	 * Tests the write() method with a null Object array.
	 */
	@Test(expected = NullPointerException.class)
	public void testWriteObjectArrayWithNullArray() throws IOException {
		listWriter.write((Object[]) null);
	}

	/**
	 * Tests the write() method with a String array.
	 */
	@Test
	public void testWriteStringArray() throws IOException {
		listWriter.writeHeader(HEADER);
		for( CustomerStringBean customer : STRING_CUSTOMERS ) {
			final String[] customerArray = new String[] { customer.getCustomerNo(), customer.getFirstName(),
				customer.getLastName(), customer.getBirthDate(), customer.getMailingAddress(), customer.getMarried(),
				customer.getNumberOfKids(), customer.getFavouriteQuote(), customer.getEmail(),
				customer.getLoyaltyPoints() };
			listWriter.write(customerArray);
		}
		listWriter.flush();
		assertEquals(CSV_FILE, writer.toString());
	}

	/**
	 * Tests the write() method with a null String array.
	 */
	@Test(expected = NullPointerException.class)
	public void testWriteStringArrayWithNullArray() throws IOException {
		listWriter.write((String[]) null);
	}

	/**
	 * Tests the constructor with a null writer.
	 */
	@SuppressWarnings("resource")
	@Test(expected = NullPointerException.class)
	public void testConstructorWillNullWriter() {
		new CsvListWriter(null, PREFS);
	}

	/**
	 * Tests the constructor with a null CsvPreference.
	 */
	@SuppressWarnings("resource")
	@Test(expected = NullPointerException.class)
	public void testConstructorWillNullPreference() {
		new CsvListWriter(writer, null);
	}

}


text:
// Copyright 2021 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.bazel.repository.downloader;

import java.io.IOException;

/** An exception indicates that the size of downloaded content doesn't match the Content-Length. */
public class ContentLengthMismatchException extends IOException {
  private final long actualSize;
  private final long expectedSize;

  public ContentLengthMismatchException(long actualSize, long expectedSize) {
    super(String.format("Bytes read %s but wanted %s", actualSize, expectedSize));
    this.actualSize = actualSize;
    this.expectedSize = expectedSize;
  }

  public long getActualSize() {
    return actualSize;
  }

  public long getExpectedSize() {
    return expectedSize;
  }
}

redpajama_set_name: RedPajamaGithub


text:
:- encoding(utf8).
:- module(
  file_ext,
  [
    append_directories/2,         % +Directories, -Directory
    cat/2,                        % +Out, +Files
    change_file_name_extension/4, % +File1, +Extension1, +Extension2, +File2
    compress_file/1,              % +FromFile
    compress_file/2,              % +FromFile, ?ToFile
    concatenate_files/2,          % +Files, +ConcatenatedFile
    convert_file/2,               % +File, +Format
    convert_file/3,               % +FromFile, +Format, ?ToFile
    create_directory/1,           % +Directory
    create_file_directory/1,      % +File
    delete_files_by_extension/1,  % +Extension
    delete_files_by_extension/2,  % +Directory, +Extension
    delete_files_by_extensions/1, % +Extensions
    delete_files_by_extensions/2, % +Directory, +Extensions
    directory_file/2,             % +Directory, -File
    directory_file_path2/3,       % ?Directory, ?File, ?Path
    directory_parent/2,           % +ChildDirectory, -ParentDirectory
    directory_path/2,             % ?Directory, ?Path
    directory_path_recursive/2,   % +Directory, -Path
    directory_subdirectories/2,   % ?Directory, ?Subdirectories
    directory_subdirectory/2,     % +Directory, ?Subdirectory
    directory_subdirectory/3,     % +Directory, ?Local, ?Subdirectory
    file_call/2,                  % +File, Goal_1
    file_extension/2,             % +File, -Extension
    file_extensions/2,            % +File, -Extensions
    file_extensions_media_type/2, % +Extensions, -MediaType
    file_line/2,                  % +File, -Line
    file_media_type/2,            % +File, -MediaType
    file_mode/2,                  % +File, +Mode
    file_name/2,                  % ?File, ?Name
    file_name_extension2/3,       % ?File, ?Name, ?Extension
    file_name_extensions/3,       % ?File, ?Name, ?Extensions
    file_size/2,                  % +File, -Size
    file_to_string/2,             % +File, -String
    guess_file_encoding/2,        % +File, ?Encoding
    home_directory/1,             % ?Directory
    is_dummy_file/1,              % +File
    is_empty_directory/1,         % +Directory
    is_empty_file/1,              % +File
    peek_file/3,                  % +File, +Size, -String
    read_from_file/2,             % +File, :Goal_1
    read_from_file/3,             % +File, :Goal_1, +Options
    read_write_file/2,            % +FromFile, :Goal_2
    read_write_file/3,            % +FromFile, :Goal_2, +Options
    read_write_file/4,            % +FromFile, :Goal_2, +ReadOptions, +WriteOptions
    read_write_files/3,           % +FromFile, +ToFile, :Goal_2
    read_write_files/4,           % +FromFile, +ToFile, :Goal_2, +Options
    read_write_files/5,           % +FromFile, +ToFile, :Goal_2, +ReadOptions, +WriteOptions
    recode_file/1,                % +File
    recode_file/2,                % +File, +FromEncoding
    recode_files/2,               % +FromFile, +ToFile
    recode_files/3,               % +FromFile, +FromEncoding, +ToFile
    sort_file/1,                  % +File
    sort_file/2,                  % +File, +Options
    touch/1,                      % +File
    working_directory/1,          % -Directory
    write_to_file/2,              % +File, :Goal_1
    write_to_file/3               % +File, :Goal_1, +Options
  ]
).
:- reexport(library(filesex)).
:- reexport(library(stream_ext)).

/** <module> File extensions

@author Wouter Beek
@version 2017-2020
*/

:- use_module(library(apply)).
:- use_module(library(error)).
:- use_module(library(lists)).
:- use_module(library(option)).
:- use_module(library(readutil)).
:- use_module(library(yall)).
:- use_module(library(zlib)).

:- use_module(library(call_ext)).
:- use_module(library(media_type)).
:- use_module(library(sort_ext)).
:- use_module(library(stream_ext)).
:- use_module(library(thread_ext)).

:- meta_predicate
    call_file_(+, +, 1, +),
    call_files_(+, +, +, +, 2, +, +),
    file_call(+, 1),
    read_from_file(+, 1),
    read_from_file(+, 1, +),
    read_write_file(+, 2),
    read_write_file(+, 2, +),
    read_write_file(+, 2, +, +),
    read_write_files(+, +, 2),
    read_write_files(+, +, 2, +),
    read_write_files(+, +, 2, +, +),
    write_to_file(+, 1),
    write_to_file(+, 1, +).

:- multifile
    error:has_type/2.

error:has_type(directory, Directory) :-
  var(Directory), !,
  instantiation_error(Directory).
error:has_type(directory, Directory) :-
  \+ exists_directory(Directory), !,
  existence_error(directory, Directory).
error:has_type(directory, Directory) :-
  error:has_type(atom, Directory).
error:has_type(media_type, media(Supertype/Subtype,Parameters)) :-
  maplist(error:has_type(atom), [Supertype,Subtype]),
  error:has_type(list(compound), Parameters).

%! append_directories(+Directories:list(atom), -Directory:atom) is det.

append_directories([], '/') :- !.
append_directories([H], H) :- !.
append_directories([H|T], Dir) :-
  append_directories_(H, T, Dir).

append_directories_(Dir, [], Dir) :- !.
append_directories_(Dir1, [H|T], Dir3) :-
  append_directories(Dir1, H, Dir2),
  append_directories_(Dir2, T, Dir3).

%! append_directories(+Directory1:atom, +Directory2:atom, -Directory:atom) is det.
%
% Returns the directory name obtained by concatenating the given
% directory names.
%
% The empty atom in the first position indicates the root directory.
%
% Does *not* ensure that any of the directories exist.

append_directories(Dir1, Dir2, Dir3) :-
  directory_subdirectories(Dir1, Subdirs1),
  directory_subdirectories(Dir2, Subdirs2),
  append(Subdirs1, Subdirs2, Subdirs3),
  directory_subdirectories(Dir3, Subdirs3).

%! cat(+Out:stream, +Files:list(atom)) is det.

cat(Out, Files) :-
  maplist(cat_file(Out), Files).

cat_file(Out, File) :-
  read_from_file(File, {Out}/[In]>>copy_stream_data(In, Out)).

%! change_file_name_extension(+File1:atom, +Extension1:atom, +Extension2:atom, +File2:atom) is det.

change_file_name_extension(File1, Ext1, Ext2, File2) :-
  file_name_extension(Base, Ext1, File1),
  file_name_extension(Base, Ext2, File2).

%! compress_file(+FromFile:atom) is det.
%! compress_file(+FromFile:atom, +ToFile:atom) is det.
%! compress_file(+FromFile:atom, -ToFile:atom) is det.

compress_file(FromFile) :-
  compress_file(FromFile, _).

compress_file(FromFile, ToFile) :-
  (var(ToFile) -> file_name_extension(FromFile, gz, ToFile) ; true),
  read_write_files(FromFile, ToFile, copy_stream_data).

%! concatenate_files(+Files, +ConcatenatedFile) is det.

concatenate_files(Files, File) :-
  setup_call_cleanup(
    open(File, write, Out),
    concatenate_files0(Files, Out),
    close(Out)
  ).

concatenate_files0([], _) :- !.
concatenate_files0([H|T], Out) :- !,
  setup_call_cleanup(
    open(H, read, In),
    copy_stream_data(In, Out),
    close(In)
  ),
  concatenate_files0(T, Out).

%! convert_file(+File:atom, +Format:atom) is det.
%! convert_file(+FromFile:atom, +Format:atom, ?ToFile:atom) is det.
%
% @see Formats are 'documented' over at
% https://cgit.freedesktop.org/libreoffice/core/tree/filter/source/config/fragments/filters
%
% @see Encodings are 'documented' over at
% https://wiki.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Filter_Options

convert_file(File, Format) :-
  convert_file(File, Format, _).

convert_file(FromFile, Format, ToFile) :-
  call_must_be(convert_format, Format),
  from_to_file_(FromFile, [Format], ToFile),
  file_directory_name(ToFile, ToDir),
  process_create(
    path(libreoffice),
    ['--convert-to',Format,'--infilter=CSV:44,34,76,1','--outdir',ToDir,file(FromFile)],
    []
  ).

convert_format(csv).

%! create_directory(+Directory:atom) is det.

create_directory(Dir) :-
  exists_directory(Dir), !.
create_directory(Dir) :-
  make_directory_path(Dir).

%! create_file_directory(+Path) is det.
%
% Ensures that the directory structure for the given file exists.

create_file_directory(Path) :-
  (exists_directory(Path) -> Dir = Path ; directory_file_path(Dir, _, Path)),
  create_directory(Dir).

%! delete_files_by_extension(+Extension:atom) is det.
%! delete_files_by_extension(+Directory:atom, +Extension:atom) is det.

delete_files_by_extension(Ext) :-
  working_directory(Dir),
  delete_files_by_extension(Dir, Ext).

delete_files_by_extension(Dir, Ext) :-
  format(atom(Wildcard1), "*.~a", [Ext]),
  directory_file_path(Dir, Wildcard1, Wildcard2),
  expand_file_name(Wildcard2, Files),
  maplist(delete_file, Files).

%! delete_files_by_extensions(+Extensions:list(atom)) is det.
%! delete_files_by_extensions(+Directory:atom, +Extensions:list(atom)) is det.

delete_files_by_extensions(Exts) :-
  working_directory(Dir),
  delete_files_by_extensions(Dir, Exts).

delete_files_by_extensions(Dir, Exts) :-
  threaded_maplist_1(delete_files_by_extension(Dir), Exts).

% directory_file(+Directory:atom, -File:atom) is nondet.
%
% Non-deterministic variant of directory_files/2 that skips dummy
% files.

directory_file(Dir, File) :-
  directory_files(Dir, Files),
  member(File, Files),
  \+ is_dummy_file(File).

%! directory_file_path2(+Directory:atom, +File:atom, -Path:atom) is det.
%! directory_file_path2(+Directory:atom, -File:atom, -Path:atom) is nondet.
%! directory_file_path2(-Directory:atom, -File:atom, +Path:atom) is det.
%
% Instantiation pattern (+,-,-) is not supported by
% directory_file_path/3 from the standard library.

directory_file_path2(Dir, File, Path) :-
  ground(Dir), var(File), var(Path), !,
  directory_file(Dir, File),
  directory_file_path(Dir, File, Path).
directory_file_path2(Dir, File, Path) :-
  directory_file_path(Dir, File, Path).

%! directory_parent(+ChildDirectory:atom, -ParentDirectory:atom) is det.

directory_parent(Dir1, Dir2) :-
  directory_subdirectories(Dir1, Subdirs1),
  once(append(Subdirs2, [_], Subdirs1)),
  directory_subdirectories(Dir2, Subdirs2).

%! directory_path(+Directory:atom, -Path:atom) is nondet.
%! directory_path(-Directory:atom, +Path:atom) is det.

directory_path(Dir, Path) :-
  directory_file(Dir, File),
  directory_file_path(Dir, File, Path).

%! directory_path_recursive(+Directory:atom, -Path:atom) is nondet.

directory_path_recursive(Dir, Path) :-
  directory_path(Dir, Path0),
  (   exists_directory(Path0)
  ->  directory_path_recursive(Path0, Path)
  ;   Path = Path0
  ).

%! directory_subdirectories(+Directory:atom, -Subdirectories:list(atom)) is det.
%! directory_subdirectories(-Directory:atom, +Subdirectories:list(atom)) is det.
%
% Occurrences of `.` and `..` in `Directory' are resolved.
%
% The empty atom in the first position indicates the root directory.
%
% For absolute directory names the first subdirectory name is the
% empty atom.

directory_subdirectories(Dir, Subdirs2) :-
  ground(Dir), !,
  atomic_list_concat(Subdirs1, /, Dir),
  resolve_subdirectories(Subdirs1, Subdirs2).
directory_subdirectories(Dir, Subdirs1) :-
  resolve_subdirectories(Subdirs1, Subdirs2),
  atomic_list_concat(Subdirs2, /, Dir).

%! directory_subdirectory(+Directory:atom, +SubDirectory:atom) is semidet.
%! directory_subdirectory(+Directory:atom, -SubDirectory:atom) is nondet.

directory_subdirectory(Dir, Subdir) :-
  directory_subdirectory(Dir, _, Subdir).

%! directory_subdirectory(+Directory:atom, +Local:atom, +SubDirectory:atom) is semidet.
%! directory_subdirectory(+Directory:atom, +Local:atom, -SubDirectory:atom) is semidet.
%! directory_subdirectory(+Directory:atom, -Local:atom, -SubDirectory:atom) is nondet.

directory_subdirectory(Dir, Local, Subdir) :-
  ground(Local), !,
  directory_file_path(Dir, Local, Subdir),
  exists_directory(Subdir).
directory_subdirectory(Dir, Local, Subdir) :-
  directory_path(Dir, Subdir),
  exists_directory(Subdir),
  directory_file_path(_, Local, Subdir).

%! file_call(+File:atom, :Goal_1) is det.

file_call(File, Goal_1) :-
  setup_call_cleanup(
    open(File, read, In),
    call(Goal_1, In),
    close(In)
  ).

%! file_extension(+File:atom, -Extension:atom) is nondet.

file_extension(File, Ext) :-
  file_extensions(File, Exts),
  member(Ext, Exts).

%! file_extensions(+File:atom, -Extensions:list(atom)) is det.

file_extensions(File, Exts) :-
  file_name_extensions(File, _, Exts).

%! file_extensions_media_type(+Extensions:list(atom), -MediaType:media_type) is det.

file_extensions_media_type(Exts, MediaType) :-
  member(Ext, Exts),
  media_type_extension(MediaType, Ext), !.

%! file_line(+File:atom, -Line:string) is nondet.

file_line(File, Line) :-
  read_from_file(File, {Line}/[In]>>stream_line(In, Line)).

%! file_media_type(+File:atom, -MediaType:compound) is nondet.

file_media_type(File, MediaType) :-
  file_extension(File, Ext),
  media_type_extension(MediaType, Ext).

%! file_mode(+File:atom, +Mode:oneof([append,read,write])) is det.
%
% @throws existence_error
% @throws permission_error

file_mode(File, Mode) :-
  (   exists_file(File)
  ->  (   access_file(File, Mode)
      ->  true
      ;   permission_error(Mode, file, File)
      )
  ;   existence_error(file, File)
  ).

%! file_name(+File:atom, +Name:atom) is semidet.
%! file_name(+File:atom, -Name:atom) is det.

file_name(File, Name) :-
  file_name_extensions(File, Name, _).

%! file_name_extension2(+File:atom, -Name:atom, -Extension:atom) is det.
%! file_name_extension2(-File:atom, +Name:atom, +Extension:atom) is det.

file_name_extension2(File, Name, Ext) :-
  file_name_extensions(File, Name, [Ext]).

%! file_name_extensions(+File:atom, -Name:atom, -Extensions:list(atom)) is det.
%! file_name_extensions(-File:atom, +Name:atom, +Extensions:list(atom)) is det.

file_name_extensions(File, Name, Exts) :-
  atomic_list_concat([Name|Exts], ., File).

%! file_size(+File:atom, -Size:nonneg) is det.
%
% @see Wrapper around size_file/2.

file_size(File, Size) :-
  size_file(File, Size).

%! file_to_string(+File:atom, -String:string) is det.

file_to_string(File, String) :-
  read_file_to_string(File, Codes, []),
  string_codes(String, Codes).

%! guess_file_encoding(+File:atom, +Encoding:atom) is det.
%! guess_file_encoding(+File:atom, -Encoding:atom) is det.
%
% When Encoding is instantiated to an encoding different from the
% guessed encoding, the error unexpected_encoding/2 is thrown.
%
% @see guess_encoding/2.

guess_file_encoding(File, Enc1) :-
  read_from_file(
    File,
    {Enc2}/[In]>>guess_encoding(In, Enc2),
    [type(binary)]
  ),
  (   var(Enc1)
  ->  Enc1 = Enc2
  ;   stream_ext:clean_encoding_(Enc1, Enc3),
      Enc3 == Enc2
  ->  true
  ;   throw(error(unexpected_encoding(Enc2,Enc1),guess_file_encoding/2))
  ).

%! home_directory(+Directory:atom) is semidet.
%! home_directory(-Directory:atom) is nondet.

home_directory(Dir) :-
  expand_file_name(~, [Dir]).

%! is_dummy_file(+File:atom) is semidet.

is_dummy_file(.).
is_dummy_file(..).

%! is_empty_directory(+Directory:atom) is semidet.

is_empty_directory(Dir) :-
  exists_directory(Dir),
  \+ directory_file(Dir, _).

%! is_empty_file(+File:atom) is semidet.

is_empty_file(File) :-
  read_from_file(File, at_end_of_stream).

%! peek_file(+File:atom, +Size:nonneg, -String:string) is det.

peek_file(File, Size, Str) :-
  read_from_file(File, {Size,Str}/[In]>>peek_string(In, Size, Str)).

%! read_from_file(+File:atom, :Goal_1) is det.
%! read_from_file(+File:atom, :Goal_1, +Options:list(compound)) is det.
%
% Calls Goal_1 on the input stream derived from the given File.  If
% the filen name ends in `.gz', GNU zip decompression is applied.

read_from_file(File, Goal_1) :-
  read_from_file(File, Goal_1, []).

read_from_file(File, Goal_1, Options) :-
  call_file_(File, read, Goal_1, Options).

%! read_write_file(+File:atom, :Goal_2) is det.
%! read_write_file(+File:atom, :Goal_2, +ReadOptions:list(compound), +WriteOptions:list(compound)) is det.

read_write_file(File, Goal_2) :-
  read_write_file(File, Goal_2, []).

read_write_file(File, Goal_2, Options) :-
  read_write_file(File, Goal_2, Options, Options).

read_write_file(File, Goal_2, ReadOptions, WriteOptions) :-
  file_name_extensions(File, Base, FromExts),
  (   append(Exts, [gz], FromExts)
  ->  append(Exts, [tmp,gz], TmpExts),
      file_name_extensions(TmpFile, Base, TmpExts)
  ;   file_name_extension(File, tmp, TmpFile)
  ),
  read_write_files(File, TmpFile, Goal_2, ReadOptions, WriteOptions),
  rename_file(TmpFile, File).

%! read_write_files(+FromFile:atom, +ToFile:atom, :Goal_2) is det.
%! read_write_files(+FromFile:atom, +ToFile:atom, :Goal_2, +Options:list(compound)) is det.
%! read_write_files(+FromFile:atom, +ToFile:atom, :Goal_2, +ReadOptions:list(compound), +WriteOptions:list(compound)) is det.

read_write_files(FromFile, ToFile, Goal_2) :-
  read_write_files(FromFile, ToFile, Goal_2, []).

read_write_files(FromFile, ToFile, Goal_2, Options) :-
  read_write_files(FromFile, ToFile, Goal_2, Options, Options).

read_write_files(FromFile, ToFile, Goal_2, ReadOptions, WriteOptions) :-
  create_file_directory(ToFile),
  call_files_(FromFile, read, ToFile, write, Goal_2, ReadOptions, WriteOptions).

%! recode_file(+FromFile:atom) is det.
%! recode_file(+FromFile:atom, +FromEncoding:atom) is det.
%
% Recodes the given File from the given FromEncoding to UTF-8.

recode_file(File) :-
  guess_file_encoding(File, Enc),
  recode_file(File, Enc).

% Optimization: do not copy stream contents when the encoding remains
% the same.
recode_file(_, utf8) :- !.
recode_file(File, Enc) :-
  read_write_file(File, {Enc}/[In,Out]>>recode_stream(In, Enc, Out), [type(binary)]).

%! recode_files(+FromFile:atom, +ToFile:atom) is det.
%! recode_files(+FromFile:atom, +FromEncoding:atom, +ToFile:atom) is det.

recode_files(FromFile, ToFile) :-
  guess_file_encoding(FromFile, Enc),
  recode_files(FromFile, Enc, ToFile).

recode_files(FromFile, Enc1, ToFile) :-
  stream_ext:clean_encoding_(Enc1, Enc2),
  (   % Optimization: do not copy stream contents when the encoding
      % remains the same.
      Enc2 == utf8
  ->  true
  ;   read_write_files(FromFile, ToFile, {Enc2}/[In,Out]>>recode_stream(In, Enc2, Out), [type(binary)])
  ).

%! resolve_subdirectories(+Subdirectories1:list(atom), -Subdirectories2:list(atom)) is det.
%
% Resolves `.' and `..'.

resolve_subdirectories([], []) :- !.
resolve_subdirectories([''], []) :- !.
resolve_subdirectories([.|T1], T2) :- !,
  resolve_subdirectories(T1, T2).
resolve_subdirectories([_,..|T1], T2) :- !,
  resolve_subdirectories(T1, T2).
resolve_subdirectories([H|T1], [H|T2]) :-
  resolve_subdirectories(T1, T2).

%! sort_file(+File:atom) is det.
%! sort_file(+File:atom, +Options:list(compound)) is det.

sort_file(File) :-
  sort_file(File, []).

sort_file(File, Options) :-
  read_write_file(
    File,
    {Options}/[In,Out]>>(
      sort_stream(In, ProcOut, Options),
      call_cleanup(
        copy_stream_data(ProcOut, Out),
        close(ProcOut)
      )
    )
  ).

%! touch(+File) is det.

touch(File) :-
  setup_call_cleanup(
    open(File, write, Out),
    true,
    close(Out)
  ).

%! working_directory(-Directory:atom) is det.

working_directory(Directory) :-
  working_directory(Directory, Directory).

%! write_to_file(+File:atom, :Goal_1) is det.
%! write_to_file(+File:atom, :Goal_1, +Options:list(compound)) is det.
%
% If File's directory does not exist it is created.

write_to_file(File, Goal_1) :-
  write_to_file(File, Goal_1, []).

write_to_file(File, Goal_1, Options) :-
  create_file_directory(File),
  call_file_(File, write, Goal_1, Options).

% GENERICS %

%! call_file_(+File:atom, +Mode:oneof([append,read,write]), :Goal_1, +Options:list(compound)) is det.
%
% @arg Options The following options are supported:
%
%      * mode(+oneof([append,read,write]) Overrules the default mode.

call_file_(File, Mode1, Goal_1, Options) :-
  option(mode(Mode2), Options, Mode1),
  setup_call_cleanup(
    open_file_(File, Mode2, Stream, Options),
    call(Goal_1, Stream),
    close(Stream)
  ).

%! call_files_(+File1:atom, +Mode1:oneof([append,read,write]), +File2:atom, +Mode2:oneof([append,read,write]), :Goal_2, +Options1:list(compound), +Options2:list(compound)) is det.

call_files_(File1, Mode1, File2, Mode2, Goal_2, Options1, Options2) :-
  setup_call_cleanup(
    maplist(
      open_file_,
      [File1,File2],
      [Mode1,Mode2],
      [Stream1,Stream2],
      [Options1,Options2]
    ),
    call(Goal_2, Stream1, Stream2),
    maplist(close, [Stream1,Stream2])
  ).

%! from_to_file_(+FromFile:atom, +Extensions:list(atom), +ToFile:atom) is semidet.
%! from_to_file_(+FromFile:atom, +Extensions:list(atom), -ToFile:atom) is det.

from_to_file_(FromFile, Exts, ToFile) :-
  var(ToFile), !,
  directory_file_path2(Dir, FromBase, FromFile),
  file_name(FromBase, Local),
  file_name_extensions(ToBase, Local, Exts),
  directory_file_path2(Dir, ToBase, ToFile).
from_to_file_(_, _, _).

%! open_file_(+File:atom, +Mode:oneof([append,read,write]), -Stream:stream, +Options:list(compoind)) is det.

open_file_(File, Mode, Stream2, Options) :-
  access_file(File, Mode),
  open_gz_(File, Mode, Stream1, Options),
  open_hash_(Stream1, Stream2, Options).

%! open_gz_(+File:atom, +Mode:oneof([append,read,write]), -Stream:stream, +Options:list(compound)) is det.

open_gz_(File, Mode, Stream, Options) :-
  file_name_extension(_, gz, File), !,
  gzopen(File, Mode, Stream, Options).
open_gz_(File, Mode, Stream, Options) :-
  open(File, Mode, Stream, Options).

%! open_hash_(+Stream1:stream, -Stream2:stream, +Options:list(compound)) is semidet.

open_hash_(Stream1, Stream2, Options) :-
  select_algorithm_option_(Algorithm, Options), !,
  open_hash_stream(Stream1, Stream2, [algorithm(Algorithm),close_parent(false)]).
open_hash_(Stream, Stream, _).

select_algorithm_option_(md5, Options) :-
  option(md5(_), Options).
select_algorithm_option_(sha1, Options) :-
  option(sha1(_), Options).
select_algorithm_option_(sha224, Options) :-
  option(sha224(_), Options).
select_algorithm_option_(sha256, Options) :-
  option(sha256(_), Options).
select_algorithm_option_(sha384, Options) :-
  option(sha384(_), Options).
select_algorithm_option_(sha512, Options) :-
  option(sha512(_), Options).


text:
from __future__ import absolute_import

import logging
import six

from sentry import options
from sentry.models import ProjectOption

from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.template.loader import render_to_string
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.http import Http404
from requests.exceptions import HTTPError

def default_plugin_config(plugin, project, request):
    if plugin.can_enable_for_projects() and \
       not plugin.can_configure_for_project(project):
        raise Http404()

    plugin_key = plugin.get_conf_key()
    form_class = plugin.get_conf_form(project)
    template = plugin.get_conf_template(project)

    if form_class is None:
        return HttpResponseRedirect(reverse(
            'sentry-manage-project', args=[project.organization.slug, project.slug]))

    test_results = None

    form = form_class(
        request.POST if request.POST.get('plugin') == plugin.slug else None,
        initial=plugin.get_conf_options(project),
        prefix=plugin_key,
    )
    if form.is_valid():
        if 'action_test' in request.POST and plugin.is_testable():
            try:
                test_results = plugin.test_configuration(project)
            except Exception as exc:
                if isinstance(exc, HTTPError):
                    test_results = '%s\n%s' % (exc, exc.response.text[:256])
                elif hasattr(exc, 'read') and callable(exc.read):
                    test_results = '%s\n%s' % (exc, exc.read()[:256])
                else:
                    logging.exception('Plugin(%s) raised an error during test',
                                      plugin_key)
                    test_results = 'There was an internal error with the Plugin'
            if not test_results:
                test_results = 'No errors returned'
        else:
            for field, value in six.iteritems(form.cleaned_data):
                key = '%s:%s' % (plugin_key, field)
                if project:
                    ProjectOption.objects.set_value(project, key, value)
                else:
                    options.set(key, value)

            messages.add_message(
                request, messages.SUCCESS,
                _('Your settings were saved successfully.'))
            return HttpResponseRedirect(request.path)

    # TODO(mattrobenolt): Reliably determine if a plugin is configured
    # if hasattr(plugin, 'is_configured'):
    #     is_configured = plugin.is_configured(project)
    # else:
    #     is_configured = True
    is_configured = True

    return mark_safe(render_to_string(template, {
        'form': form,
        'request': request,
        'plugin': plugin,
        'plugin_description': plugin.get_description() or '',
        'plugin_test_results': test_results,
        'plugin_is_configured': is_configured,
    }, context_instance=RequestContext(request)))

def default_issue_plugin_config(plugin, project, form_data):
    plugin_key = plugin.get_conf_key()
    for field, value in six.iteritems(form_data):
        key = '%s:%s' % (plugin_key, field)
        if project:
            ProjectOption.objects.set_value(project, key, value)
        else:
            options.set(key, value)

def default_plugin_options(plugin, project):
    form_class = plugin.get_conf_form(project)
    if form_class is None:
        return {}

    NOTSET = object()
    plugin_key = plugin.get_conf_key()
    initials = plugin.get_form_initial(project)
    for field in form_class.base_fields:
        key = '%s:%s' % (plugin_key, field)
        if project is not None:
            value = ProjectOption.objects.get_value(project, key, NOTSET)
        else:
            value = options.get(key)
        if value is not NOTSET:
            initials[field] = value
    return initials


text:
package com.bugsnag.testapp.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class TestSpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestSpringBootApplication.class, args);
    }
}


text:
package de.schwedt.weightlifting.app.gallery;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import de.schwedt.weightlifting.app.MainActivity;
import de.schwedt.weightlifting.app.UpdateableItem;
import de.schwedt.weightlifting.app.UpdateableWrapper;
import de.schwedt.weightlifting.app.WeightliftingApp;
import de.schwedt.weightlifting.app.helper.JsonParser;

public class Galleries extends UpdateableWrapper {

    public static final String FILE_NAME = "galleries.json";
    public static ArrayList<GalleryItem> itemsToMark = new ArrayList<>();
    public final static int navigationPosition = MainActivity.FRAGMENT_GALLERY;
    public final static int subPosition = 0;

    public static ArrayList<GalleryItem> casteArray(ArrayList<UpdateableItem> array) {
        ArrayList<GalleryItem> convertedItems = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            convertedItems.add((GalleryItem) array.get(i));
        }
        return convertedItems;
    }

    public static void markNewItems(ArrayList<UpdateableItem> oldItems, ArrayList<UpdateableItem> newItems) {
        ArrayList<GalleryItem> oldGalleryItems = casteArray(oldItems);
        ArrayList<GalleryItem> newGalleryItems = casteArray(newItems);
        for (int i = 0; i < newGalleryItems.size(); i++) {
            boolean isNew = true;
            for (int j = 0; j < oldGalleryItems.size(); j++) {
                if (newGalleryItems.get(i).getTitle().equals(oldGalleryItems.get(j).getTitle()) && Arrays.equals(newGalleryItems.get(i).getImageUrls(), oldGalleryItems.get(j).getImageUrls()) && newGalleryItems.get(i).getUrl().equals(oldGalleryItems.get(j).getUrl())) {
                    isNew = false;
                    break;
                }
            }
            if (isNew) {
                itemsToMark.add(newGalleryItems.get(i));
            }
        }
    }

    public void refreshItems() {
        String TAG = "Galleries";
        String UPDATE_URL = "https://raw.githubusercontent.com/WGierke/weightlifting_schwedt/updates/production/galleries.json";
        super.update(UPDATE_URL, FILE_NAME, TAG);
    }

    protected void updateWrapper(String result) {
        Galleries newItems = new Galleries();
        newItems.parseFromString(result);
        if (items.size() > 0) {
            keepOldReferences(items, newItems.getItems());
            markNewItems(items, newItems.getItems());
        }
        items = newItems.getItems();
    }

    public void parseFromString(String jsonString) {
        //Log.d(WeightliftingApp.TAG, "Parsing gallery JSON...");
        try {
            ArrayList<UpdateableItem> newItems = new ArrayList<>();

            JsonParser jsonParser = new JsonParser();
            jsonParser.getJsonFromString(jsonString);

            JSONArray galleries = jsonParser.getJsonArray("galleries");
            for (int i = 0; i < galleries.length(); i++) {
                try {
                    JSONObject gallery = galleries.getJSONObject(i);

                    GalleryItem item = new GalleryItem();
                    item.setTitle(gallery.getString("title"));
                    item.setUrl(gallery.getString("url"));

                    JSONArray gallery_images = gallery.getJSONArray(("images"));
                    List<String> image_urls = new ArrayList<>();
                    for (int j = 0; j < gallery_images.length(); j++) {
                        image_urls.add(gallery_images.getString(j));
                    }
                    item.setImageUrls(image_urls.toArray(new String[image_urls.size()]));
                    //imageLoader.preloadImage(item.getImageUrls()[0]);
                    newItems.add(item);
                } catch (Exception ex) {
                    Log.e(WeightliftingApp.TAG, "Error while parsing gallery #" + i);
                    ex.printStackTrace();
                }
            }

            setItems(newItems);
            setLastUpdate((new Date()).getTime());
            Log.i(WeightliftingApp.TAG, "Galleries parsed, " + newItems.size() + " items found");
        } catch (Exception ex) {
            Log.e(WeightliftingApp.TAG, "Error while parsing galleries");
            ex.printStackTrace();
        }
    }

    private void keepOldReferences(ArrayList<UpdateableItem> oldItems, ArrayList<UpdateableItem> newItems) {
        ArrayList<GalleryItem> oldGalleryItems = casteArray(oldItems);
        ArrayList<GalleryItem> newGalleryItems = casteArray(newItems);
        for (int i = 0; i < newGalleryItems.size(); i++) {
            for (int j = 0; j < oldGalleryItems.size(); j++) {
                if ((newGalleryItems.get(i)).equals(oldGalleryItems.get(j))) {
                    newGalleryItems.set(i, oldGalleryItems.get(j));
                }
            }
        }
    }
}


text:
namespace Microsoft.Azure.Management.Synapse.Models
{

    /// <summary>
    /// Defines values for EventHubDataFormat.
    /// </summary>
    public static class EventHubDataFormat
    {
        public const string MULTIJSON = "MULTIJSON";
        public const string JSON = "JSON";
        public const string CSV = "CSV";
        public const string TSV = "TSV";
        public const string SCSV = "SCSV";
        public const string SOHSV = "SOHSV";
        public const string PSV = "PSV";
        public const string TXT = "TXT";
        public const string RAW = "RAW";
        public const string SINGLEJSON = "SINGLEJSON";
        public const string AVRO = "AVRO";
        public const string TSVE = "TSVE";
        public const string PARQUET = "PARQUET";
        public const string ORC = "ORC";
        public const string APACHEAVRO = "APACHEAVRO";
        public const string W3CLOGFILE = "W3CLOGFILE";
    }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>GroupListWidget: File List | Piles</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link href="/assets/css/tabs.css" rel="stylesheet" type="text/css"/>

<link href="/assets/css/navtree.css" rel="stylesheet" type="text/css"/>

<link href="/assets/css/styleSheetFile.css" rel="stylesheet" type="text/css" />

<link rel="icon"
  type="image/png"
  href="/assets/images/pile-16.png">
<link rel="shortcut icon"
  type="image/png"
  href="/assets/images/pile-16.png">
<link rel="stylesheet" href="/assets/css/main.css">

Piles

    home
    docs
    piles
    GitHub

GroupListWidget Pile
     version 0.0.1

The pile attempts to provide a widget that is capable of presenting

Main Page

Classes

Files

File List

File List

Here is a list of all documented files with brief descriptions:

 grouplistdelegate.h

 grouplistgroup.h

 grouplistwidget-private.h	Declarations for GroupListWidget class

 grouplistwidget.cc	Definitions for GROUPLISTWIDGET class

 grouplistwidget.h	Declarations for GroupListWidget class

 groupmodel.cc	Definitions for GroupModel class

 groupmodel.h	Declarations for GroupModel class

 groupsubmodel.cc	Definitions for GroupSubModel class

 groupsubmodel.h	Declarations for GroupSubModel class

<address class="footer"></address>


text:
package com.flowpowered.engine.util.thread.snapshotable;

import com.flowpowered.api.util.thread.annotation.DelayedWrite;
import com.flowpowered.api.util.thread.annotation.LiveRead;
import com.flowpowered.api.util.thread.annotation.SnapshotRead;

/**
 * A snapshotable object that supports primitive shorts
 */
public class SnapshotableShort implements Snapshotable {
    private volatile short next;
    private short snapshot;

    public SnapshotableShort(SnapshotManager manager, short initial) {
        next = initial;
        snapshot = initial;
        if (manager != null) {
            manager.add(this);
        }
    }

    /**
     * Sets the next value for the Snapshotable
     */
    @DelayedWrite
    public void set(short next) {
        this.next = next;
    }

    /**
     * Gets the snapshot value for
     *
     * @return the stable snapshot value
     */
    @SnapshotRead
    public short get() {
        return snapshot;
    }

    /**
     * Gets the live value
     *
     * @return the unstable Live "next" value
     */
    @LiveRead
    public short getLive() {
        return next;
    }

    /**
     * Copies the next value to the snapshot value
     */
    @Override
    public void copySnapshot() {
        snapshot = next;
    }
}


text:
local http_socket = require('socket.http')
local url_parser = require('socket.url')
local ltn12 = require('ltn12')
local json = require('cjson.safe')
local xml = require('xml')
local md5sum = require('md5') -- TODO: Make modular?
local base64 = require('base64')

local requests = {
  _DESCRIPTION = 'Http requests made simpler',
  http_socket = http_socket
}

local _requests = {}

--User facing function the make a request use Digest Authentication
--TODO: Determine what else should live in authentication
function requests.HTTPDigestAuth(user, password)
  return { _type = 'digest', user = user, password = password}
end

--User facing function the make a request use Basic Authentication
--TODO: Determine what else should live in authentication
function requests.HTTPBasicAuth(user, password)
  return { _type = 'basic', user = user, password = password}
end

function requests.post(url, args)
  return requests.request("POST", url, args)
end

function requests.get(url, args)
  return requests.request("GET", url, args)
end

function requests.delete(url, args)
  return requests.request("DELETE", url, args)
end

function requests.patch(url, args)
  return requests.request("PATCH", url, args)
end

function requests.put(url, args)
  return requests.request("PUT", url, args)
end

function requests.options(url, args)
  return requests.request("OPTIONS", url, args)
end

function requests.head(url, args)
  return requests.request("HEAD", url, args)
end

function requests.trace(url, args)
  return requests.request("TRACE", url, args)
end

--Sets up all the data for a request and makes the request
function requests.request(method, url, args)
  local request

  if type(url) == "table" then
    request = url
  else
    request = args or {}
    request.url = url
  end

  request.method = method
  _requests.parse_args(request)

  -- TODO: Find a better way to do this
  if request.auth and request.auth._type == 'digest' then
    local response = _requests.make_request(request)
    return _requests.use_digest(response, request)
  else
    return _requests.make_request(request)
  end
end

--Makes a request
function _requests.make_request(request)
  local response_body = {}
  local full_request = {
    method = request.method,
    url = request.url,
    headers = request.headers,
    source = ltn12.source.string(request.data),
    sink = ltn12.sink.table(response_body),
    redirect = request.allow_redirects,
    proxy = request.proxy
  }

  local response = {}
  local ok

  ok, response.status_code, response.headers, response.status = requests.http_socket.request(full_request)

  assert(ok, 'error in '..request.method..' request: '..response.status_code)
  response.text = table.concat(response_body)
  response.json = function () return json.decode(response.text) end
  response.xml = function () return xml.load(response.text) end

  return response
end

--Parses through all the possible arguments for a request
function _requests.parse_args(request)
  _requests.check_url(request)
  _requests.check_data(request)
  _requests.create_header(request)
  _requests.check_timeout(request.timeout)
  _requests.check_redirect(request.allow_redirects)
end

--Format the the url based on the params argument
function _requests.format_params(url, params) -- TODO: Clean
  if not params or next(params) == nil then return url end

  url = url..'?'
  for key, value in pairs(params) do
    if tostring(value) then
      url = url..tostring(key)..'='

      if type(value) == 'table' then
        local val_string = ''

        for _, val in ipairs(value) do
          val_string = val_string..tostring(val)..','
        end

        url = url..val_string:sub(0, -2)
      else
        url = url..tostring(value)
      end

      url = url..'&'
    end
  end

  return url:sub(0, -2)
end

--Check that there is a URL given and append to it if params are passed in.
function _requests.check_url(request)
  assert(request.url, 'No url specified for request')
  request.url = _requests.format_params(request.url, request.params)
end

-- Add to the HTTP header
function _requests.create_header(request)
  request.headers = request.headers or {}
  request.headers['Content-Length'] = request.data:len()

  if request.cookies then
    if request.headers.cookie then
      request.headers.cookie = request.headers.cookie..'; '..request.cookies
    else
      request.headers.cookie = request.cookies
    end
  end

  if request.auth then
    _requests.add_auth_headers(request)
  end
end

--Makes sure that the data is in a format that can be sent
function _requests.check_data(request)
  request.data = request.data or ''

  if type(request.data) == "table" then
    request.data = json.encode(request.data)
  end
end

--Set the timeout
function _requests.check_timeout(timeout)
  http_socket.TIMEOUT = timeout or 5
end

--Checks is allow_redirects parameter is set correctly
function _requests.check_redirect(allow_redirects)
  if allow_redirects and type(allow_redirects) ~= "boolean" then
    error("allow_redirects expects a boolean value. received type = "..type(allow_redirects))
  end
end

--Create the Authorization header for Basic Auth
function _requests.basic_auth_header(request)
  local encoded = base64.encode(request.auth.user..':'..request.auth.password)
  request.headers.Authorization = 'Basic '..encoded
end

-- Create digest authorization string for request header TODO: Could be better, but it should work
function _requests.digest_create_header_string(auth)
  local authorization = ''
  authorization = 'Digest username="'..auth.user..'", realm="'..auth.realm..'", nonce="'..auth.nonce
  authorization = authorization..'", uri="'..auth.uri..'", qop='..auth.qop..', nc='..auth.nc
  authorization = authorization..', cnonce="'..auth.cnonce..'", response="'..auth.response..'"'

  if auth.opaque then
    authorization = authorization..', opaque="'..auth.opaque..'"'
  end

  return authorization
end

--MD5 hash all parameters
local function md5_hash(...)
  return md5sum.sumhexa(table.concat({...}, ":"))
end

-- Creates response hash TODO: Add functionality
function _requests.digest_hash_response(auth_table)
  return md5_hash(
    md5_hash(auth_table.user, auth_table.realm, auth_table.password),
    auth_table.nonce,
    auth_table.nc,
    auth_table.cnonce,
    auth_table.qop,
    md5_hash(auth_table.method, auth_table.uri)
  )
end

-- Add digest authentication to the request header
function _requests.digest_auth_header(request)
  if not request.auth.nonce then return end

  request.auth.cnonce = request.auth.cnonce or string.format("%08x", os.time())

  request.auth.nc_count = request.auth.nc_count or 0
  request.auth.nc_count = request.auth.nc_count + 1

  request.auth.nc = string.format("%08x", request.auth.nc_count)

  local url = url_parser.parse(request.url)
  request.auth.uri = url_parser.build{path = url.path, query = url.query}
  request.auth.method = request.method
  request.auth.qop = 'auth'

  request.auth.response = _requests.digest_hash_response(request.auth)

  request.headers.Authorization = _requests.digest_create_header_string(request.auth)
end

--Checks the resonse code and adds additional headers for Digest Auth
-- TODO: Rename this
function _requests.use_digest(response, request)
  if response.status_code == 401 then
    _requests.parse_digest_response_header(response,request)
    _requests.create_header(request)
    response = _requests.make_request(request)
    response.auth = request.auth
    response.cookies = request.headers.cookie
    return response
  else
    response.auth = request.auth
    response.cookies = request.headers.cookie
    return response
  end
end

--Parse the first response from the host to make the Authorization header
function _requests.parse_digest_response_header(response, request)
  for key, value in response.headers['www-authenticate']:gmatch('(%w+)="(%S+)"') do
    request.auth[key] = value
  end

  if request.headers.cookie then
    request.headers.cookie = request.headers.cookie..'; '..response.headers['set-cookie']
  else
    request.headers.cookie = response.headers['set-cookie']
  end

  request.auth.nc_count = 0
end

-- Call the correct authentication header function
function _requests.add_auth_headers(request)
  local auth_func = {
    basic = _requests.basic_auth_header,
    digest = _requests.digest_auth_header
  }

  auth_func[request.auth._type](request)
end

--Return public functions
requests._private = _requests
return requests


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2013-2020 Scott Warner

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="5dip"
        android:paddingLeft="15dip"
        android:paddingRight="15dip"
        android:orientation="vertical" >

        <com.tortel.deploytrack.view.SquareDecoView
            android:id="@+id/graph"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dip"
            />

        <TextView
            android:id="@+id/main"
            style="@style/Percentage"
            />

        <TextView
            android:id="@+id/daterange"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="5dip"
            android:paddingRight="5dip"
            android:textStyle="bold"
            android:gravity="center"
            />

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="5dip"
            android:paddingRight="5dip"
            android:layout_gravity="center"
            >

	        <TextView
	            android:id="@+id/second"
	            android:layout_height="wrap_content"
	            android:layout_width="wrap_content"
	            android:paddingBottom="5dip"
	            android:gravity="center"
	            />

            <TextView
                android:id="@+id/comma"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="@string/comma"
                android:gravity="center"
                />

            <TextView
                android:id="@+id/third"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:gravity="center"
                />

        </LinearLayout>

    </LinearLayout>
</ScrollView>


text:
#include <aws/kendra/model/MemberUser.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace kendra
{
namespace Model
{

MemberUser::MemberUser() :
    m_userIdHasBeenSet(false)
{
}

MemberUser::MemberUser(JsonView jsonValue) :
    m_userIdHasBeenSet(false)
{
  *this = jsonValue;
}

MemberUser& MemberUser::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("UserId"))
  {
    m_userId = jsonValue.GetString("UserId");

    m_userIdHasBeenSet = true;
  }

  return *this;
}

JsonValue MemberUser::Jsonize() const
{
  JsonValue payload;

  if(m_userIdHasBeenSet)
  {
   payload.WithString("UserId", m_userId);

  }

  return payload;
}

} // namespace Model
} // namespace kendra
} // namespace Aws


text:
import React from 'react'
import {connect} from 'cerebral/react'
import {state} from 'cerebral/tags'

import Clients from '../Clients'
import Projects from '../Projects'
import Tasks from '../Tasks'
import Today from '../Today'

const VIEWS = {
  Clients,
  Projects,
  Tasks,
  Today
}

export default connect(
  {
    selectedView: state`app.$selectedView`
  },
  function Workspace ({selectedView}) {
    const CurrentView = VIEWS[selectedView]
    return (
      <div className='section'>
        <CurrentView />
      </div>
    )
  }
)


text:
package de.javakaffee.web.msm.integration;

import static de.javakaffee.web.msm.integration.TestUtils.*;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;

import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.util.Arrays;

import net.spy.memcached.ConnectionFactory;
import net.spy.memcached.DefaultConnectionFactory;
import net.spy.memcached.MemcachedClient;

import org.apache.http.HttpException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.thimbleware.jmemcached.MemCacheDaemon;

import de.javakaffee.web.msm.MemcachedBackupSession;
import de.javakaffee.web.msm.MemcachedNodesManager;
import de.javakaffee.web.msm.MemcachedNodesManager.StorageClientCallback;
import de.javakaffee.web.msm.MemcachedSessionService.SessionManager;
import de.javakaffee.web.msm.SessionIdFormat;
import de.javakaffee.web.msm.Statistics;
import de.javakaffee.web.msm.SuffixLocatorConnectionFactory;
import de.javakaffee.web.msm.integration.TestUtils.LoginType;
import de.javakaffee.web.msm.integration.TestUtils.RecordingSessionActivationListener;
import de.javakaffee.web.msm.integration.TestUtils.Response;
import de.javakaffee.web.msm.integration.TestUtils.SessionAffinityMode;
import de.javakaffee.web.msm.storage.MemcachedStorageClient.ByteArrayTranscoder;

/**
 * Integration test testing tomcat failover (tomcats failing).
 *
 * @author Martin Grotzke
 * @version $Id$
 */
public abstract class TomcatFailoverIntegrationTest {

    private static final Log LOG = LogFactory.getLog( TomcatFailoverIntegrationTest.class );

    private static final String GROUP_WITHOUT_NODE_ID = "withoutNodeId";

    private MemCacheDaemon<?> _daemon;
    private MemCacheDaemon<?> _daemon2 = null;
    private MemcachedClient _client;

    private final StorageClientCallback _storageClientCallback = new StorageClientCallback() {
        @Override
        public byte[] get(final String key) {
            return _client.get(key, ByteArrayTranscoder.INSTANCE);
        }
    };

    private TomcatBuilder<?> _tomcat1;
    private TomcatBuilder<?> _tomcat2;

    private static final int TC_PORT_1 = 18888;
    private static final int TC_PORT_2 = 18889;

    private static final String JVM_ROUTE_2 = "tc2";
    private static final String JVM_ROUTE_1 = "tc1";

    private static final String NODE_ID = "n1";
    private static final int MEMCACHED_PORT = 21211;
    private String _memcachedNodes;

    private DefaultHttpClient _httpClient;

    @BeforeMethod
    public void setUp(final Method testMethod) throws Throwable {

        final InetSocketAddress address = new InetSocketAddress( "localhost", MEMCACHED_PORT );
        _daemon = createDaemon( address );
        _daemon.start();

        final String[] testGroups = testMethod.getAnnotation(Test.class).groups();
        final String nodePrefix = testGroups.length == 0 || !GROUP_WITHOUT_NODE_ID.equals(testGroups[0]) ? NODE_ID + ":" : "";
        _memcachedNodes = nodePrefix + "localhost:" + MEMCACHED_PORT;

        try {
            _tomcat1 = startTomcat( TC_PORT_1, JVM_ROUTE_1 );
            _tomcat2 = startTomcat( TC_PORT_2, JVM_ROUTE_2 );

        } catch ( final Throwable e ) {
            LOG.error( "could not start tomcat.", e );
            throw e;
        }

        final MemcachedNodesManager nodesManager = MemcachedNodesManager.createFor(_memcachedNodes, null, null, _storageClientCallback);
        final ConnectionFactory cf = nodesManager.isEncodeNodeIdInSessionId()
            ? new SuffixLocatorConnectionFactory( nodesManager, nodesManager.getSessionIdFormat(), Statistics.create(), 1000, 1000 )
            : new DefaultConnectionFactory();
        _client = new MemcachedClient( cf, Arrays.asList( address ) );

        _httpClient = new DefaultHttpClient();
    }

    abstract TestUtils<?> getTestUtils();

    private TomcatBuilder<?> startTomcat( final int port, final String jvmRoute ) throws Exception {
        return startTomcat( port, SessionAffinityMode.STICKY, jvmRoute, null );
    }

    private TomcatBuilder<?> startTomcat( final int port, final SessionAffinityMode sessionAffinityMode,
            final String jvmRoute, final LoginType loginType ) throws Exception {
        return getTestUtils().tomcatBuilder().port(port).memcachedNodes(_memcachedNodes).storageKeyPrefix(null)
                .sticky(sessionAffinityMode.isSticky()).jvmRoute(jvmRoute).loginType(loginType).buildAndStart();
    }

    @AfterMethod
    public void tearDown() throws Exception {
        _client.shutdown();
        _httpClient.getConnectionManager().shutdown();
        _tomcat1.stop();
        _tomcat2.stop();
        _daemon.stop();
        if(_daemon2 != null)
            _daemon2.stop();
    }

    /**
     * Test for issue #38:
     * Notify HttpSessionActivationListeners when loading a session from memcached
     * @throws Exception
     */
    @Test( enabled = true )
    public void testHttpSessionActivationListenersNotifiedOnLoadWithJvmRoute() throws Exception {

        final SessionManager manager1 = _tomcat1.getManager();
        final SessionManager manager2 = _tomcat2.getManager();

        final SessionIdFormat format = new SessionIdFormat();

        final String sessionId1 = get( _httpClient, TC_PORT_1, null ).getSessionId();
        assertEquals( format.extractJvmRoute( sessionId1 ), JVM_ROUTE_1 );

        final MemcachedBackupSession session = (MemcachedBackupSession) manager1.findSession( sessionId1 );
        session.setAttribute( "listener", new RecordingSessionActivationListener() );

        get( _httpClient, TC_PORT_1, sessionId1 );

        final String sessionId2 = get( _httpClient, TC_PORT_2, sessionId1 ).getSessionId();
        assertEquals( format.stripJvmRoute( sessionId2 ), format.stripJvmRoute( sessionId1 ) );
        assertEquals( format.extractJvmRoute( sessionId2 ), JVM_ROUTE_2 );

        final MemcachedBackupSession loaded = (MemcachedBackupSession) manager2.findSession( sessionId2 );
        assertNotNull( loaded );
        final RecordingSessionActivationListener listener = (RecordingSessionActivationListener) loaded.getAttribute( "listener" );
        assertNotNull( listener );

        final String notifiedSessionId = listener.getSessionDidActivate();
        assertEquals( notifiedSessionId, sessionId2 );
    }

    /**
     * Test for issue #38:
     * Notify HttpSessionActivationListeners when loading a session from memcached
     * @throws Exception
     */
    @Test( enabled = true )
    public void testHttpSessionActivationListenersNotifiedOnLoadWithoutJvmRoute() throws Exception {

        _tomcat1.stop();
        _tomcat2.stop();

        _tomcat1 = startTomcat( TC_PORT_1, null );
        _tomcat2 = startTomcat( TC_PORT_2, null );

        final SessionManager manager1 = _tomcat1.getManager();
        final SessionManager manager2 = _tomcat2.getManager();

        final SessionIdFormat format = new SessionIdFormat();

        final String sessionId1 = get( _httpClient, TC_PORT_1, null ).getSessionId();
        assertNull( format.extractJvmRoute( sessionId1 ) );

        final MemcachedBackupSession session = (MemcachedBackupSession) manager1.findSession( sessionId1 );
        session.setAttribute( "listener", new RecordingSessionActivationListener() );

        get( _httpClient, TC_PORT_1, sessionId1 );

        final String sessionId2 = get( _httpClient, TC_PORT_2, sessionId1 ).getSessionId();
        assertEquals( sessionId2, sessionId1 );

        final MemcachedBackupSession loaded = (MemcachedBackupSession) manager2.findSession( sessionId2 );
        assertNotNull( loaded );
        final RecordingSessionActivationListener listener = (RecordingSessionActivationListener) loaded.getAttribute( "listener" );
        assertNotNull( listener );

        final String notifiedSessionId = listener.getSessionDidActivate();
        assertEquals( notifiedSessionId, sessionId2 );
    }

    /**
     * Tests that when two tomcats are running and one tomcat fails the other
     * tomcat can take over the session.
     *
     * @throws IOException
     * @throws InterruptedException
     * @throws HttpException
     */
    @Test( enabled = true )
    public void testTomcatFailover() throws IOException, InterruptedException, HttpException {

        final SessionIdFormat format = new SessionIdFormat();

        final String key = "foo";
        final String value = "bar";
        final String sessionId1 = post( _httpClient, TC_PORT_1, null, key, value ).getSessionId();
        assertEquals( format.extractJvmRoute( sessionId1 ), JVM_ROUTE_1 );

        final Object session = _client.get( sessionId1 );
        assertNotNull( session, "Session not found in memcached: " + sessionId1 );

        final Response response = get( _httpClient, TC_PORT_2, sessionId1 );
        final String sessionId2 = response.getSessionId();
        assertNull( _client.get( sessionId1 ) );
        assertNotNull( _client.get( sessionId2 ) );

        assertEquals( format.stripJvmRoute( sessionId1 ), format.stripJvmRoute( sessionId2 ) );
        assertEquals( format.extractJvmRoute( sessionId2 ), JVM_ROUTE_2 );

        /* check session attributes could be read
         */
        final String actualValue = response.get( key );
        assertEquals( value, actualValue );

        Thread.sleep( 10 );

    }

    /**
     * Related to issue/feature 105 (single memcached node without node id): tomcat failover must work with this configuration.
     */
    @Test( enabled = true, groups = GROUP_WITHOUT_NODE_ID )
    public void testTomcatFailoverWithSingleNodeWithoutConfiguredNodeId() throws IOException, InterruptedException, HttpException {
        // with this group (GROUP_WITHOUT_NODE_ID) the setup method does no set the memcached node id
        // in the memcached nodes configuration. the tomcat failover test does not rely on the node id
        // so that we can just reuse it...
        testTomcatFailover();
    }

    /**
     * Tests that the session that was taken over by another tomcat is not
     * sent again by this tomcat if it was not modified.
     *
     * @throws IOException
     * @throws InterruptedException
     * @throws HttpException
     */
    @Test( enabled = true )
    public void testLoadedSessionOnlySentIfModified() throws IOException, InterruptedException, HttpException {

        /* create a session on tomcat1
         */
        final String key = "foo";
        final String value = "bar";
        final String sessionId1 = post( _httpClient, TC_PORT_1, null, key, value ).getSessionId();
        assertEquals( 1, _daemon.getCache().getSetCmds() );

        final SessionIdFormat format = new SessionIdFormat();

        /* request the session on tomcat2
         */
        final Response response = get( _httpClient, TC_PORT_2, sessionId1 );
        assertEquals( format.stripJvmRoute( sessionId1 ), format.stripJvmRoute( response.getSessionId() ) );
        assertEquals( 2, _daemon.getCache().getSetCmds() );

        /* post key/value already stored in the session again (on tomcat2)
         */
        post( _httpClient, TC_PORT_2, sessionId1, key, value );
        assertEquals( 2, _daemon.getCache().getSetCmds() );

        /* post another key/value pair (on tomcat2)
         */
        post( _httpClient, TC_PORT_2, sessionId1, "bar", "baz" );
        assertEquals( 3, _daemon.getCache().getSetCmds() );

        Thread.sleep( 10 );

    }

    @Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
    public void testSerializationOfAuthStuffWithFormAuth( final SessionAffinityMode stickyness ) throws Exception {

        _tomcat1.stop();
        _tomcat2.stop();

        _tomcat1 = startTomcat( TC_PORT_1, stickyness, stickyness.isSticky() ? JVM_ROUTE_1 : null, LoginType.FORM );
        _tomcat2 = startTomcat( TC_PORT_2, stickyness, stickyness.isSticky() ? JVM_ROUTE_2 : null, LoginType.FORM );

        _tomcat1.setChangeSessionIdOnAuth( false );
        _tomcat2.setChangeSessionIdOnAuth( false );

        /* tomcat1: request secured resource, login and check that secured resource is accessable
         */
        final String sessionId = loginWithForm(_httpClient, TC_PORT_1);

        /* tomcat1 failover "simulation":
         * on tomcat2, we now be able to access the secured resource directly
         * with the first request
         */
        final Response tc2Response1 = get( _httpClient, TC_PORT_2, sessionId );
        if ( stickyness.isSticky() ) {
            assertEquals( tc2Response1.getResponseSessionId(), new SessionIdFormat().changeJvmRoute( sessionId, JVM_ROUTE_2 ) );
        }
        else {
            assertEquals( tc2Response1.getSessionId(), sessionId );
        }

    }

    @Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
    public void testSerializationOfAuthStuffWithBasicAuth( final SessionAffinityMode stickyness ) throws Exception {

        _tomcat1.stop();
        _tomcat2.stop();

        _tomcat1 = startTomcat( TC_PORT_1, stickyness, stickyness.isSticky() ? JVM_ROUTE_1 : null, LoginType.BASIC );
        _tomcat2 = startTomcat( TC_PORT_2, stickyness, stickyness.isSticky() ? JVM_ROUTE_2 : null, LoginType.BASIC );

        _tomcat1.setChangeSessionIdOnAuth( false );
        _tomcat2.setChangeSessionIdOnAuth( false );

        /* tomcat1: request secured resource, login and check that secured resource is accessable
         */
        final Response tc1Response1 = get( _httpClient, TC_PORT_1, null,
                new UsernamePasswordCredentials( TestUtils.USER_NAME, TestUtils.PASSWORD ) );
        final String sessionId = tc1Response1.getSessionId();

        assertEquals( sessionId, tc1Response1.get( TestServlet.ID ) );

        /* tomcat1 failover "simulation":
         * on tomcat2, we now should be able to access the secured resource directly
         * with the first request
         */
        final Response tc2Response1 = get( _httpClient, TC_PORT_2, sessionId );
        if ( stickyness.isSticky() ) {
            assertEquals( tc2Response1.getResponseSessionId(), new SessionIdFormat().changeJvmRoute( sessionId, JVM_ROUTE_2 ) );
        }
        else {
            assertEquals( tc2Response1.getSessionId(), sessionId );
        }

    }

    @Test( enabled = true )
    public void testSessionOnlyLoadedOnceWithAuth() throws Exception {

        _tomcat1.stop();
        _tomcat2.stop();

        _tomcat1 = startTomcat( TC_PORT_1, SessionAffinityMode.STICKY, JVM_ROUTE_1, LoginType.BASIC );
        _tomcat2 = startTomcat( TC_PORT_2, SessionAffinityMode.STICKY, JVM_ROUTE_2, LoginType.BASIC );

        _tomcat1.setChangeSessionIdOnAuth( false );
        _tomcat2.setChangeSessionIdOnAuth( false );

        /* tomcat1: request secured resource, login and check that secured resource is accessable
         */
        final Response tc1Response1 = get( _httpClient, TC_PORT_1, null,
                new UsernamePasswordCredentials( TestUtils.USER_NAME, TestUtils.PASSWORD ) );
        final String sessionId = tc1Response1.getSessionId();

        assertEquals( sessionId, tc1Response1.get( TestServlet.ID ) );
        assertEquals( _daemon.getCache().getGetHits(), 0 );

        /* on tomcat1 failover and session takeover by tomcat2, msm in tomcat2 should
         * load the session only once.
         */
        final Response tc2Response1 = get( _httpClient, TC_PORT_2, sessionId );
        assertEquals( tc2Response1.getResponseSessionId(), new SessionIdFormat().changeJvmRoute( sessionId, JVM_ROUTE_2 ) );
        assertEquals( _daemon.getCache().getGetHits(), 1 );

    }

    @Test( enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER )
    public void testSessionModificationOnTomcatFailoverNotLostWithAuth( final SessionAffinityMode stickyness ) throws Exception {

        _tomcat1.stop();
        _tomcat2.stop();

        _tomcat1 = startTomcat( TC_PORT_1, stickyness, stickyness.isSticky() ? JVM_ROUTE_1 : null, LoginType.BASIC );
        _tomcat2 = startTomcat( TC_PORT_2, stickyness, stickyness.isSticky() ? JVM_ROUTE_2 : null, LoginType.BASIC );

        _tomcat1.setChangeSessionIdOnAuth( false );
        _tomcat2.setChangeSessionIdOnAuth( false );

        final Response tc1Response1 = get( _httpClient, TC_PORT_1, null, new UsernamePasswordCredentials( TestUtils.USER_NAME, TestUtils.PASSWORD ) );
        final String sessionId = tc1Response1.getSessionId();
        assertEquals( sessionId, tc1Response1.get( TestServlet.ID ) );

        /* on tomcat1 failover and session takeover by tomcat2, the changes made to the
         * session during this request must be available in the following request(s)
         */
        final Response tc2Response1 = post( _httpClient, TC_PORT_2, "/", sessionId, asMap( "foo", "bar" ) );
        if ( stickyness.isSticky() ) {
            assertEquals( tc2Response1.getResponseSessionId(), new SessionIdFormat().changeJvmRoute( sessionId, JVM_ROUTE_2 ) );
        }
        else {
            assertEquals( tc2Response1.getSessionId(), sessionId );
        }

        final Response tc2Response2 = get( _httpClient, TC_PORT_2, tc2Response1.getResponseSessionId() );
        assertEquals( tc2Response2.get( "foo" ), "bar" );

    }

    @Test( enabled = true )
    public void testTomcatFailoverMovesSessionToNonFailoverNode() throws Exception {

        _daemon2 = startMemcached(MEMCACHED_PORT + 1);
        final String memcachedNodes = _memcachedNodes + "," + "n2:localhost:" + (MEMCACHED_PORT + 1);

        _tomcat1.getService().setMemcachedNodes(memcachedNodes);
        _tomcat1.getService().setFailoverNodes("n1");
        _tomcat2.getService().setMemcachedNodes(memcachedNodes);
        _tomcat2.getService().setFailoverNodes("n2");

        final SessionIdFormat format = new SessionIdFormat();

        final String key = "foo";
        final String value = "bar";
        final String sessionId1 = post( _httpClient, TC_PORT_1, null, key, value ).getSessionId();
        assertEquals( format.extractMemcachedId( sessionId1 ), "n2" );
        assertEquals(_daemon.getCache().getCurrentItems(), 0);
        assertEquals(_daemon2.getCache().getCurrentItems(), 1);

        // failover simulation, just request the session from tomcat2
        final Response response = get( _httpClient, TC_PORT_2, sessionId1 );
        final String sessionId2 = response.getSessionId();
        assertEquals( format.extractMemcachedId( sessionId2 ), "n1" );
        assertEquals(_daemon.getCache().getCurrentItems(), 1);

        assertEquals( format.stripJvmRoute( sessionId1 ).replaceAll("n2", "n1"), format.stripJvmRoute( sessionId2 ) );

        /* check session attributes could be read
         */
        final String actualValue = response.get( key );
        assertEquals( value, actualValue );

    }

    private MemCacheDaemon<?> startMemcached(final int memcachedPort) throws IOException {
        final InetSocketAddress address = new InetSocketAddress( "localhost", memcachedPort );
        final MemCacheDaemon<?> daemon2 = createDaemon( address );
        daemon2.start();
        return daemon2;
    }

}


text:
This gem aims to provide a CLI that import data from production to a local environment.

It focus Rails and ActiveRecord but it would be great to support more frameworks and ORMs.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'cherry_pick'
```

And then execute:

    $ bundle

## Usage

`cherry_pick` needs a configuration file that is just plain Ruby. In this configuration file
you describe both source and target environments (ie: database configurations) alongside with
the models you need to pick from the source.

``` ruby
#
# Load what you need to get your AR models!
#

require "./config/evironment.rb"
Rails.application.eager_load!

#
# Use your database.yml
#

require "erb"
require "yaml"

renderer = ERB.new(File.read("./config/database.yml"))
database_configs = YAML::load(renderer.result())

#
# Declare the database where the data has to be picked
#

source_db database_configs["production"]

#
# Setup the target where the data has to be imported
#

target_db database_configs["development"]

#
# The fetch block will define what to do while we're connected to the source database
#

fetch do
  # Each get will get an in-memory version of a given model and all related models
  get User.where(id: 42)

  # You can limit the exploration of the graph with the except policy
  policy max_depth: 6, except: [
    "versions",            # Don't follow any association named `versions`
    "posts/related_posts", # Don't follow `related_posts` from any `posts` association
    "comments/author/*",   # Don't follow any association after and `author` from a `comments` association
  ]

  # OR You can direct the graph using the policy with the only policy
  policy max_depth: 6, only: [
    "/posts/comments/author", # Starting from the roots, only get posts, their comments and authors
  ]
end

#
# The import block will configure how data are imported back in the targt database
#

import do
  # Each hook will run for each object saved
  before_save User do |u|
    u.password = "password"
  end
end
```

## Controlling exploration

During the traversal of the object graph, a _path_ will be attached to each object. The path
starts with `/` when the model is directly fetched from the `get`s. After each traversal, the
path gets a new element. Following the configuration, here are a few examples:

- `/versions` would match the association named `versions of the root `User`
- `versions` without the leading `/` would match any associations named `versions`
- `posts/related_posts` would match any `related_posts` following a `posts` association

By using those paths, it is possible to control the way the traversal of the association-graph.

## TODO

- Select precisely the relations to follow
- Improve the CLI in order to specify a `get` from the command line
- Support `has_and_belongs_to_many` associations

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/nicoolas25/cherry_pick.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


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

    <META HTTP-EQUIV="Cache-Control" CONTENT="no-store, no-cache, must-revalidate">
    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8" lang="en">
    <meta name="robots" content="none">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <link rel="stylesheet" type="text/css" media="all" href="../DefaultCSS/s.css">
    <title>External Code Formatter</title>

External Code Formatter

External Code Formatter is a plugin for integrating Eclipse's code formatter, as well as
                any other command line tools for code formatting, into IntelliJ IDEA. This solves the
                problem of maintaining a common code style in a team, where both IDEA and Eclipse are used.

Configuring External Code Formatter

Copyright © 2007-2009 Esko Luontola. All rights reserved


text:
package ar.com.larreta.stepper.messages;

public class MappingEntry extends JSONable {

	private String methods;
	private String patterns;
	private String produces;

	public String getMethods() {
		return methods;
	}
	public void setMethods(String methods) {
		this.methods = methods;
	}
	public String getPatterns() {
		return patterns;
	}
	public void setPatterns(String patterns) {
		this.patterns = patterns;
	}
	public String getProduces() {
		return produces;
	}
	public void setProduces(String produces) {
		this.produces = produces;
	}

}


text:
#ifndef __AGGMAX_H__
#define __AGGMAX_H__

#include "commonTable.h"
#include "value.h"
#include "aggFactory.h"

class AggMax :
  public CommonTable::AggFunc
{
public:
  AggMax();

  virtual ~AggMax();

  void
  reset();

  void
  first(ValuePtr);

  void
  process(ValuePtr);

  ValuePtr
  result();

  // This is necessary for the class to register itself with the
  // factory.
  DECLARE_PUBLIC_INITS(AggMax)

private:
  /** The current max value for this aggregate */
  ValuePtr _currentMax;

  // This is necessary for the class to register itself with the
  // factory.
  DECLARE_PRIVATE_INITS

};

#endif // AGGMAX_H


text:
<?xml version="1.0" encoding="UTF-8"?>
<artifact name="Eventstore_bpmn_task" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
    <file>BPMN_Task_Instance_Data_Publish.xml</file>
</artifact>


text:
require 'abstract_unit'

class HttpTokenAuthenticationTest < ActionController::TestCase
  class DummyController < ActionController::Base
    before_filter :authenticate, :only => :index
    before_filter :authenticate_with_request, :only => :display
    before_filter :authenticate_long_credentials, :only => :show

    def index
      render :text => "Hello Secret"
    end

    def display
      render :text => 'Definitely Maybe'
    end

    def show
      render :text => 'Only for loooooong credentials'
    end

    private

    def authenticate
      authenticate_or_request_with_http_token do |token, options|
        token == 'lifo'
      end
    end

    def authenticate_with_request
      if authenticate_with_http_token { |token, options| token == '"quote" pretty' && options[:algorithm] == 'test' }
        @logged_in = true
      else
        request_http_token_authentication("SuperSecret")
      end
    end

    def authenticate_long_credentials
      authenticate_or_request_with_http_token do |token, options|
        token == '1234567890123456789012345678901234567890' && options[:algorithm] == 'test'
      end
    end
  end

  AUTH_HEADERS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION', 'REDIRECT_X_HTTP_AUTHORIZATION']

  tests DummyController

  AUTH_HEADERS.each do |header|
    test "successful authentication with #{header.downcase}" do
      @request.env[header] = encode_credentials('lifo')
      get :index

      assert_response :success
      assert_equal 'Hello Secret', @response.body, "Authentication failed for request header #{header}"
    end
    test "successful authentication with #{header.downcase} and long credentials" do
      @request.env[header] = encode_credentials('1234567890123456789012345678901234567890', :algorithm => 'test')
      get :show

      assert_response :success
      assert_equal 'Only for loooooong credentials', @response.body, "Authentication failed for request header #{header} and long credentials"
    end
  end

  AUTH_HEADERS.each do |header|
    test "unsuccessful authentication with #{header.downcase}" do
      @request.env[header] = encode_credentials('h4x0r')
      get :index

      assert_response :unauthorized
      assert_equal "HTTP Token: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header}"
    end
    test "unsuccessful authentication with #{header.downcase} and long credentials" do
      @request.env[header] = encode_credentials('h4x0rh4x0rh4x0rh4x0rh4x0rh4x0rh4x0rh4x0r')
      get :show

      assert_response :unauthorized
      assert_equal "HTTP Token: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header} and long credentials"
    end
  end

  test "authentication request without credential" do
    get :display

    assert_response :unauthorized
    assert_equal "HTTP Token: Access denied.\n", @response.body
    assert_equal 'Token realm="SuperSecret"', @response.headers['WWW-Authenticate']
  end

  test "authentication request with invalid credential" do
    @request.env['HTTP_AUTHORIZATION'] = encode_credentials('"quote" pretty')
    get :display

    assert_response :unauthorized
    assert_equal "HTTP Token: Access denied.\n", @response.body
    assert_equal 'Token realm="SuperSecret"', @response.headers['WWW-Authenticate']
  end

  test "authentication request with valid credential" do
    @request.env['HTTP_AUTHORIZATION'] = encode_credentials('"quote" pretty', :algorithm => 'test')
    get :display

    assert_response :success
    assert assigns(:logged_in)
    assert_equal 'Definitely Maybe', @response.body
  end

  private

  def encode_credentials(token, options = {})
    ActionController::HttpAuthentication::Token.encode_credentials(token, options)
  end
end


text:
// +build linux

/*
 * Minio Cloud Storage, (C) 2016,2017 Minio, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package sys

import (
	"os"
	"syscall"

	"github.com/minio/minio/pkg/cgroup"
)

// Get the final system memory limit chosen by the user.
// by default without any configuration on a vanilla Linux
// system you would see physical RAM limit. If cgroup
// is configured at some point in time this function
// would return the memory limit chosen for the given pid.
func getMemoryLimit() (sysLimit uint64, err error) {
	if sysLimit, err = getSysinfoMemoryLimit(); err != nil {
		// Physical memory info is not accessible, just exit here.
		return 0, err
	}

	// Following code is deliberately ignoring the error.
	cGroupLimit, gerr := cgroup.GetMemoryLimit(os.Getpid())
	if gerr != nil {
		// Upon error just return system limit.
		return sysLimit, nil
	}

	// cgroup limit is lesser than system limit means
	// user wants to limit the memory usage further
	// treat cgroup limit as the system limit.
	if cGroupLimit <= sysLimit {
		sysLimit = cGroupLimit
	}

	// Final system limit.
	return sysLimit, nil

}

// Get physical RAM size of the node.
func getSysinfoMemoryLimit() (limit uint64, err error) {
	var si syscall.Sysinfo_t
	if err = syscall.Sysinfo(&si); err != nil {
		return 0, err
	}

	// Some fields in syscall.Sysinfo_t have different  integer sizes
	// in different platform architectures. Cast all fields to uint64.
	totalRAM := uint64(si.Totalram)
	unit := uint64(si.Unit)

	// Total RAM is always the multiplicative value
	// of unit size and total ram.
	limit = unit * totalRAM
	return limit, nil
}

// GetStats - return system statistics, currently only
// supported value is TotalRAM.
func GetStats() (stats Stats, err error) {
	var limit uint64
	limit, err = getMemoryLimit()
	if err != nil {
		return Stats{}, err
	}

	stats.TotalRAM = limit
	return stats, nil
}


text:
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

import { ColumnComponent } from './column.component';
import { Issue } from '../../models/issue';
import { IssuesService } from '../../services/issues.service';
import { ProjectsService } from '../../services/projects.service';

describe('ColumnComponent', () => {
  let component: ColumnComponent;
  let fixture: ComponentFixture<ColumnComponent>;
  let fakeIssuesService = jasmine.createSpyObj('IssuesService', ['listIssues']);
  let fakeProjectsService = jasmine.createSpyObj('ProjectsService', ['getColorByProjectId', 'getName']);

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ColumnComponent ],
      providers: [
        { provide: IssuesService , useValue: fakeIssuesService },
        { provide: ProjectsService , useValue: fakeProjectsService },
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fakeIssuesService.listIssues.calls.reset();
    fakeProjectsService.getColorByProjectId.calls.reset();
    fixture = TestBed.createComponent(ColumnComponent);
    component = fixture.componentInstance;
    component.projects = Observable.of([]);
    fixture.detectChanges();
  });

  it('should get issues on refresh', () => {
    let issue = new Issue();
    issue.title = 'lala';
    issue.iid = '14';
    let issues = [issue];
    fakeIssuesService.listIssues.and.returnValue(Observable.of(issues));
    component = new ColumnComponent(fakeIssuesService, fakeProjectsService);
    component.label = 'labelle';

    component.refresh();
    expect(component.issues).toEqual(issues);
    expect(fakeIssuesService.listIssues).toHaveBeenCalledWith('labelle');
  });
});


text:
namespace rx
{
NativeWindow9::NativeWindow9(EGLNativeWindowType window) : NativeWindowD3D(window)
{
}

bool NativeWindow9::initialize()
{
    return true;
}

bool NativeWindow9::getClientRect(LPRECT rect) const
{
    return GetClientRect(getNativeWindow(), rect) == TRUE;
}

bool NativeWindow9::isIconic() const
{
    return IsIconic(getNativeWindow()) == TRUE;
}

// static
bool NativeWindow9::IsValidNativeWindow(EGLNativeWindowType window)
{
    return IsWindow(window) == TRUE;
}

}  // namespace rx