text:
<?php

namespace Sonata\PageBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * CacheCompilerPass.
 *
 * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */
class CacheCompilerPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $services = array();

        foreach ($container->findTaggedServiceIds('sonata.page.manager') as $id => $attributes) {
            if (!$container->hasDefinition($id)) {
                continue;
            }

            $services[$attributes[0]['type']] = new Reference($id);
        }

        if ($container->hasDefinition('sonata.page.cache.esi')) {
            $container->getDefinition('sonata.page.cache.esi')->replaceArgument(6, $services);
        }

        if ($container->hasDefinition('sonata.page.cache.ssi')) {
            $container->getDefinition('sonata.page.cache.ssi')->replaceArgument(4, $services);
        }
    }
}


text:
['json', 'resolv', 'resolv-replace', 'socket', 'celluloid',
 'trollop'].each { |e| require e }

['./dispatcher', '../plugin_components', '../plugins',
 '../actionpayload', '../registrationpayload'].each do |f|
  path = File.absolute_path(File.dirname(__FILE__) + '/' + f)
  puts "Requiring: #{path}."
  require path
end

Thread.abort_on_exception = true

$opts = Trollop::options do

  opt "registration.server", "Required for heartbeat signal.",
    :type => :string, :required => true

  opt "registration.server.port", "Default port is 3000.",
    :type => :int, :required => false, :default => 3000

  opt "agent.dispatch.port", "The port that accepts rpc requests.",
    :type => :int, :required => true

  opt "registration.wait.period", "Number of seconds to wait between registration attempts.",
    :type => :int, :default => 5

  opt "heartbeat.wait.period", "Number of seconds to wait between heartbeat events.",
    :type => :int, :default => 5

  opt "extra.plugin.dir", "Absolute directory path for plugins.",
    :type => :string, :required => false

end

module ClientRegistrationHeartbeatStateMachine

  def self.start
    Thread.new { register; establish_heartbeat }; accept_rpc_requests
  end

  def self.register
    begin
      @conn = TCPSocket.new($opts["registration.server"], $opts["registration.server.port"])
      payload = RegistrationPayload.new(:dispatch_port => $opts["agent.dispatch.port"])
      @conn.write payload.serialize
    rescue Errno::ECONNREFUSED, Errno::EPIPE, Exception => e
      puts e.class
      wait_period = $opts["registration.wait.period"]
      puts "Registration connection refused or broken. Retrying in #{wait_period} seconds."
      sleep wait_period; retry
    end
  end

  def self.establish_heartbeat
    Thread.new do
      loop do
        begin
          @conn.write "OK"; @conn.flush
          sleep $opts["heartbeat.wait.period"]
        rescue Errno::EPIPE
          puts "Looks like the registry died."; break
        rescue Errno::ECONNRESET
          puts "Registry closed connection on us."; break
        end
      end
      restart_heartbeat
    end
  end

  def self.restart_heartbeat
    puts "Re-establishing heartbeat."
    register; establish_heartbeat
  end

  # as what is sent out during the registration attempt.
  def self.accept_rpc_requests
    Thread.new do
      dispatcher = Dispatcher.new($opts["extra.plugin.dir"])
      puts "Starting dispatch listener: port = #{$opts["agent.dispatch.port"]}."
      listener = TCPServer.new($opts["agent.dispatch.port"])
      while true
        conn = listener.accept
        puts "Action dispatch connection accepted."
        begin
          # this is the only line that can throw an exception
          result = dispatcher.dispatch ActionPayload.deserialize(conn.gets.strip)
          conn.write result.serialize
        rescue Exception => e
          puts e
        ensure
          conn.flush; conn.close
        end
      end
    end
  end

end

ClientRegistrationHeartbeatStateMachine.start
sleep

redpajama_set_name: RedPajamaGithub


text:
CKEDITOR.plugins.setLang( 'liststyle', 'fi', {
	armenian: 'Armeenialainen numerointi',
	bulletedTitle: 'Numeroimattoman listan ominaisuudet',
	circle: 'Ympyrä',
	decimal: 'Desimaalit (1, 2, 3, jne.)',
	decimalLeadingZero: 'Desimaalit, alussa nolla (01, 02, 03, jne.)',
	disc: 'Levy',
	georgian: 'Georgialainen numerointi (an, ban, gan, etc.)',
	lowerAlpha: 'Pienet aakkoset (a, b, c, d, e, jne.)',
	lowerGreek: 'Pienet kreikkalaiset (alpha, beta, gamma, jne.)',
	lowerRoman: 'Pienet roomalaiset (i, ii, iii, iv, v, jne.)',
	none: 'Ei mikään',
	notset: '<ei asetettu>',
	numberedTitle: 'Numeroidun listan ominaisuudet',
	square: 'Neliö',
	start: 'Alku',
	type: 'Tyyppi',
	upperAlpha: 'Isot aakkoset (A, B, C, D, E, jne.)',
	upperRoman: 'Isot roomalaiset (I, II, III, IV, V, jne.)',
	validateStartNumber: 'Listan ensimmäisen numeron tulee olla kokonaisluku.'
} );


text:
<?php
// Administration

// Verification de securite
if (!defined("TOOLS_MANAGER"))
{
        die ("accès direct interdit");
}

$buffer->str(
'
Le plugin "Tags" vous permet de gerer des mots clés par page et ajoute des actions pour les consulter par flux RSS, moteur de recherche ou liste.
'

);

?>


text:
import org.scalatest.{Matchers, FlatSpec}

class NonEmptyListTest  extends FlatSpec with Matchers  {

  "A non empty list" should "be require at least one element" in  {
    new NonEmptyList(3).toList shouldEqual List(3)
    //new NonEmptyList() will not compile
  }

}


text:
FROM microsoft/dotnet:2.1-sdk AS build

COPY Sample.Web.Api /src

WORKDIR /src

# Publish release version of App
RUN dotnet publish -c Release -o /app -f netcoreapp2.1

FROM microsoft/dotnet:2.1-aspnetcore-runtime AS runtime

WORKDIR /app

COPY --from=build /app /app

ENTRYPOINT ["dotnet", "Sample.Web.Api.dll"]


text:
package org.tigris.subversion.javahl;

/**
 * Subversion notification interface.
 *
 * Implement this interface and implement the onNotify method
 * to provide a custom notification handler to the Modify
 * class.
 * If you need to pass extra information to the notification
 * handler then just add these to you implementing class
 * @deprecated Use Notify2 instead
 */
public interface Notify
{
    /**
     * Handler for Subversion notifications.
     *
     * Override this function to allow Subversion to
     * send notifications
     * @param path on which action happen
     * @param action subversion action, see svn_wc_notify_action_t
     * @param kind node kind of path after action occurred
     * @param mimeType mime type of path after action occurred
     * @param contentState state of content after action occurred
     * @param propState state of properties after action occurred
     * @param revision revision number  after action occurred
     */
    public void onNotify(String path, int action, int kind, String mimeType,
                         int contentState, int propState, long revision);

    /**
     * The type of action occuring.  The values are defined in the
     * interface NotifyAction for building reasons.
     */
    public static final class Action implements NotifyAction
    {
        /**
         * Returns the textual representation for the action kind
         * @param action kind of action
         * @return english text
         */
        public static final String getActionName(int action)
        {
            return NotifyAction.actionNames[action];
        }

    }
    /**
     * The type of notification that is occuring.  The values are
     * defined in the interface NotifyStatus for building reasons.
     */
    public static final class Status implements NotifyStatus
   {
        /**
         * Returns the textual representation for the notification type
         * @param status    type of the notification
         * @return  english text
         */
        public static final String getStatusName(int status)
        {
            return NotifyStatus.statusNames[status];
        }
    }
}


text:
package main

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"github.com/Comcast/traffic_control/test/router/data"
	"github.com/Comcast/traffic_control/test/router/load"
	"io/ioutil"
	"net/http"
	"net/url"
	"net/http/cookiejar"
)

var done chan struct{}
var resultChan chan data.HttpResult
var results []data.HttpResult

type credentials struct {
	User     string `json: "u"`
	Password string `json:"p"`
}

var opsCookies []*http.Cookie

func handler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	if r.Method == "GET" && r.URL.Path == "/report" {
		data, err := ioutil.ReadFile("foo.json")
		if err != nil {
			fmt.Fprintf(w, err.Error())
			return
		}

		fmt.Fprintf(w, string(data))
	}

	if r.Method == "POST" && r.URL.Path == "/api/1.2/user/login" {

		tr := &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}

		client := &http.Client{Transport: tr}

		url := fmt.Sprintf("https://%v/api/1.2/user/login", r.URL.Query().Get("opsHost"))

		resp, err := client.Post(url, "application/json", r.Body)
		defer resp.Body.Close();

		if err != nil {
			fmt.Println("Failed to proxy authentication to traffic ops", err.Error())
			w.WriteHeader(500)
			return
		}

		if resp.StatusCode != 200 {
			fmt.Println("Dangit!!!! got non 200", resp)
			w.WriteHeader(500)
			return
		}

		opsCookies = resp.Cookies()
		fmt.Println("ops cookies",opsCookies)

		for _, cookie := range resp.Cookies() {
			fmt.Println("cookie",cookie)
			http.SetCookie(w, cookie)
		}

		fmt.Println("woo-hoo I think I proxied authentication!!!")

		w.Write([]byte(fmt.Sprintf("{\"opsHost\":\"%v\"}", r.URL.Query().Get("opsHost"))));
		return
	}

	opsHost := r.URL.Query().Get("opsHost")
	if len(opsHost) > 0 {
		tr := &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}

		client := &http.Client{Transport: tr}

		urlString := fmt.Sprintf("https://%v%v", r.URL.Query().Get("opsHost"), r.URL.Path)
		u, err := url.Parse(urlString)

		if err != nil {
			fmt.Println("Failed parsing", urlString,err.Error())
			w.WriteHeader(500);
			return
		}

		if u == nil {
			fmt.Println("Crap")
			w.WriteHeader(500)
			return
		}

		fmt.Println("url", u)

		fmt.Println("AAAAA")
		fmt.Println(opsCookies)
		fmt.Println("BBBB")

		fmt.Println("client",client)
		fmt.Println("jar", client.Jar)

		client.Jar, err = cookiejar.New(nil)

		if err != nil {
			fmt.Println("Failed setting up cookie jar")
			w.WriteHeader(500)
			return
		}

		client.Jar.SetCookies(u, opsCookies)

		fmt.Println(client.Jar)

		resp, err := client.Get(urlString)
		defer resp.Body.Close()

		if err != nil {
			fmt.Println("Failed to proxy ", r.URL, "to host", r.URL.Query().Get("opsHost"))
			w.WriteHeader(500)
			return
		}

		buf, err := ioutil.ReadAll(resp.Body)

		if err != nil {
			fmt.Println("Failed reading body of response!")
			w.WriteHeader(500)
		}

		fmt.Println("proxying response",string(buf))
		w.Write(buf)
		return
	}

	if r.Method == "POST" && r.URL.Path == "/loadtest" {
		results = nil
		var lt load.LoadTest
		err := json.NewDecoder(r.Body).Decode(&lt)

		if err != nil {
			fmt.Println("Failed to unmarshal Json!", err.Error())
		}

		done = make(chan struct{})
		resultChan = load.DoLoadTest(lt, done)

		go func() {
			for {
				select {
				case result := <-resultChan:
					results = append(results, result)
				case <-done:
					return
				}
			}
		}()

		w.Write([]byte(`{"status":"started"}`))
	}

	if r.Method == "GET" && r.URL.Path == "/loadtest" {
		b, _ := json.MarshalIndent(results, "", "  ")

		w.Header().Add("Content-Type", "application/json")
		w.Write(b)
	}
}

