text:
require 'dfp_api'
require 'dfp_api_statement'

API_VERSION = :v201502

def get_licas_by_statement()
  # Get DfpApi instance and load configuration from ~/dfp_api.yml.
  dfp = DfpApi::Api.new

  # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
  # the configuration file or provide your own logger:
  # dfp.logger = Logger.new('dfp_xml.log')

  # Get the LineItemCreativeAssociationService.
  lica_service = dfp.service(:LineItemCreativeAssociationService, API_VERSION)

  # Set the line item to get LICAs by.
  line_item_id = 'INSERT_LINE_ITEM_ID_HERE'.to_i

  # Create a statement to only select LICAs for the given line item ID.
  statement = DfpApiStatement::FilterStatement.new(
      'WHERE lineItemId = :line_item_id ORDER BY lineItemId, orderId ASC',
      [
          {:key => 'line_item_id',
           :value => {:value => line_item_id, :xsi_type => 'NumberValue'}}
      ]
  )

  # Get LICAs by statement.
  page = lica_service.get_line_item_creative_associations_by_statement(
      statement.toStatement())

  if page and page[:results]
    page[:results].each_with_index do |lica, index|
      puts "%d) LICA with line item ID: %d, creative ID: %d and status: %s." %
          [index + statement.offset,
           lica[:line_item_id], lica[:creative_id], lica[:status]]
    end
  end

  # Print a footer.
  if page.include?(:total_result_set_size)
    puts "Number of results found: %d" % page[:total_result_set_size]
  end
end

if __FILE__ == $0
  begin
    get_licas_by_statement()

  # HTTP errors.
  rescue AdsCommon::Errors::HttpError => e
    puts "HTTP Error: %s" % e

  # API errors.
  rescue DfpApi::Errors::ApiException => e
    puts "Message: %s" % e.message
    puts 'Errors:'
    e.errors.each_with_index do |error, index|
      puts "\tError [%d]:" % (index + 1)
      error.each do |field, value|
        puts "\t\t%s: %s" % [field, value]
      end
    end
  end
end


text:
<?php
/**
 * Template part for displaying a message that posts cannot be found
 *
 * @link https://codex.wordpress.org/Template_Hierarchy
 *
 * @package merry-go
 */

?>

<?php esc_html_e( 'Nothing Found', 'merry-go' ); ?>

		<?php
		if ( is_home() && current_user_can( 'publish_posts' ) ) : ?>

<?php
				printf(
					wp_kses(
						/* translators: 1: link to WP admin new post page. */
						__( 'Ready to publish your first post? Get started here.', 'merry-go' ),
						array(
							'a' => array(
								'href' => array(),
							),
						)
					),
					esc_url( admin_url( 'post-new.php' ) )
				);
			?>

		<?php elseif ( is_search() ) : ?>

<?php esc_html_e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'merry-go' ); ?>

			<?php
				get_search_form();

		else : ?>

<?php esc_html_e( 'It seems we can’t find what you’re looking for. Perhaps searching can help.', 'merry-go' ); ?>

			<?php
				get_search_form();

		endif; ?>

redpajama_set_name: RedPajamaGithub


text:
// -*- c++ -*-
// Generated by gmmproc 2.46.2 -- DO NOT MODIFY!
#ifndef _GIOMM_SETTINGSSCHEMASOURCE_P_H
#define _GIOMM_SETTINGSSCHEMASOURCE_P_H

#include <glibmm/private/object_p.h>

#endif /* _GIOMM_SETTINGSSCHEMASOURCE_P_H */


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <bool name="false_bool_value">false</bool>
  <bool name="true_bool_value">true</bool>
  <bool name="zero_is_false">0</bool>
  <bool name="integers_are_true">7</bool>
  <bool name="reference_to_true">@true_bool_value</bool>
  <item name="true_as_item" type="bool">true</item>
  <bool name="different_resource_boolean">false</bool>
  <bool name="typed_array_true">true</bool>
</resources>


text:
import { FullscreenService } from './fullscreen-service/fullscreen.service';
import { Dimensions } from './models/dimensions';
import { ElementRef } from '@angular/core';
import * as i0 from "@angular/core";
export declare class MimeDomHelper {
    private fullscreen;
    constructor(fullscreen: FullscreenService);
    getBoundingClientRect(el: ElementRef): Dimensions;
    isDocumentInFullScreenMode(): boolean;
    toggleFullscreen(): void;
    setFocusOnViewer(): void;
    private createFullscreenDimensions;
    private createDimensions;
    private getFullscreenWidth;
    private getFullscreenHeight;
    static ɵfac: i0.ɵɵFactoryDeclaration<MimeDomHelper, never>;
    static ɵprov: i0.ɵɵInjectableDeclaration<MimeDomHelper>;
}


text:
package org.apache.bigtop.bazaar.datagenerator.moleculardynamics;

import static org.junit.Assert.assertEquals;

import java.util.Random;

import org.apache.bigtop.bazaar.datagenerator.moleculardynamics.Constants;
import org.apache.bigtop.bazaar.datagenerator.moleculardynamics.Vec2D;
import org.apache.bigtop.bazaar.datagenerator.moleculardynamics.VelocitySampler;
import org.junit.Test;

public class TestVelocitySampler
{
	static final double EPS = 1e-3;

	@Test
	public void testKineticEnergy()
	{
		final int N_SAMPLES = 100000;
		final int N_PARTICLES = 100;
		final double mass = 2.0;
		final double temperature = 300.0; // Kelvin

		/*
		 * From kinetic theory:
		 * avg KE = D / 2 * k_B * T
		 *
		 * where KE = kinetic energy
		 * T = temperature
		 * D = degrees of freedom (2 * number of particles in our case)
		 * k_B = Boltzmann's constant
		 */
		final double expectedKE = N_PARTICLES * Constants.BOLTZMANN * temperature;

		Random rng = new Random();
		VelocitySampler sampler = new VelocitySampler(temperature, mass, rng);

		double averageKE = 0.0;
		for(int i = 0; i < N_SAMPLES; i++)
		{
			double totalKE = 0.0;
			for(int j = 0; j < N_PARTICLES; j++)
			{
				Vec2D velocities = sampler.sample();
				totalKE += 0.5 * mass * velocities.squaredNorm();
			}

			averageKE += totalKE / (double) N_SAMPLES;
		}

		double percentError = (expectedKE - averageKE) / expectedKE;
		assertEquals("Observed KE: " + averageKE + ", expected KE: " + expectedKE + ", percent error: " + percentError,
				0.0, percentError, EPS);
	}
}


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

      Intro to Ruby & Web Dev: The Object Model · grit| commit

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/hyde.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-144-precomposed.png">
                                 <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

          grit| commit

daily learnings as a ruby dev

      Home

            About

            Archive

© 2015. All rights reserved.

Intro to Ruby & Web Dev: The Object Model

  10 Sep 2014

What is OOP?

A way for progammers to deal with large, complex systems.
One small change could be catastrophic in terms of the impact it could have on relevant parts within the system.
Prorgrammers needed to create containers for code that could be changed without impacting the entire program. To section off code that performs certain procedures so that it became an interation of many small parts as opposed to one massive blob of code dependenies.

Encapsulation

is hiding peices of functionality and making it unavailable to the rest of the code base. It is form of data protection so that the data cannot change or be manipulated without intention. This allows your code to achieve new levels of complexity creating objects and exposin interfaces (i.e. methods) that allow these methods to interact.

Polymorphism

ability for data to be represented as many different types.
Allows pre-written code to be used for different purposes.

Inheritance

class inherits the behavior of another class -- referred to as the superclass.
This gives Ruby Programmers the ability to define large usabilty and smaller Subclass, with more defined, detailed behavior.

Modules

Modules are similar to classes in the they contain shared behavior, however you cannot create an object with a module. A module, must be mixed in with a class using the reserved word: include. This is called a "mixin" and after used in a module, the behanviors declared in the module are available to the class and its objects.

What are objects?

In Ruby, everything is an object.
Objects are created from classes.

Class

Ruby defines attributes and behaviors of its objects in classes

Instantation

creating an object/instance of a class

Module

A collection of behaviors that useable by other classes, called mixins using the word "include"

Example:
Create a class, create an object, use a mixin.

module Speak
  def speak(sound)
    puts #{sound}
  end
end

class HumanBeing
  include Speak
end

jamela = Humanbeing.new

jamela.speak('Hello!')

Related Posts

            Build Robust & Production Quality Applications - Lesson 8: - Mocks & Stubs
            18 Jul 2015

            Build Robust & Production Quality Applications - Lesson 8: - Mocks & Stubs
            17 Jul 2015

            Build Robust & Production Quality Applications - Lesson 8: - Mocking
            16 Jul 2015


text:
using System;
using System.Net;

namespace Cimpress.Extensions.Http
{
    public class NotSuccessHttpResponseException : Exception
    {
        HttpStatusCode StatusCode { get; }

        public NotSuccessHttpResponseException(string message, HttpStatusCode statusCode) : base(message)
        {
            StatusCode = statusCode;
        }
    }
}


text:
import { isDev, isTest } from './server';

const devDB = 'mongodb://localhost:27017/pb-db-dev';
const testDB = 'mongodb://localhost:27017/pb-db-test';
const prodDB = 'mongodb://localhost:27017/pb-db-prod';

export const mongoURI = process.env.MONGODB_URI || (isDev ? devDB : isTest ? testDB : prodDB);


text:
import pytest
import os
import json
from cosrlib.document.html import HTMLDocument
from tests.testdata.html_page_samples import SAMPLES

NEWSPAPER_DIR = "tests/testdata/html_newspaper_testcases"
NEWSPAPER_TESTCASES = os.listdir("%s/html/" % NEWSPAPER_DIR)

MOZILLA_READABILITY_DIR = "tests/testdata/html_mozilla_readability_testcases"
MOZILLA_READABILITY_TESTCASES = os.listdir(MOZILLA_READABILITY_DIR)

@pytest.mark.parametrize(("sample_name", ), [[name] for name in SAMPLES.iterkeys()])
def test_parsing_samples(sample_name):
    metadata = SAMPLES[sample_name]

    sample_file = "tests/testdata/html_page_samples/%s" % sample_name
    with open(sample_file, "r") as f:
        html = f.read()

        page = HTMLDocument(html).parse()

        if "title" in metadata:
            assert metadata["title"] == page.get_title()

        if "summary" in metadata:
            assert metadata["summary"] == page.get_summary()

        # for k, g in sorted(page.get_word_groups().items()):
        #   print k, g

        words = page.get_all_words()

        # Uncomment this to debug
        if metadata.get("debug"):
            print words

        for word in metadata.get("assert_words_missing", []):
            assert word not in words

        for word in metadata.get("assert_words", []):
            assert word in words

@pytest.mark.parametrize("test_name", NEWSPAPER_TESTCASES)
def _test_newspaper_testcases(test_name):
    with open("%s/html/%s" % (NEWSPAPER_DIR, test_name)) as fhtml:
        with open("%s/text/%s" % (NEWSPAPER_DIR, test_name.replace(".html", ".txt"))) as ftxt:
            html = fhtml.read()
            txt = ftxt.read()
            word_groups = txt.split("\n\n")

            doc = HTMLDocument(html).parse()

            doc_word_groups = []
            for wg in doc.analysis["word_groups"]:
                doc_word_groups.append(wg[0])

            assert doc_word_groups == word_groups

