text:
"""Component for monitoring activity on a folder."""
import logging
import os

import voluptuous as vol

from homeassistant.const import EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

CONF_FOLDER = "folder"
CONF_PATTERNS = "patterns"
DEFAULT_PATTERN = "*"
DOMAIN = "folder_watcher"

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN: vol.All(
            cv.ensure_list,
            [
                vol.Schema(
                    {
                        vol.Required(CONF_FOLDER): cv.isdir,
                        vol.Optional(CONF_PATTERNS, default=[DEFAULT_PATTERN]): vol.All(
                            cv.ensure_list, [cv.string]
                        ),
                    }
                )
            ],
        )
    },
    extra=vol.ALLOW_EXTRA,
)

def setup(hass, config):
    """Set up the folder watcher."""
    conf = config[DOMAIN]
    for watcher in conf:
        path = watcher[CONF_FOLDER]
        patterns = watcher[CONF_PATTERNS]
        if not hass.config.is_allowed_path(path):
            _LOGGER.error("folder %s is not valid or allowed", path)
            return False
        Watcher(path, patterns, hass)

    return True

def create_event_handler(patterns, hass):
    """Return the Watchdog EventHandler object."""
    from watchdog.events import PatternMatchingEventHandler

    class EventHandler(PatternMatchingEventHandler):
        """Class for handling Watcher events."""

        def __init__(self, patterns, hass):
            """Initialise the EventHandler."""
            super().__init__(patterns)
            self.hass = hass

        def process(self, event):
            """On Watcher event, fire HA event."""
            _LOGGER.debug("process(%s)", event)
            if not event.is_directory:
                folder, file_name = os.path.split(event.src_path)
                self.hass.bus.fire(
                    DOMAIN,
                    {
                        "event_type": event.event_type,
                        "path": event.src_path,
                        "file": file_name,
                        "folder": folder,
                    },
                )

        def on_modified(self, event):
            """File modified."""
            self.process(event)

        def on_moved(self, event):
            """File moved."""
            self.process(event)

        def on_created(self, event):
            """File created."""
            self.process(event)

        def on_deleted(self, event):
            """File deleted."""
            self.process(event)

    return EventHandler(patterns, hass)

class Watcher:
    """Class for starting Watchdog."""

    def __init__(self, path, patterns, hass):
        """Initialise the watchdog observer."""
        from watchdog.observers import Observer

        self._observer = Observer()
        self._observer.schedule(
            create_event_handler(patterns, hass), path, recursive=True
        )
        hass.bus.listen_once(EVENT_HOMEASSISTANT_START, self.startup)
        hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, self.shutdown)

    def startup(self, event):
        """Start the watcher."""
        self._observer.start()

    def shutdown(self, event):
        """Shutdown the watcher."""
        self._observer.stop()
        self._observer.join()

redpajama_set_name: RedPajamaGithub


text:
package com.chequer.axboot.core.model.extract.template;

public class TemplateKeys {

	public static final String IMPORT_PACKAGES = "importPackages";

	public static final String ANNOTATIONS = "annotations";

	public static final String TARGET_PACKAGE_NAME = "targetPackageName";

	public static final String CONTROLLER_PACKAGE_NAME = "controllerPackageName";

	public static final String BASE_PACKAGE_NAME = "packageName";

	public static final String DOMAIN_PACKAGE_NAME = "domainPackageName";

	public static final String ENTITY_FIELDS = "entityFields";

	public static final String COLUMNS = "columns";

	public static final String SELECT_COLUMNS = "selectColumns";

	public static final String VALUES = "values";

	public static final String ID_WHERE = "idWhere";

	public static final String SET_COLUMNS = "setColumns";

	public static final String ENTITY_CLASS_NAME = "entityClassName";

	public static final String ENTITY_CLASS_FIELD_NAME = "entityClassFieldName";

	public static final String SERVICE_CLASS_NAME = "serviceClassName";

	public static final String SERVICE_CLASS_FIELD_NAME = "serviceClassFieldName";

	public static final String REPOSITORY_CLASS_NAME = "repositoryClassName";

	public static final String REPOSITORY_CLASS_FIELD_NAME = "repositoryClassFieldName";

	public static final String TABLE_NAME = "tableName";

	public static final String TABLE_COMMENT = "tableComment";

	public static final String KEY_FIELDS = "keyFields";

	public static final String KEY_CLASS_NAME = "keyClassName";

	public static final String KEY_CLASS_REF_NAME = "keyClassRefName";