func main() {
	done = make(chan struct{})

	http.HandleFunc("/", handler)
	http.ListenAndServe(":8888", nil)
}


text:
package org.apache.velocity.runtime.parser;

import org.apache.velocity.runtime.parser.node.SimpleNode;
import org.apache.velocity.util.introspection.Info;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 *
Track location in template files during rendering by populating the slf4j MDC tags file, line and column.

 *
An MDC-aware logger can then use this info to display the template location in the message

 *
For instance with webapp-slf4j-logger, it's enough to use %file, %line and %column in the logger format string.

 *
Since this feature can have a performance impact, it has to be enabled in velocity.properties using:

 *
runtime.log.track_location = true

 *
(typically in a development environment)

 *
 * @author Claude Brisson
 * @version $Id:$
 * @since 2.2
 */

public class LogContext
{
    protected static Logger logger = LoggerFactory.getLogger("rendering");

    public static final String MDC_FILE = "file";
    public static final String MDC_LINE = "line";
    public static final String MDC_COLUMN = "column";

    private boolean trackLocation;

    public LogContext(boolean trackLocation)
    {
        this.trackLocation = trackLocation;
    }

    private static ThreadLocal<Deque<StackElement>> contextStack = new ThreadLocal<Deque<StackElement>>()
    {
        @Override
        public Deque<StackElement> initialValue()
        {
            return new ArrayDeque<>();
        }
    };

    private static class StackElement
    {
        protected StackElement(SimpleNode src, Info info)
        {
            this.src = src;
            this.info = info;
        }

        protected SimpleNode src;
        protected int count = 1;
        protected Info info;
    }

    public void pushLogContext(SimpleNode src, Info info)
    {
        if (!trackLocation)
        {
            return;
        }
        Deque<StackElement> stack = contextStack.get();
        StackElement last = stack.peek();
        if (last != null && last.src == src)
        {
            ++last.count;
        }
        else
        {
            stack.push(new StackElement(src, info));
            setLogContext(info);
        }
    }

    public void popLogContext()
    {
        if (!trackLocation)
        {
            return;
        }
        Deque<StackElement> stack = contextStack.get();
        StackElement last = stack.peek();
        if (last == null)
        {
            logger.error("log context is already empty");
            return;
        }
        if (--last.count == 0)
        {
            stack.pop();
            last = stack.peek();
            if (last == null)
            {
                clearLogContext();
            }
            else
            {
                setLogContext(last.info);
            }
        }
    }

    private void setLogContext(Info info)
    {
        MDC.put(MDC_FILE, info.getTemplateName());
        MDC.put(MDC_LINE, String.valueOf(info.getLine()));
        MDC.put(MDC_COLUMN, String.valueOf(info.getColumn()));
    }

    private void clearLogContext()
    {
        MDC.remove(MDC_FILE);
        MDC.remove(MDC_LINE);
        MDC.remove(MDC_COLUMN);
    }

    private static final String STACKTRACE_LINE = "    %s at %s[line %d, column %d]";

    public String[] getStackTrace()
    {
        if (!trackLocation)
        {
            return null;
        }
        Deque<StackElement> stack = contextStack.get();
        List<String> levels = new ArrayList<>();
        for (StackElement level : stack)
        {
            String line = String.format(STACKTRACE_LINE,
                level.src.literal(),
                level.info.getTemplateName(),
                level.info.getLine(),
                level.info.getColumn());
            levels.add(line);
        }
        return levels.size() > 0 ? levels.toArray(new String[levels.size()]) : null;
    }
}


text:
@implementation WPSPSegmenterPresenceInfo

- (instancetype)initWithFromDate:(long long)fromDate untilDate:(long long)untilDate elapsedTime:(long long)elapsedTime {
    if (self = [super init]) {
        _fromDate = fromDate;
        _untilDate = untilDate;
        _elapsedTime = elapsedTime;
    }
    return self;
}

@end

@implementation WPSPSegmenterData

+ (NSArray<NSDictionary *> *)getEvents {
    NSArray<NSDictionary *> *trackedEvents = WPConfiguration.sharedConfiguration.trackedEvents;
    NSMutableArray<NSDictionary *> *rtn = [[NSMutableArray alloc] initWithCapacity:trackedEvents.count];
    for (NSDictionary *event in trackedEvents) {
        NSMutableDictionary *evt = [[NSMutableDictionary alloc] initWithDictionary:event];
        if (evt[@"creationDate"] == nil && evt[@"actionDate"] != nil) {
            evt[@"creationDate"] = evt[@"actionDate"];
        }
        [rtn addObject:evt];
    }
    return [[NSArray alloc] initWithArray:rtn];
}

+ (instancetype)forCurrentUser {
    NSString *userId = [WonderPush userId];
    NSMutableDictionary *installationData = [NSMutableDictionary dictionaryWithDictionary:[WPJsonSyncInstallation forCurrentUser].sdkState];
    if (userId) installationData[@"userId"] = userId;
    NSArray <NSDictionary *> *events = [self getEvents];
    WPConfiguration *configuration = WPConfiguration.sharedConfiguration;

    WPPresencePayload *presence = [[WonderPush presenceManager] lastPresencePayload];
    WPSPSegmenterPresenceInfo *presenceInfo = presence ? [[WPSPSegmenterPresenceInfo alloc] initWithFromDate:(long long)(presence.fromDate.timeIntervalSince1970 * 1000) untilDate:(long long)(presence.untilDate.timeIntervalSince1970 * 1000) elapsedTime:(long long)(presence.elapsedTime * 1000)] : nil;

    NSDate *lastAppOpenDate = configuration.lastAppOpenDate;
    WPLogDebug(@"Creating segmenter with installation data %@", installationData);
    WPSPSegmenterData *data = [[WPSPSegmenterData alloc]
                               initWithInstallation:installationData
                               allEvents:events
                               presenceInfo:presenceInfo
                               lastAppOpenDate:(long long)(lastAppOpenDate.timeIntervalSince1970 * 1000)];
    return data;
}

- (instancetype)initWithInstallation:(NSDictionary *)installation allEvents:(NSArray<NSDictionary *> *)allEvents presenceInfo:(WPSPSegmenterPresenceInfo * _Nullable)presenceInfo lastAppOpenDate:(long long)lastAppOpenDate {
    if (self = [super init]) {
        _installation = installation;
        _allEvents = [NSArray arrayWithArray:allEvents];
        _presenceInfo = presenceInfo;
        _lastAppOpenDate = lastAppOpenDate;
    }
    return self;
}

@end

@implementation WPSPSegmenter

- (instancetype)initWithData:(WPSPSegmenterData *)data {
    if (self = [super init]) {
        _data = data;
    }
    return self;
}

+ (WPSPASTCriterionNode *)parseInstallationSegment:(NSDictionary *)segmentInput {
    return [[WPSPSegmentationDSLParser defaultParser] parse:segmentInput dataSource:[WPSPInstallationSource new]];
}

- (BOOL)parsedSegmentMatchesInstallation:(WPSPASTCriterionNode *)parsedInstallationSegment {
    id rtn = [parsedInstallationSegment accept:[[WPSPInstallationVisitor alloc] initWithData:self.data]];
    if ([rtn isKindOfClass:NSNumber.class]) {
        return [rtn boolValue];
    }
    return NO;
}

@end

@implementation WPSPInstallationVisitor

- (id)visitFieldSource:(WPSPFieldSource *)dataSource {
    return [super visitFieldSource:dataSource withObject:self.data.installation];
}

@end

@implementation WPSPEventVisitor

- (instancetype)initWithData:(WPSPSegmenterData *)data event:(NSDictionary *)event {
    if (self = [super initWithData:data]) {
        _event = event;
    }
    return self;
}

- (id)visitFieldSource:(WPSPFieldSource *)dataSource {
    return [super visitFieldSource:dataSource withObject:self.event];
}

@end

@interface WPSPBaseVisitor ()

@property (nonatomic, assign, readonly) BOOL debug;

@end

@implementation WPSPBaseVisitor

- (instancetype)initWithData:(WPSPSegmenterData *)data {
    if (self = [super init]) {
        _debug = WPLogEnabled();
        _data = data;
    }
    return self;
}

///
/// WPSPASTValueVisitor
///

- (nonnull id)visitASTUnknownValueNode:(nonnull WPSPASTUnknownValueNode *)node {
    WPLog(@"Unsupported unknown value of type %@ with value %@", node.key, node.value);
    return [NSNull null];
}

- (nonnull id)visitBooleanValueNode:(nonnull WPSPBooleanValueNode *)node {
    return node.value;
}

- (nonnull id)visitNullValueNode:(nonnull WPSPNullValueNode *)node {
    return node.value;
}

- (nonnull id)visitNumberValueNode:(nonnull WPSPNumberValueNode *)node {
    return node.value;
}

- (nonnull id)visitStringValueNode:(nonnull WPSPStringValueNode *)node {
    return node.value;
}

-(nonnull id) visitDateValueNode:(WPSPDateValueNode *)node {
    return node.value;
}

-(nonnull id) visitRelativeDateValueNode:(WPSPRelativeDateValueNode *)node {
    return [NSNumber numberWithLongLong:([node.duration applyTo:[NSDate dateWithTimeIntervalSince1970:(WPUtil.getServerDate / 1000.0)]].timeIntervalSince1970 * 1000)];
}

-(nonnull id) visitDurationValueNode:(WPSPDurationValueNode *)node {
    return node.value;
}

-(nonnull id) visitGeoLocationValueNode:(WPSPGeoLocationValueNode *)node {
    return node.value;
}

-(nonnull id) visitGeoBoxValueNode:(WPSPGeoBoxValueNode *)node {
    return node.value;
}

-(nonnull id) visitGeoCircleValueNode:(WPSPGeoCircleValueNode *)node {
    return node.value;
}

-(nonnull id) visitGeoPolygonValueNode:(WPSPGeoPolygonValueNode *)node {
    return node.value;
}

///
/// WPSPASTCriterionVisitor
///