# TODO: also use these in formatting.py for the titles in the metadata files
@pytest.mark.parametrize("test_name", MOZILLA_READABILITY_TESTCASES)
def _test_mozilla_readability_testcases(test_name):
    with open("%s/%s/source.html" % (MOZILLA_READABILITY_DIR, test_name)) as fhtml:
        with open("%s/%s/expected.html" % (MOZILLA_READABILITY_DIR, test_name)) as fsimple:
            html = fhtml.read()
            simple = fsimple.read()

            doc = HTMLDocument(html).parse()
            doc_simple = HTMLDocument(simple).parse()

            doc_word_groups = []
            for wg in doc.analysis["word_groups"]:
                doc_word_groups.append(wg[0])

            doc_simple_word_groups = []
            for wg in doc_simple.analysis["word_groups"]:
                doc_simple_word_groups.append(wg[0])

            assert doc_word_groups == doc_simple_word_groups


text:
package org.apache.reef.tests.rack.awareness;
import org.apache.reef.runtime.local.client.parameters.RackNames;
import org.apache.reef.tang.annotations.Name;
import org.apache.reef.tang.annotations.NamedParameter;

@NamedParameter(default_value = RackNames.DEFAULT_RACK_NAME, short_name = "rack")
public class RackNameParameter implements Name<String> {
}


text:
function getMediaFilePath(mediaItem) {
  return "ext-content/" + mediaItem.dir + '/' + mediaItem.title +
    mediaItem.file_ext;
}

function renderPdf(mediaItem) {
  // Note embed nor iframe works great to render pdf. So, this is workaround until better alternative is found.
  window.location = getMediaFilePath(mediaItem);
}

/*
 * Load media_list from the json file
 */
$.getJSON("data/media_files_list.json", function(result) {
  var mediaFiles = $(result).filter(function() {
    return this.category == "documents";
  });
  $.each(mediaFiles, function(i, mediaItem) {
    var btn = $("<button></button>", {
      "type": "button",
      "class": "btn btn-primary btn-lg gradient round btn-block ellipsis",
      "value": mediaItem
    }).appendTo("#files_list");
    btn.html(mediaItem.title);
    btn.on("click", function() {
      renderPdf(mediaItem);
    });
  });
}); // end of getJSON()


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRefTingkatKesulitanSoalTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('ref_tingkat_kesulitan_soal', function (Blueprint $table) {
            $table->increments('id');
            $table->string('nama'); //nama level kesulitan soal
            $table->string('keterangan'); //keterangan mengenai level soal
            $table->timestamps();
        });

        $data_insert = [
              ['id'=>1, 'nama' => 'Sulit'],
              ['id' => 2, 'nama' => 'Sedang'],
              ['id' => 3, 'nama' => 'Mudah']
            ];
        \DB::table('ref_tingkat_kesulitan_soal')->insert($data_insert);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('ref_tingkat_kesulitan_soal');
    }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>

//TOC structure as defined by OMAP35XX TRM.
typedef struct {
  unsigned int  Start;
  unsigned int  Size;
  unsigned int  Reserved1;
  unsigned int  Reserved2;
  unsigned int  Reserved3;
  unsigned char Filename[12];
} TOC_DATA;

//NOTE: OMAP3430 TRM has CHSETTINGS and CHRAM structures.
typedef struct {
  unsigned int   SectionKey;
  unsigned char  Valid;
  unsigned char  Version;
  unsigned short Reserved;
  unsigned int   Flags;
  unsigned int   PRM_CLKSRC_CTRL;
  unsigned int   PRM_CLKSEL;
  unsigned int   CM_CLKSEL1_EMU;
  unsigned int   CM_CLKSEL_CORE;
  unsigned int   CM_CLKSEL_WKUP;
  unsigned int   CM_CLKEN_PLL_DPLL3;
  unsigned int   CM_AUTOIDLE_PLL_DPLL3;
  unsigned int   CM_CLKSEL1_PLL;
  unsigned int   CM_CLKEN_PLL_DPLL4;
  unsigned int   CM_AUTOIDLE_PLL_DPLL4;
  unsigned int   CM_CLKSEL2_PLL;
  unsigned int   CM_CLKSEL3_PLL;
  unsigned int   CM_CLKEN_PLL_MPU;
  unsigned int   CM_AUTOIDLE_PLL_MPU;
  unsigned int   CM_CLKSEL1_PLL_MPU;
  unsigned int   CM_CLKSEL2_PLL_MPU;
  unsigned int   CM_CLKSTCTRL_MPU;
} CHSETTINGS_DATA;

typedef struct {
  unsigned int   SectionKey;
  unsigned char  Valid;
  unsigned char  Reserved1;
  unsigned char  Reserved2;
  unsigned char  Reserved3;
  unsigned short SDRC_SYSCONFIG_LSB;
  unsigned short SDRC_CS_CFG_LSB;
  unsigned short SDRC_SHARING_LSB;
  unsigned short SDRC_ERR_TYPE_LSB;
  unsigned int   SDRC_DLLA_CTRL;
  unsigned short Reserved4;
  unsigned short Reserved5;
  unsigned int   SDRC_POWER;
  unsigned short MEMORY_TYPE_CS0;
  unsigned short Reserved6;
  unsigned int   SDRC_MCFG_0;
  unsigned short SDRC_MR_0_LSB;
  unsigned short SDRC_EMR1_0_LSB;
  unsigned short SDRC_EMR2_0_LSB;
  unsigned short SDRC_EMR3_0_LSB;
  unsigned int   SDRC_ACTIM_CTRLA_0;
  unsigned int   SDRC_ACTIM_CTRLB_0;
  unsigned int   SDRC_RFRCTRL_0;
  unsigned short MEMORY_TYPE_CS1;
  unsigned short Reserved7;
  unsigned int   SDRC_MCFG_1;
  unsigned short SDRC_MR_1_LSB;
  unsigned short SDRC_EMR1_1_LSB;
  unsigned short SDRC_EMR2_1_LSB;
  unsigned short SDRC_EMR3_1_LSB;
  unsigned int   SDRC_ACTIM_CTRLA_1;
  unsigned int   SDRC_ACTIM_CTRLB_1;
  unsigned int   SDRC_RFRCTRL_1;
  unsigned int   Reserved8;
  unsigned short Flags;
  unsigned short Reserved9;
} CHRAM_DATA;

#define CHSETTINGS_START      0xA0
#define CHSETTINGS_SIZE       0x50
#define CHRAM_START           0xF0
#define CHRAM_SIZE            0x5C
#define CLOSING_TOC_ITEM_SIZE 4

unsigned char gConfigurationHeader[512];
unsigned int  gImageExecutionAddress;
char          *gInputImageFile = NULL;
char          *gOutputImageFile = NULL;
char          *gDataFile = NULL;

static
void
PrintUsage (
  void
  )
{
  printf("Usage..\n");
}

static
void
PopulateCHSETTINGSData (
  FILE            *DataFile,
  CHSETTINGS_DATA *CHSETTINGSData
  )
{
  unsigned int Value;

  CHSETTINGSData->SectionKey            = 0xC0C0C0C1;
  CHSETTINGSData->Valid                 = 0x1;
  CHSETTINGSData->Version               = 0x1;
  CHSETTINGSData->Reserved              = 0x00;
  CHSETTINGSData->Flags                 = 0x050001FD;

  //General clock settings.
  fscanf(DataFile, "PRM_CLKSRC_CTRL=0x%08x\n", &Value);
  CHSETTINGSData->PRM_CLKSRC_CTRL = Value;
  fscanf(DataFile, "PRM_CLKSEL=0x%08x\n", &Value);
  CHSETTINGSData->PRM_CLKSEL = Value;
  fscanf(DataFile, "CM_CLKSEL1_EMU=0x%08x\n", &Value);
  CHSETTINGSData->CM_CLKSEL1_EMU = Value;

  //Clock configuration
  fscanf(DataFile, "CM_CLKSEL_CORE=0x%08x\n", &Value);
  CHSETTINGSData->CM_CLKSEL_CORE = Value;
  fscanf(DataFile, "CM_CLKSEL_WKUP=0x%08x\n", &Value);
  CHSETTINGSData->CM_CLKSEL_WKUP = Value;

  //DPLL3 (Core) settings
  fscanf(DataFile, "CM_CLKEN_PLL_DPLL3=0x%08x\n", &Value);
  CHSETTINGSData->CM_CLKEN_PLL_DPLL3 = Value;
  fscanf(DataFile, "CM_AUTOIDLE_PLL_DPLL3=0x%08x\n", &Value);
  CHSETTINGSData->CM_AUTOIDLE_PLL_DPLL3 = Value;
  fscanf(DataFile, "CM_CLKSEL1_PLL=0x%08x\n", &Value);
  CHSETTINGSData->CM_CLKSEL1_PLL = Value;

  //DPLL4 (Peripheral) settings
  fscanf(DataFile, "CM_CLKEN_PLL_DPLL4=0x%08x\n", &Value);
  CHSETTINGSData->CM_CLKEN_PLL_DPLL4 = Value;
  fscanf(DataFile, "CM_AUTOIDLE_PLL_DPLL4=0x%08x\n", &Value);
  CHSETTINGSData->CM_AUTOIDLE_PLL_DPLL4 = Value;
  fscanf(DataFile, "CM_CLKSEL2_PLL=0x%08x\n", &Value);
  CHSETTINGSData->CM_CLKSEL2_PLL = Value;
  fscanf(DataFile, "CM_CLKSEL3_PLL=0x%08x\n", &Value);
  CHSETTINGSData->CM_CLKSEL3_PLL = Value;

  //DPLL1 (MPU) settings
  fscanf(DataFile, "CM_CLKEN_PLL_MPU=0x%08x\n", &Value);
  CHSETTINGSData->CM_CLKEN_PLL_MPU = Value;
  fscanf(DataFile, "CM_AUTOIDLE_PLL_MPU=0x%08x\n", &Value);
  CHSETTINGSData->CM_AUTOIDLE_PLL_MPU = Value;
  fscanf(DataFile, "CM_CLKSEL1_PLL_MPU=0x%08x\n", &Value);
  CHSETTINGSData->CM_CLKSEL1_PLL_MPU = Value;
  fscanf(DataFile, "CM_CLKSEL2_PLL_MPU=0x%08x\n", &Value);
  CHSETTINGSData->CM_CLKSEL2_PLL_MPU = Value;
  fscanf(DataFile, "CM_CLKSTCTRL_MPU=0x%08x\n", &Value);
  CHSETTINGSData->CM_CLKSTCTRL_MPU = Value;
}