	public static final String RETURN_KEY_NAME = "returnKeyName";

	public static final String VO_FIELDS = "voFields";

	public static final String VO_CLASS_NAME = "voClassName";

	public static final String VO_CLASS_FIELD_NAME = "voClassFieldName";

	public static final String API_PATH = "apiPath";

	public static final String CONTROLLER_CLASS_NAME = "controllerClassName";

	public static final String MYBATIS_CLASS_NAME = "mybatisClassName";

	public static final String MYBATIS_CLASS_FIELD_NAME = "mybatisClassFieldName";
}


text:
/*
 *
 * Test file encode/decode operations via write/read/write/read
 * sequence to detect any data corruption problems.  This does not
 * verify that the image is correct, only that encode/decode process
 * is repeatable.
 *
 * Written by Bob Friesenhahn <bfriesen@simple.dallas.tx.us>
 *
 * The image returned by both reads must be identical (or deemed close
 * enough) in order for the test to pass.
 * */

#if !defined(_VISUALC_)
#include <magick/magick-config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#if defined(_VISUALC_)
#include <stdlib.h>
#include <sys\types.h>
#endif
#include <time.h>
#include <magick/MagickCore.h>

int main ( int argc, char **argv )
{
  Image
    *final = (Image *) NULL,
    *original = (Image *) NULL;

  const MagickInfo
    *magick_info;

  char
    filename[80],
    format[MaxTextExtent],
    infile[MaxTextExtent],
    size[MaxTextExtent];

  int
    arg = 1,
    exit_status = 0,
    rows = 0,
    columns = 0,
    pause = 0;

  double
    fuzz_factor = 0;

  ImageInfo
    *imageInfo;

  ExceptionInfo
    exception;

  if (LocaleNCompare("rwfile",argv[0],7) == 0)
    MagickCoreGenesis((char *) NULL,MagickTrue);
  else
    MagickCoreGenesis(*argv,MagickTrue);

  imageInfo=CloneImageInfo(0);
  GetExceptionInfo( &exception );

  for (arg=1; arg < argc; arg++)
    {
      char
        *option = argv[arg];

      if (*option == '-')
        {
          if (LocaleCompare("compress",option+1) == 0)
            {
              arg++;
              option=argv[arg];
              imageInfo->compression=UndefinedCompression;
              if (LocaleCompare("None",option) == 0)
                imageInfo->compression=NoCompression;
              if (LocaleCompare("BZip",option) == 0)
                imageInfo->compression=BZipCompression;
              if (LocaleCompare("Fax",option) == 0)
                imageInfo->compression=FaxCompression;
              if (LocaleCompare("Group4",option) == 0)
                imageInfo->compression=Group4Compression;
              if (LocaleCompare("JPEG",option) == 0)
                imageInfo->compression=JPEGCompression;
              if (LocaleCompare("Lossless",option) == 0)
                imageInfo->compression=LosslessJPEGCompression;
              if (LocaleCompare("LZW",option) == 0)
                imageInfo->compression=LZWCompression;
              if (LocaleCompare("RLE",option) == 0)
                imageInfo->compression=RLECompression;
              if (LocaleCompare("Zip",option) == 0)
                imageInfo->compression=ZipCompression;
            }
          else if (LocaleCompare("debug",option+1) == 0)
              (void) SetLogEventMask(argv[++arg]);
          else if (LocaleCompare("depth",option+1) == 0)
            {
              imageInfo->depth=QuantumDepth;
              arg++;
              if ((arg == argc) || !sscanf(argv[arg],"%ld",&imageInfo->depth))
                {
                  (void) printf("-depth argument missing or not integer\n");
                  (void) fflush(stdout);
                  exit_status = 1;
                  goto program_exit;
                }
if (0)
              if(imageInfo->depth != 8 && imageInfo->depth != 16 && imageInfo->depth != 32)
                {
                  (void) printf("-depth (%ld) not 8, 16, or 32\n", imageInfo->depth);
                  (void) fflush(stdout);
                  exit_status = 1;
                  goto program_exit;
                }
            }
          else if (LocaleCompare("log",option+1) == 0)
              (void) SetLogFormat(argv[++arg]);
          else if (LocaleCompare("pause",option+1) == 0)
              pause=1;
          else if (LocaleCompare("size",option+1) == 0)
            {
              arg++;
              if ((arg == argc) || !IsGeometry(argv[arg]))
                {
                  (void) printf("-size argument missing or not geometry\n");
                  (void) fflush(stdout);
                  exit_status = 1;
                  goto program_exit;
                }
              (void) CloneString(&imageInfo->size,argv[arg]);
            }
          else if (LocaleCompare("verbose",option+1) == 0)
            {
              imageInfo->verbose+=1;
            }
        }
      else
        break;
    }
  if (arg != argc-2)
    {
      (void) printf("arg=%d, argc=%d\n", arg, argc);
      (void) printf ( "Usage: %s [-compress algorithm -debug events -depth integer -log format -size geometry -verbose] infile format\n", argv[0] );
      (void) fflush(stdout);
      exit_status = 1;
      goto program_exit;
    }

  (void) strncpy(infile, argv[arg], MaxTextExtent-1 );
  arg++;
  (void) strncpy( format, argv[arg], MaxTextExtent-1 );

  for (arg=0; arg < argc; arg++)
    (void) printf("%s ", argv[arg]);
  (void) printf("\n");
  (void) fflush(stdout);

  /*
   * Read original image
   */

  imageInfo->dither = 0;
  (void) strncpy( imageInfo->filename, infile, MaxTextExtent-1 );
  (void) fflush(stdout);
  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
    "Reading image %s", imageInfo->filename);
  original = ReadImage ( imageInfo, &exception );
  if (exception.severity >= ErrorException)
    {
      CatchException(&exception);
      exit_status = 1;
      goto program_exit;
    }
  if ( original == (Image *)NULL )
    {
      (void) printf ( "Failed to read original image %s\n", imageInfo->filename );
      (void) fflush(stdout);
      exit_status = 1;
      goto program_exit;
    }

  /*
   * Obtain original image size if format requires it
   */
  rows    = original->rows;
  columns = original->columns;
  size[0] = '\0';
  magick_info=GetMagickInfo(format,&exception);
  if (magick_info && magick_info->raw)
    FormatMagickString( size, MaxTextExtent, "%dx%d", columns, rows );

  /*
   * Save image to file
   */
  (void) sprintf( filename, "out_1.%s", format );
  (void) strncpy( original->magick, format, MaxTextExtent-1 );
  (void) strncpy( original->filename, filename, MaxTextExtent-1 );
  original->delay = 10;
  (void) fflush(stdout);
  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
    "Writing image %s", original->filename);
  WriteImage ( imageInfo, original );
  imageInfo->depth=original->depth;
   original =DestroyImage( original );
  original = (Image*)NULL;

  /*
   * Read image back from file
   */
  (void) strncpy( imageInfo->magick, format, MaxTextExtent-1 );
  (void) strncpy( imageInfo->filename, filename, MaxTextExtent-1 );
  if ( size[0] != '\0' )
    CloneString( &imageInfo->size, size );
  (void) fflush(stdout);
  original = ReadImage ( imageInfo, &exception );
  if (exception.severity >= ErrorException)
    {
      CatchException(&exception);
      exit_status = 1;
      goto program_exit;
    }
  if ( original == (Image *)NULL )
    {
      (void) printf ( "Failed to read image from file in format %s\n",
               imageInfo->magick );
      (void) fflush(stdout);
      exit_status = 1;
      goto program_exit;
    }

  /*
   * Save image to file
   */
  (void) sprintf( filename, "out_2.%s", format );
  (void) strncpy( original->magick, format, MaxTextExtent-1 );
  (void) strncpy( original->filename, filename, MaxTextExtent-1 );
  original->delay = 10;
  (void) fflush(stdout);
  WriteImage ( imageInfo, original );

  /*
   * Read image back from file
   */
  (void) strncpy( imageInfo->magick, format, MaxTextExtent-1 );
  (void) strncpy( imageInfo->filename, filename, MaxTextExtent-1 );
  if ( size[0] != '\0' )
    CloneString( &imageInfo->size, size );
  (void) fflush(stdout);
  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
    "Reading image %s", imageInfo->filename);
  final = ReadImage ( imageInfo, &exception );
  if (exception.severity >= ErrorException)
    {
      CatchException(&exception);
      exit_status = 1;
      goto program_exit;
    }
  if ( final == (Image *)NULL )
    {
      (void) printf ( "Failed to read image from file in format %s\n",
               imageInfo->magick );
      (void) fflush(stdout);
      exit_status = 1;
      goto program_exit;
    }

  /*
   * Check final output
   */

  fuzz_factor = 0.0;