- (nonnull id)visitASTUnknownCriterionNode:(nonnull WPSPASTUnknownCriterionNode *)node {
    WPLog(@"Unsupported unknown criterion %@ with value %@", node.key, node.value);
    return @NO;
}

- (nonnull id)visitMatchAllCriterionNode:(nonnull WPSPMatchAllCriterionNode *)node {
    if (_debug) WPLog(@"[%@] return true", NSStringFromSelector(_cmd));
    return @YES;
}

- (nonnull id)visitAndCriterionNode:(nonnull WPSPAndCriterionNode *)node {
    for (WPSPASTCriterionNode *child in node.children) {
        if (!((NSNumber *)[child accept:self]).boolValue) {
            if (_debug) WPLog(@"[%@] return false because %@ is false", NSStringFromSelector(_cmd), child);
            return @NO;
        }
    }
    if (_debug) WPLog(@"[%@] return true", NSStringFromSelector(_cmd));
    return @YES;
}

- (nonnull id)visitOrCriterionNode:(nonnull WPSPOrCriterionNode *)node {
    for (WPSPASTCriterionNode *child in node.children) {
        if (((NSNumber *)[child accept:self]).boolValue) {
            if (_debug) WPLog(@"[%@] return true because %@ is true", NSStringFromSelector(_cmd), child);
            return @YES;
        }
    }
    if (_debug) WPLog(@"[%@] return false", NSStringFromSelector(_cmd));
    return @NO;
}

- (nonnull id)visitNotCriterionNode:(nonnull WPSPNotCriterionNode *)node {
    NSNumber *rtn = [NSNumber numberWithBool:!((NSNumber *)[node.child accept:self]).boolValue];
    if (_debug) WPLog(@"[%@] return %@", NSStringFromSelector(_cmd), rtn);
    return rtn;
}

- (nonnull id)visitAllCriterionNode:(nonnull WPSPAllCriterionNode *)node {
    NSArray<id> *dataSourceValues = [node.context.dataSource accept:self];
    if (![dataSourceValues isKindOfClass:NSArray.class]) {
        WPLog(@"[%@] Unexpected dataSourceValues: %@", NSStringFromSelector(_cmd), dataSourceValues);
    }
    for (WPSPASTValueNode *value in node.values) {
        BOOL found = NO;
        id actualValue = [value accept:self];
        if (actualValue == nil || [[NSNull null] isEqual:actualValue]) {
            if (dataSourceValues.count == 0) {
                found = YES;
            }
        } else {
            for (id dataSourceValue in dataSourceValues) {
                if ([actualValue isEqual:dataSourceValue]) {
                    found = true;
                    break;
                }
            }
        }
        if (!found) {
            if (_debug) WPLog(@"[%@] return false because %@ is not contained in %@", NSStringFromSelector(_cmd), actualValue, dataSourceValues);
            return @NO;
        }
    }
    if (_debug) WPLog(@"[%@] return true for %@", NSStringFromSelector(_cmd), dataSourceValues);
    return @YES;
}

- (nonnull id)visitAnyCriterionNode:(nonnull WPSPAnyCriterionNode *)node {
    NSArray<id> *dataSourceValues = [node.context.dataSource accept:self];
    if (![dataSourceValues isKindOfClass:NSArray.class]) {
        WPLog(@"[%@] Unexpected dataSourceValues: %@", NSStringFromSelector(_cmd), dataSourceValues);
    }
    for (WPSPASTValueNode *value in node.values) {
        id actualValue = [value accept:self];
        if (actualValue == nil || [[NSNull null] isEqual:actualValue]) {
            if (dataSourceValues.count == 0) {
                if (_debug) WPLog(@"[%@] return true for %@", NSStringFromSelector(_cmd), dataSourceValues);
                return @YES;
            }
        }
        for (id dataSourceValue in dataSourceValues) {
            if ([actualValue isEqual:dataSourceValue]) {
                if (_debug) WPLog(@"[%@] return true for %@", NSStringFromSelector(_cmd), dataSourceValues);
                return @YES;
            }
        }
    }
    if (_debug) WPLog(@"[%@] return false for %@", NSStringFromSelector(_cmd), dataSourceValues);
    return @NO;
}

NSComparisonResult compareObjectOrThrow(id a, id b) {
    if ([[NSNull null] isEqual:a]) a = nil;
    if ([[NSNull null] isEqual:b]) b = nil;
    if (a == nil && b == nil) return 0;
    if (a == nil) return -compareObjectOrThrow(b, nil);
    // Now a is non nil, we'll compare depending on its type, and take an appropriate zero-value for b if it is nil
    if ([a isKindOfClass:NSNumber.class] && [WPJsonUtil isBoolNumber:a]) {
        if (b == nil) b = @NO;
        if ([b isKindOfClass:NSNumber.class] && [WPJsonUtil isBoolNumber:b]) {
            return [((NSNumber *)a) compare:b];
        }
    } else if ([a isKindOfClass:NSNumber.class]) {
        if (b == nil) b = @0;
        if ([b isKindOfClass:NSNumber.class]) {
            return [((NSNumber *)a) compare:b];
        }
    } else if ([a isKindOfClass:NSString.class]) {
        if (b == nil) b = @"";
        if ([b isKindOfClass:NSString.class]) {
            return [((NSString *)a) compare:b];
        }
    }
    @throw @"cannot compare the given types";
}

- (nonnull id)visitComparisonCriterionNode:(nonnull WPSPComparisonCriterionNode *)node {
    NSArray<id> *dataSourceValues = [node.context.dataSource accept:self];
    if (![dataSourceValues isKindOfClass:NSArray.class]) {
        WPLog(@"[%@] Unexpected dataSourceValues: %@", NSStringFromSelector(_cmd), dataSourceValues);
    }
    BOOL result = NO;
    id actualValue = [node.value accept:self];
    for (WPSPASTValueNode *dataSourceValue in dataSourceValues) {
        @try {
            NSComparisonResult comparison = compareObjectOrThrow(dataSourceValue, actualValue);
            if (node.comparator == WPSPComparatorGt) {
                result = comparison == NSOrderedDescending;
            } else if (node.comparator == WPSPComparatorGte) {
                result = comparison != NSOrderedAscending;
            } else if (node.comparator == WPSPComparatorLt) {
                result = comparison == NSOrderedAscending;
            } else if (node.comparator == WPSPComparatorLte) {
                result = comparison != NSOrderedDescending;
            }
        } @catch (id ignored) {}
        if (result) {
            break;
        }
    }
    if (_debug) {
        NSString *comparatorStr = @"??";
        if (node.comparator == WPSPComparatorGt) comparatorStr = @"gt";
        else if (node.comparator == WPSPComparatorGte) comparatorStr = @"gte";
        else if (node.comparator == WPSPComparatorLt) comparatorStr = @"lt";
        else if (node.comparator == WPSPComparatorLte) comparatorStr = @"lte";
        WPLog(@"[%@] return %@ because %@ %@ %@ %@", NSStringFromSelector(_cmd), result ? @"true" : @"false", dataSourceValues, result ? @"is" : @"is not", comparatorStr, actualValue);
    }
    return result ? @YES : @NO;
}

- (nonnull id)visitEqualityCriterionNode:(nonnull WPSPEqualityCriterionNode *)node {
    NSArray<id> *dataSourceValues = [node.context.dataSource accept:self];
    if (![dataSourceValues isKindOfClass:NSArray.class]) {
        WPLog(@"[%@] Unexpected dataSourceValues: %@", NSStringFromSelector(_cmd), dataSourceValues);
    }
    id actualValue = [node.value accept:self];
    BOOL result = NO;
    if (actualValue == nil || [[NSNull null] isEqual:actualValue]) {
        result = dataSourceValues.count == 0 ? YES : NO;
    } else {
        for (id dataSourceValue in dataSourceValues) {
            if (!dataSourceValue || [dataSourceValue isKindOfClass:NSNull.class]) continue;
            if (([actualValue isKindOfClass:NSNumber.class] && [WPJsonUtil isBoolNumber:actualValue]) || ([dataSourceValue isKindOfClass:NSNumber.class] && [WPJsonUtil isBoolNumber:dataSourceValue])) {
                if ([actualValue isKindOfClass:NSNumber.class] && [WPJsonUtil isBoolNumber:actualValue] && [dataSourceValue isKindOfClass:NSNumber.class] && [WPJsonUtil isBoolNumber:dataSourceValue]) {
                    result = ((NSNumber *)actualValue).boolValue == ((NSNumber *)dataSourceValue).boolValue;
                } else {
                    result = NO;
                }
            } else if ([actualValue isKindOfClass:NSNumber.class]) {
                if ([dataSourceValue isKindOfClass:NSNumber.class]) {
                    result = [actualValue isEqual:dataSourceValue];
                } else {
                    result = NO;
                }
            } else {
                result = [actualValue isEqual:dataSourceValue];
            }
            if (result) break;
        }
    }
    if (_debug) WPLog(@"[%@] return %@ because %@ %@ %@", NSStringFromSelector(_cmd), result ? @"true" : @"false", dataSourceValues, result ? @"==" : @"!=", actualValue);
    return result ? @YES : @NO;
}

- (nonnull id)visitGeoCriterionNode:(nonnull WPSPGeoCriterionNode *)node {
    if (_debug) WPLog(@"[%@] unsupported", NSStringFromSelector(_cmd));
    return @NO;
}

- (nonnull id)visitInsideCriterionNode:(nonnull WPSPInsideCriterionNode *)node {
    if (_debug) WPLog(@"[%@] unsupported", NSStringFromSelector(_cmd));
    return @NO;
}

- (nonnull id)visitJoinCriterionNode:(nonnull WPSPJoinCriterionNode *)node {
    if ([node.context.dataSource isKindOfClass:WPSPEventSource.class]) {
        for (NSDictionary *event in self.data.allEvents) {
            WPSPEventVisitor *eventVisitor = [[WPSPEventVisitor alloc] initWithData:self.data event:event];
            if (((NSNumber *)[node.child accept:eventVisitor]).boolValue) {
                if (_debug) WPLog(@"[%@] return true for event %@", NSStringFromSelector(_cmd), event);
                return @YES;
            }
        }
        if (_debug) WPLog(@"[%@] return false for all events", NSStringFromSelector(_cmd));
        return @NO;
    }
    if ([node.context.dataSource isKindOfClass:WPSPInstallationSource.class]) {
        WPSPInstallationVisitor *installationVisitor = [[WPSPInstallationVisitor alloc] initWithData:self.data];
        id result = [node.child accept:installationVisitor];
        if (_debug) WPLog(@"[%@] return %@ for installation", NSStringFromSelector(_cmd), [result boolValue] ? @"true" : @"false");
        return result;
    }
    WPLog(@"[%@] return false for unsupported %@", NSStringFromSelector(_cmd), NSStringFromClass(node.context.dataSource.class));
    return @NO;
}