static
void
PopulateCHRAMData (
  FILE       *DataFile,
  CHRAM_DATA *CHRAMData
  )
{
  unsigned int Value;

  CHRAMData->SectionKey         = 0xC0C0C0C2;
  CHRAMData->Valid              = 0x1;

  fscanf(DataFile, "SDRC_SYSCONFIG_LSB=0x%04x\n", &Value);
  CHRAMData->SDRC_SYSCONFIG_LSB = Value;
  fscanf(DataFile, "SDRC_CS_CFG_LSB=0x%04x\n", &Value);
  CHRAMData->SDRC_CS_CFG_LSB    = Value;
  fscanf(DataFile, "SDRC_SHARING_LSB=0x%04x\n", &Value);
  CHRAMData->SDRC_SHARING_LSB   = Value;
  fscanf(DataFile, "SDRC_ERR_TYPE_LSB=0x%04x\n", &Value);
  CHRAMData->SDRC_ERR_TYPE_LSB  = Value;
  fscanf(DataFile, "SDRC_DLLA_CTRL=0x%08x\n", &Value);
  CHRAMData->SDRC_DLLA_CTRL     = Value;
  fscanf(DataFile, "SDRC_POWER=0x%08x\n", &Value);
  CHRAMData->SDRC_POWER         = Value;
  fscanf(DataFile, "MEMORY_TYPE_CS0=0x%04x\n", &Value);
  CHRAMData->MEMORY_TYPE_CS0    = Value;
  fscanf(DataFile, "SDRC_MCFG_0=0x%08x\n", &Value);
  CHRAMData->SDRC_MCFG_0        = Value;
  fscanf(DataFile, "SDRC_MR_0_LSB=0x%04x\n", &Value);
  CHRAMData->SDRC_MR_0_LSB      = Value;
  fscanf(DataFile, "SDRC_EMR1_0_LSB=0x%04x\n", &Value);
  CHRAMData->SDRC_EMR1_0_LSB    = Value;
  fscanf(DataFile, "SDRC_EMR2_0_LSB=0x%04x\n", &Value);
  CHRAMData->SDRC_EMR2_0_LSB    = Value;
  fscanf(DataFile, "SDRC_EMR3_0_LSB=0x%04x\n", &Value);
  CHRAMData->SDRC_EMR3_0_LSB    = Value;
  fscanf(DataFile, "SDRC_ACTIM_CTRLA_0=0x%08x\n", &Value);
  CHRAMData->SDRC_ACTIM_CTRLA_0 = Value;
  fscanf(DataFile, "SDRC_ACTIM_CTRLB_0=0x%08x\n", &Value);
  CHRAMData->SDRC_ACTIM_CTRLB_0 = Value;
  fscanf(DataFile, "SDRC_RFRCTRL_0=0x%08x\n", &Value);
  CHRAMData->SDRC_RFRCTRL_0     = Value;
  fscanf(DataFile, "MEMORY_TYPE_CS1=0x%04x\n", &Value);
  CHRAMData->MEMORY_TYPE_CS1    = Value;
  fscanf(DataFile, "SDRC_MCFG_1=0x%08x\n", &Value);
  CHRAMData->SDRC_MCFG_1        = Value;
  fscanf(DataFile, "SDRC_MR_1_LSB=0x%04x\n", &Value);
  CHRAMData->SDRC_MR_1_LSB      = Value;
  fscanf(DataFile, "SDRC_EMR1_1_LSB=0x%04x\n", &Value);
  CHRAMData->SDRC_EMR1_1_LSB    = Value;
  fscanf(DataFile, "SDRC_EMR2_1_LSB=0x%04x\n", &Value);
  CHRAMData->SDRC_EMR2_1_LSB    = Value;
  fscanf(DataFile, "SDRC_EMR3_1_LSB=0x%04x\n", &Value);
  CHRAMData->SDRC_EMR3_1_LSB    = Value;
  fscanf(DataFile, "SDRC_ACTIM_CTRLA_1=0x%08x\n", &Value);
  CHRAMData->SDRC_ACTIM_CTRLA_1 = Value;
  fscanf(DataFile, "SDRC_ACTIM_CTRLB_1=0x%08x\n", &Value);
  CHRAMData->SDRC_ACTIM_CTRLB_1 = Value;
  fscanf(DataFile, "SDRC_RFRCTRL_1=0x%08x\n", &Value);
  CHRAMData->SDRC_RFRCTRL_1     = Value;

  CHRAMData->Flags              = 0x0003;
}

static
void
PrepareConfigurationHeader (
  void
  )
{
  TOC_DATA        Toc;
  CHSETTINGS_DATA CHSETTINGSData;
  CHRAM_DATA      CHRAMData;
  unsigned int    ConfigurationHdrOffset = 0;
  FILE            *DataFile;

  // Open data file
  DataFile = fopen(gDataFile, "rb");
  if (DataFile == NULL) {
    fprintf(stderr, "Can't open data file %s.\n", gDataFile);
    exit(1);
  }

  //Initialize configuration header.
  memset(gConfigurationHeader, 0x00, sizeof(gConfigurationHeader));

  //CHSETTINGS TOC
  memset(&Toc, 0x00, sizeof(TOC_DATA));
  Toc.Start = CHSETTINGS_START;
  Toc.Size = CHSETTINGS_SIZE;
  strcpy((char *)Toc.Filename, (const char *)"CHSETTINGS");
  memcpy(gConfigurationHeader + ConfigurationHdrOffset, &Toc, sizeof(TOC_DATA));

  //Populate CHSETTINGS Data
  memset(&CHSETTINGSData, 0x00, sizeof(CHSETTINGS_DATA));
  PopulateCHSETTINGSData(DataFile, &CHSETTINGSData);
  memcpy(gConfigurationHeader + Toc.Start, &CHSETTINGSData, Toc.Size);

  //Adjust ConfigurationHdrOffset to point to next TOC
  ConfigurationHdrOffset += sizeof(TOC_DATA);

  //CHRAM TOC
  memset(&Toc, 0x00, sizeof(TOC_DATA));
  Toc.Start = CHRAM_START;
  Toc.Size = CHRAM_SIZE;
  strcpy((char *)Toc.Filename, (const char *)"CHRAM");
  memcpy(gConfigurationHeader + ConfigurationHdrOffset, &Toc, sizeof(TOC_DATA));

  //Populate CHRAM Data
  memset(&CHRAMData, 0x00, sizeof(CHRAM_DATA));
  PopulateCHRAMData(DataFile, &CHRAMData);
  memcpy(gConfigurationHeader + Toc.Start, &CHRAMData, Toc.Size);

  //Adjust ConfigurationHdrOffset to point to next TOC
  ConfigurationHdrOffset += sizeof(TOC_DATA);

  //Closing TOC item
  memset(gConfigurationHeader + ConfigurationHdrOffset, 0xFF, CLOSING_TOC_ITEM_SIZE);
  ConfigurationHdrOffset += CLOSING_TOC_ITEM_SIZE;

  // Close data file
  fclose(DataFile);
}

static
void
ConstructImage (
  void
  )
{
  FILE         *InputFile;
  FILE         *OutputFile;
  unsigned int InputImageFileSize;
  struct       stat FileStat;
  char         Ch;
  unsigned int i;

  InputFile = fopen(gInputImageFile, "rb");
  if (InputFile == NULL) {
    fprintf(stderr, "Can't open input file.\n");
    exit(0);
  }

  // Get the size of the input image.
  fstat(fileno(InputFile), &FileStat);
  InputImageFileSize = FileStat.st_size;

  OutputFile = fopen(gOutputImageFile, "wb");
  if (OutputFile == NULL) {
    fprintf(stderr, "Can't open output file %s.\n", gOutputImageFile);
    exit(0);
  }

  // Write Configuration header
  fwrite(gConfigurationHeader, 1, sizeof(gConfigurationHeader), OutputFile);

  // Write image header (Input image size, execution address)
  fwrite(&InputImageFileSize, 1, 4, OutputFile);
  fwrite(&gImageExecutionAddress, 1, 4, OutputFile);

  // Copy input image to the output file.
  for (i = 0; i < InputImageFileSize; i++) {
    fread(&Ch, 1, 1, InputFile);
    fwrite(&Ch, 1, 1, OutputFile);
  }

  fclose(InputFile);
  fclose(OutputFile);
}

int
main (
  int    argc,
  char** argv
  )
{
  char          Ch;
  unsigned char *ptr;
  int           i;
  int           TwoArg;

  if (argc == 1) {
    PrintUsage ();
    exit(1);
  }

  for (i=1; i < argc; i++) {
    if (argv[i][0] == '-') {
      // TwoArg TRUE -E 0x123, FALSE -E0x1234
      TwoArg = (argv[i][2] != ' ');
      switch (argv[i][1]) {
        case 'E': /* Image execution address */
          gImageExecutionAddress = strtoul (TwoArg ? argv[i+1] : &argv[i][2], (char **)&ptr, 16);
          break;

        case 'I': /* Input image file */
          gInputImageFile = TwoArg ? argv[i+1] : &argv[i][2];
          break;

        case 'O': /* Output image file */
          gOutputImageFile = TwoArg ? argv[i+1] : &argv[i][2];
          break;

        case 'D': /* Data file */
          gDataFile = TwoArg ? argv[i+1] : &argv[i][2];
          break;

        default:
          abort ();
      }
    }
  }

  //Prepare configuration header
  PrepareConfigurationHeader ();

  //Build image with configuration header + image header + image
  ConstructImage ();

  return 0;
}


text:
<?php
/**
 *
 * This file is part of the Aura project for PHP.
 *
 * @package Aura.Uri
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 *
 */
namespace Aura\Uri;

/**
 *
 * Object representation of the Public Suffix List
 *
 * @package Aura.Uri
 *
 */
class PublicSuffixList
{
    /**
     *
     * Public suffix list data.
     *
     * @var array
     *
     */
    protected $psl;

    /**
     *
     * Constructor.
     *
     * @param array $list Array representation of the Public Suffix List
     *
     */
    public function __construct(array $list)
    {
        $this->psl = $list;
    }

    /**
     * Returns the public suffix portion of provided host
     *
     * @param  string $host host
     * @return string public suffix
     */
    public function getPublicSuffix($host)
    {
        if (strpos($host, '.') === 0) {
            return null;
        }

        if (strpos($host, '.') === false) {
            return null;
        }

        $host = strtolower($host);
        $parts = array_reverse(explode('.', $host));
        $publicSuffix = array();
        $psl = $this->psl;

        foreach ($parts as $part) {
            if (array_key_exists($part, $psl)
                && array_key_exists('!', $psl[$part])) {
                break;
            }

            if (array_key_exists($part, $psl)) {
                array_unshift($publicSuffix, $part);
                $psl = $psl[$part];
                continue;
            }

            if (array_key_exists('*', $psl)) {
                array_unshift($publicSuffix, $part);
                $psl = $psl['*'];
                continue;
            }

            // Avoids improper parsing when $host's subdomain + public suffix ===
            // a valid public suffix (e.g. host 'us.example.com' and public suffix 'us.com')
            break;
        }

        // Apply algorithm rule #2: If no rules match, the prevailing rule is "*".
        if (empty($publicSuffix)) {
            $publicSuffix[0] = $parts[0];
        }

        return implode('.', array_filter($publicSuffix, 'strlen'));
    }

    /**
     * Returns registerable domain portion of provided host
     *
     * Per the test cases provided by Mozilla
     * (http://mxr.mozilla.org/mozilla-central/source/netwerk/test/unit/data/test_psl.txt?raw=1),
     * this method should return null if the domain provided is a public suffix.
     *
     * @param  string $host host
     * @return string registerable domain
     */
    public function getRegisterableDomain($host)
    {
        if (strpos($host, '.') === false) {
            return null;
        }

        $host = strtolower($host);
        $publicSuffix = $this->getPublicSuffix($host);

        if ($publicSuffix === null || $host == $publicSuffix) {
            return null;
        }

        $publicSuffixParts = array_reverse(explode('.', $publicSuffix));
        $hostParts = array_reverse(explode('.', $host));
        $registerableDomainParts = array_slice($hostParts, 0, count($publicSuffixParts) + 1);

        return implode('.', array_reverse($registerableDomainParts));
    }

    /**
     * Returns the subdomain portion of provided host
     *
     * @param  string $host host
     * @return string subdomain
     */
    public function getSubdomain($host)
    {
        $host = strtolower($host);
        $registerableDomain = $this->getRegisterableDomain($host);

        if ($registerableDomain === null || $host == $registerableDomain) {
            return null;
        }

        $registerableDomainParts = array_reverse(explode('.', $registerableDomain));
        $hostParts = array_reverse(explode('.', $host));
        $subdomainParts = array_slice($hostParts, count($registerableDomainParts));

        return implode('.', array_reverse($subdomainParts));
    }
}


text:
package de.intarsys.tools.functor;

import java.util.regex.Pattern;

import de.intarsys.tools.string.StringTools;

/**
 * A common superclass for {@link IDeclarationElement} instances. This one has a
 * very simple implementation for modifiers. Only the presence of the modifier
 * string fragment in declared modifier string is checked.
 *
 */