#if defined(UseHDRI)
  fuzz_factor = 0.06;
#endif
  if ( !strcmp( "JPEG", format ) ||
       !strcmp( "JNG", format ) ||
       !strcmp( "JPG", format ) ||
       !strcmp( "JPG24", format ) ||
       !strcmp( "JP2", format ) ||
       !strcmp( "PAL", format ) ||
       !strcmp( "GRAY", format ) ||
       !strcmp( "CMYK", format ) ||
       !strcmp( "PCD", format ) ||
       !strcmp( "PCDS", format ) ||
       !strcmp( "PGM", format ) ||
       !strcmp( "PPM", format ) ||
       !strcmp( "PNM", format ) ||
       !strcmp( "SGI", format ) ||
       !strcmp( "XPM", format ) ||
       !strcmp( "UYVY", format ) ||
       !strcmp( "YUV", format ) || (final->compression == JPEGCompression))
    fuzz_factor = 0.06;

  SetImageColorspace(final,original->colorspace);
  if ( !IsImagesEqual(original, final ) &&
       (original->error.normalized_mean_error > fuzz_factor) )
    {
      (void) printf( "R/W file check for format \"%s\" failed: %u/%.6f/%.6fe\n",
              format,(unsigned int) original->error.mean_error_per_pixel,
              original->error.normalized_mean_error,
              original->error.normalized_maximum_error);
      (void) fflush(stdout);
      exit_status = 1;
      goto program_exit;
    }

 program_exit:
  if (original)
     original =DestroyImage( original );
  original = (Image*)NULL;
  if (final)
     final =DestroyImage( final );
  final = (Image*)NULL;

  imageInfo =DestroyImageInfo( imageInfo );
  DestroyExceptionInfo( &exception );
  MagickCoreTerminus();

  if (pause)
    (void) getc(stdin);
  return exit_status;
}


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