- (nonnull id)visitLastActivityDateCriterionNode:(nonnull WPSPLastActivityDateCriterionNode *)node {
    id result = nil;
    if (node.dateComparison == nil) {
        result = self.data.lastAppOpenDate > 0 ? @YES : @NO;
    } else {
        result = [node.dateComparison accept:self];
    }
    if (_debug) WPLog(@"[%@] return %@", NSStringFromSelector(_cmd), result);
    return result;
}

- (nonnull id)visitPrefixCriterionNode:(nonnull WPSPPrefixCriterionNode *)node {
    NSArray<id> *dataSourceValues = [node.context.dataSource accept:self];
    if (![dataSourceValues isKindOfClass:NSArray.class]) {
        WPLog(@"[%@] Unexpected dataSourceValues: %@", NSStringFromSelector(_cmd), dataSourceValues);
    }
    NSString *actualValue = [node.value accept:self];
    if (![actualValue isKindOfClass:NSString.class]) {
        WPLog(@"[%@] value %@ is not a string", NSStringFromSelector(_cmd), actualValue);
        return @NO;
    }
    BOOL result = NO;
    for (id dataSourceValue in dataSourceValues) {
        if (![dataSourceValue isKindOfClass:NSString.class]) {
            WPLog(@"[%@] value %@ is not a string", NSStringFromSelector(_cmd), dataSourceValue);
            continue;
        }
        result = [((NSString *)dataSourceValue) hasPrefix:actualValue];
        if (result) break;
    }
    if (_debug) WPLog(@"[%@] return %@ because %@ %@ %@", NSStringFromSelector(_cmd), result ? @"true" : @"false", dataSourceValues, result ? @"starts with" : @"does not start with", actualValue);
    return result ? @YES : @NO;
}

- (nonnull id)visitPresenceCriterionNode:(nonnull WPSPPresenceCriterionNode *)node {
    // Are we present right now?
    BOOL present = self.data.presenceInfo == nil || (self.data.presenceInfo.untilDate >= [WPUtil getServerDate] && self.data.presenceInfo.fromDate <= [WPUtil getServerDate]);
    if (present != node.present) {
        if (_debug) WPLog(@"[%@] return false because presence mismatch, expected %@", NSStringFromSelector(_cmd), node.present ? @"present" : @"absent");
        return @NO;
    }

    if (node.elapsedTimeComparison != nil && !((NSNumber *)[node.elapsedTimeComparison accept:self]).boolValue) {
        if (_debug) WPLog(@"[%@] return false because elapsedTime mismatch", NSStringFromSelector(_cmd));
        return @NO;
    }
    if (node.sinceDateComparison != nil && !((NSNumber *)[node.sinceDateComparison accept:self]).boolValue) {
        if (_debug) WPLog(@"[%@] return false because sinceDate mismatch", NSStringFromSelector(_cmd));
        return @NO;
    }
    if (_debug) WPLog(@"[%@] return true", NSStringFromSelector(_cmd));
    return @YES;
}

- (nonnull id)visitSubscriptionStatusCriterionNode:(nonnull WPSPSubscriptionStatusCriterionNode *)node {
    NSString *pushTokenData = [WPNSUtil stringForKey:@"data" inDictionary:[WPNSUtil dictionaryForKey:@"pushToken" inDictionary:self.data.installation]];
    BOOL hasPushToken = [pushTokenData isKindOfClass:NSString.class] && [(NSString *)pushTokenData length] > 0;
    NSString *preferencesSubscriptionStatus = [WPNSUtil stringForKey:@"subscriptionStatus" inDictionary:[WPNSUtil dictionaryForKey:@"preferences" inDictionary:self.data.installation]];
    WPSPSubscriptionStatus actualStatus;
    if (!hasPushToken) {
        actualStatus = WPSPSubscriptionStatusOptOut;
    } else if ([@"optOut" isEqual:preferencesSubscriptionStatus]) {
        actualStatus = WPSPSubscriptionStatusSoftOptOut;
    } else {
        actualStatus = WPSPSubscriptionStatusOptIn;
    }
    id result = node.subscriptionStatus == actualStatus ? @YES : @NO;
    NSString *statusString = nil;
    switch (actualStatus) {
        case WPSPSubscriptionStatusOptIn:
            statusString = @"optIn";
        case WPSPSubscriptionStatusOptOut:
            statusString = @"optOut";
        case WPSPSubscriptionStatusSoftOptOut:
            statusString = @"softOptOut";
    }
    if (_debug) WPLog(@"[%@] return %@ because we are %@", NSStringFromSelector(_cmd), result ? @"true" : @"false", statusString ?: @"unknown");
    return result;
}

///
/// WPSPDataSourceVisitor
///

- (nonnull id)visitEventSource:(nonnull WPSPEventSource *)dataSource {
    return @[];
}

// The following method is voluntarily left for subclasses,
// which should call [visitFieldSource:withObject:] with the right object.
//- (nonnull id)visitFieldSource:(nonnull WPSPFieldSource *)dataSource {
//}

- (NSArray<id> *)visitFieldSource:(WPSPFieldSource *)dataSource withObject:(NSDictionary *)object {
    WPSPFieldPath *fieldPath = dataSource.fullPath;
    id curr = object;
    for (NSString *part in fieldPath.parts) {
        if ([curr isKindOfClass:NSDictionary.class]) {
            curr = curr[part];
        } else if ([curr isKindOfClass:NSArray.class]) {
            NSInteger index = -1;
            if ([[NSScanner scannerWithString:part] scanInteger:&index]) {
                curr = curr[index];
            } else {
                curr = nil;
            }
        } else {
            curr = nil;
        }
    }
    NSArray<id> *rtn;
    if ([curr isKindOfClass:NSArray.class]) {
        // Ignore nulls
        NSExpression *lhs = [NSExpression expressionForEvaluatedObject];
        NSExpression *rhs = [NSExpression expressionForConstantValue:[NSNull null]];
        NSPredicate *filterDifferent = [NSComparisonPredicate predicateWithLeftExpression:lhs rightExpression:rhs modifier:NSDirectPredicateModifier type:NSNotEqualToPredicateOperatorType options:0];
        rtn = [curr filteredArrayUsingPredicate:filterDifferent];
    } else if (curr == nil || [[NSNull null] isEqual:curr]) {
        rtn = @[];
    } else {
        rtn = @[curr];
    }
    if (fieldPath.parts.count >= 2 && [@"custom" isEqualToString:fieldPath.parts[0]] && [fieldPath.parts.lastObject hasPrefix:@"date_"]) {
        NSMutableArray<id> *parsedDates = [NSMutableArray arrayWithCapacity:rtn.count];
        for (id item in rtn) {
            id itemToAdd = item;
            if ([item isKindOfClass:NSString.class]) {
                @try {
                    NSDate *parsed = [WPSPDefaultValueNodeParser parseAbsoluteDate:(NSString *)item];
                    if (parsed) {
                        itemToAdd = [NSNumber numberWithLongLong:(long long)(parsed.timeIntervalSince1970) * 1000LL];
                    }
                } @catch (id ignored) {}
            }
            [parsedDates addObject:itemToAdd];
        }
        rtn = [NSArray arrayWithArray:parsedDates];
    }
    return rtn;
}

- (nonnull id)visitGeoDateSource:(nonnull WPSPGeoDateSource *)dataSource {
    // TODO Implement geo
    return @[];
}

- (nonnull id)visitGeoLocationSource:(nonnull WPSPGeoLocationSource *)dataSource {
    // TODO Implement geo
    return @[];
}

- (nonnull id)visitInstallationSource:(nonnull WPSPInstallationSource *)dataSource {
    return @[];
}

- (nonnull id)visitLastActivityDateSource:(nonnull WPSPLastActivityDateSource *)dataSource {
    return @[
        [NSNumber numberWithLongLong:self.data.lastAppOpenDate],
    ];
}

- (nonnull id)visitPresenceElapsedTimeSource:(nonnull WPSPPresenceElapsedTimeSource *)dataSource {
    if (dataSource.present) {
        return @[
            [NSNumber numberWithLongLong:(self.data.presenceInfo == nil ? 0 : MAX(0, [WPUtil getServerDate] - self.data.presenceInfo.fromDate))],
        ];
    }
    return @[
        [NSNumber numberWithLongLong:(self.data.presenceInfo == nil ? 0 : self.data.presenceInfo.elapsedTime)],
    ];
}

- (nonnull id)visitPresenceSinceDateSource:(nonnull WPSPPresenceSinceDateSource *)dataSource {
    // Note: with in-apps, if we're running this, we're present.
    if (dataSource.present) {
        // When presence info is missing, assume the user just got here.
        return @[
            [NSNumber numberWithLongLong:(self.data.presenceInfo == nil ? [WPUtil getServerDate] : self.data.presenceInfo.fromDate)],
        ];
    }
    // When presence info is missing, assume the user will stay here indefinitely (yay!).
    return @[
        [NSNumber numberWithLongLong:(self.data.presenceInfo == nil ? LONG_LONG_MAX : self.data.presenceInfo.untilDate)],
    ];
}

- (nonnull id)visitUserSource:(nonnull WPSPUserSource *)dataSource {
    return @[];
}

- (nonnull id)visitFieldSource:(nonnull WPSPFieldSource *)dataSource {
    @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"%@ must be overridden", NSStringFromSelector(_cmd)] userInfo:nil];
}

@end


text:
require 'ox'

module Fieldhand
  # A set is an optional construct for grouping items for the purpose of selective harvesting.
  #
  # See https://www.openarchives.org/OAI/openarchivesprotocol.html#Set
  class Set
    attr_reader :element, :response_date

    # Return a Set with the given element and optional response date.
    #
    # Defaults the response date to the current time.
    def initialize(element, response_date = Time.now)
      @element = element
      @response_date = response_date
    end

    # Return the set's spec as its string representation.
    #
    # This means that Sets can be used as arguments that expect a set spec.
    def to_s
      spec
    end

    # Return the set's unique identifier within the repository.
    def spec
      @spec ||= element.setSpec.text
    end

    # Return the set's short human-readable name.
    def name
      @name ||= element.setName.text
    end

    # Return any descriptions of the set as an array of strings.
    #
    # As descriptions can be in any format, Fieldhand does not attempt to parse them but leave this to the user.
    def descriptions
      @descriptions ||= element.locate('setDescription').map { |description| Ox.dump(description) }
    end
  end
end


text:
Almost the same as [`writeJsonSync`](writeJson-sync.md), except that if the directory does not exist, it's created.

**Alias:** `outputJSONSync()`

- `file` `<String>`
- `object` `<Object>`
- `options` `<Object>`
  - `spaces` `<Number> | <String>` Number of spaces to indent; or a string to use for indentation (i.e. pass `'\t'` for tab indentation). See [the docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_space_argument) for more info.
  - `EOL` `<String>` Set EOL character. Default is `\n`.
  - `replacer` [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter)
  - Also accepts [`fs.writeFileSync()` options](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options)

