text:
@interface ViewController (){
    NSArray *array;
    NSArray *filterArray;
}

@end

@implementation ViewController
Producto *p;
NSMutableArray *lista;

- (void)viewDidLoad
{
    [super viewDidLoad];

    p = [[Producto alloc]init];

    // Do any additional setup after loading the view, typically from a nib.
    self.searchBar.delegate = self;
    self.mapView.delegate = self;
    NSURL *url = [NSURL URLWithString:@"http://198.61.223.60/api/consult/s2"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response,
                                               NSData *data, NSError *connectionError)
     {
         if (connectionError != nil) {
             UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                                 message:[connectionError localizedDescription]
                                                                delegate:nil
                                                       cancelButtonTitle:@"Ok"
                                                       otherButtonTitles:nil];
             [alertView show];
         }
         if (data.length > 0) {
             NSArray *array = [NSJSONSerialization JSONObjectWithData:data
                                                              options:0
                                                                error:NULL];

             CLLocationCoordinate2D location;                         // coordinates of the annotation
             NSMutableArray *newAnnotations = [NSMutableArray array]; // an array in which we'll save our annotations temporarily
             MKPointAnnotation *newAnnotation;                        // the pointer to the annotation we're adding

             // iterate through the array, adding an annotation to our our array of new annotations

             for (NSDictionary *dictionary in array)
             {
                 // retrieve latitude and longitude from the dictionary entry
                 NSNumber *lat = [NSNumber numberWithDouble:[dictionary[@"lat"] doubleValue]];
                 NSNumber *lngg = [NSNumber numberWithDouble:[dictionary[@"lng"] doubleValue]];
                 location.latitude = [lngg doubleValue];
                 location.longitude = [lat doubleValue];

                 // create the annotation

                 newAnnotation = [[MKPointAnnotation alloc] init];
                 newAnnotation.title = dictionary[@"name"];
                 newAnnotation.coordinate = location;

                 // add it to our array
                 //
                 // incidentally, generally I just add it to the mapview directly, but
                 // given that you have a didAddAnnotationViews, we'll just build up
                 // an array and add them all to the map view in one step after we're
                 // done iterating through the JSON results

                 [newAnnotations addObject:newAnnotation];

                 // clean up

             }
             MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(location, 7000100, 7000100);
             [self.mapView setRegion:region];
             [self.mapView addAnnotations:newAnnotations];

         }
     }];

    lista = [[NSMutableArray alloc]init];

    // when done, add the annotations
    [self llenarLista];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"%@",searchBar.text);
    [self.searchBar resignFirstResponder];
    for (int i = 0; i < [lista count]; i++){
        Producto *producto = [lista objectAtIndex:i];
        if([producto.nombre isEqualToString:searchBar.text]){
            CLLocationCoordinate2D location;                         // coordinates of the annotation
            NSMutableArray *newAnnotations = [NSMutableArray array]; // an array in which we'll save our annotations temporarily
            MKPointAnnotation *newAnnotation;                        // the pointer to the annotation we're adding

            location.latitude = [producto.lat doubleValue];
            location.longitude = [producto.lng doubleValue];

            // create the annotation
            newAnnotation = [[MKPointAnnotation alloc] init];
            newAnnotation.title = producto.nombre;
            newAnnotation.coordinate = location;

            MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(location, 7000100, 7000100);
            [self.mapView setRegion:region];
            [self.mapView addAnnotations:newAnnotations];
        }
    }
    //next you've to setup logic to pass search text to your mapview
}