abstract public class DeclarationElement extends Declaration implements
		IDeclarationElement {

	public static boolean validateName(String name) {
		if (StringTools.isEmpty(name)) {
			return false;
		}
		return Pattern.matches("[\\.]|[a-zA-Z0-9_]+", name);
	}

	public static boolean validatePath(String name) {
		if (StringTools.isEmpty(name)) {
			return false;
		}
		return Pattern.matches("([a-zA-Z0-9_]+\\.)+", name);
	}

	private String modifierString;

	private String name;

	private String description;

	public DeclarationElement(Object declarationContext, String name,
			String modifiers) {
		this(declarationContext, name, modifiers, null);
	}

	public DeclarationElement(Object declarationContext, String name,
			String modifiers, String description) {
		super(declarationContext);
		this.modifierString = modifiers;
		this.name = name;
		this.description = description;
	}

	public void addModifier(String modifier) {
		if (StringTools.isEmpty(modifierString)) {
			modifierString = modifier;
			return;
		}
		if (modifierString.indexOf(modifier) >= 0) {
			return;
		}
		modifierString = modifierString + ";" + modifier;
	}

	public String getDescription() {
		return description;
	}

	public String[] getModifiers() {
		if (StringTools.isEmpty(modifierString)) {
			return new String[0];
		}
		return modifierString.replaceAll("\\s", "").split("\\;");
	}

	public String getModifierString() {
		return modifierString;
	}

	public String getName() {
		return name;
	}

	public boolean hasModifier(String modifier) {
		if (modifierString == null) {
			return false;
		}
		return modifierString.indexOf(modifier) >= 0;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public void setModifierString(String modifierString) {
		this.modifierString = modifierString;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "declaration <'" + getName() + "'> [" + modifierString + "]";
	}
}


text:
package com.sun.j2ee.blueprints.opc.customerrelations.ejb;

import javax.naming.NamingException;
import javax.ejb.CreateException;
import javax.naming.InitialContext;

import javax.jms.QueueConnectionFactory;
import javax.jms.Queue;

/**
 * This class is use to get the resources to send a JMS Message
 * Any change here should also be reflected in the deployment
 * descriptors since this class uses resources specified in the
 * deployment descriptors.
 */
public class ServiceLocator {

    private InitialContext ic = null;

    public ServiceLocator() throws NamingException {
        ic = new InitialContext();
    }

    /**
     * @return the factory for the factory to get queue connections from
     */
    public  QueueConnectionFactory getQueueConnectionFactory(String qConnFactory)
                                                 throws NamingException {
        ic = new InitialContext();
        return (QueueConnectionFactory) ic.lookup(qConnFactory);
    }

    /**
     * @return the Queue Destination to send messages to
     */
    public  Queue getQueue(String mailSenderQueue) throws NamingException {
        return (Queue)ic.lookup(mailSenderQueue);
    }

    /**
     * @return the boolean value corresponding
     * to the SEND_CONFIRMATION_MAIL property.
     * If property is not present in the deployment
     * descriptor, conservatively assume that we do not send
     * status mail for each order.
     */
    public boolean getSendOrderStatusMail(String envName) {
        boolean boolVal = false;
        try {
            Boolean bool = (Boolean)ic.lookup(envName);
            if (bool != null) {
                boolVal = bool.booleanValue();
            }
        } catch (NamingException ne) {
            // If property is not present in the deployment
            // descriptor, conservatively assume that we do not send
            // confirmation mail for each order.
            System.out.println(ne);
        }
        return boolVal;
    }
}


text:
package io.vitess.jdbc;

import com.google.protobuf.ByteString;
import io.vitess.client.cursor.Cursor;
import io.vitess.client.cursor.SimpleCursor;
import io.vitess.proto.Query;
import io.vitess.util.MysqlDefs;
import io.vitess.util.StringUtils;
import io.vitess.util.charset.CharsetMapping;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Clob;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.internal.verification.VerificationModeFactory;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

/**
 * Created by harshit.gangal on 19/01/16.
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest(VitessResultSet.class)
public class VitessResultSetTest extends BaseTest {

    public Cursor getCursorWithRows() {
        /*
        INT8(1, 257), -50
        UINT8(2, 770), 50
        INT16(3, 259), -23000
        UINT16(4, 772), 23000
        INT24(5, 261), -100
        UINT24(6, 774), 100
        INT32(7, 263), -100
        UINT32(8, 776), 100
        INT64(9, 265),  -1000
        UINT64(10, 778), 1000
        FLOAT32(11, 1035), 24.53
        FLOAT64(12, 1036), 100.43
        TIMESTAMP(13, 2061), 2016-02-06 14:15:16
        DATE(14, 2062), 2016-02-06
        TIME(15, 2063), 12:34:56
        DATETIME(16, 2064), 2016-02-06 14:15:16
        YEAR(17, 785),  2016
        DECIMAL(18, 18), 1234.56789
        TEXT(19, 6163), HELLO TDS TEAM
        BLOB(20, 10260),  HELLO TDS TEAM
        VARCHAR(21, 6165), HELLO TDS TEAM
        VARBINARY(22, 10262), HELLO TDS TEAM
        CHAR(23, 6167), N
        BINARY(24, 10264), HELLO TDS TEAM
        BIT(25, 2073), 1
        ENUM(26, 2074), val123
        SET(27, 2075), val123
        TUPLE(28, 28),
        UNRECOGNIZED(-1, -1);
        */
        return new SimpleCursor(Query.QueryResult.newBuilder()
            .addFields(Query.Field.newBuilder().setName("col1").setType(Query.Type.INT8).build())
            .addFields(Query.Field.newBuilder().setName("col2").setType(Query.Type.UINT8).build())
            .addFields(Query.Field.newBuilder().setName("col3").setType(Query.Type.INT16).build())
            .addFields(Query.Field.newBuilder().setName("col4").setType(Query.Type.UINT16).build())
            .addFields(Query.Field.newBuilder().setName("col5").setType(Query.Type.INT24).build())
            .addFields(Query.Field.newBuilder().setName("col6").setType(Query.Type.UINT24).build())
            .addFields(Query.Field.newBuilder().setName("col7").setType(Query.Type.INT32).build())
            .addFields(Query.Field.newBuilder().setName("col8").setType(Query.Type.UINT32).build())
            .addFields(Query.Field.newBuilder().setName("col9").setType(Query.Type.INT64).build())
            .addFields(Query.Field.newBuilder().setName("col10").setType(Query.Type.UINT64).build())
            .addFields(
                Query.Field.newBuilder().setName("col11").setType(Query.Type.FLOAT32).build())
            .addFields(
                Query.Field.newBuilder().setName("col12").setType(Query.Type.FLOAT64).build())
            .addFields(
                Query.Field.newBuilder().setName("col13").setType(Query.Type.TIMESTAMP).build())
            .addFields(Query.Field.newBuilder().setName("col14").setType(Query.Type.DATE).build())
            .addFields(Query.Field.newBuilder().setName("col15").setType(Query.Type.TIME).build())
            .addFields(
                Query.Field.newBuilder().setName("col16").setType(Query.Type.DATETIME).build())
            .addFields(Query.Field.newBuilder().setName("col17").setType(Query.Type.YEAR).build())
            .addFields(
                Query.Field.newBuilder().setName("col18").setType(Query.Type.DECIMAL).build())
            .addFields(Query.Field.newBuilder().setName("col19").setType(Query.Type.TEXT).build())
            .addFields(Query.Field.newBuilder().setName("col20").setType(Query.Type.BLOB).build())
            .addFields(
                Query.Field.newBuilder().setName("col21").setType(Query.Type.VARCHAR).build())
            .addFields(
                Query.Field.newBuilder().setName("col22").setType(Query.Type.VARBINARY).build())
            .addFields(Query.Field.newBuilder().setName("col23").setType(Query.Type.CHAR).build())
            .addFields(Query.Field.newBuilder().setName("col24").setType(Query.Type.BINARY).build())
            .addFields(Query.Field.newBuilder().setName("col25").setType(Query.Type.BIT).build())
            .addFields(Query.Field.newBuilder().setName("col26").setType(Query.Type.ENUM).build())
            .addFields(Query.Field.newBuilder().setName("col27").setType(Query.Type.SET).build())
            .addRows(Query.Row.newBuilder().addLengths("-50".length()).addLengths("50".length())
                .addLengths("-23000".length()).addLengths("23000".length())
                .addLengths("-100".length()).addLengths("100".length()).addLengths("-100".length())
                .addLengths("100".length()).addLengths("-1000".length()).addLengths("1000".length())
                .addLengths("24.52".length()).addLengths("100.43".length())
                .addLengths("2016-02-06 14:15:16".length()).addLengths("2016-02-06".length())
                .addLengths("12:34:56".length()).addLengths("2016-02-06 14:15:16".length())
                .addLengths("2016".length()).addLengths("1234.56789".length())
                .addLengths("HELLO TDS TEAM".length()).addLengths("HELLO TDS TEAM".length())
                .addLengths("HELLO TDS TEAM".length()).addLengths("HELLO TDS TEAM".length())
                .addLengths("N".length()).addLengths("HELLO TDS TEAM".length())
                .addLengths("1".length()).addLengths("val123".length())
                .addLengths("val123".length()).setValues(ByteString
                    .copyFromUtf8("-5050-2300023000-100100-100100-1000100024.52100.432016-02-06 " +
                        "14:15:162016-02-0612:34:562016-02-06 14:15:1620161234.56789HELLO TDS TEAMHELLO TDS TEAMHELLO"
                        +
                        " TDS TEAMHELLO TDS TEAMNHELLO TDS TEAM1val123val123"))).build());
    }

    public Cursor getCursorWithRowsAsNull() {
        /*
        INT8(1, 257), -50
        UINT8(2, 770), 50
        INT16(3, 259), -23000
        UINT16(4, 772), 23000
        INT24(5, 261), -100
        UINT24(6, 774), 100
        INT32(7, 263), -100
        UINT32(8, 776), 100
        INT64(9, 265),  -1000
        UINT64(10, 778), 1000
        FLOAT32(11, 1035), 24.53
        FLOAT64(12, 1036), 100.43
        TIMESTAMP(13, 2061), 2016-02-06 14:15:16
        DATE(14, 2062), 2016-02-06
        TIME(15, 2063), 12:34:56
        DATETIME(16, 2064), 2016-02-06 14:15:16
        YEAR(17, 785),  2016
        DECIMAL(18, 18), 1234.56789
        TEXT(19, 6163), HELLO TDS TEAM
        BLOB(20, 10260),  HELLO TDS TEAM
        VARCHAR(21, 6165), HELLO TDS TEAM
        VARBINARY(22, 10262), HELLO TDS TEAM
        CHAR(23, 6167), N
        BINARY(24, 10264), HELLO TDS TEAM
        BIT(25, 2073), 0
        ENUM(26, 2074), val123
        SET(27, 2075), val123
        TUPLE(28, 28),
        UNRECOGNIZED(-1, -1);
        */
        return new SimpleCursor(Query.QueryResult.newBuilder()
            .addFields(Query.Field.newBuilder().setName("col1").setType(Query.Type.INT8).build())
            .addFields(Query.Field.newBuilder().setName("col2").setType(Query.Type.UINT8).build())
            .addFields(Query.Field.newBuilder().setName("col3").setType(Query.Type.INT16).build())
            .addFields(Query.Field.newBuilder().setName("col4").setType(Query.Type.UINT16).build())
            .addFields(Query.Field.newBuilder().setName("col5").setType(Query.Type.INT24).build())
            .addFields(Query.Field.newBuilder().setName("col6").setType(Query.Type.UINT24).build())
            .addFields(Query.Field.newBuilder().setName("col7").setType(Query.Type.INT32).build())
            .addFields(Query.Field.newBuilder().setName("col8").setType(Query.Type.UINT32).build())
            .addFields(Query.Field.newBuilder().setName("col9").setType(Query.Type.INT64).build())
            .addFields(Query.Field.newBuilder().setName("col10").setType(Query.Type.UINT64).build())
            .addFields(
                Query.Field.newBuilder().setName("col11").setType(Query.Type.FLOAT32).build())
            .addFields(
                Query.Field.newBuilder().setName("col12").setType(Query.Type.FLOAT64).build())
            .addFields(
                Query.Field.newBuilder().setName("col13").setType(Query.Type.TIMESTAMP).build())
            .addFields(Query.Field.newBuilder().setName("col14").setType(Query.Type.DATE).build())
            .addFields(Query.Field.newBuilder().setName("col15").setType(Query.Type.TIME).build())
            .addFields(
                Query.Field.newBuilder().setName("col16").setType(Query.Type.DATETIME).build())
            .addFields(Query.Field.newBuilder().setName("col17").setType(Query.Type.YEAR).build())
            .addFields(
                Query.Field.newBuilder().setName("col18").setType(Query.Type.DECIMAL).build())
            .addFields(Query.Field.newBuilder().setName("col19").setType(Query.Type.TEXT).build())
            .addFields(Query.Field.newBuilder().setName("col20").setType(Query.Type.BLOB).build())
            .addFields(
                Query.Field.newBuilder().setName("col21").setType(Query.Type.VARCHAR).build())
            .addFields(
                Query.Field.newBuilder().setName("col22").setType(Query.Type.VARBINARY).build())
            .addFields(Query.Field.newBuilder().setName("col23").setType(Query.Type.CHAR).build())
            .addFields(Query.Field.newBuilder().setName("col24").setType(Query.Type.BINARY).build())
            .addFields(Query.Field.newBuilder().setName("col25").setType(Query.Type.BIT).build())
            .addFields(Query.Field.newBuilder().setName("col26").setType(Query.Type.ENUM).build())
            .addFields(Query.Field.newBuilder().setName("col27").setType(Query.Type.SET).build())
            .addRows(Query.Row.newBuilder().addLengths("-50".length()).addLengths("50".length())
                .addLengths("-23000".length()).addLengths("23000".length())
                .addLengths("-100".length()).addLengths("100".length()).addLengths("-100".length())
                .addLengths("100".length()).addLengths("-1000".length()).addLengths("1000".length())
                .addLengths("24.52".length()).addLengths("100.43".length())
                .addLengths("2016-02-06 14:15:16".length()).addLengths("2016-02-06".length())
                .addLengths("12:34:56".length()).addLengths("2016-02-06 14:15:16".length())
                .addLengths("2016".length()).addLengths("1234.56789".length())
                .addLengths("HELLO TDS TEAM".length()).addLengths("HELLO TDS TEAM".length())
                .addLengths("HELLO TDS TEAM".length()).addLengths("HELLO TDS TEAM".length())
                .addLengths("N".length()).addLengths("HELLO TDS TEAM".length())
                .addLengths("0".length()).addLengths("val123".length()).addLengths(-1).setValues(
                    ByteString.copyFromUtf8(
                        "-5050-2300023000-100100-100100-1000100024.52100.432016-02-06 " +
                            "14:15:162016-02-0612:34:562016-02-06 14:15:1620161234.56789HELLO TDS TEAMHELLO TDS "
                            +
                            "TEAMHELLO TDS TEAMHELLO TDS TEAMNHELLO TDS TEAM0val123"))).build());
    }

    @Test public void testNextWithZeroRows() throws Exception {
        Cursor cursor = new SimpleCursor(Query.QueryResult.newBuilder()
            .addFields(Query.Field.newBuilder().setName("col0").build())
            .addFields(Query.Field.newBuilder().setName("col1").build())
            .addFields(Query.Field.newBuilder().setName("col2").build()).build());

        VitessResultSet vitessResultSet = new VitessResultSet(cursor);
        Assert.assertEquals(false, vitessResultSet.next());
    }

    @Test public void testNextWithNonZeroRows() throws Exception {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor);
        Assert.assertEquals(true, vitessResultSet.next());
        Assert.assertEquals(false, vitessResultSet.next());
    }

    @Test public void testgetString() throws SQLException {
        Cursor cursor = getCursorWithRowsAsNull();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals("-50", vitessResultSet.getString(1));
        Assert.assertEquals("50", vitessResultSet.getString(2));
        Assert.assertEquals("-23000", vitessResultSet.getString(3));
        Assert.assertEquals("23000", vitessResultSet.getString(4));
        Assert.assertEquals("-100", vitessResultSet.getString(5));
        Assert.assertEquals("100", vitessResultSet.getString(6));
        Assert.assertEquals("-100", vitessResultSet.getString(7));
        Assert.assertEquals("100", vitessResultSet.getString(8));
        Assert.assertEquals("-1000", vitessResultSet.getString(9));
        Assert.assertEquals("1000", vitessResultSet.getString(10));
        Assert.assertEquals("24.52", vitessResultSet.getString(11));
        Assert.assertEquals("100.43", vitessResultSet.getString(12));
        Assert.assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString(13));
        Assert.assertEquals("2016-02-06", vitessResultSet.getString(14));
        Assert.assertEquals("12:34:56", vitessResultSet.getString(15));
        Assert.assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString(16));
        Assert.assertEquals("2016", vitessResultSet.getString(17));
        Assert.assertEquals("1234.56789", vitessResultSet.getString(18));
        Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString(19));
        Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString(20));
        Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString(21));
        Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString(22));
        Assert.assertEquals("N", vitessResultSet.getString(23));
        Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString(24));
        Assert.assertEquals("0", vitessResultSet.getString(25));
        Assert.assertEquals("val123", vitessResultSet.getString(26));
        Assert.assertEquals(null, vitessResultSet.getString(27));
    }

    @Test public void testgetBoolean() throws SQLException {
        Cursor cursor = getCursorWithRows();
        Cursor cursorWithRowsAsNull = getCursorWithRowsAsNull();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(true, vitessResultSet.getBoolean(25));
        Assert.assertEquals(false, vitessResultSet.getBoolean(1));
        vitessResultSet = new VitessResultSet(cursorWithRowsAsNull, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(false, vitessResultSet.getBoolean(25));
        Assert.assertEquals(false, vitessResultSet.getBoolean(1));
    }

    @Test public void testgetByte() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(-50, vitessResultSet.getByte(1));
        Assert.assertEquals(1, vitessResultSet.getByte(25));
    }

    @Test public void testgetShort() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(-23000, vitessResultSet.getShort(3));
    }

    @Test public void testgetInt() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(-100, vitessResultSet.getInt(7));
    }

    @Test public void testgetLong() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(-1000, vitessResultSet.getInt(9));
    }

    @Test public void testgetFloat() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(24.52f, vitessResultSet.getFloat(11), 0.001);
    }

    @Test public void testgetDouble() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(100.43, vitessResultSet.getFloat(12), 0.001);
    }

    @Test public void testBigDecimal() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(new BigDecimal(BigInteger.valueOf(123456789), 5),
            vitessResultSet.getBigDecimal(18));
    }

    @Test public void testgetBytes() throws SQLException, UnsupportedEncodingException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertArrayEquals("HELLO TDS TEAM".getBytes("UTF-8"), vitessResultSet.getBytes(19));
    }

    @Test public void testgetDate() throws SQLException, UnsupportedEncodingException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(new java.sql.Date(116, 1, 6), vitessResultSet.getDate(14));
    }

    @Test public void testgetTime() throws SQLException, UnsupportedEncodingException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(new Time(12, 34, 56), vitessResultSet.getTime(15));
    }

    @Test public void testgetTimestamp() throws SQLException, UnsupportedEncodingException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(new Timestamp(116, 1, 6, 14, 15, 16, 0),
            vitessResultSet.getTimestamp(13));
    }

    @Test public void testgetStringbyColumnLabel() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals("-50", vitessResultSet.getString("col1"));
        Assert.assertEquals("50", vitessResultSet.getString("col2"));
        Assert.assertEquals("-23000", vitessResultSet.getString("col3"));
        Assert.assertEquals("23000", vitessResultSet.getString("col4"));
        Assert.assertEquals("-100", vitessResultSet.getString("col5"));
        Assert.assertEquals("100", vitessResultSet.getString("col6"));
        Assert.assertEquals("-100", vitessResultSet.getString("col7"));
        Assert.assertEquals("100", vitessResultSet.getString("col8"));
        Assert.assertEquals("-1000", vitessResultSet.getString("col9"));
        Assert.assertEquals("1000", vitessResultSet.getString("col10"));
        Assert.assertEquals("24.52", vitessResultSet.getString("col11"));
        Assert.assertEquals("100.43", vitessResultSet.getString("col12"));
        Assert.assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString("col13"));
        Assert.assertEquals("2016-02-06", vitessResultSet.getString("col14"));
        Assert.assertEquals("12:34:56", vitessResultSet.getString("col15"));
        Assert.assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString("col16"));
        Assert.assertEquals("2016", vitessResultSet.getString("col17"));
        Assert.assertEquals("1234.56789", vitessResultSet.getString("col18"));
        Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col19"));
        Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col20"));
        Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col21"));
        Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col22"));
        Assert.assertEquals("N", vitessResultSet.getString("col23"));
        Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col24"));
        Assert.assertEquals("1", vitessResultSet.getString("col25"));
        Assert.assertEquals("val123", vitessResultSet.getString("col26"));
        Assert.assertEquals("val123", vitessResultSet.getString("col27"));
    }

    @Test public void testgetBooleanbyColumnLabel() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(true, vitessResultSet.getBoolean("col25"));
        Assert.assertEquals(false, vitessResultSet.getBoolean("col1"));
    }

    @Test public void testgetBytebyColumnLabel() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(-50, vitessResultSet.getByte("col1"));
        Assert.assertEquals(1, vitessResultSet.getByte("col25"));
    }

    @Test public void testgetShortbyColumnLabel() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(-23000, vitessResultSet.getShort("col3"));
    }

    @Test public void testgetIntbyColumnLabel() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(-100, vitessResultSet.getInt("col7"));
    }

    @Test public void testgetLongbyColumnLabel() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(-1000, vitessResultSet.getInt("col9"));
    }

    @Test public void testgetFloatbyColumnLabel() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(24.52f, vitessResultSet.getFloat("col11"), 0.001);
    }

    @Test public void testgetDoublebyColumnLabel() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(100.43, vitessResultSet.getFloat("col12"), 0.001);
    }

    @Test public void testBigDecimalbyColumnLabel() throws SQLException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(new BigDecimal(BigInteger.valueOf(123456789), 5),
            vitessResultSet.getBigDecimal("col18"));
    }

    @Test public void testgetBytesbyColumnLabel()
        throws SQLException, UnsupportedEncodingException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertArrayEquals("HELLO TDS TEAM".getBytes("UTF-8"),
            vitessResultSet.getBytes("col19"));
    }

    @Test public void testgetDatebyColumnLabel() throws SQLException, UnsupportedEncodingException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(new java.sql.Date(116, 1, 6), vitessResultSet.getDate("col14"));
    }

    @Test public void testgetTimebyColumnLabel() throws SQLException, UnsupportedEncodingException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(new Time(12, 34, 56), vitessResultSet.getTime("col15"));
    }

    @Test public void testgetTimestampbyColumnLabel()
        throws SQLException, UnsupportedEncodingException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        vitessResultSet.next();
        Assert.assertEquals(new Timestamp(116, 1, 6, 14, 15, 16, 0),
            vitessResultSet.getTimestamp("col13"));
    }

    @Test public void testgetAsciiStream() throws SQLException, UnsupportedEncodingException {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor);
        vitessResultSet.next();
        // Need to implement AssertEquivalant
        //Assert.assertEquals((InputStream)(new ByteArrayInputStream("HELLO TDS TEAM".getBytes())), vitessResultSet
        // .getAsciiStream(19));
    }

    @Test public void testEnhancedFieldsFromCursor() throws Exception {
        Cursor cursor = getCursorWithRows();
        VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement());
        Assert.assertEquals(cursor.getFields().size(), vitessResultSet.getFields().size());
    }

    @Test public void testGetStringUsesEncoding() throws Exception {
        VitessConnection conn = getVitessConnection();
        VitessResultSet resultOne = PowerMockito.spy(new VitessResultSet(getCursorWithRows(), new VitessStatement(conn)));
        resultOne.next();
        // test all ways to get to convertBytesToString

        // Verify that we're going through convertBytesToString for column types that return bytes (string-like),
        // but not for those that return a real object
        resultOne.getString("col21"); // is a string, should go through convert bytes
        resultOne.getString("col13"); // is a datetime, should not
        PowerMockito.verifyPrivate(resultOne, VerificationModeFactory.times(1)).invoke("convertBytesToString", Matchers.any(byte[].class), Matchers.anyString());

        conn.setIncludedFields(Query.ExecuteOptions.IncludedFields.TYPE_AND_NAME);
        VitessResultSet resultTwo = PowerMockito.spy(new VitessResultSet(getCursorWithRows(), new VitessStatement(conn)));
        resultTwo.next();

        // neither of these should go through convertBytesToString, because we didn't include all fields
        resultTwo.getString("col21");
        resultTwo.getString("col13");
        PowerMockito.verifyPrivate(resultTwo, VerificationModeFactory.times(0)).invoke("convertBytesToString", Matchers.any(byte[].class), Matchers.anyString());
    }

    @Test public void testGetObjectForBitValues() throws Exception {
        VitessConnection conn = getVitessConnection();

        ByteString.Output value = ByteString.newOutput();
        value.write(new byte[] {1});
        value.write(new byte[] {0});
        value.write(new byte[] {1,2,3,4});

        Query.QueryResult result = Query.QueryResult.newBuilder()
            .addFields(Query.Field.newBuilder().setName("col1").setColumnLength(1).setType(Query.Type.BIT))
            .addFields(Query.Field.newBuilder().setName("col2").setColumnLength(1).setType(Query.Type.BIT))
            .addFields(Query.Field.newBuilder().setName("col3").setColumnLength(4).setType(Query.Type.BIT))
            .addRows(Query.Row.newBuilder()
                .addLengths(1)
                .addLengths(1)
                .addLengths(4)
                .setValues(value.toByteString()))
            .build();

        VitessResultSet vitessResultSet = PowerMockito.spy(new VitessResultSet(new SimpleCursor(result), new VitessStatement(conn)));
        vitessResultSet.next();

        Assert.assertEquals(true, vitessResultSet.getObject(1));
        Assert.assertEquals(false, vitessResultSet.getObject(2));
        Assert.assertArrayEquals(new byte[] {1,2,3,4}, (byte[]) vitessResultSet.getObject(3));

        PowerMockito.verifyPrivate(vitessResultSet, VerificationModeFactory.times(3)).invoke("convertBytesIfPossible", Matchers.any(byte[].class), Matchers.any(FieldWithMetadata.class));

        conn.setIncludedFields(Query.ExecuteOptions.IncludedFields.TYPE_AND_NAME);
        vitessResultSet = PowerMockito.spy(new VitessResultSet(new SimpleCursor(result), new VitessStatement(conn)));
        vitessResultSet.next();

        Assert.assertArrayEquals(new byte[] { 1 }, (byte[]) vitessResultSet.getObject(1));
        Assert.assertArrayEquals(new byte[] { 0 }, (byte[]) vitessResultSet.getObject(2));
        Assert.assertArrayEquals(new byte[] {1,2,3,4}, (byte[]) vitessResultSet.getObject(3));

        PowerMockito.verifyPrivate(vitessResultSet, VerificationModeFactory.times(0)).invoke("convertBytesIfPossible", Matchers.any(byte[].class), Matchers.any(FieldWithMetadata.class));
    }

    @Test public void testGetObjectForVarBinLikeValues() throws Exception {
        VitessConnection conn = getVitessConnection();

        ByteString.Output value = ByteString.newOutput();

        byte[] binary = new byte[] {1,2,3,4};
        byte[] varbinary = new byte[] {1,2,3,4,5,6,7,8,9,10,11,12,13};
        byte[] blob = new byte[MysqlDefs.LENGTH_BLOB];
        for (int i = 0; i < blob.length; i++) {
            blob[i] = 1;
        }
        byte[] fakeGeometry = new byte[] {2,3,4};

        value.write(binary);
        value.write(varbinary);
        value.write(blob);
        value.write(fakeGeometry);

        Query.QueryResult result = Query.QueryResult.newBuilder()
            .addFields(Query.Field.newBuilder().setName("col1")
                .setColumnLength(4)
                .setCharset(CharsetMapping.MYSQL_COLLATION_INDEX_binary)
                .setType(Query.Type.BINARY)
                .setFlags(Query.MySqlFlag.BINARY_FLAG_VALUE))
            .addFields(Query.Field.newBuilder().setName("col2")
                .setColumnLength(13)
                .setCharset(CharsetMapping.MYSQL_COLLATION_INDEX_binary)
                .setType(Query.Type.VARBINARY)
                .setFlags(Query.MySqlFlag.BINARY_FLAG_VALUE))
            .addFields(Query.Field.newBuilder().setName("col3") // should go to LONGVARBINARY due to below settings
                .setColumnLength(MysqlDefs.LENGTH_BLOB)
                .setCharset(CharsetMapping.MYSQL_COLLATION_INDEX_binary)
                .setFlags(Query.MySqlFlag.BINARY_FLAG_VALUE)
                .setType(Query.Type.BLOB))
            .addFields(Query.Field.newBuilder().setName("col4")
                .setType(Query.Type.GEOMETRY)
                .setCharset(CharsetMapping.MYSQL_COLLATION_INDEX_binary)
                .setType(Query.Type.BINARY)
                .setFlags(Query.MySqlFlag.BINARY_FLAG_VALUE))
            .addRows(Query.Row.newBuilder()
                .addLengths(4)
                .addLengths(13)
                .addLengths(MysqlDefs.LENGTH_BLOB)
                .addLengths(3)
                .setValues(value.toByteString()))
            .build();

        VitessResultSet vitessResultSet = PowerMockito.spy(new VitessResultSet(new SimpleCursor(result), new VitessStatement(conn)));
        vitessResultSet.next();

        // All of these types should pass straight through, returning the direct bytes
        Assert.assertArrayEquals(binary, (byte[]) vitessResultSet.getObject(1));
        Assert.assertArrayEquals(varbinary, (byte[]) vitessResultSet.getObject(2));
        Assert.assertArrayEquals(blob, (byte[]) vitessResultSet.getObject(3));
        Assert.assertArrayEquals(fakeGeometry, (byte[]) vitessResultSet.getObject(4));

        // We should still call the function 4 times
        PowerMockito.verifyPrivate(vitessResultSet, VerificationModeFactory.times(4)).invoke("convertBytesIfPossible", Matchers.any(byte[].class), Matchers.any(FieldWithMetadata.class));

        conn.setIncludedFields(Query.ExecuteOptions.IncludedFields.TYPE_AND_NAME);
        vitessResultSet = PowerMockito.spy(new VitessResultSet(new SimpleCursor(result), new VitessStatement(conn)));
        vitessResultSet.next();

        // Same as above since this doesn't really do much but pass right through for the varbinary type
        Assert.assertArrayEquals(binary, (byte[]) vitessResultSet.getObject(1));
        Assert.assertArrayEquals(varbinary, (byte[]) vitessResultSet.getObject(2));
        Assert.assertArrayEquals(blob, (byte[]) vitessResultSet.getObject(3));
        Assert.assertArrayEquals(fakeGeometry, (byte[]) vitessResultSet.getObject(4));

        // Never call because not including all
        PowerMockito.verifyPrivate(vitessResultSet, VerificationModeFactory.times(0)).invoke("convertBytesIfPossible", Matchers.any(byte[].class), Matchers.any(FieldWithMetadata.class));
    }

    @Test public void testGetObjectForStringLikeValues() throws Exception {
        ByteString.Output value = ByteString.newOutput();

        String trimmedCharStr = "wasting space";
        String varcharStr = "i have a variable length!";
        String masqueradingBlobStr = "look at me, im a blob";
        String textStr = "an enthralling string of TEXT in some foreign language";

        int paddedCharColLength = 20;
        byte[] trimmedChar = StringUtils.getBytes(trimmedCharStr, "UTF-16");
        byte[] varchar = StringUtils.getBytes(varcharStr, "UTF-8");
        byte[] masqueradingBlob = StringUtils.getBytes(masqueradingBlobStr, "US-ASCII");
        byte[] text = StringUtils.getBytes(textStr, "ISO8859_8");
        byte[] opaqueBinary = new byte[] { 1,2,3,4,5,6,7,8,9};

        value.write(trimmedChar);
        value.write(varchar);
        value.write(opaqueBinary);
        value.write(masqueradingBlob);
        value.write(text);

        Query.QueryResult result = Query.QueryResult.newBuilder()
            // This tests CHAR
            .addFields(Query.Field.newBuilder().setName("col1")
                .setColumnLength(paddedCharColLength)
                .setCharset(/* utf-16 collation index from CharsetMapping */ 54)
                .setType(Query.Type.CHAR))
            // This tests VARCHAR
            .addFields(Query.Field.newBuilder().setName("col2")
                .setColumnLength(varchar.length)
                .setCharset(CharsetMapping.MYSQL_COLLATION_INDEX_utf8)
                .setType(Query.Type.VARCHAR))
            // This tests VARCHAR that is an opaque binary
            .addFields(Query.Field.newBuilder().setName("col2")
                .setColumnLength(opaqueBinary.length)
                .setCharset(CharsetMapping.MYSQL_COLLATION_INDEX_binary)
                .setFlags(Query.MySqlFlag.BINARY_FLAG_VALUE)
                .setType(Query.Type.VARCHAR))
            // This tests LONGVARCHAR
            .addFields(Query.Field.newBuilder().setName("col3")
                .setColumnLength(masqueradingBlob.length)
                .setCharset(/* us-ascii collation index from CharsetMapping */11)
                .setType(Query.Type.BLOB))
            // This tests TEXT, which falls through the default case of the switch
            .addFields(Query.Field.newBuilder().setName("col4")
                .setColumnLength(text.length)
                .setCharset(/* corresponds to greek, from CharsetMapping */25)
                .setType(Query.Type.TEXT))
            .addRows(Query.Row.newBuilder()
                .addLengths(trimmedChar.length)
                .addLengths(varchar.length)
                .addLengths(opaqueBinary.length)
                .addLengths(masqueradingBlob.length)
                .addLengths(text.length)
                .setValues(value.toByteString()))
            .build();

        VitessConnection conn = getVitessConnection();
        VitessResultSet vitessResultSet = PowerMockito.spy(new VitessResultSet(new SimpleCursor(result), new VitessStatement(conn)));
        vitessResultSet.next();

        Assert.assertEquals(trimmedCharStr, vitessResultSet.getObject(1));
        Assert.assertEquals(varcharStr, vitessResultSet.getObject(2));
        Assert.assertArrayEquals(opaqueBinary, (byte[]) vitessResultSet.getObject(3));
        Assert.assertEquals(masqueradingBlobStr, vitessResultSet.getObject(4));
        Assert.assertEquals(textStr, vitessResultSet.getObject(5));

        PowerMockito.verifyPrivate(vitessResultSet, VerificationModeFactory.times(5)).invoke("convertBytesIfPossible", Matchers.any(byte[].class), Matchers.any(FieldWithMetadata.class));

        conn.setIncludedFields(Query.ExecuteOptions.IncludedFields.TYPE_AND_NAME);
        vitessResultSet = PowerMockito.spy(new VitessResultSet(new SimpleCursor(result), new VitessStatement(conn)));
        vitessResultSet.next();

        Assert.assertArrayEquals(trimmedChar, (byte[]) vitessResultSet.getObject(1));
        Assert.assertArrayEquals(varchar, (byte[]) vitessResultSet.getObject(2));
        Assert.assertArrayEquals(opaqueBinary, (byte[]) vitessResultSet.getObject(3));
        Assert.assertArrayEquals(masqueradingBlob, (byte[]) vitessResultSet.getObject(4));
        Assert.assertArrayEquals(text, (byte[]) vitessResultSet.getObject(5));

        PowerMockito.verifyPrivate(vitessResultSet, VerificationModeFactory.times(0)).invoke("convertBytesIfPossible", Matchers.any(byte[].class), Matchers.any(FieldWithMetadata.class));
    }

    @Test public void testGetClob() throws SQLException {
        VitessResultSet vitessResultSet = new VitessResultSet(
            new String[]{"clob"}, new Query.Type[]{Query.Type.VARCHAR},
            new String[][]{new String[] {"clobValue"}},
            new ConnectionProperties());
        Assert.assertTrue(vitessResultSet.next());

        Clob clob = vitessResultSet.getClob(1);
        Assert.assertEquals("clobValue", clob.getSubString(1, (int) clob.length()));

        clob = vitessResultSet.getClob("clob");
        Assert.assertEquals("clobValue", clob.getSubString(1, (int) clob.length()));
    }
}