## Example:

```js
const fs = require('fs-extra')

const file = '/tmp/this/path/does/not/exist/file.json'
fs.outputJsonSync(file, {name: 'JP'})

const data = fs.readJsonSync(file)
console.log(data.name) // => JP
```


text:
"""
Created on May 20, 2014

@author: Tyranic-Moron
"""
from twisted.plugin import IPlugin
from pymoronbot.moduleinterface import IModule
from pymoronbot.modules.commandinterface import BotCommand
from zope.interface import implementer

import re

from pymoronbot.message import IRCMessage
from pymoronbot.response import IRCResponse, ResponseType

from pymoronbot.utils import string

@implementer(IPlugin, IModule)
class Find(BotCommand):
    def triggers(self):
        return ['find', 'google', 'g']

    def help(self, query):
        return 'find/google/g <searchterm> - returns the first google result for the given search term'

    def execute(self, message):
        """
        @type message: IRCMessage
        """
        try:
            results = self.bot.moduleHandler.runActionUntilValue('search-web', message.Parameters)

            if not results:
                return IRCResponse(ResponseType.Say,
                                   u'[google developer key missing]',
                                   message.ReplyTo)

            firstResult = results[u'items'][0]

            title = firstResult[u'title']
            title = re.sub(r'\s+', ' ', title)
            content = firstResult[u'snippet']
            content = re.sub(r'\s+', ' ', content)  # replace multiple spaces with single ones (includes newlines?)
            content = string.unescapeXHTML(content)
            url = firstResult[u'link']
            replyText = u'{1}{0}{2}{0}{3}'.format(string.graySplitter, title, content, url)

            return IRCResponse(ResponseType.Say, replyText, message.ReplyTo)
        except Exception as x:
            print(str(x))
            return IRCResponse(ResponseType.Say, x.args, message.ReplyTo)

find = Find()


text:
"use strict";
/// <reference types="node" />
var BaseLoggerImpl;
var ColoredText;
module.exports = class NullLogger {
    constructor(...scopes) {
        this.isDeathRun = false;
        this.scopes = scopes;
    }
    static makeColored(text, color) {
        return new (ColoredText || (ColoredText = require("./baseimpl").ColoredText))(text, color);
    }
    static makeLoggerImpl() {
        if (process.env.LOGGER_IMPL) {
            var plugin = require(process.env.LOGGER_IMPL);
            if (plugin.default)
                return new (plugin.default);
            return new plugin();
        }
        var plugins = [
            "0-silent-logger",
            "1-cli-color-logger",
            "2-text-logger"
        ];
        var $break = new Object();
        var _impl;
        try {
            plugins.forEach(function (plugin) {
                try {
                    plugin = require("./impl/" + plugin);
                    _impl = new plugin();
                }
                catch (e) {
                    return;
                }
                throw $break;
            });
        }
        catch (e) {
            if (e !== $break)
                throw e;
        }
        return _impl;
    }
    /**
     * Log data to the specified implementation.
     *
     * @param level The logging level to use
     * @param loggerOrScopes The logger, scope(s)
     * @param messages The message data to log
     * @param impl The logger implementation
     */
    static log(level, loggerOrScopes, messages, impl = NullLogger.active) {
        return (impl || NullLogger.active || (NullLogger.active = NullLogger.makeLoggerImpl())).log(level, loggerOrScopes, messages);
    }
    /**
     * Log with gears level
     *
     * @param messages The message data to log
     */
    static gears(...messages) {
        NullLogger.log(0 /* Gears */, undefined, messages);
    }
    /**
     * Log with performance level
     *
     * @param messages The message data to log
     */
    static performance(...messages) {
        NullLogger.log(2 /* Performance */, undefined, messages);
    }
    /**
     * Log with performance level
     *
     * @param messages The message data to log
     */
    static perf(...messages) {
        NullLogger.log(2 /* Performance */, undefined, messages);
    }
    /**
     * Log with debugging level
     *
     * @param messages The message data to log
     */
    static debugging(...messages) {
        NullLogger.log(1 /* Debugging */, undefined, messages);
    }
    /**
     * Log with debugging level
     *
     * @param messages The message data to log
     */
    static debug(...messages) {
        NullLogger.log(1 /* Debugging */, undefined, messages);
    }
    /**
     * Log with information level
     *
     * @param messages The message data to log
     */
    static info(...messages) {
        NullLogger.log(4 /* Information */, undefined, messages);
    }
    /**
     * Log with information level
     *
     * @param messages The message data to log
     */
    static information(...messages) {
        NullLogger.log(4 /* Information */, undefined, messages);
    }
    /**
     * Log with warning level
     *
     * @param messages The message data to log
     */
    static warn(...messages) {
        NullLogger.log(5 /* Warning */, undefined, messages);
    }
    /**
     * Log with warning level
     *
     * @param messages The message data to log
     */
    static warning(...messages) {
        NullLogger.log(5 /* Warning */, undefined, messages);
    }
    /**
     * Log with error level
     *
     * @param messages The message data to log
     */
    static error(...messages) {
        NullLogger.log(7 /* Fatal */, undefined, messages);
    }
    /**
     * Log with fatal level, then exit with code 1
     *
     * @param messages The message data to log
     */
    static fatal(...messages) {
        NullLogger.log(7 /* Fatal */, undefined, messages);
        process.exit(1);
    }
    /**
     * Change the minimum logging level
     *
     * @param level The new minimum logging level to use
     */
    static setMinLevel(level) {
        if (!BaseLoggerImpl)
            BaseLoggerImpl = require("./baseimpl").default;
        if (typeof level === "string")
            BaseLoggerImpl.setMinLevel(level);
        else
            BaseLoggerImpl.MIN_LEVEL = level;
    }
    /**
     * Return the minimum logging level
     */
    static minLevel() {
        if (!BaseLoggerImpl)
            BaseLoggerImpl = require("./baseimpl").default;
        return BaseLoggerImpl.MIN_LEVEL;
    }
    /**
     * Return the filename of the logging implementation, when available
     */
    static impl() {
        return NullLogger.active.filename;
    }
    /**
     * Log with gears level
     *
     * @param messages The message data to log
     */
    gears(...messages) {
        NullLogger.log(0 /* Gears */, this, messages);
        return this;
    }
    /**
     * Measure the duration a function takes to execuse.
     * If the function returns a promise, waits for the promise to complete.
     *
     * @param name The name of the timer
     * @param impl The function implementation to measure
     */
    timer(name, impl) {
        var logger = this.extend(name);
        NullLogger.log(3 /* Timer */, logger, ["Running function", name]);
        var start = +new Date;
        const promise = impl(logger);
        if (promise instanceof Promise) {
            promise.catch(function (err) {
                NullLogger.log(6 /* Error */, logger, ["Function", name, "errored:", err]);
            });
            promise.finally(function () {
                NullLogger.log(3 /* Timer */, logger, ["Function", name, "took " + ((+new Date) - start) + "ms."]);
            });
        }
        else
            NullLogger.log(3 /* Timer */, logger, ["Function", name, "took " + ((+new Date) - start) + "ms."]);
        return this;
    }
    /**
     * Measure the duration a function takes to execuse, in a inherently asynchronious way.
     *
     * @param name The name of the timer
     * @param impl The function implementation to measure
     */
    timerAsync(name, impl) {
        var logger = this.extend(name);
        NullLogger.log(3 /* Timer */, logger, ["Starting function", name]);
        var start = +new Date;
        impl(logger, function (err) {
            if (err instanceof Error)
                NullLogger.log(6 /* Error */, logger, ["Function", name, "errored:", err]);
            NullLogger.log(3 /* Timer */, logger, ["Function", name, "took " + ((+new Date) - start) + "ms."]);
        });
        return this;
    }
    /**
     * Log with performance level
     *
     * @param messages The message data to log
     */
    performance(...messages) {
        NullLogger.log(2 /* Performance */, this, messages);
        return this;
    }
    /**
     * Log with performance level
     *
     * @param messages The message data to log
     */
    perf(...messages) {
        NullLogger.log(2 /* Performance */, this, messages);
        return this;
    }
    /**
     * Log with debugging level
     *
     * @param messages The message data to log
     */
    debugging(...messages) {
        NullLogger.log(1 /* Debugging */, this, messages);
        return this;
    }
    /**
     * Log with debugging level
     *
     * @param messages The message data to log
     */
    debug(...messages) {
        NullLogger.log(1 /* Debugging */, this, messages);
        return this;
    }
    /**
     * Log with information level
     *
     * @param messages The message data to log
     */
    info(...messages) {
        NullLogger.log(4 /* Information */, this, messages);
        return this;
    }
    /**
     * Log with information level
     *
     * @param messages The message data to log
     */
    information(...messages) {
        NullLogger.log(4 /* Information */, this, messages);
        return this;
    }
    /**
     * Log with warning level
     *
     * @param messages The message data to log
     */
    warn(...messages) {
        NullLogger.log(5 /* Warning */, this, messages);
        return this;
    }
    /**
     * Log with warning level
     *
     * @param messages The message data to log
     */
    warning(...messages) {
        NullLogger.log(5 /* Warning */, this, messages);
        return this;
    }
    /**
     * Log with error level
     *
     * @param messages The message data to log
     */
    error(...messages) {
        NullLogger.log(6 /* Error */, this, messages);
        return this;
    }
    /**
     * Log with error level, and exit with code 1 after
     *
     * @param messages The message data to log
     */
    fatal(...messages) {
        NullLogger.log(7 /* Fatal */, this, messages);
        process.exit(1);
    }
    /**
     * Return a new NullLogger that extends this one
     *
     * @param messages The message data to log
     */
    extend(...scopes) {
        var merged = this.scopes.slice(0);
        merged.push.apply(merged, scopes);
        var logger = new NullLogger();
        logger.scopes = merged;
        return logger;
    }
    /**
     * Execute within a group, using a new temporary NullLogger
     *
     * @param messages The message data to log
     */
    group(name, impl) {
        impl(this.extend(name));
        return this;
    }
    /**
     * Update a specific scope at a specific index
     *
     * @param messages The message data to log
     */
    updateScopeName(scope, index = -1) {
        if (index < 0)
            this.scopes[this.scopes.length + index] = scope;
        else
            this.scopes[index] = scope;
        delete this.scopeCache;
        return this;
    }
    /**
     * Return a specific scope at a specific index
     *
     * @param messages The message data to log
     */
    scopeName(index = -1) {
        if (index < 0)
            return this.scopes[this.scopes.length + index];
        else
            return this.scopes[index];
    }
    static useWithDeathHandler(scriptToRun, ondeath, implementation) {
        try {
            require('death')(function (signal, err) {
                if (ondeath)
                    ondeath(signal, err);
            });
        }
        catch (e) {
        }
    }
};
//# sourceMappingURL=logger.js.map


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