namespace WebJs_NancyOwin_ConsoleWebHost.Mapping.loadingFailed
{

	public class Rootobject
	{
		public string _index { get; set; }
		public string _type { get; set; }
		public string _id { get; set; }
		public int _score { get; set; }
		public _Source _source { get; set; }
	}

	public class _Source
	{
		public string type { get; set; }
		public Info info { get; set; }
	}

	public class Info
	{
		public string type { get; set; }
		public string key { get; set; }
		public Text text { get; set; }
	}

	public class Text
	{
		public int id { get; set; }
		public Result result { get; set; }
	}

	public class Result
	{
		public string subject { get; set; }
		public string message { get; set; }
		public Data data { get; set; }
	}

	public class Data
	{
		public bool canceled { get; set; }
		public string errorText { get; set; }
		public string requestId { get; set; }
		[JsonProperty(PropertyName = "timestamp")]
		[JsonConverter(typeof(UnixDateTimeConverter))]
		public DateTime timestamp { get; set; }
		public string type { get; set; }
	}

}


text:
<?php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

use Zend\Form\Element;
use Zend\Stdlib\Hydrator;

class PageController extends AbstractActionController
{

    protected $em;
    public function getEntityManager()
    {
        if (null === $this->em) {
            $this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
        }
        return $this->em;
    }

    public function viewAction()
    {
        $id = (int)$this->getEvent()->getRouteMatch()->getParam('id');
        if (!$id) {
            return $this->redirect()->toRoute('home');
        }
        try{
            $page = $this->getEntityManager()->find('Cms\Entity\Page', $id);
        }
        catch(\Exception $e){
            $response   = $this->response;
            $event	  = $this->getEvent();
            $routeMatch = $event->getRouteMatch();
            $response->setStatusCode(404);
            $event->setParam('exception', new \Exception('Page Inconnue'.$id));
            $event->setController('page');
            return ;
        }

//        $dql ="SELECT p FROM Cms\Entity\Page p WHERE p.category = ".$id;
//        $query = $this->getEntityManager()->createQuery($dql);
//        $pages = $query->getResult();

        $menus = [];
        $articles = [];
        $stuctureElements = json_decode($page->block_element);
        if($stuctureElements) {
            foreach($stuctureElements as $structureElt) {
                switch($structureElt->element_type) {
                    case 'menu':
                        $menu = $this->getEntityManager()->find('Cms\Entity\Menu', $structureElt->element_id);
                        $menus[] = $menu;
                        break;
                    case 'article':
                        $article = $this->getEntityManager()->find('Cms\Entity\Article', $structureElt->element_id);
                        $articles[] = $article;
                        break;
                }
            }
        }

        return new ViewModel(array(
            'page' => $page,
            'menus' => $menus,
            'articles' => $articles,
        ));
    }
}