text:
<?php

namespace {

from('Hoa')

/**
 * \Hoa\Graph\Exception
 */
-> import('Graph.Exception');

}

namespace Hoa\Graph {

/**
 * Class \Hoa\Graph.
 *
 * Get instance of different graph type.
 * When getting an instance of a type of a graph, the graph type (e.g.
 * \Hoa\Graph\AdjacencyList) extends this class. It is like an abstract
 * factory…
 *
 * @author     Ivan Enderlin <ivan.enderlin@hoa-project.net>
 * @copyright  Copyright © 2007-2012 Ivan Enderlin.
 * @license    New BSD License
 */

abstract class Graph {

    /**
     * Graph type.
     *
     * @const string
     */
    const TYPE_ADJACENCYLIST = 'AdjacencyList';

    /**
     * Allow loop when building graph (when adding nodes).
     *
     * @const bool
     */
    const ALLOW_LOOP         = true;

    /**
     * Disallow loop when building graph (when adding nodes).
     *
     * @const bool
     */
    const DISALLOW_LOOP      = false;

    /**
     * Propagate delete.
     *
     * @const bool
     */
    const DELETE_CASCADE     = true;

    /**
     * Restrict delete.
     *
     * @const bool
     */
    const DELETE_RESTRICT    = false;

    /**
     * All nodes.
     *
     * @var \Hoa\Graph array
     */
    protected $nodes = array();