namespace WifiSnifferPositioningService.baselogic
{
    /// <summary>
    /// Encapsulates functionality for calculating the distance between two points
    /// represented by latitude and longitude cordinates
    /// </summary>
    public class DistanceMeasurements
    {
        /// <summary>
        /// The radius of the earth
        /// </summary>
        const double kEarthRadiusKms = 6376.5;

        /// <summary>
        /// Converts an angle to a radian.
        /// </summary>
        /// <param name="input">The angle that is to be converted.</param>
        /// <returns>The angle in radians.</returns>
        private static double ToRadians(double input)
        {
            return input * (Math.PI / 180);
        }

        /**
         *  Calculates the distance, in kilometers, between the old and new location, each
         * represented by a latitude and a longitude
         */
        public static double CalculateMovedDistanceInKm(double oldLat, double oldLng, double newLat, double newLng)
        {
            double dDistance = double.MinValue;
            double dLat1InRad = oldLat * (Math.PI / 180);
            double dLong1InRad = oldLng * (Math.PI / 180);
            double dLat2InRad = newLat * (Math.PI / 180);
            double dLong2InRad = newLng * (Math.PI / 180);
            double dLongitude = dLong2InRad - dLong1InRad;
            double dLatitude = dLat2InRad - dLat1InRad;
            double a = Math.Pow(Math.Sin(dLatitude / 2), 2) + Math.Cos(dLat1InRad) * Math.Cos(dLat2InRad) * Math.Pow(Math.Sin(dLongitude / 2), 2);
            //Converts rectangular coordinates (x, y) to polar (r, theta).
            double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
            dDistance = kEarthRadiusKms * c;
            return dDistance;
        }

        //http://stackoverflow.com/questions/120283/working-with-latitude-longitude-values-in-java
        public static double haversineDistanceKm(double lat1, double lng1, double lat2, double lng2)
        {
            double earthRadius = 6371;
            double dLat = ToRadians(lat2 - lat1);
            double dLng = ToRadians(lng2 - lng1);
            double sindLat = Math.Sin(dLat / 2);
            double sindLng = Math.Sin(dLng / 2);
            double a = Math.Pow(sindLat, 2) + Math.Pow(sindLng, 2) * Math.Cos(lat1) * Math.Cos(lat2);
            double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
            double dist = earthRadius * c;

            return dist;
        }

        public static double haversineDistanceMeters(double lat1, double lng1, double lat2, double lng2)
        {
            return haversineDistanceKm(lat1, lng2, lat2, lng2) * 1000;
        }

        /**
        /// Calculates the distance, in meters, between the old and new location, each
        /// represented by a latitude and a longitude
        */
        public static double CalculateMoveddistanceInMeters(double oldLat, double oldLng, double newLat, double newLng)
        {
            return CalculateMovedDistanceInKm(oldLat, oldLng, newLat, newLng) * 1000;
        }
    }
}


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

namespace ConvertSpeedUnits
{
    class ConvertSpeedUnits
    {
        static void Main(string[] args)
        {
            float distance = float.Parse(Console.ReadLine()); //in meters

            float miles = 1609f;

            float hours =   float.Parse(Console.ReadLine());
            float minutes = float.Parse(Console.ReadLine());
            float seconds = float.Parse(Console.ReadLine());

            float time = (hours * 3600) + (minutes * 60) + seconds;
            float mps = distance / time;
            float kmh = (distance / 1000.0f) / (time / 3600.0f);
            float mph = (kmh / miles) * 1000.0f;

            //Console.WriteLine("{0:f6}", mps);
            //Console.WriteLine("{0:f6}", kmh);
            //Console.WriteLine("{0:f6}", mph);

            Console.WriteLine(mps);
            Console.WriteLine(kmh);
            Console.WriteLine(mph);

        }
    }
}


text:
/* global $ */

const Nightmare = require('nightmare');
const rp = require('request-promise');
const zones = require('../zones.json');

const userAgent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36';
const loginUri = 'https://zeus.sii.cl/AUT2000/InicioAutenticacion/IngresoRutClave.html?https://misii.sii.cl/cgi_misii/siihome.cgi';
const boletasUri = 'http://www.sii.cl/boleta_honorarios/';

const getDestinataryName = rut => {
  const options = {
    uri: 'https://siichile.herokuapp.com/consulta',
    qs: {rut: rut},
    json: true
  };
  return rp(options).then(data => data.razon_social);
};

const sendCredentials = user => {
  $('#rutcntr').val(user.rut);
  $('#rutcntr').blur();
  $('#clave').val(user.password);
  $('a[href="javascript:ejecuta_opcion()"]')[0].click();
};

const gotToLast = () => {
  $('a[href="javascript:muestra_oculta_opc(1)"]')[0].click();
  $('#menu1 ul li:nth-child(2) a')[0].click();
};

const gotToDestinatary = () => {
  $('a[href="javascript:muestra_oculta_opc(1)"]')[0].click();
  $('#menu1 ul li:nth-child(1) a')[0].click();
};

const selectLast = () => {
  $('a[href="javascript:envia();"]')[0].click();
};

const selectRetention = () => {
  $('input[name=OptTipoRetencion]').val('RETRECEPTOR');
  $('#cmdContinuar').click();
};

const fillForm = (work, destinatary, zone, commune) => {
  destinatary = destinatary || null;
  zone = zone || null;
  commune = commune || null;
  $('#valor_prestacion_1').val(work.value);
  if (work.description) $('#desc_prestacion_1').val(work.description);
  if (destinatary !== null) {
    $('input[name=txt_rut_destinatario]').val(destinatary.rut);
    $('input[name=txt_dv_destinatario]').val(destinatary.dv);
    $('input[name=txt_nombres_destinatario]').val(destinatary.name);
    $('input[name=txt_domicilio_destinatario]').val(destinatary.address);
  }
  if (zone !== null) {
    $('select[name=cod_region]').val(zone);
    $('select[name=cod_region]').change();
  }
  if (commune !== null) {
    $('select[name=cbo_comuna]').val(commune);
    $('select[name=cbo_comuna]').change();
  }
};

const createPreview = () => {
  $('input[name=cmdAceptar]').click();
};

const confirm = () => {
  $('input[name=cmdconfirmar]').click();
};

const sendEmail = () => {
  $('#cmdenviar').click();
};

const confirmSendEmail = () => {
  $('#cmdcontinuar').click();
};

const exit = () => {
  $('#cmdsalir').click();
};

const byLastInvoice = (user, work) => {
  return new Promise((resolve, reject) => {
    new Nightmare()
      .viewport(1000, 1000)
      .useragent(userAgent)
      .goto(loginUri)
      .wait()
      .evaluate(sendCredentials, user)
      .wait(1000)
      .goto(boletasUri)
      .evaluate(gotToLast)
      .wait(1000)
      .evaluate(selectLast)
      .wait(1000)
      .evaluate(fillForm, work)
      .wait(1000)
      .evaluate(createPreview)
      .wait(1000)
      .evaluate(confirm)
      .wait(1000)
      .evaluate(sendEmail)
      .wait(1000)
      .evaluate(confirmSendEmail)
      .wait(1000)
      .evaluate(exit)
      .run(err => {
        if (err) return reject(err);
        resolve();
      });
  });
};

const byDestinatary = (user, work, destinatary, zone, commune) => {
  return new Promise((resolve, reject) => {
    new Nightmare()
      .viewport(1000, 1000)
      .useragent(userAgent)
      .goto(loginUri)
      .wait()
      .evaluate(sendCredentials, user)
      .wait(1000)
      .goto(boletasUri)
      .evaluate(gotToDestinatary)
      .wait(1000)
      .evaluate(selectRetention)
      .wait(1000)
      .evaluate(fillForm, work, destinatary, zone, commune)
      .wait(1000)
      .evaluate(createPreview)
      .wait(1000)
      .evaluate(confirm)
      .wait(1000)
      .evaluate(sendEmail)
      .wait(1000)
      .evaluate(confirmSendEmail)
      .wait(1000)
      .evaluate(exit)
      .run(err => {
        if (err) return reject(err);
        resolve();
      });
  });
};

module.exports = {
  byLastInvoice: byLastInvoice,
  byDestinatary: byDestinatary,
  getDestinataryName: getDestinataryName,
  zones: zones
};


text:
require 'jdbc_common'
require 'db/mssql'