text:
//====================================================================================
//
// Purpose: Provide abstraction into setting a destination position in the scene
// As this is an abstract class, it should never be used on it's own.
//
// Events Emitted:
//
// DestinationMarkerEnter - is emitted when an object is collided with
// DestinationMarkerExit - is emitted when the object is no longer collided
// DestinationMarkerSet - is emmited when the destination is set
//
// Event Payload:
//
// distance - The distance between the origin and the collided destination
// target - The Transform of the destination object
// destiationPosition - The world position of the destination marker
// enableTeleport - Determine if the DestinationSet event should allow teleporting
// controllerIndex - The optional index of the controller the pointer is attached to
//
//====================================================================================
namespace VRTK
{
    using UnityEngine;

    public struct DestinationMarkerEventArgs
    {
        public float distance;
        public Transform target;
        public Vector3 destinationPosition;
        public bool enableTeleport;
        public uint controllerIndex;
    }

    public delegate void DestinationMarkerEventHandler(object sender, DestinationMarkerEventArgs e);

    public abstract class VRTK_DestinationMarker : MonoBehaviour
    {
        public bool enableTeleport = true;

        public event DestinationMarkerEventHandler DestinationMarkerEnter;
        public event DestinationMarkerEventHandler DestinationMarkerExit;
        public event DestinationMarkerEventHandler DestinationMarkerSet;

        protected string invalidTargetWithTagOrClass;
        protected float navMeshCheckDistance;
        protected bool headsetPositionCompensation;

        public virtual void OnDestinationMarkerEnter(DestinationMarkerEventArgs e)
        {
            if (DestinationMarkerEnter != null)
            {
                DestinationMarkerEnter(this, e);
            }
        }

        public virtual void OnDestinationMarkerExit(DestinationMarkerEventArgs e)
        {
            if (DestinationMarkerExit != null)
            {
                DestinationMarkerExit(this, e);
            }
        }

        public virtual void OnDestinationMarkerSet(DestinationMarkerEventArgs e)
        {
            if (DestinationMarkerSet != null)
            {
                DestinationMarkerSet(this, e);
            }
        }

        public virtual void SetInvalidTarget(string name)
        {
            invalidTargetWithTagOrClass = name;
        }

        public virtual void SetNavMeshCheckDistance(float distance)
        {
            navMeshCheckDistance = distance;
        }

        public virtual void SetHeadsetPositionCompensation(bool state)
        {
            headsetPositionCompensation = state;
        }

        protected DestinationMarkerEventArgs SetDestinationMarkerEvent(float distance, Transform target, Vector3 position, uint controllerIndex)
        {
            DestinationMarkerEventArgs e;
            e.controllerIndex = controllerIndex;
            e.distance = distance;
            e.target = target;
            e.destinationPosition = position;
            e.enableTeleport = enableTeleport;
            return e;
        }
    }
}


text:
function [ EA ] = generateEnrichedEventsList( EA,HA )

EA.sigEventNameArray = cell(size(EA.uniqueSignatureArray,1),1);

% 1. Construire une matrice de caractère pour chaque évènement de signature
symptom = cell(size(EA.uniqueSignatureArray));
for iEvent = 1:size(EA.uniqueSignatureArray,1)
    for jSymptom =1:EA.signatureSize
        if EA.uniqueSignatureArray(iEvent,jSymptom) == 1
            symptom(iEvent,jSymptom) = {'+'};
        elseif EA.uniqueSignatureArray(iEvent,jSymptom) == 0
            symptom(iEvent,jSymptom) = {'.'};
        elseif EA.uniqueSignatureArray(iEvent,jSymptom) == -1
             symptom(iEvent,jSymptom) = {'-'};
        else
            symptom(iEvent,jSymptom) = {'*'};
        end
    end
end

% 2. Construire la notation en concaténant les séries de caractères
for iEvent = 1:size(EA.uniqueSignatureArray,1)
    name = 'R';
    for jSymptom =1:EA.signatureSize
        name = strcat(name,symptom(iEvent,jSymptom));
    end
    EA.sigEventNameArray(iEvent,1) = {name};
end

% 3. Evenements de signature observables
for iEvent = (HA.eventsNo+1):(EA.eventsNo-1)
    iSig = iEvent - HA.eventsNo;
    EA.events(iEvent).id = iEvent;
    EA.events(iEvent).name = char(EA.sigEventNameArray{iSig,1});
    EA.events(iEvent).obs = 1;
    EA.events(iEvent).fault = 0;