    /**
     * If allow loop when building graph, it is set to ALLOW_LOOP (true),
     * DISALLOW_LOOP (false) else.
     *
     * @var \Hoa\Graph bool
     */
    protected $loop  = self::DISALLOW_LOOP;

    /**
     * Get an empty graph.
     *
     * @access  protected
     * @param   bool       $loop    Allow or not loop.
     * @return  void
     */
    protected function __construct ( $loop = self::DISALLOW_LOOP ) {

        $this->allowLoop($loop);
    }

    /**
     * Make an instance of a specific graph.
     *
     * @access  public
     * @param   string  $type    Type of graph needed.
     * @return  void
     * @throw   \Hoa\Graph\Exception
     */
    public static function getInstance ( $type = self::TYPE_ADJACENCYLIST ) {

        if($type != self::TYPE_ADJACENCYLIST)
            throw new Exception(
                'Type %s is not supported. Only self:TYPE_ADJACENCYLIST is ' .
                'supported.', 0, $type);

        $arguments = func_get_args();
        array_shift($arguments);

        return dnew('Hoa\Graph\\' . $type, $arguments);
    }

    /**
     * Add a node.
     *
     * @access  public
     * @param   \Hoa\Graph\IGraph\Node  $node      Node to add.
     * @param   mixed                   $parent    Parent of node.
     * @return  void
     * @throw   \Hoa\Graph\Exception
     */
    abstract public function addNode ( \Hoa\Graph\IGraph\Node $node,
                                       $parent = array() );