class MSSQLSimpleTest < Test::Unit::TestCase
  include SimpleTestMethods
  include ActiveRecord3TestMethods
  include DirtyAttributeTests

  include ExplainSupportTestMethods if ar_version("3.1")

  # MS SQL 2005 doesn't have a DATE class, only TIMESTAMP

  # String comparisons are insensitive by default
  undef_method :test_validates_uniqueness_of_strings_case_sensitive

  # @override
  def test_save_timestamp_with_usec
    timestamp = Time.utc(1942, 11, 30, 01, 53, 59, 123_000)
    e = DbType.create! :sample_timestamp => timestamp
    if ar_version('3.0')
      assert_timestamp_equal timestamp, e.reload.sample_timestamp
    else
      assert_datetime_equal timestamp, e.reload.sample_timestamp # only sec
    end
  end

  # @override
  def test_time_usec_formatting_when_saved_into_string_column
    e = DbType.create!(:sample_string => '', :sample_text => '')
    t = Time.now
    value = Time.local(t.year, t.month, t.day, t.hour, t.min, t.sec, 0)
    if ar_version('4.2')
      str = value.to_s
    elsif ActiveRecord::VERSION::MAJOR >= 3
      # AR-3 adapters override quoted_date which is called always when a
      # Time like value is passed (... as well for string/text columns) :
      str = value.utc.to_s(:db) << '.' << sprintf("%03d", value.usec)
    else # AR-2.x #quoted_date did not do TZ conversions
      str = value.to_s(:db)
    end
    e.sample_string = value
    e.sample_text = value
    e.save!; e.reload
    assert_equal str, e.sample_string
    assert_equal str, e.sample_text
  end

  def test_does_not_munge_quoted_strings
    example_quoted_values = [%{'quoted'}, %{D\'oh!}]
    example_quoted_values.each do |value|
      entry = Entry.create!(:title => value)
      entry.reload
      assert_equal(value, entry.title)
    end
  end

  def test_change_column_default
    Entry.connection.change_column "entries", "title", :string, :default => "new default"
    Entry.reset_column_information
    assert_equal("new default", Entry.new.title)

    Entry.connection.change_column "entries", "title", :string, :default => nil
    Entry.reset_column_information
    assert_equal(nil, Entry.new.title)
  end

  def test_change_column_nullability
    Entry.connection.change_column "entries", "title", :string, :null => true
    Entry.reset_column_information
    title_column = Entry.columns.find { |c| c.name == "title" }
    assert(title_column.null)

    Entry.connection.change_column "entries", "title", :string, :null => false
    Entry.reset_column_information
    title_column = Entry.columns.find { |c| c.name == "title" }
    assert(!title_column.null)
  end

  def test_change_column_without_default_option_should_drop_existing_default
    Entry.reset_column_information
    status_column = Entry.columns.find { |c| c.name == 'status' }
    assert_equal :string, status_column.type
    assert_equal 'unknown', status_column.default

    Entry.connection.change_column :entries, :status, :text

    Entry.reset_column_information
    status_column = Entry.columns.find { |c| c.name == 'status' }
    assert_equal :text, status_column.type
    assert !status_column.default
  end

  def test_change_column_with_default_option_should_set_new_default
    Entry.reset_column_information
    status_column = Entry.columns.find { |c| c.name == 'status' }
    assert_equal :string, status_column.type
    assert_equal 'unknown', status_column.default

    Entry.connection.change_column :entries, :status, :text, :default => 'new'

    Entry.reset_column_information
    status_column = Entry.columns.find { |c| c.name == 'status' }
    assert_equal :text, status_column.type
    assert_equal 'new', status_column.default
  end

  [nil, "NULL", "null", "(null)", "(NULL)"].each_with_index do |v, i|
    define_method "test_null_#{i}" do
      entry = Entry.create!(:title => v, :content => v)
      entry = Entry.find(entry.id)
      assert_equal [v, v], [entry.title, entry.content], "writing #{v.inspect} " +
        "should read back as #{v.inspect} for both string and text columns"
    end
  end

  # ACTIVERECORD_JDBC-124
  def test_model_does_not_have_row_num_column
    User.create! :login => 'row_num'
    model = User.first
    assert_false model.attributes.keys.include?("_row_num")
    assert_false model.respond_to?(:_row_num)
  end

  def test_returns_charset
    assert_not_nil ActiveRecord::Base.connection.charset
  end

  def test_rename_table
    user = User.create! :login => 'luser'
    begin
      ActiveRecord::Base.connection.rename_table 'users', 'lusers'
      lusers = Class.new(ActiveRecord::Base)
      lusers.table_name = 'lusers'
      assert_kind_of ActiveRecord::Base, lusers.find(user.id)
    ensure
      CreateUsers.up rescue nil
      ActiveRecord::Base.connection.execute("DROP TABLE lusers") rescue nil
    end
  end

  def test_remove_column_with_index
    ActiveRecord::Schema.define do
      add_column :entries, 'another_column', :string
      add_index :entries, 'another_column'
    end

    columns = ActiveRecord::Base.connection.columns("entries")
    assert columns.find { |col| col.name == 'another_column' }

    ActiveRecord::Schema.define do
      remove_column "entries", 'another_column'
    end

    columns = ActiveRecord::Base.connection.columns("entries")
    assert ! columns.find { |col| col.name == 'another_column' }
  end

  def test_remove_column_with_constraint
    ActiveRecord::Schema.define do
      add_column :entries, 'another_column', :string
      ActiveRecord::Base.connection.execute "ALTER TABLE entries ADD CONSTRAINT another_column_constraint CHECK (another_column != '!');"
    end

    columns = ActiveRecord::Base.connection.columns("entries")
    assert columns.find { |col| col.name == 'another_column' }

    ActiveRecord::Schema.define do
      remove_column "entries", 'another_column'
    end

    columns = ActiveRecord::Base.connection.columns("entries")
    assert ! columns.find { |col| col.name == 'another_column' }
  end

  # from include DirtyAttributeTests :

#  ActiveRecord::AttributeMethods.class_eval do
#
#    # Filters the primary keys and readonly attributes from the attribute names.
#    def attributes_for_update(attribute_names)
#      result = attribute_names.reject do |name|
#        readonly_attribute?(name)
#      end
#      puts "attributes_for_update(attribute_names) #{attribute_names.inspect}\n result = #{result.inspect}"
#      result
#    end
#
#  end

  def test_partial_update_with_updated_at
    # NOTE: partial updates won't work on MS-SQL :
    #   with_partial_updates User, false do
    #     assert_queries(1) { user.save! }
    #   end
    # ActiveRecord::JDBCError: Cannot update identity column 'id'.: UPDATE [entries] SET [title] = N'foo', [id] = 1, [updated_on] = '2015-09-11 11:11:55.182', [content] = NULL, [status] = N'unknown', [rating] = NULL, [user_id] = NULL WHERE [entries].[id] = 1
    # since ActiveRecord::AttributeMethods#attributes_for_update only checks for
    # readonly_attribute? and not pk_attribute?(name) as well ...
    # other adapters such as MySQL simply accept/ignore similar UPDATE as valid
    #
  end

  def test_partial_update_with_updated_on
  end

  def test_find_by_sql_WITH_statement
    user = User.create! :login => 'ferko'
    Entry.create! :title => 'aaa', :user_id => user.id
    entries = Entry.find_by_sql '' +
      'WITH EntryAndUser (title, login, updated_on) AS ' +
      '(' +
      ' SELECT e.title, u.login, e.updated_on ' +
      ' FROM entries e INNER JOIN users u ON e.user_id = u.id ' +
      ')' +
      ' ' +
      'SELECT * FROM EntryAndUser ORDER BY title ASC'
    assert entries.first
    assert entries.first.title
    assert entries.first.login
  end

  def test_exec
    ActiveRecord::Base.connection.execute "CREATE PROCEDURE usp_allentries AS SELECT * FROM entries"

    assert ActiveRecord::Base.connection.exec_query(" EXEC usp_allentries ")

    # exec_sql = "EXEC sp_msforeachdb 'SELECT count(*) FROM sys.objects'"
    # NOTE: our _execute logic assumes all EXEC statements to do an update :
    # assert_not_empty ActiveRecord::Base.connection.execute(exec_sql) # [ { '' => 42 }]
  ensure
    ActiveRecord::Base.connection.execute "DROP PROCEDURE usp_allentries" rescue nil
  end

  def test_current_user
    # skip if ActiveRecord::Base.connection.send(:sqlserver_2000?)
    assert_equal 'dbo', ActiveRecord::Base.connection.current_user
  end

  def test_default_schema
    # skip if ActiveRecord::Base.connection.send(:sqlserver_2000?)
    assert_equal 'dbo', ActiveRecord::Base.connection.default_schema
  end

  test 'returns correct visitor type' do
    assert_not_nil visitor = connection.instance_variable_get(:@visitor)
    assert defined? Arel::Visitors::SQLServer
    assert_kind_of Arel::Visitors::SQLServer, visitor
  end if ar_version('3.0')

end

class MSSQLHasManyThroughTest < Test::Unit::TestCase
  include HasManyThroughMethods
end


text:
class SpeechTools < Formula
  desc "C++ speech software library from the University of Edinburgh"
  homepage "http://festvox.org/docs/speech_tools-2.4.0/"
  url "http://festvox.org/packed/festival/2.5/speech_tools-2.5.0-release.tar.gz"
  sha256 "e4fd97ed78f14464358d09f36dfe91bc1721b7c0fa6503e04364fb5847805dcc"
  revision 1
  head "https://github.com/festvox/speech_tools.git", branch: "master"

  livecheck do
    url "http://festvox.org/packed/festival/?C=M&O=D"
    regex(%r{href=["']?v?(\d+(?:\.\d+)+)/?["' >]}i)
  end

  bottle do
    rebuild 1
    sha256 cellar: :any,                 big_sur:      "cabb028b487d5baa5c9c1bb67a982a285ab2af2194ac429fb80f0675e2bd9f6e"
    sha256 cellar: :any,                 catalina:     "e25823939149f50f343c2e6bd8521b302067a0eb3106df6b40ff96b2d1a70c21"
    sha256 cellar: :any,                 mojave:       "3ede4e21772a17e0c0a109151406ad82943ba77b0cad2249c0cac51e063d24ea"
    sha256 cellar: :any_skip_relocation, x86_64_linux: "367d922ef74f4977cd3fca29461b4814af733073cbba6cc066d5b85a729daf26"
  end

  depends_on "libomp"

  uses_from_macos "ncurses"

  conflicts_with "align", because: "both install `align` binaries"

  def install
    ENV.deparallelize
    # Xcode doesn't include OpenMP directly any more, but with these
    # flags we can force the compiler to use the libomp we provided
    # as a dependency.  Normally you can force this on autoconf by
    # setting "ac_cv_prog_cxx_openmp" and "LIBS", but this configure
    # script does OpenMP its own way so we need to actually edit the script:
    inreplace "configure", "-fopenmp", "-Xpreprocessor -fopenmp -lomp"
    system "./configure", "--prefix=#{prefix}"
    system "make"
    # install all executable files in "main" directory
    bin.install Dir["main/*"].select { |f| File.file?(f) && File.executable?(f) }
  end

  test do
    rate_hz = 16000
    frequency_hz = 100
    duration_secs = 5
    basename = "sine"
    txtfile = "#{basename}.txt"
    wavfile = "#{basename}.wav"
    ptcfile = "#{basename}.ptc"

    File.open(txtfile, "w") do |f|
      scale = 2 ** 15 - 1
      samples = Array.new(duration_secs * rate_hz) do |i|
        (scale * Math.sin(frequency_hz * 2 * Math::PI * i / rate_hz)).to_i
      end
      f.puts samples
    end

    # convert to wav format using ch_wave
    system bin/"ch_wave", txtfile,
      "-itype", "raw",
      "-istype", "ascii",
      "-f", rate_hz.to_s,
      "-o", wavfile,
      "-otype", "riff"

    # pitch tracking to est format using pda
    system bin/"pda", wavfile,
      "-shift", (1 / frequency_hz.to_f).to_s,
      "-o", ptcfile,
      "-otype", "est"

    # extract one frame from the middle using ch_track, capturing stdout
    value = frequency_hz * duration_secs / 2
    pitch = shell_output("#{bin}/ch_track #{ptcfile} -from #{value} -to #{value}")

    # should be 100 (Hz)
    assert_equal frequency_hz, pitch.to_i
  end
end


text:
[?php if ($field->isPartial()): ?]
  [?php include_partial('<?php echo $this->getModuleName() ?>/'.$name, array('form' => $form, 'attributes' => $attributes instanceof sfOutputEscaper ? $attributes->getRawValue() : $attributes)) ?]
[?php elseif ($field->isComponent()): ?]
  [?php include_component('<?php echo $this->getModuleName() ?>', $name, array('form' => $form, 'attributes' => $attributes instanceof sfOutputEscaper ? $attributes->getRawValue() : $attributes)) ?]
[?php else: ?]

hasError() and print ' errors' ?]">
      [?php echo $form[$name]->renderLabel($label) ?]

      	[?php echo $form[$name]->render($attributes instanceof sfOutputEscaper ? $attributes->getRawValue() : $attributes) ?]

    		[?php echo $form[$name]->renderError() ?]

      [?php if ($help || $help = $form[$name]->renderHelp()): ?]

					[?php echo __($help, array(), '<?php echo $this->getI18nCatalogue() ?>') ?]

      [?php endif; ?]

[?php endif; ?]


text:
class ApplicationController < ActionController::Base

  include Wagn::AuthenticatedSystem
  include Wagn::Location
  include Recaptcha::Verify

  before_filter :per_request_setup, :except=>[:fast_404]
  layout nil

  attr_reader :card
  attr_accessor :recaptcha_count

  def fast_404
    message = "
404 Page Not Found
"
    render :text=>message, :layout=>false, :status=>404
  end

  protected
  def per_request_setup
#    ActiveSupport::Notifications.instrument 'wagn.per_request_setup', :message=>"" do
      request.format = :html if !params[:format] #is this used??

      # these should not be Wagn::Conf, but more like WagnEnv
      Wagn::Conf[:host] = host = request.env['HTTP_HOST']
      Wagn::Conf[:base_url] = request.protocol + host
      Wagn::Conf[:main_name] = nil
      Wagn::Conf[:controller] = self

      Wagn::Cache.renew

      Card::Format.ajax_call = ajax?
      Account.current_id = self.current_account_id || Card::AnonID

      # RECAPTCHA HACKS
      Wagn::Conf[:recaptcha_on] = !Account.logged_in? &&     # this too
        !!( Wagn::Conf[:recaptcha_public_key] && Wagn::Conf[:recaptcha_private_key] )
      @recaptcha_count = 0
  end

  def ajax?
    request.xhr? || params[:simulate_xhr]
  end

  def html?
    [nil, 'html'].member?(params[:format])
  end

  # ----------( rendering methods ) -------------

  def wagn_redirect url
    url = wagn_url url #make sure we have absolute url
    if ajax?
      render :text => url, :status => 303
    else
      redirect_to url
    end
  end

  def render_errors
    view   = card.error_view   || :errors
    status = card.error_status || 422
    show view, status
  end

  def show view = nil, status = 200
    format = request.parameters[:format]
    format = :file if !FORMATS.split('|').member? format #unknown format

    opts = ( params[:slot] || {} ).deep_symbolize_keys
    opts[:view] = view || params[:view]

    formatter = Card::Format.new card, :controller=>self, :format=>format, :inclusion_opts=>opts[:items]
    result = formatter.render_show opts
    status = formatter.error_status || status

    if format==:file && status==200
      send_file *result
    else
      args = { :text=>result, :status=>status }
      args[:content_type] = 'text/text' if format == :file
      render args
    end
  end

  rescue_from Exception do |exception|
    Rails.logger.info "exception = #{exception.class}: #{exception.message}"

    @card ||= Card.new

    view, status = case exception
      ## arguably the view and status should be defined in the error class;
      ## some are redundantly defined in view
      when Wagn::PermissionDenied, Card::PermissionDenied
        [ :denial, 403]
      when Wagn::NotFound, ActiveRecord::RecordNotFound, ActionController::MissingFile
        [ :not_found, 404 ]
      when Wagn::BadAddress
        [ :bad_address, 404 ]
      when Wagn::Oops
        card.errors.add :exception, exception.message
        # Wagn:Oops error messages are visible to end users and are generally not treated as bugs.
        # Probably want to rename accordingly.
        [ :errors, 422]
      else #the following indicate a code problem and therefore require full logging
        Rails.logger.info exception.backtrace*"\n"
        notify_airbrake exception if Airbrake.configuration.api_key

        if ActiveRecord::RecordInvalid === exception
          [ :errors, 422]
        elsif Wagn::Conf[:migration] or Rails.logger.level == 0 # could also just check non-production mode...
          raise exception
        else
          [ :server_error, 500 ]
        end
      end

    show view, status
  end
end


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

namespace NotDivisibleNumbers
{
    class NotDivisibleNumbers
    {
        static void Main()
        {
            int numN = int.Parse(Console.ReadLine());

            Console.Write("1");

            for (int i = 2; i < numN+1; i++)
            {
                if ( i%3 !=0 && i%7 !=0)
                {
                    Console.Write(" {0}", i);
                }
            }
        }
    }
}


text:
import os.path

from .model import Distribution

class ConfigError(Exception):

    def __init__(self, attr_name):
        super(Exception, self).__init__(
            'Missing CodeSignConfig attribute "{}"'.format(attr_name))

class CodeSignConfig(object):
    """Code sign base configuration object.

    A CodeSignConfig contains properties that provide path component information
    to locate products for code signing and options that control the code
    signing process.

    There is a class hierarchy of CodeSignConfig objects, with the
    build_props_config.BuildPropsConfig containing injected variables from the
    build process. Configs for Chromium and Google Chrome subclass that to
    control signing options further. And then derived configurations are
    created for internal signing artifacts and when using |model.Distribution|
    objects.
    """

    def __init__(self,
                 identity,
                 installer_identity=None,
                 notary_user=None,
                 notary_password=None,
                 notary_asc_provider=None):
        """Creates a CodeSignConfig that will sign the product using the static
        properties on the class, using the code signing identity passed to the
        constructor.

        Args:
            identity: The name of the code signing identity to use for non-PKG
                files. This can be any value that `codesign -s <identity>`
                accepts, like the hex-encoded SHA1 hash of the certificate. Must
                not be None.
            installer_identity: The name of the code signing identity to use for
                PKG files. This will be passed as the parameter for the call to
                `productbuild --sign <identity>`. Note that a hex-encoded SHA1
                hash is not a valid option, as it is for |identity| above. The
                common name of the cert will work. If there is any distribution
                that is packaged in a PKG this must not be None.
            notary_user: Optional string username that will be used to
                authenticate to Apple's notary service if notarizing.
            notary_password: Optional string password or password reference
                (e.g. @keychain, see `xcrun altool -h`) that will be used to
                authenticate to Apple's notary service if notarizing.
            notary_asc_provider: Optional string that will be used as the
                `--asc-provider` argument to `xcrun altool`, to be used when
                notary_user is associated with multiple Apple developer teams.
        """
        assert identity
        self._identity = identity
        self._installer_identity = installer_identity
        self._notary_user = notary_user
        self._notary_password = notary_password
        self._notary_asc_provider = notary_asc_provider

    @staticmethod
    def is_chrome_branded():
        """Returns True if the build is an official Google Chrome build and
        should use Chrome-specific resources.

        This is a @staticmethod and not a @property so that it can be tested
        during the process of creating a CodeSignConfig object.
        """
        raise ConfigError('is_chrome_branded')

    @property
    def identity(self):
        """Returns the code signing identity that will be used to sign the
        products, everything but PKG files.
        """
        return self._identity

    @property
    def installer_identity(self):
        """Returns the code signing identity that will be used to sign the
        PKG file products.
        """
        return self._installer_identity

    @property
    def notary_user(self):
        """Returns the username for authenticating to Apple's notary service."""
        return self._notary_user

    @property
    def notary_password(self):
        """Returns the password or password reference for authenticating to
        Apple's notary service.
        """
        return self._notary_password

    @property
    def notary_asc_provider(self):
        """Returns the ASC provider for authenticating to Apple's notary service
        when notary_user is associatetd with multiple Apple developer teams.
        """
        return self._notary_asc_provider

    @property
    def app_product(self):
        """Returns the product name that is used for the outer .app bundle.
        This is displayed to the user in Finder.
        """
        raise ConfigError('app_product')

    @property
    def product(self):
        """Returns the branding product name. This can match |app_product|
        for some release channels. Other release channels may customize
        app_product, but components internal to the app bundle will still
        refer to |product|. This is used to locate the build products from
        the build system, while |app_product| is used when customizing for
        |model.Distribution| objects.
        """
        raise ConfigError('product')

    @property
    def version(self):
        """Returns the version of the application."""
        raise ConfigError('version')

    @property
    def base_bundle_id(self):
        """Returns the base CFBundleIdentifier that is used for the outer app
        bundle, and to which sub-component identifiers are appended.
        """
        raise ConfigError('base_bundle_id')

    @property
    def codesign_requirements_basic(self):
        """Returns the codesign --requirements string that is combined with
        a designated identifier requirement string of a
        |model.CodeSignedProduct|. This requirement is applied to all
        CodeSignedProducts.
        """
        return ''

    @property
    def codesign_requirements_outer_app(self):
        """Returns the codesign --requirements string for the outer app bundle.
        This is used in conjunction with |codesign_requirements_basic|."""
        return ''

    @property
    def provisioning_profile_basename(self):
        """Returns the basename of the provisioning profile used to sign the
        outer app bundle. This file with a .provisionprofile extension is
        located in the |packaging_dir|.
        """
        raise ConfigError('provisioning_profile_basename')

    @property
    def packaging_basename(self):
        """Returns the file basename of the packaged output files."""
        return '{}-{}'.format(self.app_product.replace(' ', ''), self.version)

    @property
    def distributions(self):
        """Returns a list of |model.Distribution| objects that customize the
        results of signing. This must contain at least one Distribution, which
        can be a default Distribution.
        """
        return [Distribution()]

    @property
    def run_spctl_assess(self):
        """Returns whether the final code signed binary should be assessed by
        Gatekeeper after signing.
        """
        return True

    @property
    def inject_get_task_allow_entitlement(self):
        """Returns whether the com.apple.security.get-task-allow entitlement
        should be added to all entitlement files. This will permit attaching a
        debugger to a signed process, if the binary was signed with the
        hardened runtime.
        """
        return False

    # Computed Properties ######################################################

    @property
    def app_dir(self):
        """Returns the path to the outer app bundle directory."""
        return '{.app_product}.app'.format(self)

    @property
    def resources_dir(self):
        """Returns the path to the outer app's Resources directory."""
        return os.path.join(self.app_dir, 'Contents', 'Resources')

    @property
    def framework_dir(self):
        """Returns the path to the app's framework directory."""
        return '{0.app_dir}/Contents/Frameworks/{0.product} Framework.framework'.format(
            self)

    @property
    def packaging_dir(self):
        """Returns the path to the packaging and installer tools."""
        return '{.product}_Packaging'.format(self)


text:
package guiced.package1.package2.package3.package4;

import guiced.services.GuicedService1;

public class Class5 {
  @com.google.inject.Inject
  private GuicedService1 guicedService1;

  public Class5() {
    //  stuff goes here
  }
  // lots of methods here
}


text:
class ParticipantDecorator < ApplicationDecorator
  delegate_all
end


text:
import { test } from 'qunit';

test( 'has access to options', t => {
	const View = Ractive.extend({
		onconstruct ( options ){
			options.template = '{{foo}}';
			options.data = { foo: 'bar' };
		}
	});

	new View({
		el: fixture
	});

	t.equal( fixture.innerHTML, 'bar' );
});