end

% 4. Evenement de signature non observable
EA.events(EA.eventsNo).id = EA.eventsNo;
EA.events(EA.eventsNo).name = 'Runobs';
EA.events(EA.eventsNo).obs = 0;
EA.events(EA.eventsNo).fault = 0;

end


text:
module TagsHelper
  REGEXS = [[Supertag::Usertag::USERTAG_REGEX, :usertag_path],
            [Supertag::Hashtag::HASHTAG_REGEX, :hashtag_path],
            [Supertag::Moneytag::MONEYTAG_REGEX, :moneytag_path]]

  def linkify_tags(taggable_content)
    text = taggable_content.to_s

    REGEXS.each do |regex, path|
      text = text.gsub(regex) {link_to($&, send(path, $2), class: 'tag')}
    end

    text.html_safe
  end

  def render_hashtaggable(hashtaggable)
    klass        = hashtaggable.class.to_s.underscore
    view_dirname = klass.pluralize
    partial      = klass
    render "#{view_dirname}/#{partial}", {klass.to_sym => hashtaggable}
  end

  def render_usertaggable(usertaggable)
    klass        = usertaggable.class.to_s.underscore
    view_dirname = klass.pluralize
    partial      = klass
    render "#{view_dirname}/#{partial}", {klass.to_sym => usertaggable}
  end

  def render_moneytaggable(moneytaggable)
    klass        = moneytaggable.class.to_s.underscore
    view_dirname = klass.pluralize
    partial      = klass
    render "#{view_dirname}/#{partial}", {klass.to_sym => moneytaggable}
  end
end


text:
package haproxy

type PluginConfig struct {
	ProxyConfigPath             string `json:"proxy_config_path,omitempty"`
	ProxyBackendOverrideAddress string `json:"proxy_backend_override_address,omitempty"`
	ConnectTimeout              int    `json:"connect_timeout,omitempty"`
	ServerTimeout               int    `json:"server_timeout,omitempty"`
	ClientTimeout               int    `json:"client_timeout,omitempty"`
	MaxConn                     int    `json:"max_conn,omitempty"`
	Port                        int    `json:"port,omitempty"`
	PidPath                     string `json:"pid_path,omitempty"`
	SyslogAddr                  string `json:"syslog_addr,omitempty"`
	StatsUser                   string `json:"stats_user,omitempty"`
	StatsPassword               string `json:"stats_password,omitempty"`
	SSLCert                     string `json:"ssl_cert,omitempty"`
	SSLPort                     int    `json:"ssl_port,omitempty"`
	SSLOpts                     string `json:"ssl_opts,omitempty"`
	DefaultBackend              string `json:"default_backend,omitempty"`
}


text:
from __future__ import absolute_import
import re
import os
import time

from datetime import datetime
from .error import ClientCertError
from . import utils

class ClientCert(object):
    __slots__ = ['filename', 'first_commonname', 'startdate', 'enddate']

    def __init__(self, filename):
        self.filename = str(filename)

        if not os.path.exists(self.filename):
            raise ClientCertError(self.filename, "file not found")

        self.startdate = None
        self.enddate = None
        self.first_commonname = None
        self.do_openssl_lookup()
        self.assert_not_expired()

    def do_openssl_lookup(self):
        cmd = ["openssl", "x509",
                    "-in", self.filename,
                    "-noout",
                    "-subject", "-nameopt", "multiline",
                    "-dates"]
        output = utils.checked_backtick(cmd)

        self.startdate, self.enddate = self.extract_dates(output)
        self.first_commonname = self.extract_first_commonname(output)

    @staticmethod
    def _parse_date(datestr):
        # Want to match something like "Nov 15 09:49:34 2013 GMT"
        # datetime.strptime is not in Python 2.4, but the 2.6 manual has this
        # equivalent:
        return datetime(*(time.strptime(datestr, "%b %d %H:%M:%S %Y %Z")[0:6]))

    def extract_dates(self, output):
        startdate_match = re.search(r"""(?xms)
                ^ notBefore=([^\n]+) $""", output)
        enddate_match = re.search(r"""(?xms)
                ^ notAfter=([^\n]+) $""", output)
        try:
            startdate = self._parse_date(startdate_match.group(1))
            enddate = self._parse_date(enddate_match.group(1))
        except (ValueError, AttributeError) as err:
            raise ClientCertError(
                self.filename,
                "cannot determine valid dates from openssl output"
                    "\n%s\n"
                    "Error was: %s" % (output, str(err)))

        return startdate, enddate

    def extract_first_commonname(self, output):
        # Get the first commonName using the negative lookbehind assertion to make
        # sure we're capturing the right commonName if there are multiple.
        # Note that the commonName is indented since we're using multiline
        # output format.
        cn_match = re.search(r"""(?xms)
            (?!<commonName)
            ^ \s* commonName \s* = \s* ([^\n]+) $""", output)
        if not cn_match:
            raise ClientCertError(
                self.filename,
                "cannot determine commonName from openssl output\n%s\n" % output)
        return cn_match.group(1)

    def assert_not_expired(self):
        if datetime.utcnow() > self.enddate:
            raise ClientCertError(self.filename, "cert expired")
        elif datetime.utcnow() < self.startdate:
            raise ClientCertError(self.filename, "cert not valid yet")