    /**
     * Check if a node does already exist or not.
     *
     * @access  public
     * @param   mixed   $nodeId    The node ID or the node instance.
     * @return  bool
     */
    abstract public function nodeExists ( $nodeId );

    /**
     * Get a node.
     *
     * @access  public
     * @param   mixed   $nodeId    The node ID or the node instance.
     * @return  object
     * @throw   \Hoa\Graph\Exception
     */
    abstract public function getNode ( $nodeId );

    /**
     * Get all nodes.
     *
     * @access  protected
     * @return  array
     */
    protected function getNodes ( ) {

        return $this->nodes;
    }

    /**
     * Get parent of a specific node.
     *
     * @access  public
     * @param   mixed   $nodeId    The node ID or the node instance.
     * @return  object
     * @throw   \Hoa\Graph\Exception
     */
    abstract public function getParent ( $nodeId );

    /**
     * Get child of a specific node.
     *
     * @access  public
     * @param   mixed   $nodeId    The node ID or the node instance.
     * @return  object
     * @throw   \Hoa\Graph\Exception
     */
    abstract public function getChild ( $nodeId );

    /**
     * Delete a node.
     *
     * @access  public
     * @param   mixed   $nodeId       The node ID or the node instance.
     * @param   bool    $propagate    Propagate the erasure.
     * @return  void
     * @throw   \Hoa\Graph\Exception
     */
    abstract public function deleteNode ( $nodeId, $propagate = self::DELETE_RESTRICT );

    /**
     * Whether node is a leaf, i.e. does not have any child.
     *
     * @access  public
     * @param   mixed   $nodeId    The node ID or the node instance.
     * @return  bool
     * @throw   \Hoa\Graph\Exception
     */
    abstract public function isLeaf ( $nodeId );

    /**
     * Whether node is a root, i.e. does not have any parent.
     *
     * @access  public
     * @param   mixed   $nodeId    The node ID or the node instance.
     * @return  bool
     * @throw   \Hoa\Graph\Exception
     */
    abstract public function isRoot ( $nodeId );

    /**
     * Set the loop mode (self::ALLOW_LOOP or self::DISALLOW_LOOP).
     *
     * @access  public
     * @param   bool    $loop    Allow or not loop.
     * @return  bool
     */
    public function allowLoop ( $loop = self::DISALLOW_LOOP ) {

        $old        = $this->loop;
        $this->loop = $loop;

        return $old;
    }

    /**
     * Get the loop mode.
     *
     * @access  public
     * @return  bool
     */
    public function isLoopAllow ( ) {

        return $this->loop;
    }

    /**
     * Print the graph in the DOT language.
     *
     * @access  public
     * @return  string
     */
    abstract public function __toString ( );
}

}


text:
This is the default theme for docs

@todo list features of this theme