- (void)llenarLista{
    p.nombre = @"Moto";
    p.establecimiento = @"Akt";
    p.lat = [NSNumber numberWithDouble:[@10.925491 doubleValue]];
    p.lng = [NSNumber numberWithDouble:[@-74.79475 doubleValue]];
    [lista addObject:p];
    p.nombre = @"Moto";
    p.establecimiento = @"Jana`s Moto";
    p.lat = [NSNumber numberWithDouble:[@10.925491 doubleValue]];
    p.lng = [NSNumber numberWithDouble:[@-74.79475 doubleValue]];
    [lista addObject:p];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
package org.elasticsearch.gradle.info;

import org.gradle.api.provider.Provider;

import java.io.File;

public class JavaHome {
    private Integer version;
    private Provider<File> javaHome;

    private JavaHome(int version, Provider<File> javaHome) {
        this.version = version;
        this.javaHome = javaHome;
    }

    public static JavaHome of(int version, Provider<File> javaHome) {
        return new JavaHome(version, javaHome);
    }

    public Integer getVersion() {
        return version;
    }

    public Provider<File> getJavaHome() {
        return javaHome;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

class OldFilesRemoverRecursive extends OldFilesRemover {

    protected $removeEmptyDirs;
    protected $dirsToCheckIfEmpty   =   array();

    /**
     * @param RecursiveIteratorIterator $directoryIterator
     * @param DateTime $dateTime
     * @param array $extensions - optionnal - array of extensions (without the dots)
     * @param bool $removeEmptyDirs - if we need to remove empty directories
     */
    public function __construct(\RecursiveIteratorIterator $directoryIterator, \DateTime $dateTime, Array $extensions = array(), $removeEmptyDirs = true) {
        $this->directoryIterator    =   $directoryIterator;
        $this->dateTime             =   $dateTime;
        $this->extensions           =   array_map('strtolower', $extensions);
        $this->removeEmptyDirs      =   $removeEmptyDirs;
    }

    /**
     * Deletes files older than the DateTime instance submitted
     * If $removeEmptyDirs property is set to true, we'll remove the empty directories affected by deletions
     *
     * @return int Number of deleted files
     */
    public function deleteOldFiles() {

        $nbDeletedFiles = 0;

        foreach ($this->directoryIterator AS $file)
            if ($this->isValid($file))
                unlink((string)$file->getPathName()) AND $this->addDirToCheck($file->getPath()) AND $nbDeletedFiles++;

        if ($nbDeletedFiles > 0)
            $this->files = array();

        if ($this->removeEmptyDirs)
            foreach ($this->dirsToCheckIfEmpty AS &$dir)
                if (count(glob($dir . DIRECTORY_SEPARATOR . '*')) === 0)
                    unlink($dir);

        $this->dirsToCheckIfEmpty = array();

        return $nbDeletedFiles;
    }

    /**
     * Checks that a file is a real file, that it has expired, and its extension
     * @param SplFileInfo $file
     * @return bool
     */
    protected function isValid(\SplFileInfo $file) {
        return ($file->isFile() && DateTime::CreateFromFormat('U', $file->getMTime()) < $this->dateTime && (!$this->extensions || in_array(strtolower($file->getExtension()), $this->extensions)));
    }

    /**
     * Adds a directory to check later if it's empty or not
     * @param $dir
     * @return bool
     */
    protected function addDirToCheck($dir) {
        if (!in_array($dir, $this->dirsToCheckIfEmpty))
            $this->dirsToCheckIfEmpty[] = $dir;
        return true;
    }

}


text:
package dotty.tools
package dottydoc
package core

import dotc.core.Contexts.Context
import model._
import model.internal._
import transform.DocMiniPhase

class PackageObjectsPhase extends DocMiniPhase {

  override def transformPackage(implicit ctx: Context) = { case pkg: PackageImpl =>
    pkg
      .members
      .collectFirst { case o: Object if o.symbol.isPackageObject => o }
      .map { obj =>
        pkg.copy(
          members = obj.members ++ pkg.members,
          superTypes = obj.superTypes,
          comment = obj.comment
        )
      }
      .getOrElse(pkg) :: Nil
  }

  override def transformObject(implicit ctx: Context) = { case obj: Object =>
    if (obj.symbol.isPackageObject) Nil
    else obj :: Nil
  }
}


text:
#include <stdlib.h>
#include <new>
#include "sgx_defs.h"
#include "sgx_trts.h"
#include "internal/se_cdefs.h"
#include "internal/cpprt_internal.h"

//allocates size bytes of storage space.
//aligned to represent an object of that size
//and returns a non-null pointer to the first byte of this block.
//On failure, it throws a bad_alloc exception.
SGX_WEAK void* SGXAPI operator new(size_t dwBytes) throw(std::bad_alloc)
{
	void* address =  malloc(dwBytes);
	while ( address == NULL ){
		if ( !call_newh() ){
			throw std::bad_alloc();
		}
		address =  malloc(dwBytes);
	}
	return address;
}


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

namespace Boxes.Integration.Setup.Interception
{
    using System;

    /// <summary>
    /// contains information on when and where to apply an Aspect
    /// </summary>
    public class InterceptorMeta
    {
        /// <summary>
        /// when to apply this interceptor
        /// </summary>
        public Predicate<InterceptionContext> Where { get; set; }

        /// <summary>
        /// the interceptor to apply
        /// </summary>
        public Type Interceptor { get; set; }
    }
}


text:
package de.taimos.dvalin.monitoring.aws;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.amazonaws.services.cloudwatch.AmazonCloudWatch;
import com.amazonaws.services.cloudwatch.model.Dimension;
import com.amazonaws.services.cloudwatch.model.MetricDatum;
import com.amazonaws.services.cloudwatch.model.PutMetricDataRequest;
import com.amazonaws.services.cloudwatch.model.StandardUnit;

import de.taimos.dvalin.cloud.aws.AWSClient;
import de.taimos.dvalin.monitoring.MetricInfo;
import de.taimos.dvalin.monitoring.MetricSender;
import de.taimos.dvalin.monitoring.MetricUnit;

/**
 * Metric sender using AWS CloudWatch
 */
@Component
public class AWSMetricSender implements MetricSender {

    @AWSClient
    private AmazonCloudWatch cloudWatch;

    @Override
    public void sendMetric(MetricInfo metric, Double value) {
        PutMetricDataRequest req = new PutMetricDataRequest();
        req.setNamespace(metric.getNamespace());

        MetricDatum metricDatum = new MetricDatum();
        metricDatum.withMetricName(metric.getMetric());
        metricDatum.withUnit(this.convertUnit(metric.getUnit()));
        metricDatum.withDimensions(this.getDimensionsFromMetricInfo(metric));
        metricDatum.withValue(value);
        req.setMetricData(Collections.singleton(metricDatum));
        this.cloudWatch.putMetricData(req);
    }

    private List<Dimension> getDimensionsFromMetricInfo(MetricInfo metric) {
        List<Dimension> dimensions = new ArrayList<>();
        for (Map.Entry<String, String> entry : metric.getDimensions().entrySet()) {
            dimensions.add(new Dimension().withName(entry.getKey()).withValue(entry.getValue()));
        }
        return dimensions;
    }

    private StandardUnit convertUnit(MetricUnit unit) {
        final StandardUnit awsunit;
        switch (unit) {
        case Bits:
            awsunit = StandardUnit.Bits;
            break;
        case BitsSecond:
            awsunit = StandardUnit.BitsSecond;
            break;
        case Bytes:
            awsunit = StandardUnit.Bytes;
            break;
        case BytesSecond:
            awsunit = StandardUnit.BytesSecond;
            break;
        case Count:
            awsunit = StandardUnit.Count;
            break;
        case CountSecond:
            awsunit = StandardUnit.CountSecond;
            break;
        case Seconds:
            awsunit = StandardUnit.Seconds;
            break;
        case Milliseconds:
            awsunit = StandardUnit.Milliseconds;
            break;
        case None:
            awsunit = StandardUnit.None;
            break;
        case Percent:
            awsunit = StandardUnit.Percent;
            break;
        default:
            throw new IllegalArgumentException("Invalid unit " + unit);
        }
        return awsunit;
    }
}


text:
"""
Input: raw imported file
Output: list type processed data
Purpose: Process raw data to a manageable form
Methods (1):
        process_file(1 argument type textfile)
           expected: one row contains one value
"""

import importer as importer

# File processor
def process_file(filename):
    # Get file contents
    imported_file = importer.import_file(filename)

    # Add data to list
    # \n - newline
    processed_list = imported_file.split("\n")

    return processed_list


text:
namespace Dropbox.Api.Auth
{
    using sys = System;
    using col = System.Collections.Generic;
    using re = System.Text.RegularExpressions;

    using enc = Dropbox.Api.Stone;

    /// <summary>
    /// <para>The token from o auth1 error object</para>
    /// </summary>
    public class TokenFromOAuth1Error
    {
        #pragma warning disable 108

        /// <summary>
        /// <para>The encoder instance.</para>
        /// </summary>
        internal static enc.StructEncoder<TokenFromOAuth1Error> Encoder = new TokenFromOAuth1ErrorEncoder();

        /// <summary>
        /// <para>The decoder instance.</para>
        /// </summary>
        internal static enc.StructDecoder<TokenFromOAuth1Error> Decoder = new TokenFromOAuth1ErrorDecoder();

        /// <summary>
        /// <para>Initializes a new instance of the <see cref="TokenFromOAuth1Error" />
        /// class.</para>
        /// </summary>
        public TokenFromOAuth1Error()
        {
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is
        /// InvalidOauth1TokenInfo</para>
        /// </summary>
        public bool IsInvalidOauth1TokenInfo
        {
            get
            {
                return this is InvalidOauth1TokenInfo;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a InvalidOauth1TokenInfo, or <c>null</c>.</para>
        /// </summary>
        public InvalidOauth1TokenInfo AsInvalidOauth1TokenInfo
        {
            get
            {
                return this as InvalidOauth1TokenInfo;
            }
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is AppIdMismatch</para>
        /// </summary>
        public bool IsAppIdMismatch
        {
            get
            {
                return this is AppIdMismatch;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a AppIdMismatch, or <c>null</c>.</para>
        /// </summary>
        public AppIdMismatch AsAppIdMismatch
        {
            get
            {
                return this as AppIdMismatch;
            }
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is Other</para>
        /// </summary>
        public bool IsOther
        {
            get
            {
                return this is Other;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a Other, or <c>null</c>.</para>
        /// </summary>
        public Other AsOther
        {
            get
            {
                return this as Other;
            }
        }

        #region Encoder class

        /// <summary>
        /// <para>Encoder for  <see cref="TokenFromOAuth1Error" />.</para>
        /// </summary>
        private class TokenFromOAuth1ErrorEncoder : enc.StructEncoder<TokenFromOAuth1Error>
        {
            /// <summary>
            /// <para>Encode fields of given value.</para>
            /// </summary>
            /// <param name="value">The value.</param>
            /// <param name="writer">The writer.</param>
            public override void EncodeFields(TokenFromOAuth1Error value, enc.IJsonWriter writer)
            {
                if (value is InvalidOauth1TokenInfo)
                {
                    WriteProperty(".tag", "invalid_oauth1_token_info", writer, enc.StringEncoder.Instance);
                    InvalidOauth1TokenInfo.Encoder.EncodeFields((InvalidOauth1TokenInfo)value, writer);
                    return;
                }
                if (value is AppIdMismatch)
                {
                    WriteProperty(".tag", "app_id_mismatch", writer, enc.StringEncoder.Instance);
                    AppIdMismatch.Encoder.EncodeFields((AppIdMismatch)value, writer);
                    return;
                }
                if (value is Other)
                {
                    WriteProperty(".tag", "other", writer, enc.StringEncoder.Instance);
                    Other.Encoder.EncodeFields((Other)value, writer);
                    return;
                }
                throw new sys.InvalidOperationException();
            }
        }

        #endregion

        #region Decoder class

        /// <summary>
        /// <para>Decoder for  <see cref="TokenFromOAuth1Error" />.</para>
        /// </summary>
        private class TokenFromOAuth1ErrorDecoder : enc.UnionDecoder<TokenFromOAuth1Error>
        {
            /// <summary>
            /// <para>Create a new instance of type <see cref="TokenFromOAuth1Error" />.</para>
            /// </summary>
            /// <returns>The struct instance.</returns>
            protected override TokenFromOAuth1Error Create()
            {
                return new TokenFromOAuth1Error();
            }

            /// <summary>
            /// <para>Decode based on given tag.</para>
            /// </summary>
            /// <param name="tag">The tag.</param>
            /// <param name="reader">The json reader.</param>
            /// <returns>The decoded object.</returns>
            protected override TokenFromOAuth1Error Decode(string tag, enc.IJsonReader reader)
            {
                switch (tag)
                {
                    case "invalid_oauth1_token_info":
                        return InvalidOauth1TokenInfo.Decoder.DecodeFields(reader);
                    case "app_id_mismatch":
                        return AppIdMismatch.Decoder.DecodeFields(reader);
                    default:
                        return Other.Decoder.DecodeFields(reader);
                }
            }
        }

        #endregion

        /// <summary>
        /// <para>Part or all of the OAuth 1.0 access token info is invalid.</para>
        /// </summary>
        public sealed class InvalidOauth1TokenInfo : TokenFromOAuth1Error
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<InvalidOauth1TokenInfo> Encoder = new InvalidOauth1TokenInfoEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<InvalidOauth1TokenInfo> Decoder = new InvalidOauth1TokenInfoDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="InvalidOauth1TokenInfo" />
            /// class.</para>
            /// </summary>
            private InvalidOauth1TokenInfo()
            {
            }

            /// <summary>
            /// <para>A singleton instance of InvalidOauth1TokenInfo</para>
            /// </summary>
            public static readonly InvalidOauth1TokenInfo Instance = new InvalidOauth1TokenInfo();

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="InvalidOauth1TokenInfo" />.</para>
            /// </summary>
            private class InvalidOauth1TokenInfoEncoder : enc.StructEncoder<InvalidOauth1TokenInfo>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(InvalidOauth1TokenInfo value, enc.IJsonWriter writer)
                {
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="InvalidOauth1TokenInfo" />.</para>
            /// </summary>
            private class InvalidOauth1TokenInfoDecoder : enc.StructDecoder<InvalidOauth1TokenInfo>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="InvalidOauth1TokenInfo"
                /// />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override InvalidOauth1TokenInfo Create()
                {
                    return InvalidOauth1TokenInfo.Instance;
                }

            }

            #endregion
        }

        /// <summary>
        /// <para>The authorized app does not match the app associated with the supplied access
        /// token.</para>
        /// </summary>
        public sealed class AppIdMismatch : TokenFromOAuth1Error
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<AppIdMismatch> Encoder = new AppIdMismatchEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<AppIdMismatch> Decoder = new AppIdMismatchDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="AppIdMismatch" />
            /// class.</para>
            /// </summary>
            private AppIdMismatch()
            {
            }

            /// <summary>
            /// <para>A singleton instance of AppIdMismatch</para>
            /// </summary>
            public static readonly AppIdMismatch Instance = new AppIdMismatch();

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="AppIdMismatch" />.</para>
            /// </summary>
            private class AppIdMismatchEncoder : enc.StructEncoder<AppIdMismatch>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(AppIdMismatch value, enc.IJsonWriter writer)
                {
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="AppIdMismatch" />.</para>
            /// </summary>
            private class AppIdMismatchDecoder : enc.StructDecoder<AppIdMismatch>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="AppIdMismatch" />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override AppIdMismatch Create()
                {
                    return AppIdMismatch.Instance;
                }

            }

            #endregion
        }

        /// <summary>
        /// <para>The other object</para>
        /// </summary>
        public sealed class Other : TokenFromOAuth1Error
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<Other> Encoder = new OtherEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<Other> Decoder = new OtherDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="Other" /> class.</para>
            /// </summary>
            private Other()
            {
            }

            /// <summary>
            /// <para>A singleton instance of Other</para>
            /// </summary>
            public static readonly Other Instance = new Other();

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="Other" />.</para>
            /// </summary>
            private class OtherEncoder : enc.StructEncoder<Other>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(Other value, enc.IJsonWriter writer)
                {
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="Other" />.</para>
            /// </summary>
            private class OtherDecoder : enc.StructDecoder<Other>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="Other" />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override Other Create()
                {
                    return Other.Instance;
                }

            }

            #endregion
        }
    }
}


text:
#ifndef __SGE__
#define __SGE__

// Includes
#include <GLFW/glfw3.h> /* GLFW */
#include <iostream>
#define _USE_MATH_DEFINES /* math.h allowance of constant math defines like PI = 3.141 ect. */
#include <math.h>
#include <exception>
#include <stdexcept>
#include <sstream>
#include <string>
#include <vector>
#include <stdbool.h>
#include "pack.h"
// End of Includes

#define 	COMMENT_OUT 		0
#defined 	COMMENT_BAD_PROG	0
#defined 	COMMENT_DEPRECATED	0

//SE Utilities
#if COMMENT_DEPRECATED //entire file is deprecated
namespace seu
{
	//Portable Datatypes
	/// Portable Character Datatype
	typedef int16_t		SEchar;
	/// Portable Integer Datatype
	typedef int16_t		SEint;
	/// Portable Unsigned Integer Datatype
	typedef uint16_t	SEuint;
	/// Portable Long Datatype
	typedef int32_t		SElong;
	/// Portable Unsigned Long Datatype
	typedef uint32_t	SEulong;
	/// Portable Float Datatype
	typedef int32_t 	SEfloat;
	/// Portable Double Datatype
	typedef int64_t 	SEdouble;
	/// Portable Boolean Datatype
	typedef _Bool		SEbool;
	//End of Portable Datatypes

	/**
	 *	A Portable way to convert a C standard datatype to platform-independent datatype
	 *
	 *	@param pack The C standard datatype
	 *
	 *	@return The independent datatype equal to the C standard datatype
	 */
	uint64_t packInteger(long double pack);
	/**
	 *	A Portable way to convert a platform-independent datatype to C standard datatype
	 *
	 *	@param unpack The independent datatype
	 *
	 *	@return The C standard integer(any numerical datatype) equal to the packed orignal datatype
	 */
	long double unpackInteger(uint64_t unpack);

	///An exception class for the SpartanEngine
	class Exception: public std::exception
	{
	public:
		/**
		 *  The constructor of Exception
		 *
		 *  @param msg The message the Exception is returning
		 */
		Exception(const char* msg);

		/**
		 *  The deconstructor of Exception
		 */
		~Exception();

		/**
		 *  Gets the message the Exception is holding
		 *
		 *  @return The message the exception is holding
		 */
		virtual const char* what() const;

		/**
		 *  Gets the message the Exception is holding
		 *
		 *  @return The message the exception is holding
		 */
		virtual std::string getMessage() const;
		std::string operator <<(std::string all);
		std::string operator <<(const char* all);
	private:
		std::string msg_;///<Message this Exception is holding
	};
}
//End of SE Utilities

//SE Math
namespace sem
{
	/**
	 *	Generates a random number
	 *
	 *	Generates a random numbers using the standard c++ number generator
	 *	with srand handled by the function
	 *
	 *	@param lowerRange	The lowest possible number for the generator
	 *	@param higherRange	The highest possible number for the generator
	 *
	 *	@return A random number between lowerRange and higherRange
	 */
	seu::SEfloat random(seu::SEfloat lowerRange, seu::SEfloat higherRange);

	/**
	 *	Gets PI
	 *
	 *	@return PI
	 */
	seu::SEdouble PI();

	/**
	 *	Calculates the Distance between two points
	 *
	 *	Calculates the Distance between two 3D points using
	 *	Spartan Engine Vectors
	 *
	 *	@param point1	The start point
	 *	@param point2	The end point
	 *
	 *	@return The Vector difference
	 */
	seu::Vector distance(seu::Vector point1, seu::Vector point2);

	/**
	 *	Converts Radians to Degrees
	 *
	 *	@param radian	The radian to convert
	 *
	 *	@return The degree of radian
	 */
	seu::SEfloat toDegrees(seu::SEfloat radian);

	/**
	 *	Converts Degrees to Radians
	 *
	 *	@param degree	The degree to convert
	 *
	 *	@return The radian of degree
	 */
	seu::SEfloat toRadians(seu::SEfloat degree);

	/**
	 *	Provides the fraction of time
	 *
	 *	Provides the fraction of time based on
	 *	current
	 *
	 *	@param start	The start of the time
	 *	@param end		The end of the time
	 *	@param current	The current time to divide turn into a fraction
	 *
	 *	@return The fraction of time
	 */
	seu::SEfloat fractionTime(seu::SEfloat start, seu::SEfloat end, seu::SEfloat current);

	/**
	 *	Gets the square root of square
	 *
	 *	Gets the square root of square but is much more accurate and
	 *	faster then the standard library
	 *
	 *	@param square	The number to find the square root of
	 *
	 *	@return The square root of square
	 */
	seu::SEfloat sqrt(seu::SEfloat square);

	/**
	 *
	 *	Gets the sin of x
	 *
	 *	Gets the sine of x in radians unless convert
	 *	is true
	 *
	 *	@param x		The number to get the sin of
	 *	@param convert	Use to get a degree instead	Default: false
	 *
	 *	@return	The sin of x (in radians unless convert = true)
	 *
	*/
	seu::SEfloat sin(seu::SEfloat x, seu::SEbool convert = false);

	/**
	 *
	 *	Gets the cos of x
	 *
	 *	Gets the cosine of x in radians unless convert
	 *	is true
	 *
	 *	@param x		The number to get the cos of
	 *	@param convert	Use to get a degree instead	Default: false
	 *
	 *	@return	The cos of x (in radians unless convert = true)
	 *
	*/
	seu::SEfloat cos(seu::SEfloat x, seu::SEbool convert = false);

	/**
	 *
	 *	Gets the tan of x
	 *
	 *	Gets the tangent of x in radians unless convert
	 *	is true
	 *
	 *	@param x		The number to get the tan of
	 *	@param convert	Use to get a degree instead	Default: false
	 *
	 *	@return	The tan of x (in radians unless convert = true)
	 *
	*/
	seu::SEfloat tan(seu::SEfloat x, seu::SEbool convert = false);
}
//End of SE Math

//SE Physics
namespace sep
{
	/**
	 *	The active Physics Properties that an object can have
	 */
	class PhysicsProperties
	{
	public:
		/**
		 *	The constructor for PhysicsProperties
		 *
		 *	@param gravity		Whether gravity is enabled for this object Default: true
		 *	@param collision	Whether collisions are active in this object Default: true
		 *	@param rigidBody	Whether an object has rigid body transformations (like rotating down a hill as a sphere) Default: true
		 *	@param otherPhysics	Whether an alternate act of physics is taken into account Deafult: true
		 **/
		PhysicsProperties(seu::SEbool gravity = true, seu::SEbool collision = true, seu::SEbool rigidBody = true, seu::SEbool otherPhysics = true);

		/**
		 *	The destructor for PhysicProperties
		 **/
		~PhysicsProperties();

		/**
		 *	Toggles whether gravity is active or not
		 *
		 *	@return Whether gravity is currently enabled
		 **/
		seu::SEbool ToggleGravity();

		/**
		 *	Toggles whether collision detection is active
		 *
		 *	@return Whether collisions are currently active
		 **/
		seu::SEbool ToggleCollision();

		/**
		 *	Toggles whether Rigid Body transformations are possible
		 *
		 *	@return Whether rigid bodies for this object are active
		 **/
		seu::SEbool ToggleRigidBody();

		/**
		 *	Toggles whether physics are possible for this object
		 *
		 *	@return Whether physics for this object are active
		 **/
		seu::SEbool TogglePhysics();

		/**
		 *	Toggles whether alternate non-describe physics are possible
		 *
		 *	@return Whether alternate non-describe physics for this object are active
		 **/
		seu::SEbool ToggleAlternatePhysics();

		/**
		 *	Returns whether gravity is enabled or not
		 *
		 *	@return If gravity is active for this object
		 **/
		seu::SEbool HasGravity();

		/**
		 *	Returns whether collisions are enabled or not
		 *
		 *	@return If collisions are active for this object
		 **/
		seu::SEbool HasCollision();

		/**
		 *	Returns whether rigid body transformations are enabled or not
		 *
		 *	@return If rigid body transformations are active for this object
		 **/
		seu::SEbool HasRigidBody();

		/**
		 *	Returns whether alternate nondescribe physics are enabled or not
		 *
		 *	@return If alternate nondescribe physics are active for this object
		 **/
		seu::SEbool UsesAlternatePhysics();
	private:
		seu::SEbool gravity;///<Boolean of enabled gravity
		seu::SEbool collision;///<Boolean of enabled collision
		seu::SEbool rigidBody;///<Boolean of enabled rigid body physics
		seu::SEbool otherPhysics;///<Boolean of alternate enabled physics
	};

	/**
	 *  The physic holder for entities
	 *
	 **/
	class PhysicsState
	{
	public:
		/**
		 *  The constructor of PhysicsState
		 *
		 *  @param position The position this state holds for its object
		 *  @param rotation The rotation(recommended in degrees) this state holds for its object
		 *  @param velocity The velocity this state holds for its object (increases the position according to its states)
		 *  @param acceleration The acceleration this state holds for it object (increases the velocity according to it state)
		 *	@param pProps The PhysicsState current physical properties to apply to this object
		 */
		PhysicsState(seu::Vector position = seu::Vector(), seu::Vector rotation = seu::Vector(), seu::Vector velocity = seu::Vector(), seu::Vector acceleration = seu::Vector(), PhysicsProperties pProps = PhysicsProperties());

		/**
		 *  The deconstructor of PhysicsState
		 */
		~PhysicsState();

		seu::Vector position; ///< The States' current position
		seu::Vector rotation; ///< The States' current rotation
		seu::Vector velocity; ///< The States' current velocity
		seu::Vector acceleration; ///< The States' current acceleration
		PhysicsProperties physicsProps; ///< The properties for this physics state
	};

	class PhysicsEntity
	{
	public:
		/**
		 *  The constructor of PhysicsEntity
		 *
		 *  @param state The PhysicsState that represents this entity
		 */
		PhysicsEntity(PhysicsState state);

		/**
		 *  The deconstructor of PhysicsEntity
		 */
		~PhysicsEntity();

		/**
		 *  The function that updates the this PhysicsEntity
		 */
		void Update();
		PhysicsState pState; ///< The PhysicsState that represents this entity
	};

	class Gravity
	{
	public:
		/**
		 *  The constructor of Gravity
		 *
		 *  @param gravity The 3D gravity strength in certains direction that effects all gravity enabled objects
		 */
		Gravity(seu::Vector gravity);

		/**
		 *  The deconstructor of Gravity
		 */
		~Gravity();

		/**
		 *  Gets the current gravity
		 *
		 *  @return The objects current gravity strength
		 */
		virtual seu::Vector GetGravity();
	private:
		seu::Vector gravity;///<Gravities Directions
	};

	class Gravity3D
	{
	public:
		/**
		 *  The constructor of Gravity3D
		 *
		 *  @param grav_strength The strength of the gravitational pull
		 *  @param grav_location The location that this gravity is pulling towards
		 */
		Gravity3D(seu::Vector grav_location);

		/**
		 *  The deconstructor of Gravity3D
		 */
		~Gravity3D();

		/**
		 *  Gets the location of gravity
		 *
		 *  @return The location of the gravity
		 */
		seu::Vector GetLocation();

		/**
		 *  Gets the strength of the gravity
		 *
		 *  @return The strength of gravity
		 */
		seu::Vector GetGravity();
	private:
		seu::Vector grav_location;///<Location of this Gravity
		seu::Vector grav_strength;///<Strength of this Gravity
	};

}

//End of SE Physics

//SE Graphics
namespace seg
{
	struct Vertex
	{
		seu::Vector vertex;///<Vertex Location
		seu::Vector normal;///<Vertex Normal
		///Vertex Texturing
		seu::SEfloat s0, t0;///<Vertex Texturing
	};

	struct Triangle
	{
		Vertex a;///<First Vertex of this Triangle
		Vertex b;///<Second Vertex of this Triangle
		Vertex c;///<Third Vertex of this Triangle
		unsigned short index[3];///<Indexes for the this Triangle
	};

	struct TriangleVector
	{
		std::vector<Triangle> triangles;
	};

	class VBO
	{
	public:
		VBO(TriangleVector holder);
		~VBO();
		void Render();
	private:
		unsigned int vaoID[1];
		unsigned int vboID[1];
	};

	class Object
	{
	public:
		Object(seu::Vector position);
		virtual seu::SEbool Start();
		virtual void Update();
		virtual void Stop();
		void SetPosition(seu::Vector pos);
		seu::Vector GetPosition();
	private:
		seu::Vector position;
		virtual void UpdateGraphics();
	};

	class FlatObject ///Simple Flatly Rendered Object
	{
	public:
		FlatObject(seu::DDVector position, seu::SEfloat scale = 1.0);
		virtual seu::SEbool Start();
		virtual void Update();
		virtual void Stop();
		void SetPosition(seu::DDVector pos);
		seu::DDVector GetPosition();
		void SetScale(seu::SEfloat scale = 1.0);
		float GetScale();
	private:
		seu::DDVector position;
		seu::SEfloat scale;
		virtual void UpdateGraphics();
	};
}
#endif
//End of SE Graphics

#endif /* defined(__SGE__) */


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->
<resources>
	<string name="app_name" translatable="false">ConnectBot</string>

	<string name="copyright_info" translatable="false">ConnectBot is provided under the Apache License, Version 2.0 (the “License”).  Here are a few key points:\n\nYou may not use this program except in compliance with the License. You may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.</string>

	<!-- "Up" button in virtual keyboard. -->
	<string name="button_key_up">\u25B2</string>
	<!-- "Down" button in virtual keyboard. -->
	<string name="button_key_down">\u25BC</string>
	<!-- "Left" button in virtual keyboard. -->
	<string name="button_key_left">\u25C0</string>
	<!-- "Right" button in virtual keyboard. -->
	<string name="button_key_right">\u25B6</string>
</resources>


text:
package com.devopstest.composite.model;

import lombok.Data;

/**
 * Created by demo
 */
@Data
public class Venue {
    private String venueName;
    private boolean isAvailable;
    private long reservationId;
    private String bookingDate;
    private String personName;
}


text:
package twitter4j.examples.search;

import twitter4j.*;

import java.util.List;

/**
 * @author Yusuke Yamamoto - yusuke at mac.com
 * @since Twitter4J 2.1.7
 */
public class SearchTweets {
    /**
     * Usage: java twitter4j.examples.search.SearchTweets [query]
     *
     * @param args search query
     */
    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("java twitter4j.examples.search.SearchTweets [query]");
            System.exit(-1);
        }
        Twitter twitter = new TwitterFactory().getInstance();
        try {
            Query query = new Query(args[0]);
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
        }
    }
}


text:
<?xml version="1.0" encoding="ISO-8859-1" ?>

<document>
    <properties>
        <title>Apache Synapse - Sample 255</title>
    </properties>

<definitions xmlns="http://ws.apache.org/ns/synapse">

    <proxy name="StockQuoteProxy" transports="vfs">

        <target>
            <inSequence>
                <header name="Action" value="urn:getQuote"/>
            </inSequence>
            <endpoint>
                <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
            </endpoint>
            <outSequence>
                <property action="set" name="OUT_ONLY" value="true"/>
                <send>
                    <endpoint>
                        <address uri="mailto:user@host"/> <!--CHANGE-->
                    </endpoint>
                </send>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>

        <parameter name="transport.vfs.FileURI">vfs:ftp://guest:guest@localhost/test?vfs.passive=true</parameter> <!--CHANGE-->
        <parameter name="transport.vfs.ContentType">text/xml</parameter>
        <parameter name="transport.vfs.FileNamePattern">.*\.xml</parameter>
        <parameter name="transport.PollInterval">15</parameter>
    </proxy>

</definitions>

            <subsection name="Objective">

                    In sample 254 we looked at how the VFS transport
                    can be used to read files from the local file system. VFS transport can also be
                    used to read files from FTP, SFTP and CIFS sites. This sample illustrates how to
                    read from a remote FTP site and send the content to a remote client as an e-mail.

            </subsection>
            <subsection name="Pre-requisites">

ant stockquote -Daddurl=http://localhost:9000/services/SimpleStockQuoteService -Dtrpurl=http://localhost:8280/

Sat Nov 18 21:01:23 IST 2006 SimpleStockQuoteService :: Generating quote for : IBM

Standard :: Stock price = $95.26454380258552

                            This sample requires access to a FTP site and an e-mail account.

                            Deploy the SimpleStockQuoteService in the sample Axis2 server and start Axis2

                            Enable the VFS transport listener for Synapse (refer VFS setup guide for
                            more details).

                            Enable the mail transport sender for Synapse
                            (refer  Mail transport setup
                            guide for more details).

                            Create a new test directory in the FTP site.

                            Open the repository/conf/sample/synapse_sample_255.xml and edit the
                            transport.vfs.FileURI parameter to point to the test directory in the FTP
                            server. Also change the endpoint in the out sequence to point to your
                            e-mail account.

                            Start Synapse using the configuration numbered 255 (repository/conf/sample/synapse_sample_255.xml)

                                Unix/Linux: sh synapse.sh -sample 255

                                Windows: synapse.bat -sample 255

            </subsection>
            <subsection name="Executing the Client">

                    Copy the test.xml file in the repository/conf/sample/resources/vfs directory to
                    the directory given in transport.vfs.FileURI above (i.e the test directory in
                    FTP server). This file contains a simple stock quote request in XML/SOAP format.

<?xml version='1.0' encoding='UTF-8'?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://www.w3.org/2005/08/addressing">
    <soapenv:Body>
            <m0:getQuote xmlns:m0="http://services.samples">
                    <m0:request>
                            <m0:symbol>IBM</m0:symbol>
                    </m0:request>
            </m0:getQuote>
    </soapenv:Body>
</soapenv:Envelope>

                    VFS transport will pick up the file from the FTP site and send the content to
                    the stock quote service in Axis2 over HTTP. Response from Axis2 will be sent to
                    the mail endpoint as an e-mail. It should show up in the configured e-mail account
                    after a few seconds.

            </subsection>

Back to Catalog

</document>


text:
require 'spec_helper'

describe ActiveModel::Serializer::Validator do
  describe :valid? do
    subject { ActiveModel::Serializer.new(OpenStruct.new(foo: 'bar')) }
    before { ActiveModel::Serializer.stub(:valid_against_schema?).and_return(stubbed_validation) }

    context 'with empty errors' do
      let(:stubbed_validation) { [] }
      it { should be_valid }
    end

    context 'with errors' do
      let(:stubbed_validation) { ['First error', 'Second error'] }
      it { should_not be_valid }
    end
  end

  describe :valid_against_schema? do
    before do
      try_remove_const(:ProductSerializer)

      ProductSerializer = Class.new(ActiveModel::Serializer) do
        self.root = false
        attributes :id, :name, :price, :tags
      end
    end

    subject { ActiveModel::Serializer.valid_against_schema?(product_schema, serializer) }
    let(:serializer) { ProductSerializer.new(serializable) }
    let(:schema) { product_schema }

    context 'without validaton errors' do
      let(:serializable) { OpenStruct.new(id: 4, name: "Widget", price: 1200, tags: %w(foo bar baz)) }
      it { should be_empty }
    end

    context 'with validaton errors' do
      let(:serializable) { OpenStruct.new(id: 4, price: 1200, tags: %w(foo bar baz)) }
      it { should_not be_empty }
      its(:length) { should eql 1 }
    end
  end

  describe :json_schema do
    subject { ProductSerializer.new(serializable) }
    let(:set_schema!) { ProductSerializer.json_schema schema_file }

    before do
      try_remove_const(:ProductSerializer)

      ProductSerializer = Class.new(ActiveModel::Serializer) do
        self.root = false
        attributes :id, :name, :price, :tags
      end
    end

    context 'with existing file' do
      let(:schema_file) { File.expand_path("../fixtures/product.jsonschema", __FILE__) }
      before { set_schema! }

      context 'with valid serializable' do
        let(:serializable) { OpenStruct.new(id: 4, name: "Widget", price: 1200, tags: %w(foo bar baz)) }
        it { should be_valid }
      end

      context 'with invalid serializable' do
        let(:serializable) { OpenStruct.new }
        it { should_not be_valid }
      end
    end

    context 'with unknown file as schema' do
      let(:schema_file) { File.expand_path("../fixtures/non-existing-file.jsonschema", __FILE__) }
      it { expect { set_schema! }.to raise_error ActiveModel::Serializer::Validator::InvalidSchemaError, 'Schema file does not exist.' }
    end

    context 'with a non-supported type as schema' do
      let(:schema_file) { true }
      it { expect { set_schema! }.to raise_error ActiveModel::Serializer::Validator::InvalidSchemaError, 'Schema must be a path to a file or a Hash.' }
    end
  end
end


text:
Texture::Texture(int width,int height,Texture_Types type) : width(width), height(height), texture_type(type), gl_texture_type(GL_TEXTURE_2D) {
    glGenTextures(1,&texture_id);

    switch(type) {
    case TEXTURE_DEPTH:
        gl_texture_type=GL_TEXTURE_2D;
        glBindTexture(gl_texture_type,texture_id);
        glTexImage2D(gl_texture_type,0,GL_DEPTH32F_STENCIL8,width,height,0,GL_DEPTH_COMPONENT,GL_FLOAT,NULL);
        break;

    case TEXTURE_RGBA:
        gl_texture_type=GL_TEXTURE_2D;
        glBindTexture(gl_texture_type,texture_id);
        glTexImage2D(gl_texture_type,0,GL_RGBA32F,width,height,0,GL_RGBA,GL_FLOAT,NULL);
        break;

    case TEXTURE_DEPTH_LAYERED:
        gl_texture_type=GL_TEXTURE_2D_ARRAY;
        glBindTexture(gl_texture_type,texture_id);
        glTexImage3D(gl_texture_type,0,GL_DEPTH32F_STENCIL8,width,height,SHADOWING_MAX_LAYERS,0,GL_DEPTH_COMPONENT,GL_FLOAT,NULL);
        break;

    default:
        std::cout<<"Texture spec problem"<<std::endl;
        break;
    }
    glTexParameterf(gl_texture_type, GL_TEXTURE_COMPARE_MODE, GL_NONE);
    glTexParameterf(gl_texture_type, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameterf(gl_texture_type, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameterf(gl_texture_type, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameterf(gl_texture_type, GL_TEXTURE_WRAP_T, GL_REPEAT);
    unbind();
}

Texture::Texture(const char *filename) : width(-1), height(-1), texture_type(TEXTURE_RGBA), gl_texture_type(GL_TEXTURE_2D) {
    texture_id = SOIL_load_OGL_texture
	(
            filename,
            SOIL_LOAD_AUTO,
            SOIL_CREATE_NEW_ID,
            SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT
            );

}

Texture::~Texture() {
    glDeleteTextures(1,&texture_id);
}

GLuint Texture::id() {
    return texture_id;
}

int Texture::get_width() {
    return width;
}

int Texture::get_height() {
    return height;
}

void Texture::bind(int texture_index) {
    if(texture_index!=-1) {
        glActiveTexture(GL_TEXTURE0 + texture_index);
    }
    glBindTexture(gl_texture_type,texture_id);
}

void Texture::unbind() {
    glBindTexture(gl_texture_type,0);
}

GLenum Texture::get_gl_texture_type() {
    return gl_texture_type;
}

void Texture::set_data(void *data,int xoffset,int yoffset,int data_width,int data_height) {
    if(data_width==-1) {
        data_width=width;
    }
    if(data_height==-1) {
        data_height=height;
    }

    switch(texture_type) {
    case TEXTURE_RGBA:
        glTexSubImage2D(GL_TEXTURE_2D,0,xoffset,yoffset,data_width,data_height,GL_RGBA,GL_FLOAT,data);
        break;

    default:
        Logger::log(LOG_ERROR)<<"Can't set data in a depth texture"<<std::endl;
        break;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using NUnit.Framework;
using Redis.Core;

namespace Redis.Tests
{
	[TestFixture]
	public class PerformanceTests
	{
		private IRedisFactory redisFactory;
		private IRedis redis;

		[TestFixtureSetUp]
		public void TestFixtureSetUp()
		{
			this.redisFactory = new RedisFactory();
		}

		[SetUp]
		public void SetUp()
		{
			var connection = new RedisConnection("localhost", dbIndex: 10);
			this.redis = this.redisFactory.CreateRedis(connection);

			this.redis.FlushDB();
		}

		[Test]
		public void Looped_set_get_vs_pipeline_set_get()
		{
			const int commandCount = 2000;
			var stopwatch = new Stopwatch();

			// Looped SET ------------------------------------

			stopwatch.Start();

			for (int i = 0; i < commandCount; i++)
			{
				var key = "key" + i;
				var value = "value" + i;
				this.redis.Set(key, value);
			}

			stopwatch.Stop();

			Console.WriteLine("Looped SET   : {0} commands {1}ms", commandCount, stopwatch.ElapsedMilliseconds);

			// Looped GET ------------------------------------

			stopwatch.Restart();

			var loopedGetResults = new List<string>();

			for (int i = 0; i < commandCount; i++)
			{
				var key = "key" + i;
				loopedGetResults.Add(this.redis.Get(key));
			}

			stopwatch.Stop();

			for (int i = 0; i < commandCount; i++)
			{
				Assert.That(loopedGetResults[i] == "value" + i);
			}

			Console.WriteLine("Looped GET   : {0} commands {1}ms", commandCount, stopwatch.ElapsedMilliseconds);

			// Pipeline SET ----------------------------------

			this.redis.FlushDB();

			stopwatch.Restart();

			using (var pipe = this.redis.CreatePipeline(true))
			{
				for (int i = 0; i < commandCount; i++)
				{
					var key = "key" + i;
					var value = "value" + i;
					pipe.Add(x => x.Set(key, value));
				}

				pipe.Commit();
			}

			stopwatch.Stop();

			Console.WriteLine("Pipeline SET : {0} commands {1}ms", commandCount, stopwatch.ElapsedMilliseconds);

			// Pipeline GET ----------------------------------

			stopwatch.Restart();

			var pipelineGetResults = new List<IRedisResult<string>>();

			using (var pipe = this.redis.CreatePipeline(true))
			{
				for (int i = 0; i < commandCount; i++)
				{
					var key = "key" + i;
					pipelineGetResults.Add(pipe.Add(x => x.Get(key)));
				}

				pipe.Commit();
			}

			stopwatch.Stop();

			for (int i = 0; i < commandCount; i++)
			{
				Assert.That(pipelineGetResults[i].Value == "value" + i);
			}

			Console.WriteLine("Pipeline GET : {0} commands {1}ms", commandCount, stopwatch.ElapsedMilliseconds);
		}
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><meta name=keywords content=Concord Flight Envelope></meta>
<link rel=stylesheet type=text/css href=styles.css></link>

Posts about: "Flight Envelope" [Posts: 21 Pages: 2]

Page Links: First
 Previous
 1
 2

 Last
 Index Page

NW1
24th Jun 2011, 00:15
permalink
 Post: 1399

  <<

   I'm guessing you mean rate of climb rather than IAS?

  >>

  <<No, I meant the airspeed you'd be flying at while climbing (post takeoff)>>

   OK, then the answer to your Q's:

  Also what was the typical climb speed

  - At lift-off?

   About 200kts

  - Once 240 kts is achieved?

   240kts

  - At minimum maneuvering speed at typical takeoff weight?

   Vla after takeoff was V2 until 15,000'. I.E. about 220kts

  - At MTOGW?

   V2 didn't vary much by weight

   Out of JFK we flew at Vmo once further than 12nms from the coast. Vmo=400kts IAS at low level.

   Out of LHR overland the IAS restriction was 300kts until past the speed limit point early in the SID - much less draggy than 250kts and hence better climb rates. But you'd quickly be released to get to 400kts (barder's pole) where it was designed to be flown.

  <<Why higher speed? That have to do with shockwaves and the resulting pressure distribution differences?>>

   The flight envelope was bigger and more complex than subsonic types: it was developed in flight test and probably had many considerations involved. I think someone posted it earlier in this thread in graphical form (from the flight manual) if you want to see it. In practice, you had to be aware of three basic parameters - IAS, Mach and CG position (the CG "corridor"). Once understood, it wasn't that difficult to keep up with it...and the IAS and Machmeters had barber's poles handily programmed to show the limiting values (including, cleverly, max temp on the nose Tmo=127 degrees celcius).

   Regarding climb rates - best ROC was at 400kts (MTOW) or 380kts (MLW). As speed reduced below that, drag increased and ROC reduced. At MTOW and 400kts you'd get about 4000fpm max dry power. At 250kts it was all noise and very few feet per minute - after noise abate procedures you had to lower the nose, just barely climb, and get IAS up toward min drag as soon as possible. With an engine failed go for 300kts minimum - Vmo as soon as you can.

  <<shockwaves and the resulting pressure distribution differences>>

   You had to avoid the "transonic" region due to these effects: maximum subsonic cruise was 0.95M due to the auto-stabilised flying controls become over-active as shockwaves started to "dance" around the airframe (usually asymmetrically). This calmed down by about 1.3M in the acceleration (when the intake ramps started to do their thing). To accelerate to 2.0M you needed reheat until 1.7M so you didn't hang around between 0.95M and 1.7M. FL260 was best for subsonic cruise because at that level 400kts IAS = 0.95M...

   Last edited by NW1; 24th Jun 2011 at

    09:09

   .

Page Links: First
 Previous
 1
 2

 Last
 Index Page


text:
<form method="post">
    <input type="hidden" name="action" value="global_options" />

                Category Order Plugin Support
                <input name="support_category_order" type="checkbox" id="support_category_order" value="1" {% if global_options.support_category_order %}checked="checked" {% endif %}/>

                X-Sendfile Support
                <input name="use_sendfile" type="checkbox" id="use_sendfile" value="1" {% if global_options.use_sendfile %}checked="checked" {% endif %}/>

<input type="submit" name="submit" id="submit" class="button-primary" value="Save Changes">

</form>


text:
package com.alorma.github.sdk.services.issues.story;

import com.alorma.github.sdk.bean.dto.request.IssueRequest;
import com.alorma.github.sdk.bean.dto.response.Issue;
import com.alorma.github.sdk.bean.issue.IssueEvent;
import com.alorma.github.sdk.bean.issue.IssueStory;
import core.GithubComment;
import core.issues.Label;
import java.util.List;
import retrofit.Callback;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.Headers;
import retrofit.http.PATCH;
import retrofit.http.POST;
import retrofit.http.Path;
import retrofit.http.Query;
import rx.Observable;

public interface IssueStoryService {

    //Async
    @POST("/repos/{owner}/{name}/issues")
    void create(@Path("owner") String owner, @Path("name") String repo, @Body IssueRequest issue,
                Callback<IssueStory> callback);

    @GET("/repos/{owner}/{name}/issues/{num}")
    void detail(@Path("owner") String owner, @Path("name") String repo, @Path("num") int num,
                Callback<Issue> issueCallback);

    @Headers({"Accept: application/vnd.github.squirrel-girl-preview"})
    @GET("/repos/{owner}/{name}/issues/{num}/comments")
    void comments(@Path("owner") String owner, @Path("name") String repo, @Path("num") int num,
                  Callback<List<GithubComment>> callback);

    @Headers({"Accept: application/vnd.github.squirrel-girl-preview"})
    @GET("/repos/{owner}/{name}/issues/{num}/comments")
    void comments(@Path("owner") String owner, @Path("name") String repo, @Path("num") int num,
                  @Query("page") int page, Callback<List<GithubComment>> callback);

    @GET("/repos/{owner}/{name}/issues/{num}/events")
    void events(@Path("owner") String owner, @Path("name") String repo, @Path("num") int num,
                Callback<List<IssueEvent>> callback);

    @GET("/repos/{owner}/{name}/issues/{num}/events")
    void events(@Path("owner") String owner, @Path("name") String repo, @Path("num") int num,
                @Query("page") int page, Callback<List<IssueEvent>> callback);

    @PATCH("/repos/{owner}/{name}/issues/{num}")
    void closeIssue(@Path("owner") String owner, @Path("name") String repo, @Path("num") int num,
                    @Body IssueRequest issueRequest, Callback<Issue> callback);

    @POST("/repos/{owner}/{name}/issues/{num}/comments")
    void addComment(@Path("owner") String owner, @Path("name") String repo, @Path("num") int num,
                    @Body GithubComment comment, Callback<GithubComment> callback);

    @GET("/repos/{owner}/{name}/issues/{num}/labels")
    void labels(@Path("owner") String owner, @Path("name") String repo, @Path("num") int num,
                Callback<List<Label>> issueCallback);

    @GET("/repos/{owner}/{name}/issues/{num}/labels")
    void labels(@Path("owner") String owner, @Path("name") String repo, @Path("num") int num,
                @Query("page") int page, Callback<List<Label>> issueCallback);

    //Sync
    @POST("/repos/{owner}/{name}/issues")
    IssueStory create(@Path("owner") String owner, @Path("name") String repo,
                      @Body IssueRequest issue);

    @GET("/repos/{owner}/{name}/issues/{num}")
    Issue detail(@Path("owner") String owner, @Path("name") String repo, @Path("num") int num);

    @PATCH("/repos/{owner}/{name}/issues/{num}")
    Issue closeIssue(@Path("owner") String owner, @Path("name") String repo, @Path("num") int num,
                     @Body IssueRequest issueRequest);

    @POST("/repos/{owner}/{name}/issues/{num}/comments")
    GithubComment addComment(@Path("owner") String owner, @Path("name") String repo,
                             @Path("num") int num, @Body GithubComment comment);

    @GET("/repos/{owner}/{name}/issues/{num}/labels")
    List<Label> labels(@Path("owner") String owner, @Path("name") String repo, @Path("num") int num);

    @GET("/repos/{owner}/{name}/issues/{num}/labels")
    List<Label> labels(@Path("owner") String owner, @Path("name") String repo, @Path("num") int num,
                       @Query("page") int page);

    // Observable

    @Headers({"Accept: application/vnd.github.squirrel-girl-preview"})
    @GET("/repos/{owner}/{name}/issues/{num}")
    Observable<Issue> detailObs(@Path("owner") String owner, @Path("name") String repo,
                                @Path("num") int num);

    @GET("/repos/{owner}/{name}/issues/{num}/comments")
    Observable<List<GithubComment>> commentsObs(@Path("owner") String owner,
                                                @Path("name") String repo, @Path("num") int num);

    @GET("/repos/{owner}/{name}/issues/{num}/comments")
    Observable<List<GithubComment>> commentsObs(@Path("owner") String owner,
                                                @Path("name") String repo, @Path("num") int num
            , @Query("page") int page);
}


text:
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE RankNTypes          #-}
{-# LANGUAGE ViewPatterns        #-}

module Unison.CommandLine where

import Unison.Prelude

import           Control.Concurrent              (forkIO, killThread)
import           Control.Concurrent.STM          (atomically)
import qualified Control.Monad.Extra             as Monad
import qualified Control.Monad.Reader            as Reader
import qualified Control.Monad.State             as State
import           Data.Configurator               (autoReload, autoConfig)
import           Data.Configurator.Types         (Config, Worth (..))
import           Data.List                       (isSuffixOf, isPrefixOf)
import           Data.ListLike                   (ListLike)
import qualified Data.Map                        as Map
import qualified Data.Set                        as Set
import qualified Data.Text                       as Text
import           Prelude                         hiding (readFile, writeFile)
import qualified System.Console.Haskeline        as Line
import           System.FilePath                 ( takeFileName )
import           Unison.Codebase                 (Codebase)
import qualified Unison.Codebase                 as Codebase
import qualified Unison.Codebase.Branch          as Branch
import           Unison.Codebase.Causal          ( Causal )
import qualified Unison.Codebase.Causal          as Causal
import           Unison.Codebase.Editor.Input    (Event(..), Input(..))
import qualified Unison.Server.SearchResult    as SR
import qualified Unison.Codebase.Watch           as Watch
import           Unison.CommandLine.InputPattern (InputPattern (parse))
import qualified Unison.HashQualified'           as HQ
import           Unison.Names2 (Names0)
import qualified Unison.Util.ColorText           as CT
import qualified Unison.Util.Find                as Find
import qualified Unison.Util.Pretty              as P
import           Unison.Util.TQueue              (TQueue)
import qualified Unison.Util.TQueue              as Q
import qualified Data.Configurator as Config

disableWatchConfig :: Bool
disableWatchConfig = False

allow :: FilePath -> Bool
allow p =
  -- ignore Emacs .# prefixed files, see https://github.com/unisonweb/unison/issues/457
  not (".#" `isPrefixOf` takeFileName p) &&
  (isSuffixOf ".u" p || isSuffixOf ".uu" p)

watchConfig :: FilePath -> IO (Config, IO ())
watchConfig path = if disableWatchConfig then pure (Config.empty, pure ()) else do
  (config, t) <- autoReload autoConfig [Optional path]
  pure (config, killThread t)

watchFileSystem :: TQueue Event -> FilePath -> IO (IO ())
watchFileSystem q dir = do
  (cancel, watcher) <- Watch.watchDirectory dir allow
  t <- forkIO . forever $ do
    (filePath, text) <- watcher
    atomically . Q.enqueue q $ UnisonFileChanged (Text.pack filePath) text
  pure (cancel >> killThread t)

watchBranchUpdates :: IO (Branch.Branch IO) -> TQueue Event -> Codebase IO v a -> IO (IO ())
watchBranchUpdates currentRoot q codebase = do
  (cancelExternalBranchUpdates, externalBranchUpdates) <-
    Codebase.rootBranchUpdates codebase
  thread <- forkIO . forever $ do
    updatedBranches <- externalBranchUpdates
    currentRoot <- currentRoot
    -- Since there's some lag between when branch files are written and when
    -- the OS generates a file watch event, we skip branch update events
    -- that are causally before the current root.
    --
    -- NB: Sadly, since the file watching API doesn't have a way to silence
    -- the events from a specific individual write, this is ultimately a
    -- heuristic. If a fairly recent head gets deposited at just the right
    -- time, it would get ignored by this logic. This seems unavoidable.
    let maxDepth = 20 -- if it's further back than this, consider it new
    let isNew b = not <$> beforeHash maxDepth b (Branch._history currentRoot)
    notBefore <- filterM isNew (toList updatedBranches)
    when (length notBefore > 0) $
      atomically . Q.enqueue q . IncomingRootBranch $ Set.fromList notBefore
  pure (cancelExternalBranchUpdates >> killThread thread)

-- `True` if `h` is found in the history of `c` within `maxDepth` path length
-- from the tip of `c`
beforeHash :: forall m h e . Monad m => Word -> Causal.RawHash h -> Causal m h e -> m Bool
beforeHash maxDepth h c =
  Reader.runReaderT (State.evalStateT (go c) Set.empty) (0 :: Word)
  where
  go c | h == Causal.currentHash c = pure True
  go c = do
    currentDepth :: Word <- Reader.ask
    if currentDepth >= maxDepth
    then pure False
    else do
      seen <- State.get
      cs <- lift . lift $ toList <$> sequence (Causal.children c)
      let unseens = filter (\c -> c `Set.notMember` seen) cs
      State.modify' (<> Set.fromList cs)
      Monad.anyM (Reader.local (1+) . go) unseens

warnNote :: String -> String
warnNote s = "⚠  " <> s

backtick :: IsString s => P.Pretty s -> P.Pretty s
backtick s = P.group ("`" <> s <> "`")

backtickEOS :: IsString s => P.Pretty s -> P.Pretty s
backtickEOS s = P.group ("`" <> s <> "`.")

tip :: (ListLike s Char, IsString s) => P.Pretty s -> P.Pretty s
tip s = P.column2 [("Tip:", P.wrap s)]

note :: (ListLike s Char, IsString s) => P.Pretty s -> P.Pretty s
note s = P.column2 [("Note:", P.wrap s)]

aside :: (ListLike s Char, IsString s) => P.Pretty s -> P.Pretty s -> P.Pretty s
aside a b = P.column2 [(a <> ":", b)]

warn :: (ListLike s Char, IsString s) => P.Pretty s -> P.Pretty s
warn = emojiNote "⚠"

problem :: (ListLike s Char, IsString s) => P.Pretty s -> P.Pretty s
problem = emojiNote "❗"

bigproblem :: (ListLike s Char, IsString s) => P.Pretty s -> P.Pretty s
bigproblem = emojiNote "‼"

emojiNote :: (ListLike s Char, IsString s) => String -> P.Pretty s -> P.Pretty s
emojiNote lead s = P.group (fromString lead) <> "\n" <> P.wrap s

nothingTodo :: (ListLike s Char, IsString s) => P.Pretty s -> P.Pretty s
nothingTodo = emojiNote "😶"

completion :: String -> Line.Completion
completion s = Line.Completion s s True

completion' :: String -> Line.Completion
completion' s = Line.Completion s s False

prettyCompletion :: (String, P.Pretty P.ColorText) -> Line.Completion
-- -- discards formatting in favor of better alignment
-- prettyCompletion (s, p) = Line.Completion s (P.toPlainUnbroken p) True
-- preserves formatting, but Haskeline doesn't know how to align
prettyCompletion (s, p) = Line.Completion s (P.toAnsiUnbroken p) True

-- avoids adding a space after successful completion
prettyCompletion' :: (String, P.Pretty P.ColorText) -> Line.Completion
prettyCompletion' (s, p) = Line.Completion s (P.toAnsiUnbroken p) False

prettyCompletion'' :: Bool -> (String, P.Pretty P.ColorText) -> Line.Completion
prettyCompletion'' spaceAtEnd (s, p) = Line.Completion s (P.toAnsiUnbroken p) spaceAtEnd

fuzzyCompleteHashQualified :: Names0 -> String -> [Line.Completion]
fuzzyCompleteHashQualified b q0@(HQ.fromString -> query) = case query of
  Nothing -> []
  Just query ->
    fixupCompletion q0 $
      makeCompletion <$> Find.fuzzyFindInBranch b query
  where
  makeCompletion (sr, p) =
    prettyCompletion' (HQ.toString . SR.name $ sr, p)

fuzzyComplete :: String -> [String] -> [Line.Completion]
fuzzyComplete q ss =
  fixupCompletion q (prettyCompletion' <$> Find.simpleFuzzyFinder q ss id)

exactComplete :: String -> [String] -> [Line.Completion]
exactComplete q ss = go <$> filter (isPrefixOf q) ss where
  go s = prettyCompletion'' (s == q)
           (s, P.hiBlack (P.string q) <> P.string (drop (length q) s))

prefixIncomplete :: String -> [String] -> [Line.Completion]
prefixIncomplete q ss = go <$> filter (isPrefixOf q) ss where
  go s = prettyCompletion'' False
           (s, P.hiBlack (P.string q) <> P.string (drop (length q) s))

-- workaround for https://github.com/judah/haskeline/issues/100
-- if the common prefix of all the completions is smaller than
-- the query, we make all the replacements equal to the query,
-- which will preserve what the user has typed
fixupCompletion :: String -> [Line.Completion] -> [Line.Completion]
fixupCompletion _q [] = []
fixupCompletion _q [c] = [c]
fixupCompletion q cs@(h:t) = let
  commonPrefix (h1:t1) (h2:t2) | h1 == h2 = h1 : commonPrefix t1 t2
  commonPrefix _ _             = ""
  overallCommonPrefix =
    foldl commonPrefix (Line.replacement h) (Line.replacement <$> t)
  in if not (q `isPrefixOf` overallCommonPrefix)
     then [ c { Line.replacement = q } | c <- cs ]
     else cs

parseInput
  :: Map String InputPattern -> [String] -> Either (P.Pretty CT.ColorText) Input
parseInput patterns ss = case ss of
  []             -> Left ""
  command : args -> case Map.lookup command patterns of
    Just pat -> parse pat args
    Nothing ->
      Left
        .  warn
        .  P.wrap
        $  "I don't know how to "
        <> P.group (fromString command <> ".")
        <> "Type `help` or `?` to get help."

prompt :: String
prompt = "> "

-- `plural [] "cat" "cats" = "cats"`
-- `plural ["meow"] "cat" "cats" = "cat"`
-- `plural ["meow", "meow"] "cat" "cats" = "cats"`
plural :: Foldable f => f a -> b -> b -> b
plural items one other = case toList items of
  [_] -> one
  _ -> other

plural' :: Integral a => a -> b -> b -> b
plural' 1 one _other = one
plural' _ _one other = other


text:
package org.xsaas.xstat.dao.hibernate;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.xsaas.xstat.dao.ISelectWeightInfoDao;
import org.xsaas.xstat.po.SelectWeightInfo;

public class SelectWeightInfoDao extends HibernateDaoSupport implements	ISelectWeightInfoDao {

	public void delete(SelectWeightInfo data) {
		this.getHibernateTemplate().delete(data);
	}
	public SelectWeightInfo getSelectWeightInfo(Long selectWeightID) {

		return (SelectWeightInfo) this.getHibernateTemplate().get(SelectWeightInfo.class, selectWeightID);
	}
	public void save(SelectWeightInfo data) {
		this.getHibernateTemplate().save(data);

	}
	public void update(SelectWeightInfo data) {
		this.getHibernateTemplate().update(data);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SelectWeightInfo> findByPage(final int firstResult,final int maxResult) {
		List<SelectWeightInfo> list = this.getHibernateTemplate().executeFind(new HibernateCallback() {
			 public Object doInHibernate(Session s) throws HibernateException, SQLException {
				 Criteria query = s.createCriteria(SelectWeightInfo.class);
				 query.add(Restrictions.eq("status", 1));
				 query.addOrder(Order.desc("selectWeightID"));
				 query.setFirstResult(firstResult);
				 query.setMaxResults(maxResult);
				 return query.list();
			 }
		});
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public int getTotalByDelStatus() {
		Criteria query = this.getSession().createCriteria(SelectWeightInfo.class);
		query.setProjection(Projections.rowCount());
		query.add(Restrictions.eq("status", 2));
		query.setMaxResults(1);
		List list = query.list();
		int result = 0;
		if(list.size() > 0) {
			Object obj = list.get(0);
			if(obj != null) {
				result = (Integer)obj;
			}
		}
		return result;
	}
	@SuppressWarnings("unchecked")
	@Override
	public int getTotal() {
		Criteria query = this.getSession().createCriteria(SelectWeightInfo.class);
		query.setProjection(Projections.count("selectWeightID"));
		query.add(Restrictions.eq("status",1));
		query.setMaxResults(1);
		List list = query.list();
		int result = 0;
		if(list.size() > 0) {
			Object obj = list.get(0);
			if(obj != null) {
				result = (Integer)obj;
			}
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public int getCountWeight(Long inquisitionID, Long partID) {
		Criteria query = this.getSession().createCriteria(SelectWeightInfo.class);
		query.setProjection(Projections.sum("weight"));
		query.add(Restrictions.eq("inquisitionID", inquisitionID));
		query.add(Restrictions.eq("partID", partID));
		query.add(Restrictions.eq("status",1));
		query.setMaxResults(1);
		List list = query.list();
		int result = 0;
		if(list.size() > 0) {
			Object obj = list.get(0);
			if(obj != null) {
				result = (Integer)obj;
			}
		}
		return result;
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<SelectWeightInfo> findByDelStatus(final int firstResult, final int maxResult) {
		List<SelectWeightInfo> list = this.getHibernateTemplate().executeFind(new HibernateCallback() {
			 public Object doInHibernate(Session s) throws HibernateException, SQLException {
				 Criteria query = s.createCriteria(SelectWeightInfo.class);
				 query.add(Restrictions.eq("status", 2));
				 query.addOrder(Order.desc("selectWeightID"));
				 query.setFirstResult(firstResult);
				 query.setMaxResults(maxResult);
				 return query.list();
			 }
		});
		return list;
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<SelectWeightInfo> findByPage(Long inquisitionID,int firstResult, int maxResult) {
		 Criteria query = this.getSession().createCriteria(SelectWeightInfo.class);
		 query.add(Restrictions.eq("inquisitionID", inquisitionID));
		 query.add(Restrictions.eq("status",1));
		 query.setFirstResult(firstResult);
		 query.setMaxResults(maxResult);
		 return query.list();
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<SelectWeightInfo> findByPage(Long inquisitionID, Long partID,
			int firstResult, int maxResult) {
		 Criteria query = this.getSession().createCriteria(SelectWeightInfo.class);
		 query.add(Restrictions.eq("inquisitionID", inquisitionID));
		 query.add(Restrictions.eq("partID", partID));
		 query.add(Restrictions.eq("status",1));
		 query.setFirstResult(firstResult);
		 query.setMaxResults(maxResult);
		 return query.list();
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<SelectWeightInfo> findByPart(Long inquisitionID, Long partID) {
		 Criteria query = this.getSession().createCriteria(SelectWeightInfo.class);
		 query.add(Restrictions.eq("inquisitionID", inquisitionID));
		 query.add(Restrictions.eq("partID", partID));
		 query.add(Restrictions.eq("status",1));
		 query.setMaxResults(Integer.MAX_VALUE);
		 return query.list();
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<SelectWeightInfo> findByPartQuestion(Long inquisitionID,Long partQuestionID) {
		 Criteria query = this.getSession().createCriteria(SelectWeightInfo.class);
		 query.add(Restrictions.eq("inquisitionID", inquisitionID));
		 query.add(Restrictions.eq("partQuestionID", partQuestionID));
		 query.add(Restrictions.eq("status",1));
		 query.setMaxResults(Integer.MAX_VALUE);
		 return query.list();
	}
	@SuppressWarnings("unchecked")
	@Override
	public SelectWeightInfo getSelectWeightInfo(Long inquisitionID,	Long partQuestionID, Long selectID) {
		 Criteria query = this.getSession().createCriteria(SelectWeightInfo.class);
		 query.add(Restrictions.eq("inquisitionID", inquisitionID));
		 query.add(Restrictions.eq("partQuestionID", partQuestionID));
		 query.add(Restrictions.eq("selectID",selectID));
		 query.add(Restrictions.eq("status",1));
		 query.setMaxResults(Integer.MAX_VALUE);
		 SelectWeightInfo swi = null;
		 List list = query.list();
		 if(list != null && list.size() > 0 ) {
			 swi = (SelectWeightInfo)list.get(0);
		 }
		return swi;
	}
	@SuppressWarnings("unchecked")
	@Override
	public int getTotal(Long inquisitionID, Long partID) {
		Criteria query = this.getSession().createCriteria(SelectWeightInfo.class);
		query.setProjection(Projections.rowCount());
		query.add(Restrictions.eq("inquisitionID", inquisitionID));
		query.add(Restrictions.eq("partID", partID));
		query.add(Restrictions.eq("status",1));
		query.setMaxResults(1);
		List list = query.list();
		int result = 0;
		if(list.size() > 0) {
			Object obj = list.get(0);
			if(obj != null) {
				result = (Integer)obj;
			}
		}
		return result;
	}
	@SuppressWarnings("unchecked")
	@Override
	public int getTotal(Long inquisitionID) {
		Criteria query = this.getSession().createCriteria(SelectWeightInfo.class);
		query.setProjection(Projections.rowCount());
		query.add(Restrictions.eq("inquisitionID", inquisitionID));
		query.add(Restrictions.eq("status",1));
		query.setMaxResults(1);
		List list = query.list();
		int result = 0;
		if(list.size() > 0) {
			Object obj = list.get(0);
			if(obj != null) {
				result = (Integer)obj;
			}
		}
		return result;
	}
	@SuppressWarnings("unchecked")
	@Override
	public int getSumWeightByQuestion(Long inquisitionID, Long partQuestionID) {
		Criteria query = this.getSession().createCriteria(SelectWeightInfo.class);
		query.setProjection(Projections.sum("weight"));
		query.add(Restrictions.eq("inquisitionID", inquisitionID));
		query.add(Restrictions.eq("partQuestionID", partQuestionID));
		query.add(Restrictions.eq("status",1));
		query.setMaxResults(1);
		List list = query.list();
		int result = 0;
		if(list.size() > 0) {
			Object obj = list.get(0);
			if(obj != null) {
				result = (Integer)obj;
			}
		}
		return result;
	}
}


text:
#include "mfcpch.h"
#include <string.h>
#include "boxread.h"
#include "unichar.h"
#include "tprintf.h"

// Box files are used ONLY DURING TRAINING, but by both processes of
// creating tr files with tesseract, and unicharset_extractor.
// read_next_box factors out the code to interpret a line of a box
// file so that applybox and unicharset_extractor interpret the same way.
// This function returns the next valid box file utf8 string and coords
// and returns true, or false on eof (and closes the file).
// It ignores the uft8 file signature, checks for valid utf-8 and allows
// space or tab between fields.
// utf8_str must be at least kBoxReadBufSize in length.
// If there are page numbers in the file, it reads them all.
bool read_next_box(FILE* box_file, char* utf8_str,
                   int* x_min, int* y_min, int* x_max, int* y_max) {
  return read_next_box(-1, box_file, utf8_str,
                       x_min, y_min, x_max, y_max);
}

// As read_next_box above, but get a specific page number. (0-based)
// Use -1 to read any page number. Files without page number all
// read as if they are page 0.
bool read_next_box(int target_page, FILE* box_file, char* utf8_str,
                   int* x_min, int* y_min, int* x_max, int* y_max) {
  static int line = 0;
  int count = 0;
  int page = 0;
  char buff[kBoxReadBufSize];                //boxfile read buffer
  char uch[kBoxReadBufSize];
  char *buffptr = buff;

  while (fgets(buff, sizeof(buff) - 1, box_file)) {
    line++;

    buffptr = buff;
    const unsigned char *ubuf = reinterpret_cast<const unsigned char*>(buffptr);
    if (ubuf[0] == 0xef && ubuf[1] == 0xbb && ubuf[2] == 0xbf)
      buffptr += 3;  // Skip unicode file designation.
    /* Check for blank lines in box file */
    while (*buffptr == ' ' || *buffptr == '\t')
      buffptr++;
    if (*buffptr != '\0') {
      count = sscanf(buffptr, "%s %d %d %d %d %d",
                     uch, x_min, y_min, x_max, y_max, &page);
      if (count != 6) {
        page = 0;
        count = sscanf(buffptr, "%s %d %d %d %d",
                       uch, x_min, y_min, x_max, y_max);
      }
      if (target_page >= 0 && target_page != page)
        continue;  // Not on the appropriate page.
      if (count == 5) {
        // Validate UTF8 by making unichars with it.
        int used = 0;
        int uch_len = strlen(uch);
        while (used < uch_len) {
          UNICHAR ch(uch + used, uch_len - used);
          int new_used = ch.utf8_len();
          if (new_used == 0) {
            tprintf("Bad utf-8 char starting with 0x%x at line %d, col %d, \n",
                    uch[used], used + 1, line);
            count = 0;
            break;
          }
          used += new_used;
        }
        if (uch_len > UNICHAR_LEN) {
          tprintf("utf-8 string too long at line %d\n", line);
          count = 0;
        }
      }
      if (count < 5) {
        tprintf("Box file format error on line %i ignored\n", line);
      } else {
        strcpy(utf8_str, uch);
        return true;             //read a box ok
      }
    }
  }
  fclose(box_file);
  line = 0;
  return false;                  //EOF
}


text:
typedef void(^YWHybridEngineBlock)(NSString *event, NSDictionary *params, WQHandlerReturnBlock retBlock, UIWebView *webView, UIViewController * viewController);

@interface YWHybridEngine : NSObject
@property (nonatomic, weak) UIWebView *webView;
@property (strong, nonatomic, readonly) YWHybridConnector *bridgeConnector;
@property (strong, nonatomic) NSString *appKey;

- (instancetype)initWithAppKey:(NSString *)appKey
                   withWebView:(UIWebView *)webView;

//处理Request
- (BOOL)handleRequest:(NSURLRequest *)request;
- (void)registerBridgeEvent:(NSString *)event handler:(YWHybridEngineBlock)engineBlock;
- (void)registerBridgeModule:(NSString *)module andMethod:(NSString *)method handler:(YWHybridEngineBlock)engineBlock;
- (void)clearBridgeEvent;

//兼容千牛接口
- (void)addInstanceObserver:(id)observer selector:(SEL)aSelector oncall:(NSString*) methodName;
- (void)removeInstanceObserver:(NSString*) methodName;
@end


text: export * from './users.router';


text:
cask "monal" do
  version "5.1.1,791"
  sha256 :no_check

  url "https://monal.im/macOS/Monal-macOS.zip"
  name "Monal"
  desc "Tool to securely connect to chat servers"
  homepage "https://monal.im/"

  livecheck do
    url :url
    strategy :extract_plist
  end

  depends_on macos: ">= :catalina"

  app "Monal.app"

  zap trash: "~/Library/Group Containers/group.monal"
end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fl. angl. 103. 1762 Jan-Jun

#### Original name
null

### Remarks
null


text:
package io.github.morgaroth.eventsmanger

import java.util.UUID

import akka.stream.stage._
import akka.stream.{Attributes, FlowShape, Inlet, Outlet}
import com.typesafe.config.Config
import io.github.morgaroth.eventsmanger.BetBlocksPostgresDriver.api._
import org.joda.time.DateTime

import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext}

case class Window(start: DateTime, end: DateTime, kind: WindowKind, state: WindowState = NotChecked, tags: List[String] = List.empty, id: UUID = UUID.randomUUID)

object Window {
  def present(start: DateTime, end: DateTime) = Window(start, end, kind = Present)

  def absent(start: DateTime, end: DateTime) = Window(start, end, kind = Absent)
}

//@formatter:off
sealed trait WindowKind { def state: String }
case object Present extends WindowKind { val state = "present" }
case object Absent extends WindowKind { val state = "absent" }
case object Coffee extends WindowKind { val state = "coffee" }
case object Meeting extends WindowKind { val state = "meeting" }
object WindowTypes {
  private val all = List(Present, Absent, Coffee, Meeting)
  private val map = all.map(x => x.state -> x).toMap
  def apply(name: String) = map(name)
}

sealed trait WindowState { def state: String }
case object Checked extends WindowState { val state = "checked" }
case object NotChecked extends WindowState { val state = "not-checked" }
object WindowStates {
  private val all = List(Checked, NotChecked)
  private val map = all.map(x => x.state -> x).toMap
  def apply(name: String) = map(name)
}
//@formatter:on

trait CustomMappers {
  implicit val wnindowKindMapper = MappedColumnType.base[WindowKind, String](e => e.state, s => WindowTypes(s))
  implicit val wnindowStateMapper = MappedColumnType.base[WindowState, String](e => e.state, s => WindowStates(s))
}

class Windows(tag: Tag) extends Table[Window](tag, "times") with CustomMappers {
  def id = column[UUID]("id", O.PrimaryKey)

  def start = column[DateTime]("start")

  def end = column[DateTime]("end")

  def state = column[WindowState]("state")

  def kind = column[WindowKind]("kind")

  def tags = column[List[String]]("tags")

  override def * = (start, end, kind, state, tags, id) <> ((Window.apply _).tupled, Window.unapply)
}

object db {
  val driver = MyPostgresDriver

  val windows = TableQuery[Windows]

  val allTables = List(windows)

  def schema(): driver.DDL = {
    import driver.api._
    allTables.map(_.schema).reduce(_ ++ _)
  }
}

case class PostgresSaver(config: Config)(implicit ex: ExecutionContext) extends GraphStage[FlowShape[Window, Window]] {

  val in = Inlet[Window]("PostgresSaver.in")
  val out = Outlet[Window]("PostgresSaver.out")

  val shape = FlowShape.of(in, out)

  override def createLogic(inheritedAttributes: Attributes): GraphStageLogic =
    new GraphStageLogic(shape) with StageLogging {
      private val DB = Database.forConfig("", config)
      FlyWayEvolutions.migrate(config)

      setHandler(in, new InHandler {
        override def onPush(): Unit = {
          val elem = grab(in)
          val task = DB.run(db.windows += elem)
          Await.ready(task, 1.second)
          task.failed.foreach { t =>
            log.error(t, s"error during save window $elem")
          }
          push(out, elem)
        }

        override def onUpstreamFinish(): Unit = {
          DB.close()
          log.info("Closing connection to DB.")
          complete(out)
        }
      })

      setHandler(out, new OutHandler {
        override def onPull(): Unit = {
          pull(in)
        }
      })
    }
}


text:
package org.gradle.process.internal;

import com.google.common.collect.Maps;
import org.gradle.api.file.FileCollection;
import org.gradle.api.internal.file.UnionFileCollection;
import org.gradle.internal.file.PathToFileResolver;
import org.gradle.internal.jvm.Jvm;
import org.gradle.process.CommandLineArgumentProvider;
import org.gradle.process.JavaForkOptions;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static org.gradle.process.internal.util.MergeOptionsUtil.canBeMerged;
import static org.gradle.process.internal.util.MergeOptionsUtil.containsAll;
import static org.gradle.process.internal.util.MergeOptionsUtil.getHeapSizeMb;
import static org.gradle.process.internal.util.MergeOptionsUtil.mergeHeapSize;
import static org.gradle.process.internal.util.MergeOptionsUtil.normalized;

public class DefaultJavaForkOptions extends DefaultProcessForkOptions implements JavaForkOptionsInternal {
    private final PathToFileResolver resolver;
    private final JvmOptions options;
    private List<CommandLineArgumentProvider> jvmArgumentProviders;

    public DefaultJavaForkOptions(PathToFileResolver resolver) {
        this(resolver, Jvm.current());
    }

    public DefaultJavaForkOptions(PathToFileResolver resolver, Jvm jvm) {
        super(resolver);
        this.resolver = resolver;
        options = new JvmOptions(resolver);
        setExecutable(jvm.getJavaExecutable());
    }

    public List<String> getAllJvmArgs() {
        if (hasJvmArgumentProviders(this)) {
            JvmOptions copy = options.createCopy();
            for (CommandLineArgumentProvider jvmArgumentProvider : jvmArgumentProviders) {
                copy.jvmArgs(jvmArgumentProvider.asArguments());
            }
            return copy.getAllJvmArgs();
        } else {
            return options.getAllJvmArgs();
        }
    }

    public void setAllJvmArgs(List<String> arguments) {
        options.setAllJvmArgs(arguments);
        if (hasJvmArgumentProviders(this)) {
            jvmArgumentProviders.clear();
        }
    }

    public void setAllJvmArgs(Iterable<?> arguments) {
        options.setAllJvmArgs(arguments);
        if (hasJvmArgumentProviders(this)) {
            jvmArgumentProviders.clear();
        }
    }

    public List<String> getJvmArgs() {
        return options.getJvmArgs();
    }

    public void setJvmArgs(List<String> arguments) {
        options.setJvmArgs(arguments);
    }

    public void setJvmArgs(Iterable<?> arguments) {
        options.setJvmArgs(arguments);
    }

    public JavaForkOptions jvmArgs(Iterable<?> arguments) {
        options.jvmArgs(arguments);
        return this;
    }

    public JavaForkOptions jvmArgs(Object... arguments) {
        jvmArgs(Arrays.asList(arguments));
        return this;
    }

    @Override
    public List<CommandLineArgumentProvider> getJvmArgumentProviders() {
        if (jvmArgumentProviders == null) {
            jvmArgumentProviders = new ArrayList<CommandLineArgumentProvider>();
        }
        return jvmArgumentProviders;
    }

    public Map<String, Object> getSystemProperties() {
        return options.getMutableSystemProperties();
    }

    public void setSystemProperties(Map<String, ?> properties) {
        options.setSystemProperties(properties);
    }

    public JavaForkOptions systemProperties(Map<String, ?> properties) {
        options.systemProperties(properties);
        return this;
    }

    public JavaForkOptions systemProperty(String name, Object value) {
        options.systemProperty(name, value);
        return this;
    }

    public FileCollection getBootstrapClasspath() {
        return options.getBootstrapClasspath();
    }

    public void setBootstrapClasspath(FileCollection classpath) {
        options.setBootstrapClasspath(classpath);
    }

    public JavaForkOptions bootstrapClasspath(Object... classpath) {
        options.bootstrapClasspath(classpath);
        return this;
    }

    public String getMinHeapSize() {
        return options.getMinHeapSize();
    }

    public void setMinHeapSize(String heapSize) {
        options.setMinHeapSize(heapSize);
    }

    public String getMaxHeapSize() {
        return options.getMaxHeapSize();
    }

    public void setMaxHeapSize(String heapSize) {
        options.setMaxHeapSize(heapSize);
    }

    public String getDefaultCharacterEncoding() {
        return options.getDefaultCharacterEncoding();
    }

    public void setDefaultCharacterEncoding(String defaultCharacterEncoding) {
        options.setDefaultCharacterEncoding(defaultCharacterEncoding);
    }

    public boolean getEnableAssertions() {
        return options.getEnableAssertions();
    }

    public void setEnableAssertions(boolean enabled) {
        options.setEnableAssertions(enabled);
    }

    public boolean getDebug() {
        return options.getDebug();
    }

    public void setDebug(boolean enabled) {
        options.setDebug(enabled);
    }

    public JavaForkOptions copyTo(JavaForkOptions target) {
        super.copyTo(target);
        options.copyTo(target);
        if (jvmArgumentProviders != null) {
            for (CommandLineArgumentProvider jvmArgumentProvider : jvmArgumentProviders) {
                target.jvmArgs(jvmArgumentProvider.asArguments());
            }
        }
        return this;
    }

    @Override
    public JavaForkOptionsInternal mergeWith(JavaForkOptions options) {
        if (hasJvmArgumentProviders(this) || hasJvmArgumentProviders(options)) {
            throw new UnsupportedOperationException("Cannot merge options with jvmArgumentProviders.");
        }
        JavaForkOptionsInternal mergedOptions = new DefaultJavaForkOptions(resolver);

        if (!canBeMerged(getExecutable(), options.getExecutable())) {
            throw new IllegalArgumentException("Cannot merge a fork options object with a different executable (this: " + getExecutable() + ", other: " + options.getExecutable() + ").");
        } else {
            mergedOptions.setExecutable(getExecutable() != null ? getExecutable() : options.getExecutable());
        }

        if (!canBeMerged(getWorkingDir(), options.getWorkingDir())) {
            throw new IllegalArgumentException("Cannot merge a fork options object with a different working directory (this: " + getWorkingDir() + ", other: " + options.getWorkingDir() + ").");
        } else {
            mergedOptions.setWorkingDir(getWorkingDir() != null ? getWorkingDir() : options.getWorkingDir());
        }

        if (!canBeMerged(getDefaultCharacterEncoding(), options.getDefaultCharacterEncoding())) {
            throw new IllegalArgumentException("Cannot merge a fork options object with a different default character encoding (this: " + getDefaultCharacterEncoding() + ", other: " + options.getDefaultCharacterEncoding() + ").");
        } else {
            mergedOptions.setDefaultCharacterEncoding(getDefaultCharacterEncoding() != null ? getDefaultCharacterEncoding() : options.getDefaultCharacterEncoding());
        }

        mergedOptions.setDebug(getDebug() || options.getDebug());
        mergedOptions.setEnableAssertions(getEnableAssertions() || options.getEnableAssertions());

        mergedOptions.setMinHeapSize(mergeHeapSize(getMinHeapSize(), options.getMinHeapSize()));
        mergedOptions.setMaxHeapSize(mergeHeapSize(getMaxHeapSize(), options.getMaxHeapSize()));

        Set<String> mergedJvmArgs = normalized(getJvmArgs());
        mergedJvmArgs.addAll(normalized(options.getJvmArgs()));
        mergedOptions.setJvmArgs(mergedJvmArgs);

        Map<String, Object> mergedEnvironment = Maps.newHashMap(getEnvironment());
        mergedEnvironment.putAll(options.getEnvironment());
        mergedOptions.setEnvironment(mergedEnvironment);

        Map<String, Object> mergedSystemProperties = Maps.newHashMap(getSystemProperties());
        mergedSystemProperties.putAll(options.getSystemProperties());
        mergedOptions.setSystemProperties(mergedSystemProperties);

        mergedOptions.setBootstrapClasspath(new UnionFileCollection(getBootstrapClasspath(), options.getBootstrapClasspath()));

        return mergedOptions;
    }

    @Override
    public boolean isCompatibleWith(JavaForkOptions options) {
        if (hasJvmArgumentProviders(this) || hasJvmArgumentProviders(options)) {
            throw new UnsupportedOperationException("Cannot compare options with jvmArgumentProviders.");
        }
        return getDebug() == options.getDebug()
                && getEnableAssertions() == options.getEnableAssertions()
                && normalized(getExecutable()).equals(normalized(options.getExecutable()))
                && getWorkingDir().equals(options.getWorkingDir())
                && normalized(getDefaultCharacterEncoding()).equals(normalized(options.getDefaultCharacterEncoding()))
                && getHeapSizeMb(getMinHeapSize()) >= getHeapSizeMb(options.getMinHeapSize())
                && getHeapSizeMb(getMaxHeapSize()) >= getHeapSizeMb(options.getMaxHeapSize())
                && normalized(getJvmArgs()).containsAll(normalized(options.getJvmArgs()))
                && containsAll(getSystemProperties(), options.getSystemProperties())
                && containsAll(getEnvironment(), options.getEnvironment())
                && getBootstrapClasspath().getFiles().containsAll(options.getBootstrapClasspath().getFiles());
    }

    private static boolean hasJvmArgumentProviders(JavaForkOptions forkOptions) {
        return forkOptions instanceof DefaultJavaForkOptions
            && hasJvmArgumentProviders((DefaultJavaForkOptions) forkOptions);
    }

    private static boolean hasJvmArgumentProviders(DefaultJavaForkOptions forkOptions) {
        return forkOptions.jvmArgumentProviders != null && !forkOptions.jvmArgumentProviders.isEmpty();
    }

}