text:
package org.jetbrains.plugins.scala.lang.resolve;

import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import org.jetbrains.plugins.scala.lang.psi.api.statements.ScTypeAlias;
import org.jetbrains.plugins.scala.lang.psi.api.statements.ScFunctionDefinition;
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.ScTypeDefinition;
import org.jetbrains.plugins.scala.util.TestUtils;

public class ImplicitParametersResolveTest extends ScalaResolveTestCase {

  public String folderPath() {
    return super.folderPath() + "resolve/implicitParameter";
  }

  public void testlocalValAsImplicitParam() throws Exception {
    PsiReference ref = findReferenceAtCaret();
    assertTrue(ref.resolve() instanceof ScFunctionDefinition);
  }
}


text:
#include "tensorflow/compiler/mlir/lite/tf_tfl_passes.h"

#include "mlir/IR/Attributes.h"  // TF:local_config_mlir
#include "mlir/IR/Module.h"  // TF:local_config_mlir
#include "mlir/Pass/Pass.h"  // TF:local_config_mlir
#include "mlir/Transforms/Passes.h"  // TF:local_config_mlir
#include "tensorflow/compiler/mlir/lite/quantization/quantization_passes.h"
#include "tensorflow/compiler/mlir/lite/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/decode_constant.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/tf_mlir_translate.h"

namespace mlir {
/// Create a pass to convert from the TFExecutor to the TF control dialect.
std::unique_ptr<OpPassBase<FuncOp>>
CreateTFExecutorToControlDialectConversion();
}  // namespace mlir

namespace tensorflow {

void AddTFToTFLConversionPasses(const mlir::TFL::PassConfig& pass_config,
                                mlir::PassManager* pass_manager) {
  pass_manager->addPass(mlir::tf_executor::CreateSwitchFoldPass());
  pass_manager->addPass(mlir::CreateTFExecutorToControlDialectConversion());
  if (!pass_config.quant_specs.serialized_quant_stats.empty()) {
    pass_manager->addPass(
        mlir::quant::CreateImportQuantStatsPassForTFControlDialect(
            pass_config.quant_specs.serialized_quant_stats));
  }
  pass_manager->addPass(mlir::TFControlFlow::CreateRaiseTFControlFlowPass());
  if (pass_config.lower_tensor_list_ops) {
    // Execute this pass before `CanonicalizerPass` in case some TensorList
    // ops are constant folded into variant types.
    // TODO(b/137125056): Move this pass after `CanonicalizerPass` after we
    // handle constant ops that produce `TensorList`.
    // TODO(haoliang): Add this pass by default.
    pass_manager->addPass(mlir::TFL::CreateLowerStaticTensorListPass());
  }

  // The ophint extractions happen before lots of other passes:
  // The assumption of ophint-extraction is each ophinted region is a black-box
  // and nodes within this black-box is NOT connected to the nodes OUTSIDE the
  // black-box.
  // Some passes may merge nodes together (such as const nodes), however, this
  // will break the ophint-extraction assumption. (The nodes within the black
  // box is not isolated anymore).
  // So ophint extraction and legalization needs to happen before
  // the canonicalization pass.
  if (pass_config.emit_builtin_tflite_ops) {
    pass_manager->addPass(mlir::TFL::CreateExtractOphintPass());
    // Convert composite op pass will happen after ophint extraction pass.
    pass_manager->addPass(mlir::TFL::CreateLegalizeOphintFuncOpPass());
  }

  // TODO(jpienaar): Revise post dialect constants.
  pass_manager->addPass(mlir::TF::CreateDecodeConstantPass());
  // Canonicalization includes const folding, which is utilized here to optimize
  // away ops that can't get constant folded after PrepareTF pass. For example,
  // tf.Conv2D is split into tf.Transpose and tfl.Conv2D.
  pass_manager->addPass(mlir::createCanonicalizerPass());

  // The below passes only make sense if Builtin TFLite ops are enabled
  // for emission.
  if (pass_config.emit_builtin_tflite_ops) {
    // Prepare for TFLite dialect, rerun canonicalization, and then legalize to
    // the TFLite dialect.
    pass_manager->addPass(mlir::TFL::CreatePrepareTFPass());
    pass_manager->addPass(mlir::createCanonicalizerPass());
    pass_manager->addPass(mlir::TFL::CreateLegalizeTFPass());
    pass_manager->addPass(mlir::TFL::CreateOptimizePass());
    if (pass_config.quant_specs.RunPropagationAndRewriteQuantizationPasses()) {
      pass_manager->addPass(
          mlir::TFL::CreatePrepareQuantizePass(pass_config.quant_specs));
      pass_manager->addPass(mlir::TFL::CreateQuantizePass());
      pass_manager->addPass(mlir::TFL::CreatePostQuantizePass(
          pass_config.emit_quant_adaptor_ops));
    }
    pass_manager->addPass(mlir::createCanonicalizerPass());
    pass_manager->addPass(mlir::createCSEPass());
    // This pass should be always at the end. Some TFL ops like unidirectional
    // sequence lstm will have stateful operands and some optimization passes
    // will merge those operands if they have identical values & types. However,
    // it's not desired by TFL. This pass serves as a "fix" pass to split the
    // merged inputs until we have 1st class variable support or reuse
    // tf.ariable to model this.
    pass_manager->addPass(mlir::TFL::CreateSplitMergedOperandsPass());
  }
}

}  // namespace tensorflow