text:
package org.apache.eagle.jpm.util.resourcefetch.model;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.util.List;

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class SparkJob {
    private int jobId;
    private String name;
    private String submissionTime;
    private String completionTime;
    private List<Integer> stageIds;
    private String status;
    private int numTasks;
    private int numActiveTasks;
    private int numCompletedTasks;
    private int numSkippedTasks;
    private int numFailedTasks;
    private int numActiveStages;
    private int numCompletedStages;
    private int numSkippedStages;
    private int numFailedStages;

    public int getJobId() {
        return jobId;
    }

    public void setJobId(int jobId) {
        this.jobId = jobId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSubmissionTime() {
        return submissionTime;
    }

    public void setSubmissionTime(String submissionTime) {
        this.submissionTime = submissionTime;
    }

    public String getCompletionTime() {
        return completionTime;
    }

    public void setCompletionTime(String completionTime) {
        this.completionTime = completionTime;
    }

    public List<Integer> getStageIds() {
        return stageIds;
    }

    public void setStageIds(List<Integer> stageIds) {
        this.stageIds = stageIds;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public int getNumTasks() {
        return numTasks;
    }

    public void setNumTasks(int numTasks) {
        this.numTasks = numTasks;
    }

    public int getNumActiveTasks() {
        return numActiveTasks;
    }

    public void setNumActiveTasks(int numActiveTasks) {
        this.numActiveTasks = numActiveTasks;
    }

    public int getNumCompletedTasks() {
        return numCompletedTasks;
    }

    public void setNumCompletedTasks(int numCompletedTasks) {
        this.numCompletedTasks = numCompletedTasks;
    }

    public int getNumSkippedTasks() {
        return numSkippedTasks;
    }

    public void setNumSkippedTasks(int numSkippedTasks) {
        this.numSkippedTasks = numSkippedTasks;
    }

    public int getNumFailedTasks() {
        return numFailedTasks;
    }

    public void setNumFailedTasks(int numFailedTasks) {
        this.numFailedTasks = numFailedTasks;
    }

    public int getNumActiveStages() {
        return numActiveStages;
    }

    public void setNumActiveStages(int numActiveStages) {
        this.numActiveStages = numActiveStages;
    }

    public int getNumCompletedStages() {
        return numCompletedStages;
    }

    public void setNumCompletedStages(int numCompletedStages) {
        this.numCompletedStages = numCompletedStages;
    }

    public int getNumSkippedStages() {
        return numSkippedStages;
    }

    public void setNumSkippedStages(int numSkippedStages) {
        this.numSkippedStages = numSkippedStages;
    }

    public int getNumFailedStages() {
        return numFailedStages;
    }

    public void setNumFailedStages(int numFailedStages) {
        this.numFailedStages = numFailedStages;
    }
}


text:
#pragma once
#include <aws/iotsitewise/IoTSiteWise_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace IoTSiteWise
{
namespace Model
{
  enum class CapabilitySyncStatus
  {
    NOT_SET,
    IN_SYNC,
    OUT_OF_SYNC,
    SYNC_FAILED
  };

namespace CapabilitySyncStatusMapper
{
AWS_IOTSITEWISE_API CapabilitySyncStatus GetCapabilitySyncStatusForName(const Aws::String& name);

AWS_IOTSITEWISE_API Aws::String GetNameForCapabilitySyncStatus(CapabilitySyncStatus value);
} // namespace CapabilitySyncStatusMapper
} // namespace Model
} // namespace IoTSiteWise
} // namespace Aws


text:
namespace WTF {

TEST(RefPtrTest, Basic)
{
    RefPtr<StringImpl> string;
    EXPECT_TRUE(!string);
    string = StringImpl::create("test");
    EXPECT_TRUE(!!string);
    string.clear();
    EXPECT_TRUE(!string);
}

TEST(RefPtrTest, MoveAssignmentOperator)
{
    RefPtr<StringImpl> a = StringImpl::create("a");
    RefPtr<StringImpl> b = StringImpl::create("b");
    // FIXME: Instead of explicitly casting to RefPtr<StringImpl>&& here, we should use std::move, but that
    // requires us to have a standard library that supports move semantics.
    b = static_cast<RefPtr<StringImpl>&&>(a);
    EXPECT_TRUE(!!b);
    EXPECT_TRUE(!a);
}

} // namespace WTF


text:
using System;

namespace Microsoft.Xna.Framework.Graphics
{
    public static class MonoGameExtensions
    {
        public static void GetNativeDxDeviceAndContext(this GraphicsDevice graphicsDevice, out IntPtr dxDevicePtr, out IntPtr dxContextPtr)
        {
            var graphicsDeviceType = typeof(GraphicsDevice);

            var d3dDeviceInfo = graphicsDeviceType.GetField("_d3dDevice", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var deviceObj = d3dDeviceInfo.GetValue(graphicsDevice);
            var deviceType = deviceObj.GetType();
            var devicePtrInfo = deviceType.GetProperty("NativePointer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            dxDevicePtr = (IntPtr)devicePtrInfo.GetValue(deviceObj);

            var d3dContextInfo = graphicsDeviceType.GetField("_d3dContext", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var contextObj = d3dContextInfo.GetValue(graphicsDevice);
            var contextType = contextObj.GetType();
            var contextPtrInfo = contextType.GetProperty("NativePointer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            dxContextPtr = (IntPtr)contextPtrInfo.GetValue(contextObj);
        }

        public static IntPtr GetNativeDxResource(this RenderTarget2D renderTarget2D)
        {
            var renderTarget2DType = typeof(RenderTarget2D);

            var textureInfo = renderTarget2DType.GetField("_texture", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var resourceObj = textureInfo.GetValue(renderTarget2D);
            var resourceType = resourceObj.GetType();
            var resourcePtrInfo = resourceType.GetProperty("NativePointer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            return (IntPtr)resourcePtrInfo.GetValue(resourceObj);
        }
    }
}


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

namespace _02.BasicStackOperations
{
    public class Startup
    {
        public static void Main()
        {
            int[] inputArgs = Console.ReadLine().Trim().Split().Select(int.Parse).ToArray();
            int[] elements = Console.ReadLine().Trim().Split().Select(int.Parse).ToArray();
            int push = inputArgs[0];
            int pop = inputArgs[1];
            int check = inputArgs[2];

            Stack<int> stack = new Stack<int>();
            for (int i = 0; i < push; i++)
            {
                stack.Push(elements[i]);
            }

            for (int i = 0; i < pop; i++)
            {
                if (stack.Count == 1)
                {
                    stack.Pop();
                    break;
                }
                stack.Pop();
            }

            if (stack.Count == 0)
            {
                Console.WriteLine(0);
            }
            else if (stack.Contains(check))
            {
                Console.WriteLine("true");
            }
            else
            {
                Console.WriteLine(stack.Min());
            }
        }
    }
}


text:
NestContact
===========

An iOS contact book app of 'NEST' series apps,
for replacing the iOS system default contact app with many good features considered,
we'll make best of it.


text:
<?php

class Resource
{
	private static $caching = false;

	private static $extensions_mime = array(
		'js' => 'application/x-javascript',
		'css' => 'text/css',
		'htm' => 'text/html',
		'html' => 'text/html',
		'xml' => 'application/xml',
		'txt' => 'text/plain',

		'svg' => 'image/svg+xml',
		'eot' => 'application/vnd.ms-fontobject',
		'woff' => 'application/font-woff',
		'otf' => 'application/octet-stream',
		'ttf' => 'application/x-font-ttf',

		'bmp' => 'image/bmp',
		'png' => 'image/png',
		'gif' => 'image/gif',
		'jpg' => 'image/jpeg',
		'jpeg' => 'image/jpeg',
		'tif' => 'image/tiff',
		'tiff' => 'image/tiff',

		'wav' => 'audio/x-wav',
		'avi' => 'video/x-msvideo',
		'mp3' => 'audio/mpeg',
		'mp4' => 'video/mp4',
		'mov' => 'video/quicktime',
		'mpe' => 'video/mpeg',
		'mpeg' => 'video/mpeg',
		'mpg' => 'video/mpeg',
		'swf' => 'application/x-shockwave-flash',

		'doc' => 'application/msword',
		'ppt' => 'application/vnd.ms-powerpoint',
		'xls' => 'application/vnd.ms-excel',
		'pdf' => 'application/pdf',
		'zip' => 'application/zip',
		'rar' => 'application/x-rar-compressed',
		'7z' => 'application/x-7z-compressed',
		'tar' => 'application/x-tar',
	);

	public static function setCaching($caching) {
		self::$caching = $caching;
	}

	public static function getMime($extension)
	{
		return self::$extensions_mime[strtolower($extension)];
	}

	public static function isResource($extension)
	{
		return array_key_exists(strtolower($extension), self::$extensions_mime);
	}

	public static function isImage($extension)
	{
		$extension = strtolower($extension);
		return ($extension == 'png' || $extension == 'gif' || $extension == 'jpg' || $extension == 'jpeg'); // only types that can be resized
	}

	public static function getMinified($filename)
	{
		$min = Common::insertMinExtension($filename);
		if (is_file($min) && filemtime($filename) < filemtime($min))
			return $min;

		// SmushIt gif -> png case
		if (substr($filename, strrpos($filename, '.') + 1) == 'gif')
		{
			$min .= '.png';
			if (is_file($min) && filemtime($filename) < filemtime($min))
				$filename = $min;
		}
		return $filename;
	}

	private static function cacheFilename($filenames, $cache_formatted_filename)
	{
		$latest_modify_time = 0;
		foreach ($filenames as $filename)
			if (!is_file(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename))
				user_error('File "' . $filename . '" could not be found', WARNING);
			else
			{
				$modify_time = filemtime(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename);
				$latest_modify_time = max($modify_time, $latest_modify_time);
			}

		$unique_scriptname = implode($filenames) . $latest_modify_time;
		return sprintf($cache_formatted_filename, sha1($unique_scriptname));
	}

	public static function cacheFiles($filenames, $extension)
	{
		$starttime_local = explode(' ', microtime());

		if ($extension == 'js' || $extension == 'css') // use minified js and css when available
			foreach ($filenames as $i => $filename)
				if (is_file(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . Common::insertMinExtension($filename)) &&
					filemtime(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename) < filemtime(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . Common::insertMinExtension($filename)))
					$filenames[$i] = Common::insertMinExtension($filename);

		$cache_filename = self::cacheFilename($filenames, 'cache/%s.' . $extension);
		if (!is_file(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $cache_filename) || !self::$caching)
		{
			$content = '';
			foreach ($filenames as $filename)
				if (is_file(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename))
					$content .= file_get_contents(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename);
			file_put_contents(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $cache_filename, $content);

			$endtime_local = explode(' ', microtime());
			$totaltime = ($endtime_local[1] + $endtime_local[0] - $starttime_local[1] - $starttime_local[0]);
			Log::caching($cache_filename . ' took ' . number_format($totaltime, 4) . 's');
		}
		return 'res/' . $cache_filename;
	}

	public static function expandUrl($url)
	{
		$filename = '';
		if (isset($url[1]) && isset($url[2]))
			if ($url[1] == 'cache')
				$filename = 'cache/' . implode('/', array_splice($url, 2));
			else if ($url[1] == 'assets')
				$filename = 'assets/' . implode('/', array_splice($url, 2));
			else if ($url[1] == 'core')
				$filename = 'core/resources/' . implode('/', array_splice($url, 2));
			else if ($url[1] == 'module')
				$filename = 'modules/' . $url[2] . '/resources/' . implode('/', array_splice($url, 3));
			else if ($url[1] == 'theme')
				$filename = 'themes/' . $url[2] . '/resources/' . implode('/', array_splice($url, 3));

		if (empty($filename))
			user_error('Could not expand URL "' . implode('/', $url) . '" to resource', ERROR);

		return $filename;
	}

	public static function imageSize($filename, $max_width, $max_height = 0)
	{
		if (!is_file(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename))
		{
			user_error('Could not find "' . $filename . '" to determine new image size', WARNING);
			return array(0, 0);
		}

		list($width, $height, $mime_type, $attribute) = getimagesize(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename);

		$new_width = $width;
		$new_height = $height;
		if ($width > $max_width && $max_width != 0)
		{
			$new_width = $max_width;
			$new_height = floor($height * ($new_width / $width));
			if ($new_height > $max_height && $max_height != 0)
			{
				$new_height = $max_height;
				$new_width = floor($width * ($new_height / $height));
			}
		}
		else if ($height > $max_height && $max_height != 0)
		{
			$new_height = $max_height;
			$new_width = floor($width * ($new_height / $height));
			if ($new_width > $max_width && $max_width != 0)
			{
				$new_width = $max_width;
				$new_height = floor($height * ($new_width / $width));
			}
		}
		return array($new_width, $new_height);
	}

	public static function imageSizeAttributes($request_url, $max_width, $max_height = 0)
	{
		$filename = self::expandUrl($request_url);
		list($new_width, $new_height) = self::imageSize($filename, $max_width, $max_height);
		return 'width="' . $new_width . '" height="' . $new_height . '"';
	}

	public static function imageResize($filename, $max_width, $max_height = 0)
	{
		$starttime_local = explode(' ', microtime());
		$cache_filename = 'cache/' . sha1($filename . '_' . $max_width . '_' . $max_height . '_' . filemtime(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename)) . '.png';
		if (!is_file(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $cache_filename))
		{
			list($width, $height, $mime_type, $attribute) = getimagesize(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename);
			list($new_width, $new_height) = self::imageSize($filename, $max_width, $max_height);

			switch (image_type_to_mime_type($mime_type))
			{
				case 'image/jpeg':
					$image = imagecreatefromjpeg(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename);
					break;

				case 'image/png':
					$image = imagecreatefrompng(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename);
					imagealphablending($image, true);
					imagesavealpha($image, true);
					break;

				case 'image/gif':
					$image = imagecreatefromgif(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename);
					break;

				default:
					user_error('Could not resize "' . $filename . '" since it is not a JPEG, PNG or GIF', WARNING);
					return $filename;
			}

			$resizedImage = imagecreatetruecolor($new_width, $new_height);
			imagealphablending($resizedImage, false);
			imagesavealpha($resizedImage, true);
			imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

			if (function_exists('imageistruecolor') && !imageistruecolor($image) && imagecolortransparent($image) > 0)
				imagetruecolortopalette($resizedImage, false, imagecolorstotal($image));

			imagepng($resizedImage, $cache_filename);
			imagedestroy($resizedImage);
			imagedestroy($image);

			$endtime_local = explode(' ', microtime());
			$totaltime = ($endtime_local[1] + $endtime_local[0] - $starttime_local[1] - $starttime_local[0]);
			Log::caching($cache_filename . ' resize took ' . number_format($totaltime, 4) . 's (' . $width . 'x' . $height . ' to ' . $new_width . 'x' . $new_height . ')');
		}
		return $cache_filename;
	}
}


text:
SET ENV="ox"
SET PACKAGE="osmnx"
CALL %USERPROFILE%\mambaforge\Scripts\activate.bat && ^
conda activate base && ^
mamba env remove -n %ENV% --yes && ^
mamba clean --all --yes --quiet --no-banner && ^
mamba create -c conda-forge --strict-channel-priority -n %ENV% --file "../docker/requirements.txt" --yes --no-banner && ^
conda activate %ENV% && ^
pip uninstall %PACKAGE% --yes && ^
pip install -e ../../. && ^
python -m ipykernel install --sys-prefix --name %ENV% --display-name "Python (%ENV%)" && ^
mamba clean --all --yes --quiet --no-banner && ^
mamba env export -n %ENV% > environment.yml && ^
mamba list --no-banner && ^
jupyter kernelspec list && ^
ipython -c "import %PACKAGE%; print('%PACKAGE% version', %PACKAGE%.__version__)"


text:
package app

import (
	"fmt"
	"github.com/spf13/cobra"
)

var (
	// VERSION is set during build
	VERSION string
)

// NewComponentsCommand Creates a cobra command for Components
func NewVersionCommand() *cobra.Command {

	var versionCmd = &cobra.Command{
		Use:   "version",
		Short: "Show applariat.io client version",
		Run: func(cmd *cobra.Command, args []string) {
			if VERSION == "" {
				VERSION = "unknown"
			}
			fmt.Println(AppLariatCmd.Use + " version " + VERSION)
		},
	}

	return versionCmd

}