text:
const { Collection } = require('discord.js');

const games = new Map();

const roulette = {
    red: [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36],
    black: [2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35]
};

const spaces = new Collection([
    ['numbers', { values: roulette.red.concat(roulette.black).concat([0]).map(item => item.toString()), multiplier: 36 }], // eslint-disable-line max-len
    ['dozens', { values: ['1-12', '13-24', '25-36'], multiplier: 3 }],
    ['columns', { values: ['1st', '2nd', '3rd'], multiplier: 3 }],
    ['halves', { values: ['1-18', '19-36'], multiplier: 2 }],
    ['parity', { values: ['even', 'odd'], multiplier: 2 }],
    ['colors', { values: ['red', 'black'], multiplier: 2 }]
]);

class Roulette {
    constructor(guildID) {
        this.guildID = guildID;
        this.players = [];
        this.winSpaces = Roulette._generateSpaces();

        games.set(this.guildID, this);
    }

    join(user, donuts, space) {
        const multiplier = this.winSpaces.includes(space)
            ? spaces.find(spc => spc.values.includes(space)).multiplier
            : 0;
        this.players.push({
            user: user,
            winnings: donuts * multiplier
        });

        games.set(this.guildID, this);
    }

    hasPlayer(userID) {
        return !!this.players.find(player => player.user.id === userID);
    }

    awaitPlayers(time) {
        return new Promise(resolve => {
            setTimeout(() => {
                games.delete(this.guildID);
                return resolve(this.players);
            }, time);
        });
    }

    static findGame(guildID) {
        return games.get(guildID) || null;
    }

    static hasSpace(space) {
        return !!spaces.find(spc => spc.values.includes(space));
    }

    static _generateSpaces() {
        const winNumber = Math.floor(Math.random() * 37);
        return [
            winNumber.toString(),
            Roulette._getColor(winNumber),
            Roulette._getRange(winNumber, 'dozens'),
            Roulette._getColumn(winNumber),
            Roulette._getRange(winNumber, 'halves'),
            Roulette._getParity(winNumber)
        ];
    }

    static _getColor(number) {
        if (number === 0) return null;
        return roulette.red.includes(number) ? 'red' : 'black';
    }

    static _getRange(number, size) {
        if (number === 0) return null;
        return spaces.get(size).values.find(value => {
            const min = parseInt(value.split('-')[0]);
            const max = parseInt(value.split('-')[1]);
            return number >= min && number <= max;
        });
    }

    static _getColumn(number) {
        if (number === 0) return null;
        return spaces.get('columns').values[(number - 1) % 3];
    }

    static _getParity(number) {
        if (number === 0) return null;
        return spaces.get('parity').values[number % 2];
    }
}

module.exports = Roulette;