text:
<?php
function tromax_customize_register_header($wp_customize) {
    //Logo Settings
    $wp_customize->add_section( 'title_tagline' , array(
        'title'      => __( 'Title, Tagline & Logo', 'tromax' ),
        'priority'   => 30,
    ) );

    $wp_customize->add_setting( 'tromax_logo_resize' , array(
        'default'     => 100,
        'sanitize_callback' => 'tromax_sanitize_positive_number',
    ) );
    $wp_customize->add_control(
        'tromax_logo_resize',
        array(
            'label' => __('Resize & Adjust Logo','tromax'),
            'section' => 'title_tagline',
            'settings' => 'tromax_logo_resize',
            'priority' => 6,
            'type' => 'range',
            'active_callback' => 'tromax_logo_enabled',
            'input_attrs' => array(
                'min'   => 30,
                'max'   => 200,
                'step'  => 5,
            ),
        )
    );

    function tromax_logo_enabled($control) {
        $option = $control->manager->get_setting('custom_logo');
        return $option->value() == true;
    }

    //Replace Header Text Color with, separate colors for Title and Description
    //Override tromax_site_titlecolor
    $wp_customize->remove_control('header_text');
    $wp_customize->remove_setting('header_textcolor');
    $wp_customize->add_setting('tromax_site_titlecolor', array(
        'default'     => '#FFFFFF',
        'sanitize_callback' => 'sanitize_hex_color',
    ));

    $wp_customize->add_control(new WP_Customize_Color_Control(
            $wp_customize,
            'tromax_site_titlecolor', array(
            'label' => __('Site Title Color','tromax'),
            'section' => 'colors',
            'settings' => 'tromax_site_titlecolor',
            'type' => 'color'
        ) )
    );

    $wp_customize->add_setting('tromax_header_desccolor', array(
        'default'     => '#777777',
        'sanitize_callback' => 'sanitize_hex_color',
    ));

    $wp_customize->add_control(new WP_Customize_Color_Control(
            $wp_customize,
            'tromax_header_desccolor', array(
            'label' => __('Site Tagline Color','tromax'),
            'section' => 'colors',
            'settings' => 'tromax_header_desccolor',
            'type' => 'color'
        ) )
    );

    //Settings For Logo Area

    $wp_customize->add_setting(
        'tromax_hide_title_tagline',
        array( 'sanitize_callback' => 'tromax_sanitize_checkbox' )
    );

    $wp_customize->add_control(
        'tromax_hide_title_tagline', array(
            'settings' => 'tromax_hide_title_tagline',
            'label'    => __( 'Hide Title and Tagline.', 'tromax' ),
            'section'  => 'title_tagline',
            'type'     => 'checkbox',
        )
    );

    function tromax_title_visible( $control ) {
        $option = $control->manager->get_setting('tromax_hide_title_tagline');
        return $option->value() == false ;
    }
}
add_action('customize_register', 'tromax_customize_register_header');


text:
import { UrlQueryValue } from '@grafana/data';
import { AdHocVariableFilter } from 'app/features/variables/types';

import { toFilters, toUrl } from './urlParser';

describe('urlParser', () => {
  describe('parsing toUrl with no filters', () => {
    it('then url params should be correct', () => {
      const filters: AdHocVariableFilter[] = [];
      const expected: string[] = [];

      expect(toUrl(filters)).toEqual(expected);
    });
  });

  describe('parsing toUrl with filters', () => {
    it('then url params should be correct', () => {
      const a = createFilter('a');
      const b = createFilter('b', '>');

      const filters: AdHocVariableFilter[] = [a, b];

      const expectedA = `${a.key}|${a.operator}|${a.value}`;
      const expectedB = `${b.key}|${b.operator}|${b.value}`;
      const expected: string[] = [expectedA, expectedB];

      expect(toUrl(filters)).toEqual(expected);
    });
  });

  describe('parsing toUrl with filters containing special chars', () => {
    it('then url params should be correct', () => {
      const a = createFilter('a|');
      const b = createFilter('b', '>');

      const filters: AdHocVariableFilter[] = [a, b];

      const expectedA = `a__gfp__-key|${a.operator}|a__gfp__-value`;
      const expectedB = `${b.key}|${b.operator}|${b.value}`;
      const expected: string[] = [expectedA, expectedB];

      expect(toUrl(filters)).toEqual(expected);
    });
  });

  describe('parsing toUrl with filters without values', () => {
    it('then url params should be correct', () => {
      const a: AdHocVariableFilter = {
        value: '',
        key: 'key',
        operator: '',
        condition: '',
      };

      const filters: AdHocVariableFilter[] = [a];

      const expectedA = `key||`;
      const expected: string[] = [expectedA];

      expect(toUrl(filters)).toEqual(expected);
    });
  });

  describe('parsing toUrl with filters with undefined values', () => {
    it('then url params should be correct', () => {
      const a = {
        value: undefined,
        key: 'key',
        operator: undefined,
        condition: '',
      } as unknown as AdHocVariableFilter;

      const filters: AdHocVariableFilter[] = [a];

      const expectedA = `key||`;
      const expected: string[] = [expectedA];

      expect(toUrl(filters)).toEqual(expected);
    });
  });

  describe('parsing toUrl with filters with number values', () => {
    it('then url params should be correct', () => {
      const a = {
        value: 1974,
        key: 'key',
        operator: '=',
        condition: '',
      } as unknown as AdHocVariableFilter;

      const filters: AdHocVariableFilter[] = [a];

      const expectedA = `key|=|1974`;
      const expected: string[] = [expectedA];

      expect(toUrl(filters)).toEqual(expected);
    });
  });

  describe('parsing toUrl with filters with boolean values', () => {
    it('then url params should be correct', () => {
      const a = {
        value: false,
        key: 'key',
        operator: '=',
        condition: '',
      } as unknown as AdHocVariableFilter;

      const filters: AdHocVariableFilter[] = [a];

      const expectedA = `key|=|false`;
      const expected: string[] = [expectedA];

      expect(toUrl(filters)).toEqual(expected);
    });
  });

  describe('parsing toFilters with url containing no filters as string', () => {
    it('then url params should be correct', () => {
      const url: UrlQueryValue = '';
      const expected: AdHocVariableFilter[] = [];
      expect(toFilters(url)).toEqual(expected);
    });
  });

  describe('parsing toFilters with url containing no filters as []', () => {
    it('then url params should be correct', () => {
      const url: UrlQueryValue = [];
      const expected: AdHocVariableFilter[] = [];
      expect(toFilters(url)).toEqual(expected);
    });
  });

  describe('parsing toFilters with url containing one filter as string', () => {
    it('then url params should be correct', () => {
      const url: UrlQueryValue = 'a-key|=|a-value';
      const a = createFilter('a', '=');
      const expected: AdHocVariableFilter[] = [a];

      expect(toFilters(url)).toEqual(expected);
    });
  });

  describe('parsing toFilters with url containing filters', () => {
    it('then url params should be correct', () => {
      const url: UrlQueryValue = ['a-key|=|a-value', 'b-key|>|b-value'];
      const a = createFilter('a', '=');
      const b = createFilter('b', '>');
      const expected: AdHocVariableFilter[] = [a, b];

      expect(toFilters(url)).toEqual(expected);
    });
  });

  describe('parsing toFilters with url containing special chars', () => {
    it('then url params should be correct', () => {
      const url: UrlQueryValue = ['a__gfp__-key|=|a__gfp__-value', 'b-key|>|b-value'];
      const a = createFilter('a|', '=');
      const b = createFilter('b', '>');
      const expected: AdHocVariableFilter[] = [a, b];

      expect(toFilters(url)).toEqual(expected);
    });
  });

  describe('parsing toFilters with url containing filter with empty values', () => {
    it('then url params should be correct', () => {
      const url: UrlQueryValue = 'key||';
      const expected: AdHocVariableFilter[] = [
        {
          value: '',
          key: 'key',
          operator: '',
          condition: '',
        },
      ];

      expect(toFilters(url)).toEqual(expected);
    });
  });

  describe('parsing toFilters with url containing no filters as string', () => {
    it('then url params should be correct', () => {
      const url: UrlQueryValue = '';
      const expected: AdHocVariableFilter[] = [];
      expect(toFilters(url)).toEqual(expected);
    });
  });
});

function createFilter(value: string, operator = '='): AdHocVariableFilter {
  return {
    value: `${value}-value`,
    key: `${value}-key`,
    operator: operator,
    condition: '',
  };
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.token = undefined;
exports.joinToken = joinToken;
exports.parseToken = parseToken;
exports.nonce = nonce;
exports.timestamp = timestamp;
exports.signature = signature;
exports.oauth1 = oauth1;

var _sha = require('sha1');

var _sha2 = _interopRequireDefault(_sha);

var _underscore = require('underscore');

var _underscore2 = _interopRequireDefault(_underscore);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function joinToken(obj) {
  var list = [];

  _underscore2.default.each(obj, function (value, key) {
    return list.push(encodeURIComponent(key + '=' + value));
  });

  return list.sort().join('&');
}

function parseToken(string) {
  var list = string.split('&');
  var map = {};

  list.forEach(function (item) {
    return map[item.substr(0, item.indexOf('='))] = item.substr(item.indexOf('=') + 1);
  });

  return map;
}

var token = exports.token = {
  join: joinToken,
  parse: parseToken
};

function nonce(length) {
  var last = null;
  var repeat = 0;
  var now = Math.pow(10, 2) * +new Date();
  var l = length ? length : 15;

  if (now == last) {
    repeat++;
  } else {
    repeat = 0;
    last = now;
  }

  var s = (now + repeat).toString();

  return +s.substr(s.length - l);
}

function timestamp() {
  return new Date().getTime();
}

function signature(req, params) {
  if (!req) return null;

  var baseURI = joinToken(params);

  return (0, _sha2.default)([encodeURIComponent(req.method.toUpperCase()), '&', req.url.toLowerCase(), '&', baseURI].join(''));
}

function oauth1(req, params, method) {
  if (!req) return null;

  var p = params && _underscore2.default.isObject(params) ? params : {};

  p.oauth_nonce = nonce(15);
  p.oauth_signature_method = method ? method : 'HMAC-SHA1';
  p.oauth_timestamp = timestamp();
  p.oauth_version = '1.0';
  p.oauth_signature = signature(req, p);

  return p;
}


text:
<?php

namespace Collections\Iterator;

use Collections\KeyedIterable;

class LazyTakeKeyedIterable implements KeyedIterable
{
    use LazyKeyedIterableTrait;

    /**
     * @var KeyedIterable
     */
    private $Enumerable;

    /**
     * @var int
     */
    private $n;

    public function __construct($Enumerable, $n)
    {
        $this->Enumerable = $Enumerable;
        $this->n = $n;
    }

    public function getIterator()
    {
        return new LazyTakeKeyedIterator($this->Enumerable->getIterator(), $this->n);
    }
}


text:
package jetbrains.jetpad.mapper;

import jetbrains.jetpad.base.Value;
import jetbrains.jetpad.model.property.Property;
import jetbrains.jetpad.model.property.ValueProperty;
import jetbrains.jetpad.test.BaseTestCase;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class SynchonizersTest extends BaseTestCase {
  @Test
  public void forEventSourceOnAttach() {
    final Value<Integer> runNum = new Value<>(0);
    Property<Boolean> prop = new ValueProperty<>();
    final Synchronizer synchronizer = Synchronizers.forEventSource(prop, new Runnable() {
      @Override
      public void run() {
        runNum.set(runNum.get() + 1);
      }
    });

    Mapper<Void, Void> mapper = new Mapper<Void, Void>(null, null) {
      @Override
      protected void registerSynchronizers(SynchronizersConfiguration conf) {
        super.registerSynchronizers(conf);
        conf.add(synchronizer);
      }
    };
    mapper.attachRoot();

    assertEquals(1, (int)runNum.get());
  }
}


text:
This Ruby gem serializes and deserializes cyclic object graphs in the [JSOG format](https://github.com/jsog/jsog).

## Source code

The official repository is (https://github.com/jsog/jsog-ruby).

## Download

Jsog is available from rubygems.org:

	$ gem install jsog

## Usage

This code mimics the standard *JSON* ruby package:

	require 'jsog'

	string = JSOG.dump(cyclicGraph);
	cyclicGraph = JSOG.parse(string);

It can be used to convert between object graphs directly:

	require 'jsog'

	jsogStructure = JSOG.encode(cyclicGraph);	// has { '@ref': 'ID' } links instead of cycles
	cyclicGraph = JSOG.decode(jsogStructure);

## Author

* Jeff Schnitzer (jeff@infohazard.org)

## License

This software is provided under the [MIT license](http://opensource.org/licenses/MIT)


text:
{% load thumbnail %}
{% if lang == "cs" %}
	Zobrazení: vizuální,
	textové
{% else %}
	Display: visual,
	text
{% endif %}

	{% for source in sources %}

						{% if source.screenshot %}
                            {% thumbnail source.screenshot "206x156" crop="center" as im %}

                            {% endthumbnail %}
						{% elif source.legacy_screenshot %}

						{% else %}

									www

						{% endif %}

{{ source }}

{% endfor %}

{% if paginator %}
    {% include "includes/paginator.html" with paginator=paginator %}
{% else %}
    {% include "includes/paginator.html" with paginator=sources %}
{% endif %}


text:
package com.sequenceiq.cloudbreak.converter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.sequenceiq.cloudbreak.api.model.AmbariDatabaseDetailsJson;
import com.sequenceiq.cloudbreak.api.model.DatabaseVendor;
import com.sequenceiq.cloudbreak.cloud.model.AmbariDatabase;

@Component
public class AmbariDatabaseDetailsJsonToAmbariDatabaseConverter extends AbstractConversionServiceAwareConverter<AmbariDatabaseDetailsJson, AmbariDatabase> {

    @Value("${cb.ambari.database.vendor}")
    private String vendor;

    @Value("${cb.ambari.database.name}")
    private String name;

    @Value("${cb.ambari.database.host}")
    private String host;

    @Value("${cb.ambari.database.port}")
    private Integer port;

    @Value("${cb.ambari.database.username}")
    private String userName;

    @Value("${cb.ambari.database.password}")
    private String password;

    @Override
    public AmbariDatabase convert(AmbariDatabaseDetailsJson source) {
        AmbariDatabase ambariDatabase;
        if (source == null || source.getVendor() == null) {
            ambariDatabase = getDefault();
        } else {
            ambariDatabase = new AmbariDatabase(source.getVendor().value(), source.getVendor().fancyName(), source.getName(), source.getHost(),
                    source.getPort(), source.getUserName(), source.getPassword());

        }
        return ambariDatabase;
    }

    private AmbariDatabase getDefault() {
        DatabaseVendor databaseVendor = DatabaseVendor.fromValue(vendor);
        return new AmbariDatabase(databaseVendor.value(), databaseVendor.fancyName(), name, host, port, userName, password);
    }

}


text:
package giraudsa.marshall.deserialisation.binary;

import java.io.IOException;

import giraudsa.marshall.deserialisation.ActionAbstrait;
import giraudsa.marshall.exception.EntityManagerImplementationException;
import giraudsa.marshall.exception.InstanciationException;
import giraudsa.marshall.exception.NotImplementedSerializeException;
import giraudsa.marshall.exception.SetValueException;
import giraudsa.marshall.exception.UnmarshallExeption;
import utils.champ.FieldInformations;

public abstract class ActionBinary<T> extends ActionAbstrait<T> {
	private int profondeur;
	protected int smallId;

	protected ActionBinary(final Class<T> type, final BinaryUnmarshaller<?> unmarshaller) {
		super(type, unmarshaller);
		if (unmarshaller != null)
			profondeur = getBinaryUnmarshaller().getProfondeur() + 1;
	}

	@Override
	protected void construitObjet() {
	}

	protected abstract void deserialisePariellement()
			throws ClassNotFoundException, NotImplementedSerializeException, IOException, UnmarshallExeption,
			InstanciationException, IllegalAccessException, EntityManagerImplementationException, SetValueException;

	protected void exporteObject() throws IllegalAccessException, EntityManagerImplementationException,
			InstanciationException, SetValueException {
		getBinaryUnmarshaller().integreObject(obj);
	}

	@SuppressWarnings("unchecked")
	protected <U> BinaryUnmarshaller<U> getBinaryUnmarshaller() {
		return (BinaryUnmarshaller<U>) unmarshaller;
	}

	@Override
	protected Object getObjet() {
		return getBinaryUnmarshaller().getObject(smallId);
	}

	int getProfondeur() {
		return profondeur;
	}

	protected abstract void initialise() throws InstanciationException, IOException, UnmarshallExeption;

	protected boolean isDejaTotalementDeSerialise() {
		return getBinaryUnmarshaller().isDejaTotalementDeSerialise(smallId);
	}

	protected boolean isDejaVu() {
		return getBinaryUnmarshaller().isDejaVu(smallId);
	}

	protected void litObject(final FieldInformations f)
			throws ClassNotFoundException, NotImplementedSerializeException, IOException, UnmarshallExeption,
			InstanciationException, IllegalAccessException, EntityManagerImplementationException, SetValueException {
		getBinaryUnmarshaller().litObject(f);
	}

	protected boolean readBoolean() throws IOException {
		return getBinaryUnmarshaller().readBoolean();
	}

	protected byte readByte() throws IOException {
		return getBinaryUnmarshaller().readByte();
	}

	protected char readChar() throws IOException {
		return getBinaryUnmarshaller().readChar();
	}

	protected double readDouble() throws IOException {
		return getBinaryUnmarshaller().readDouble();
	}

	protected float readFloat() throws IOException {
		return getBinaryUnmarshaller().readFloat();
	}

	protected int readInt() throws IOException {
		return getBinaryUnmarshaller().readInt();
	}

	protected long readLong() throws IOException {
		return getBinaryUnmarshaller().readLong();
	}

	protected short readShort() throws IOException {
		return getBinaryUnmarshaller().readShort();
	}

	protected String readUTF() throws IOException {
		return getBinaryUnmarshaller().readUTF();
	}

	// methode inutiles en binary
	@Override
	protected void rempliData(final String donnees) {
	}

	protected void set(final FieldInformations fieldInformations, final int smallId)
			throws InstanciationException, IOException, UnmarshallExeption {
		this.fieldInformations = fieldInformations;
		this.smallId = smallId;
		initialise();
	}

	protected void setDejaTotalementDeSerialise() {
		getBinaryUnmarshaller().setDejaTotalementDeSerialise(smallId);
	}

	protected void stockeObjetId() {
		getBinaryUnmarshaller().stockObjectSmallId(smallId, obj);
	}

	protected boolean strategieDeSerialiseTout() {
		return getBinaryUnmarshaller().getStrategie().serialiseTout(profondeur, fieldInformations);
	}
}


text:
module Bitsy
  class ForwardTaxCalculator

    def self.calculate(payment, min_payment, total_received_amount, initial_tax_rate, added_tax_rate)
      initial_tax_amount = AmountForInitialTaxCalculator.calculate(
        payment,
        min_payment,
        total_received_amount,
      )
      initial_tax_fee = initial_tax_amount * initial_tax_rate
      amount_for_added_tax = payment - initial_tax_amount
      added_tax_fee = amount_for_added_tax * added_tax_rate
      initial_tax_fee + added_tax_fee
    end

  end
end


text:
@implementation FileManager

@end


text:
<?php

namespace Shopery\Bundle\ErrorBundle\Listener;

use Shopery\Bundle\ErrorBundle\Exception\DecoratedHttpException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;

/**
 * Class ExceptionListener
 *
 * @author Berny Cantos <be@rny.cc>
 */
class ExceptionListener
{
    /**
     * @var \Exception[]
     */
    private $exceptions;

    /**
     * @param array $exceptions
     */
    public function __construct(array $exceptions)
    {
        $this->exceptions = $exceptions;
    }

    /**
     * @param GetResponseForExceptionEvent $event
     */
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();
        if ($exception instanceof HttpException) {
            return;
        }

        $exception = $this->decorateException($exception);
        if ($exception) {
            $event->setException($exception);
        }
    }

    private function decorateException($exception)
    {
        foreach ($this->exceptions as $className => $settings) {
            /** @var \Exception $exception */
            if (is_a($exception, $className)) {

                $code = $settings['code'];
                $message = $settings['expose_message']
                    ? $exception->getMessage()
                    : Response::$statusTexts[$code];

                return new DecoratedHttpException($code, $message, $exception);
            }
        }
    }
}


text:
using System.Collections.Generic;

namespace Akka.Streams.Util
{
    public static class ObjectExtensions
    {
        public static bool IsDefaultForType<T>(this T obj) => EqualityComparer<T>.Default.Equals(obj, default(T));
    }
}


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

namespace WebSpider.Objects.General
{
    public class TaskHeader
    {
        public Int64 ScheduleID { get; set; }
        public String TaskName { get; set; }
        public String TaskDescription { get; set; }
        public String Site { get; set; }

        public DateTime ScheduleFrom { get; set; }
        public Boolean TaskRepeat { get; set; }
        public Int32 TaskRepeatInterval { get; set; }
        public String TaskRepeatUnit { get; set; }

        public Boolean Enabled { get; set; }
        public DateTime? LastRun { get; set; }
        public DateTime? NextRun { get; set; }
        public DateTime CreatedDate { get; set; }

    }
}


text:
package com.netflix.zuul.http;

import com.netflix.zuul.FilterProcessor;
import com.netflix.zuul.ZuulRunner;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;

/**
 * Core Zuul servlet which intializes and orchestrates zuulFilter execution
 *
 * @author Mikey Cohen
 *         Date: 12/23/11
 *         Time: 10:44 AM
 */
public class ZuulServlet extends HttpServlet {

    private static final long serialVersionUID = -3374242278843351500L;
    private ZuulRunner zuulRunner;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        String bufferReqsStr = config.getInitParameter("buffer-requests");
        boolean bufferReqs = bufferReqsStr != null && bufferReqsStr.equals("true") ? true : false;

        zuulRunner = new ZuulRunner(bufferReqs);
    }

    @Override
    public void service(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse) throws ServletException, IOException {
        try {
            init((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse);

            // Marks this request as having passed through the "Zuul engine", as opposed to servlets
            // explicitly bound in web.xml, for which requests will not have the same data attached
            RequestContext context = RequestContext.getCurrentContext();
            context.setZuulEngineRan();

            try {
                preRoute();
            } catch (ZuulException e) {
                error(e);
                postRoute();
                return;
            }
            try {
                route();
            } catch (ZuulException e) {
                error(e);
                postRoute();
                return;
            }
            try {
                postRoute();
            } catch (ZuulException e) {
                error(e);
                return;
            }

        } catch (Throwable e) {
            error(new ZuulException(e, 500, "UNHANDLED_EXCEPTION_" + e.getClass().getName()));
        } finally {
            RequestContext.getCurrentContext().unset();
        }
    }

    /**
     * executes "post" ZuulFilters
     *
     * @throws ZuulException
     */
    void postRoute() throws ZuulException {
        zuulRunner.postRoute();
    }

    /**
     * executes "route" filters
     *
     * @throws ZuulException
     */
    void route() throws ZuulException {
        zuulRunner.route();
    }

    /**
     * executes "pre" filters
     *
     * @throws ZuulException
     */
    void preRoute() throws ZuulException {
        zuulRunner.preRoute();
    }

    /**
     * initializes request
     *
     * @param servletRequest
     * @param servletResponse
     */
    void init(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
        zuulRunner.init(servletRequest, servletResponse);
    }

    /**
     * sets error context info and executes "error" filters
     *
     * @param e
     */
    void error(ZuulException e) {
        RequestContext.getCurrentContext().setThrowable(e);
        zuulRunner.error();
    }

    @RunWith(MockitoJUnitRunner.class)
    public static class UnitTest {

        @Mock
        HttpServletRequest servletRequest;
        @Mock
        HttpServletResponseWrapper servletResponse;
        @Mock
        FilterProcessor processor;
        @Mock
        PrintWriter writer;

        @Before
        public void before() {
            MockitoAnnotations.initMocks(this);
        }

        @Test
        public void testProcessZuulFilter() {

            ZuulServlet zuulServlet = new ZuulServlet();
            zuulServlet = spy(zuulServlet);
            RequestContext context = spy(RequestContext.getCurrentContext());

            try {
                FilterProcessor.setProcessor(processor);
                RequestContext.testSetCurrentContext(context);
                when(servletResponse.getWriter()).thenReturn(writer);

                zuulServlet.init(servletRequest, servletResponse);
                verify(zuulServlet, times(1)).init(servletRequest, servletResponse);
                assertTrue(RequestContext.getCurrentContext().getRequest() instanceof HttpServletRequestWrapper);
                assertTrue(RequestContext.getCurrentContext().getResponse() instanceof HttpServletResponseWrapper);

                zuulServlet.preRoute();
                verify(processor, times(1)).preRoute();

                zuulServlet.postRoute();
                verify(processor, times(1)).postRoute();
//                verify(context, times(1)).unset();

                zuulServlet.route();
                verify(processor, times(1)).route();
                RequestContext.testSetCurrentContext(null);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

}


text:
package org.lockss.plugin.internationalunionofcrystallography.oai;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.lockss.daemon.Crawler.CrawlerFacade;
import org.lockss.config.Configuration;
import org.lockss.daemon.ConfigParamDescr;
import org.lockss.daemon.PluginException;
import org.lockss.plugin.ArchivalUnit;
import org.lockss.plugin.UrlCacher;
import org.lockss.plugin.UrlData;
import org.lockss.plugin.ArchivalUnit.ConfigurationException;
import org.lockss.util.CIProperties;
import org.lockss.util.Constants;
import org.lockss.util.Interval;
import org.lockss.util.ListUtil;
import org.lockss.util.Logger;
import org.lockss.util.UrlUtil;

import com.lyncode.xoai.model.oaipmh.Record;
import com.lyncode.xoai.model.xoai.Element;
import com.lyncode.xoai.model.xoai.Field;
import com.lyncode.xoai.serviceprovider.exceptions.BadArgumentException;
import com.lyncode.xoai.serviceprovider.exceptions.InvalidOAIResponse;
import com.lyncode.xoai.serviceprovider.model.Context;
import com.lyncode.xoai.serviceprovider.model.Context.KnownTransformer;
import com.lyncode.xoai.serviceprovider.parameters.ListRecordsParameters;
import com.lyncode.xoai.services.api.MetadataSearch;

public class IUCrOaiCrawlSeed extends RecordFilteringOaiPmhCrawlSeed {
  public static final String DEFAULT_DATE_TAG = "dc.date";
  public static final String DEFAULT_IDENTIFIER_TAG = "dc.identifier";
  public static final String START_URL_PREFIX = "cgi-bin/paper?";
  protected Collection<String> startUrls;
  protected String yearMonth;
  protected Pattern yearPattern = Pattern.compile("^([0-9]{4}-[0-9]{2})-[0-9]{2}$");
  protected Pattern idPattern = Pattern.compile("^http://dx.doi.org/[^/]+/([^/]+)$");
  public static final String OAI_DC_METADATA_PREFIX = "oai_dc";
  private static Logger logger =
	      Logger.getLogger(IUCrOaiCrawlSeed.class);
  private boolean error = false;

  public IUCrOaiCrawlSeed(CrawlerFacade cf) {
    super(cf);
    setMetadataPrefix(OAI_DC_METADATA_PREFIX);
    setUrlPostfix("cgi-bin/oai");
  }

  protected void populateFromConfig(Configuration config)
	      throws PluginException, ConfigurationException {
	  super.populateFromConfig(config);
	  this.baseUrl = config.get("script_url");
  }

  @Override
  protected Context buildContext(String url) {
    Context con = super.buildContext(url);
    con.withMetadataTransformer(OAI_DC_METADATA_PREFIX, KnownTransformer.OAI_DC);
    return con;
  }

  @Override
  protected Collection<String> getRecordList(ListRecordsParameters params)
	      throws ConfigurationException, IOException {
	    try {
	      String link;
	      int recNum = -1;
	      String pageRecordLink = "";
	      HashSet<String> idSet = new HashSet<String>();
	      for (Iterator<Record> recIter = getServiceProvider().listRecords(params);
	           recIter.hasNext();) {
	        Record rec = recIter.next();
	        recNum = recNum + 1;

	        link = findRecordArticleLink(rec);
	        if(!link.equals(pageRecordLink)) {
		        MetadataSearch<String> metaSearch =
		            rec.getMetadata().getValue().searcher();
		        if (checkMetaRules(metaSearch)) {
		        	if(link != null) {
		        		idSet.add(link);
		        	}
		        }
	        } else {
	        	return idSet;
	        }

	        if(recNum == 501 || recNum == 0) {
	        	pageRecordLink = link;
	        	recNum = 0;
	        }
	      }
	      return idSet;
	    } catch (InvalidOAIResponse e) {
	    	  if(e.getCause() != null && e.getCause().getMessage().contains("LOCKSS")) {
	    		  error = true;
	    		  logger.debug("OAI result errored due to LOCKSS audit proxy. Trying alternate start Url", e);
	    		  return null;
	    	  } else {
	    		  throw e;
	    	  }
	    } catch (BadArgumentException e) {
	      throw new ConfigurationException("Incorrectly formatted OAI parameter", e);
	    }
	  }

  protected void storeStartUrls(Collection<String> urlList, String url) throws IOException {
	  StringBuilder sb = new StringBuilder();
	  sb.append("\n");
	  for (String u : urlList) {
		  sb.append("" + u + "
\n");
	  }
	  sb.append("");
	  CIProperties headers = new CIProperties();
	  //Should use a constant here
	  headers.setProperty("content-type", "text/html; charset=utf-8");
      UrlData ud = new UrlData(new ByteArrayInputStream(sb.toString().getBytes(Constants.ENCODING_UTF_8)), headers, url);
      UrlCacher cacher = facade.makeUrlCacher(ud);
      cacher.storeContent();
  }

  protected String findRecordArticleLink(Record rec) {
	  MetadataSearch<String> recSearcher = rec.getMetadata().getValue().searcher();
	  List<String> idTags = recSearcher.findAll(DEFAULT_IDENTIFIER_TAG);
	  if(idTags != null && !idTags.isEmpty()) {
		  for(String value : idTags) {
			  if(value.startsWith("http://dx.doi.org/")) {
				  return value;
			  }
		  }
	  }
	  return null;
  }

  @Override
  protected void parseRules(String rule) throws ConfigurationException {
    if(rule.length() == 7) {
      try {
        yearMonth = rule;
      } catch(NumberFormatException ex) {
        throw new ConfigurationException("OAI date must be in format yyyy-mm");
      }
    } else {
      throw new ConfigurationException("OAI date must be in format yyyy-mm");
    }

  }

  @Override
  protected boolean checkMetaRules(MetadataSearch<String> metaSearch) {
    List<String> matchingTags;
    matchingTags = metaSearch.findAll(DEFAULT_DATE_TAG);
    if(matchingTags!= null && !matchingTags.isEmpty()) {
      for(String value : matchingTags) {
        try{
          String subYear;
          Matcher yearMatch = yearPattern.matcher(value);
          if(yearMatch.find()) {
            subYear = yearMatch.group(1);
            if(yearMonth.contentEquals(subYear)) {
              return true;
            }
          }
        } catch(NumberFormatException|IllegalStateException ex) {
          //wasn't a correctly formatted date, so we ignore it
          //log here
        }
      }
    }
    return false;
  }

  /**
   * Override this to provide different logic to convert OAI PMH ids to
   * corresponding article urls
   *
   * @param id
   * @param url
   * @return
 * @throws IOException
   */
  public Collection<String> idsToUrls(Collection<String> ids) throws IOException {
	String storeUrl = baseUrl + "auid=" + UrlUtil.encodeUrl(au.getAuId());
	List<String> urlList = new ArrayList<String>();
	if(error) {
		  urlList.add(storeUrl);
	  } else if(!ids.isEmpty()) {
			for (String id : ids) {
				Matcher idMatch = idPattern.matcher(id);
				if(idMatch.find()) {
					urlList.add(baseUrl + START_URL_PREFIX + idMatch.group(1));
				}
			}
		  Collections.sort(urlList);
		  storeStartUrls(urlList, storeUrl);
	  }
	return urlList;
  }
}


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

<TITLE>
SmcParser (SMC v. 6_1_0 API Specification)
</TITLE>

<META NAME="date" CONTENT="2011-11-20">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

SMC
6_1_0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

net.sf.smc.parser

Class SmcParser

java.lang.Object
  net.sf.smc.parser.SmcParser

public final class SmcParser
extends java.lang.Object

Reads in a finite state machine definition from an input
 stream and returns the
 FSM model. If
 parse() throws an exception, then call
 getMessages() for a list of parser warning and error
 messages which explain the problems found with the
 FSM definition. A new parser instance must be instantiated for
 each unique input stream. A parser instance cannot be reused
 for a different stream.

Nested Class Summary

static class
SmcParser.TargetLanguage

          The currently supported SMC target languages.

Field Summary

static int
LANGUAGE_COUNT

          SMC currently supports 17 different target languages plus
 one for an error code.

Constructor Summary

SmcParser(java.lang.String name,
          java.io.InputStream istream,
          SmcParser.TargetLanguage targetLanguage,
          boolean debugFlag)

          Creates a parser for the named FSM in the given input
 stream.

Method Summary

 java.util.List<SmcMessage>
getMessages()

          Returns the parser's warning and error messages list.

 SmcFSM
parse()

          Parses the named FSM in the given input stream and returns
 the finite state machine.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

LANGUAGE_COUNT

public static final int LANGUAGE_COUNT

SMC currently supports 17 different target languages plus
 one for an error code.

See Also:
Constant Field Values

Constructor Detail

SmcParser

public SmcParser(java.lang.String name,
                 java.io.InputStream istream,
                 SmcParser.TargetLanguage targetLanguage,
                 boolean debugFlag)

Creates a parser for the named FSM in the given input
 stream. If debugFlag is true,
 then the parser and lexer debug output will be generated.

Parameters:
name - the finite state machine's name.
istream - the input stream contains the SMC code.
targetLanguage - Generates code for this target
 language.
debugFlag - if true, turn on debug output.

Method Detail

parse

public SmcFSM parse()
             throws java.io.IOException,
                    java.lang.IllegalAccessException,
                    java.lang.reflect.InvocationTargetException

Parses the named FSM in the given input stream and returns
 the finite state machine. If this method throws an
 exception, then call getMessages() for a list of
 parser warnings and errors which explain the problems
 found in the FSM defintion.

Returns:
the parser FSM model.

Throws:

java.io.IOException - if there is a problem reading the input stream.

java.lang.IllegalAccessException - if there is a problem accessing the input stream.

java.lang.reflect.InvocationTargetException - if there is a parse error.

getMessages

public java.util.List<SmcMessage> getMessages()

Returns the parser's warning and error messages list.

Returns:
the parser's warning and error messages list.

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

SMC
6_1_0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2009. Charles W. Rapp. All Rights Reserved. Use is subject to license terms.


text:
package com.bytestree.model;

import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name = "users")
public class Users implements Serializable {

	private static final long serialVersionUID = 1948638898199176136L;

	@Id
	@Column(name = "username", unique = true, nullable = false, length = 100)
	private String username;

	@Column(name = "password", nullable = false, length = 100)
	private String password;

	@Column(name = "failed_logins")
	private Integer failedLogins;

	@Column(name = "enabled")
	private Boolean enabled;

	@Column(name = "locked")
	private Boolean locked;

	@Column(name = "last_login_date", length = 23)
	private Date lastLoginDate;

	@ManyToMany(fetch = FetchType.LAZY)
	@JoinTable(name = "authorities", joinColumns = {
			@JoinColumn(name = "user", nullable = false, updatable = false) }, inverseJoinColumns = {
					@JoinColumn(name = "role", nullable = false, updatable = false) })
	private Set<Roles> roleses = new HashSet<Roles>(0);

	public Users() {
	}

	public Users(String username, String password) {
		this.username = username;
		this.password = password;
	}

	public Users(String username, String password, Integer failedLogins,
			Boolean enabled, Boolean locked, Date lastLoginDate,
			Set<Roles> roleses) {
		this.username = username;
		this.password = password;
		this.failedLogins = failedLogins;
		this.enabled = enabled;
		this.locked = locked;
		this.lastLoginDate = lastLoginDate;
		this.roleses = roleses;
	}

	public String getUsername() {
		return this.username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Integer getFailedLogins() {
		return this.failedLogins;
	}

	public void setFailedLogins(Integer failedLogins) {
		this.failedLogins = failedLogins;
	}

	public Boolean getEnabled() {
		return this.enabled;
	}

	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
	}

	public Boolean getLocked() {
		return this.locked;
	}

	public void setLocked(Boolean locked) {
		this.locked = locked;
	}

	public Date getLastLoginDate() {
		return this.lastLoginDate;
	}

	public void setLastLoginDate(Date lastLoginDate) {
		this.lastLoginDate = lastLoginDate;
	}

	public Set<Roles> getRoleses() {
		return this.roleses;
	}

	public void setRoleses(Set<Roles> roleses) {
		this.roleses = roleses;
	}

}


text:
package com.ongxeno.bitcoinratewidget.widgetprovider.common;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.widget.Toast;

import com.ongxeno.bitcoinratewidget.model.suprnova.Suprnova;
import com.ongxeno.bitcoinratewidget.model.suprnova.UserBalance;
import com.ongxeno.bitcoinratewidget.retrofit.client.GenericPoolClient;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author Xenocide93 on 6/18/17.
 */

public abstract class AbstractGenericPoolWidgetProvider extends AbstractBxPoolMonitorWidgetProvider implements ThresholdSetterHandler {

	@Override
	public void updateBalance(final Context context) {
		new GenericPoolClient(getToken(context), getBaseUrl()).getUserBalance(new Callback<UserBalance>() {
			@Override
			public void onResponse(Call<UserBalance> call, Response<UserBalance> response) {
				if (response.body() == null) {
					setBalanceString("Error");
					updateWidgetUi(context);
					return;
				}

				UserBalance balance = response.body();
				if (balance != null) {
					Double balanceDouble = balance.getUserBalanceData().getBalanceData().getConfirmed()
							+ balance.getUserBalanceData().getBalanceData().getUnconfirmed();
					setBalanceString(formatBalance(balanceDouble, 3) + " " + getBalanceSuffix());
					updateWidgetUi(context);
				}
			}

			@Override
			public void onFailure(Call<UserBalance> call, Throwable t) {
				setBalanceString("Error");
				updateWidgetUi(context);
			}
		});
	}

	@Override
	public void updateHashRate(final Context context) {
		GenericPoolClient client = new GenericPoolClient(getToken(context), getBaseUrl());
		client.getUserStatus(new Callback<Suprnova>() {
			@Override
			public void onResponse(@NonNull Call<Suprnova> call, @NonNull Response<Suprnova> response) {
				if (response.body() == null) {
					return;
				}

				Suprnova suprnova = response.body();
				if (suprnova != null) {
					Double hashRate = suprnova.getUserStatus().getShareRateData().getHashrate() * getHashRateDisplayFactor();
					String hashRateString = formatNumber(hashRate, 0) + " " + getHashRateSuffix();
					setHashRateString(hashRateString);
					Toast.makeText(context, hashRateString, Toast.LENGTH_SHORT).show();
					double threshold = getMinHashRateThreshold();
					if (threshold > 0 && hashRate < threshold) {
						notifyWorkerDown(context, hashRate);
					}
				} else {
					setHashRateString("Error");
				}
				updateWidgetUi(context);
			}

			@Override
			public void onFailure(@NonNull Call<Suprnova> call, @NonNull Throwable t) {
				setHashRateString("Error");
				updateWidgetUi(context);
			}
		});
	}

	private String formatBalance(double d, int precision) {
		return String.valueOf(((int) (d * Math.pow(10, precision))) / Math.pow(10, precision));
	}

	@Override
	public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
		super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
	}

	protected PendingIntent getPendingSelfIntent(Context context, String action) {
		Intent intent = new Intent(context, getClass());
		intent.setAction(action);
		return PendingIntent.getBroadcast(context, 0, intent, 0);
	}

	protected double getHashRateDisplayFactor() {
		return 1d;
	}

	/**
	 * Gets access token for the api.
	 *
	 * @param context
	 *            context
	 *
	 * @return token
	 */
	protected abstract String getToken(Context context);

	/**
	 * Gets base url for GenericPoolClient.
	 *
	 * @return base url.
	 */
	protected abstract String getBaseUrl();

	/**
	 * Gets hash rate suffix.
	 *
	 * @return hash rate suffix
	 */
	protected abstract String getHashRateSuffix();

	/**
	 * Gets balance suffix.
	 *
	 * @return balance suffix
	 */
	protected abstract String getBalanceSuffix();

	/**
	 * Get min hash rate threshold to notify.
	 *
	 * @return hash rate
	 */
	protected abstract double getMinHashRateThreshold();

	/**
	 * Get unique pool ID.
	 *
	 * @return pool ID
	 */
	protected abstract int getPoolId();

}


text:
"""Certificate chain where the target certificate has an incorrect signature."""

import sys
sys.path += ['../..']

import gencerts

# Self-signed root certificate.
root = gencerts.create_self_signed_root_certificate('Root')

# Intermediate certificate to include in the certificate chain.
intermediate = gencerts.create_intermediate_certificate('Intermediate', root)

# Actual intermediate that was used to sign the target certificate. It has the
# same subject as expected, but a different RSA key from the certificate
# included in the actual chain.
wrong_intermediate = gencerts.create_intermediate_certificate('Intermediate',
                                                            root)

# Target certificate, signed using |wrong_intermediate| NOT |intermediate|.
target = gencerts.create_end_entity_certificate('Target', wrong_intermediate)

chain = [target, intermediate, root]
gencerts.write_chain(__doc__, chain, 'chain.pem')


text:
"""
fs.expose.xmlrpc
================

Server to expose an FS via XML-RPC

This module provides the necessary infrastructure to expose an FS object
over XML-RPC.  The main class is 'RPCFSServer', a SimpleXMLRPCServer subclass
designed to expose an underlying FS.

If you need to use a more powerful server than SimpleXMLRPCServer, you can
use the RPCFSInterface class to provide an XML-RPC-compatible wrapper around
an FS object, which can then be exposed using whatever server you choose
(e.g. Twisted's XML-RPC server).

"""

import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
from datetime import datetime

class RPCFSInterface(object):
    """Wrapper to expose an FS via a XML-RPC compatible interface.

    The only real trick is using xmlrpclib.Binary objects to transport
    the contents of files.
    """

    def __init__(self, fs):
        super(RPCFSInterface, self).__init__()
        self.fs = fs

    def encode_path(self, path):
        """Encode a filesystem path for sending over the wire.

        Unfortunately XMLRPC only supports ASCII strings, so this method
        must return something that can be represented in ASCII.  The default
        is base64-encoded UTF-8.
        """
        return path.encode("utf8").encode("base64")

    def decode_path(self, path):
        """Decode paths arriving over the wire."""
        return path.decode("base64").decode("utf8")

    def getmeta(self, meta_name):
        meta = self.fs.getmeta(meta_name)
        return meta

    def getmeta_default(self, meta_name, default):
        meta = self.fs.getmeta(meta_name, default)
        return meta

    def hasmeta(self, meta_name):
        return self.fs.hasmeta(meta_name)

    def get_contents(self, path):
        path = self.decode_path(path)
        data = self.fs.getcontents(path)
        return xmlrpclib.Binary(data)

    def set_contents(self, path, data):
        path = self.decode_path(path)
        self.fs.setcontents(path,data.data)

    def exists(self, path):
        path = self.decode_path(path)
        return self.fs.exists(path)

    def isdir(self, path):
        path = self.decode_path(path)
        return self.fs.isdir(path)

    def isfile(self, path):
        path = self.decode_path(path)
        return self.fs.isfile(path)

    def listdir(self, path="./", wildcard=None, full=False, absolute=False, dirs_only=False, files_only=False):
        path = self.decode_path(path)
        entries = self.fs.listdir(path,wildcard,full,absolute,dirs_only,files_only)
        return [self.encode_path(e) for e in entries]

    def makedir(self, path, recursive=False, allow_recreate=False):
        path = self.decode_path(path)
        return self.fs.makedir(path, recursive, allow_recreate)

    def remove(self, path):
        path = self.decode_path(path)
        return self.fs.remove(path)

    def removedir(self, path, recursive=False, force=False):
        path = self.decode_path(path)
        return self.fs.removedir(path, recursive, force)

    def rename(self, src, dst):
        src = self.decode_path(src)
        dst = self.decode_path(dst)
        return self.fs.rename(src, dst)

    def settimes(self, path, accessed_time, modified_time):
        path = self.decode_path(path)
        if isinstance(accessed_time, xmlrpclib.DateTime):
            accessed_time = datetime.strptime(accessed_time.value, "%Y%m%dT%H:%M:%S")
        if isinstance(modified_time, xmlrpclib.DateTime):
            modified_time = datetime.strptime(modified_time.value, "%Y%m%dT%H:%M:%S")
        return self.fs.settimes(path, accessed_time, modified_time)

    def getinfo(self, path):
        path = self.decode_path(path)
        return self.fs.getinfo(path)

    def desc(self, path):
        path = self.decode_path(path)
        return self.fs.desc(path)

    def getxattr(self, path, attr, default=None):
        path = self.decode_path(path)
        attr = self.decode_path(attr)
        return self.fs.getxattr(path, attr, default)

    def setxattr(self, path, attr, value):
        path = self.decode_path(path)
        attr = self.decode_path(attr)
        return self.fs.setxattr(path, attr, value)

    def delxattr(self, path, attr):
        path = self.decode_path(path)
        attr = self.decode_path(attr)
        return self.fs.delxattr(path, attr)

    def listxattrs(self, path):
        path = self.decode_path(path)
        return [self.encode_path(a) for a in self.fs.listxattrs(path)]

    def copy(self, src, dst, overwrite=False, chunk_size=16384):
        src = self.decode_path(src)
        dst = self.decode_path(dst)
        return self.fs.copy(src, dst, overwrite, chunk_size)

    def move(self,src,dst,overwrite=False,chunk_size=16384):
        src = self.decode_path(src)
        dst = self.decode_path(dst)
        return self.fs.move(src, dst, overwrite, chunk_size)

    def movedir(self, src, dst, overwrite=False, ignore_errors=False, chunk_size=16384):
        src = self.decode_path(src)
        dst = self.decode_path(dst)
        return self.fs.movedir(src, dst, overwrite, ignore_errors, chunk_size)

    def copydir(self, src, dst, overwrite=False, ignore_errors=False, chunk_size=16384):
        src = self.decode_path(src)
        dst = self.decode_path(dst)
        return self.fs.copydir(src, dst, overwrite, ignore_errors, chunk_size)

class RPCFSServer(SimpleXMLRPCServer):
    """Server to expose an FS object via XML-RPC.

    This class takes as its first argument an FS instance, and as its second
    argument a (hostname,port) tuple on which to listen for XML-RPC requests.
    Example::

        fs = OSFS('/var/srv/myfiles')
        s = RPCFSServer(fs,("",8080))
        s.serve_forever()

    To cleanly shut down the server after calling serve_forever, set the
    attribute "serve_more_requests" to False.
    """

    def __init__(self, fs, addr, requestHandler=None, logRequests=None):
        kwds = dict(allow_none=True)
        if requestHandler is not None:
            kwds['requestHandler'] = requestHandler
        if logRequests is not None:
            kwds['logRequests'] = logRequests
        self.serve_more_requests = True
        SimpleXMLRPCServer.__init__(self,addr,**kwds)
        self.register_instance(RPCFSInterface(fs))

    def serve_forever(self):
        """Override serve_forever to allow graceful shutdown."""
        while self.serve_more_requests:
            self.handle_request()


text:
(function(root, factory) {
	if (typeof module === 'object' && module.exports) {
		module.exports = function(d3) {
			d3.contextMenu = factory(d3);
			return d3.contextMenu;
		};
	} else {
		root.d3.contextMenu = factory(root.d3);
	}
}(	this,
	function(d3) {
		return function (menu, opts) {

			var openCallback,
				closeCallback;

			if (typeof opts === 'function') {
				openCallback = opts;
			} else {
				opts = opts || {};
				openCallback = opts.onOpen;
				closeCallback = opts.onClose;
			}

			// create the div element that will hold the context menu
			d3.selectAll('.d3-context-menu').data([1])
				.enter()
				.append('div')
				.attr('class', 'd3-context-menu');

			// close menu
			d3.select('body').on('click.d3-context-menu', function() {
				d3.select('.d3-context-menu').style('display', 'none');
				if (closeCallback) {
					closeCallback();
				}
			});

			// this gets executed when a contextmenu event occurs
			return function(data, index) {
				var elm = this;

				d3.selectAll('.d3-context-menu').html('');
				var list = d3.selectAll('.d3-context-menu').append('ul');
				list.selectAll('li').data(typeof menu === 'function' ? menu(data) : menu).enter()
					.append('li')
					.html(function(d) {
						return (typeof d.title === 'string') ? d.title : d.title(data);
					})
					.on('click', function(d, i) {
						d.action(elm, data, index);
						//d3.select('.d3-context-menu').style('display', 'none');

					});

				// the openCallback allows an action to fire before the menu is displayed
				// an example usage would be closing a tooltip
				if (openCallback) {
					if (openCallback(data, index) === false) {
						return;
					}
				}

				// display context menu
				d3.select('.d3-context-menu')
					.style('left', (d3.event.pageX - 2) + 'px')
					.style('top', (d3.event.pageY - 2) + 'px')
					.style('display', 'block');

				d3.event.preventDefault();
				d3.event.stopPropagation();
			};
		};
	}
));


text:
require 'uri'
require 'cgi'
require 'date'
require 'json'
require 'base64'
require 'erb'
require 'securerandom'
require 'time'
require 'timeliness'
require 'faraday'
require 'faraday-cookie_jar'
require 'concurrent'
require 'ms_rest'
require '2020-09-01/generated/azure_mgmt_subscriptions/module_definition'
require 'ms_rest_azure'

module Azure::Subscriptions::Mgmt::V2020_09_01
  autoload :Subscription,                                       '2020-09-01/generated/azure_mgmt_subscriptions/subscription.rb'
  autoload :Operations,                                         '2020-09-01/generated/azure_mgmt_subscriptions/operations.rb'
  autoload :AliasModel,                                         '2020-09-01/generated/azure_mgmt_subscriptions/alias_model.rb'
  autoload :SubscriptionClient,                                 '2020-09-01/generated/azure_mgmt_subscriptions/subscription_client.rb'

  module Models
    autoload :Operation,                                          '2020-09-01/generated/azure_mgmt_subscriptions/models/operation.rb'
    autoload :ErrorResponse,                                      '2020-09-01/generated/azure_mgmt_subscriptions/models/error_response.rb'
    autoload :OperationListResult,                                '2020-09-01/generated/azure_mgmt_subscriptions/models/operation_list_result.rb'
    autoload :CanceledSubscriptionId,                             '2020-09-01/generated/azure_mgmt_subscriptions/models/canceled_subscription_id.rb'
    autoload :PutAliasRequestProperties,                          '2020-09-01/generated/azure_mgmt_subscriptions/models/put_alias_request_properties.rb'
    autoload :EnabledSubscriptionId,                              '2020-09-01/generated/azure_mgmt_subscriptions/models/enabled_subscription_id.rb'
    autoload :PutAliasRequest,                                    '2020-09-01/generated/azure_mgmt_subscriptions/models/put_alias_request.rb'
    autoload :OperationDisplay,                                   '2020-09-01/generated/azure_mgmt_subscriptions/models/operation_display.rb'
    autoload :PutAliasResponseProperties,                         '2020-09-01/generated/azure_mgmt_subscriptions/models/put_alias_response_properties.rb'
    autoload :RenamedSubscriptionId,                              '2020-09-01/generated/azure_mgmt_subscriptions/models/renamed_subscription_id.rb'
    autoload :PutAliasResponse,                                   '2020-09-01/generated/azure_mgmt_subscriptions/models/put_alias_response.rb'
    autoload :ErrorResponseBody,                                  '2020-09-01/generated/azure_mgmt_subscriptions/models/error_response_body.rb'
    autoload :PutAliasListResult,                                 '2020-09-01/generated/azure_mgmt_subscriptions/models/put_alias_list_result.rb'
    autoload :SubscriptionName,                                   '2020-09-01/generated/azure_mgmt_subscriptions/models/subscription_name.rb'
    autoload :Workload,                                           '2020-09-01/generated/azure_mgmt_subscriptions/models/workload.rb'
    autoload :ProvisioningState,                                  '2020-09-01/generated/azure_mgmt_subscriptions/models/provisioning_state.rb'
  end
end


text:
<?php

namespace Rds\Request\V20140815;

class DescribeErrorLogsRequest extends \RpcAcsRequest
{
	function  __construct()
	{
		parent::__construct("Rds", "2014-08-15", "DescribeErrorLogs", "rds", "openAPI");
		$this->setMethod("POST");
	}

	private  $resourceOwnerId;

	private  $resourceOwnerAccount;

	private  $ownerAccount;

	private  $pageSize;

	private  $endTime;

	private  $dBInstanceId;

	private  $startTime;

	private  $ownerId;

	private  $pageNumber;

	public function getResourceOwnerId() {
		return $this->resourceOwnerId;
	}

	public function setResourceOwnerId($resourceOwnerId) {
		$this->resourceOwnerId = $resourceOwnerId;
		$this->queryParameters["ResourceOwnerId"]=$resourceOwnerId;
	}

	public function getResourceOwnerAccount() {
		return $this->resourceOwnerAccount;
	}

	public function setResourceOwnerAccount($resourceOwnerAccount) {
		$this->resourceOwnerAccount = $resourceOwnerAccount;
		$this->queryParameters["ResourceOwnerAccount"]=$resourceOwnerAccount;
	}

	public function getOwnerAccount() {
		return $this->ownerAccount;
	}

	public function setOwnerAccount($ownerAccount) {
		$this->ownerAccount = $ownerAccount;
		$this->queryParameters["OwnerAccount"]=$ownerAccount;
	}

	public function getPageSize() {
		return $this->pageSize;
	}

	public function setPageSize($pageSize) {
		$this->pageSize = $pageSize;
		$this->queryParameters["PageSize"]=$pageSize;
	}

	public function getEndTime() {
		return $this->endTime;
	}

	public function setEndTime($endTime) {
		$this->endTime = $endTime;
		$this->queryParameters["EndTime"]=$endTime;
	}

	public function getDBInstanceId() {
		return $this->dBInstanceId;
	}

	public function setDBInstanceId($dBInstanceId) {
		$this->dBInstanceId = $dBInstanceId;
		$this->queryParameters["DBInstanceId"]=$dBInstanceId;
	}

	public function getStartTime() {
		return $this->startTime;
	}

	public function setStartTime($startTime) {
		$this->startTime = $startTime;
		$this->queryParameters["StartTime"]=$startTime;
	}

	public function getOwnerId() {
		return $this->ownerId;
	}

	public function setOwnerId($ownerId) {
		$this->ownerId = $ownerId;
		$this->queryParameters["OwnerId"]=$ownerId;
	}

	public function getPageNumber() {
		return $this->pageNumber;
	}

	public function setPageNumber($pageNumber) {
		$this->pageNumber = $pageNumber;
		$this->queryParameters["PageNumber"]=$pageNumber;
	}

}


text:
You can also use the `AsyncSwitch` component that will update the behavior of
the `Switch`. When the `loading` prop is enabled, the `Switch` will gain a
circular progress indicator and prevent the switch from being toggled again
until the `loading` prop is set to `false` . This sort of switch is useful if
you are trying to send an API request to update some behavior, but it fails due
to some error.


text:
layout: page
description: "random thoughts from a 0xCAFED00D"
public: false
header-img: "img/home-bg.jpg"
---

## Emergency Information for Bruno, Reeta, Anaïs, Hugo and Celeste ##

**Phone Numbers**

* Home (UK): +44 1732 462739
* Cell (Reeta UK): +44 7447 019613
* Cell (Bruno UK): +44 7841 596838
* Cell (Bruno Israel): +972 52-2965552
* Work (Bruno US): +1 650 935 5251
* Skype (Bruno): brunofr
* Skype (Reeta): reetasl

**Home Address**

    Knapton, Windmill Road
    Sevenoaks
    Kent
    TN13 1TN
    United Kingdom

**Emails**

* [Reeta Laaksonen <reeta.laaksonen@gmail.com>](mailto:reeta.laaksonen@gmail.com)
* [Bruno Fernandez-Ruiz <brunofr@olympum.com>](mailto:brunofr@olympum.com)

**Medical Information**

GP Contact:

    South Park Medical Practice
    South Park
    Sevenoaks
    Kent
    TN13 1ED
    southpark.medical@nhs.net

Allergies, medication and blood groups:

* Bruno: Gluten intolerance, AB+.
* Reeta: asthmatic, lactose intolerance, O+.
* Anaïs: asthmatic, ?
* Hugo: asthmatic, lactose intolerance, ?
* Celeste: ?


text:
<?php

namespace Tests\Chromabits\Nucleus\Testing\ExampleService;

/**
 * Class ExampleA
 *
 * @author Eduardo Trujillo <ed@chromabits.com>
 * @package Tests\Chromabits\Nucleus\Testing\ExampleService
 */
class ExampleA extends ExampleBase implements ExampleAInterface
{
    /**
     * Says hello.
     *
     * @return \Chromabits\Nucleus\Strings\Rope
     */
    public function sayHello()
    {
        return rope('hello there');
    }
}


text:
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef _DRIVER_GPIO_H_
#define _DRIVER_GPIO_H_
#include "esp_err.h"
#include <esp_types.h>
#include "soc/gpio_reg.h"
#include "soc/gpio_struct.h"
#include "soc/rtc_io_reg.h"
#include "soc/io_mux_reg.h"
#include "soc/gpio_sig_map.h"
#include "rom/gpio.h"
#include "esp_attr.h"
#include "esp_intr_alloc.h"

#ifdef __cplusplus
extern "C" {
#endif

#define GPIO_SEL_0              (BIT(0))                         /*!< Pin 0 selected */
#define GPIO_SEL_1              (BIT(1))                         /*!< Pin 1 selected */
#define GPIO_SEL_2              (BIT(2))                         /*!< Pin 2 selected */
#define GPIO_SEL_3              (BIT(3))                         /*!< Pin 3 selected */
#define GPIO_SEL_4              (BIT(4))                         /*!< Pin 4 selected */
#define GPIO_SEL_5              (BIT(5))                         /*!< Pin 5 selected */
#define GPIO_SEL_6              (BIT(6))                         /*!< Pin 6 selected */
#define GPIO_SEL_7              (BIT(7))                         /*!< Pin 7 selected */
#define GPIO_SEL_8              (BIT(8))                         /*!< Pin 8 selected */
#define GPIO_SEL_9              (BIT(9))                         /*!< Pin 9 selected */
#define GPIO_SEL_10             (BIT(10))                        /*!< Pin 10 selected */
#define GPIO_SEL_11             (BIT(11))                        /*!< Pin 11 selected */
#define GPIO_SEL_12             (BIT(12))                        /*!< Pin 12 selected */
#define GPIO_SEL_13             (BIT(13))                        /*!< Pin 13 selected */
#define GPIO_SEL_14             (BIT(14))                        /*!< Pin 14 selected */
#define GPIO_SEL_15             (BIT(15))                        /*!< Pin 15 selected */
#define GPIO_SEL_16             (BIT(16))                        /*!< Pin 16 selected */
#define GPIO_SEL_17             (BIT(17))                        /*!< Pin 17 selected */
#define GPIO_SEL_18             (BIT(18))                        /*!< Pin 18 selected */
#define GPIO_SEL_19             (BIT(19))                        /*!< Pin 19 selected */

#define GPIO_SEL_21             (BIT(21))                        /*!< Pin 21 selected */
#define GPIO_SEL_22             (BIT(22))                        /*!< Pin 22 selected */
#define GPIO_SEL_23             (BIT(23))                        /*!< Pin 23 selected */

#define GPIO_SEL_25             (BIT(25))                        /*!< Pin 25 selected */
#define GPIO_SEL_26             (BIT(26))                        /*!< Pin 26 selected */
#define GPIO_SEL_27             (BIT(27))                        /*!< Pin 27 selected */

#define GPIO_SEL_32             ((uint64_t)(((uint64_t)1)<<32))  /*!< Pin 32 selected */
#define GPIO_SEL_33             ((uint64_t)(((uint64_t)1)<<33))  /*!< Pin 33 selected */
#define GPIO_SEL_34             ((uint64_t)(((uint64_t)1)<<34))  /*!< Pin 34 selected */
#define GPIO_SEL_35             ((uint64_t)(((uint64_t)1)<<35))  /*!< Pin 35 selected */
#define GPIO_SEL_36             ((uint64_t)(((uint64_t)1)<<36))  /*!< Pin 36 selected */
#define GPIO_SEL_37             ((uint64_t)(((uint64_t)1)<<37))  /*!< Pin 37 selected */
#define GPIO_SEL_38             ((uint64_t)(((uint64_t)1)<<38))  /*!< Pin 38 selected */
#define GPIO_SEL_39             ((uint64_t)(((uint64_t)1)<<39))  /*!< Pin 39 selected */

#define GPIO_PIN_REG_0          PERIPHS_IO_MUX_GPIO0_U
#define GPIO_PIN_REG_1          PERIPHS_IO_MUX_U0TXD_U
#define GPIO_PIN_REG_2          PERIPHS_IO_MUX_GPIO2_U
#define GPIO_PIN_REG_3          PERIPHS_IO_MUX_U0RXD_U
#define GPIO_PIN_REG_4          PERIPHS_IO_MUX_GPIO4_U
#define GPIO_PIN_REG_5          PERIPHS_IO_MUX_GPIO5_U
#define GPIO_PIN_REG_6          PERIPHS_IO_MUX_SD_CLK_U
#define GPIO_PIN_REG_7          PERIPHS_IO_MUX_SD_DATA0_U
#define GPIO_PIN_REG_8          PERIPHS_IO_MUX_SD_DATA1_U
#define GPIO_PIN_REG_9          PERIPHS_IO_MUX_SD_DATA2_U
#define GPIO_PIN_REG_10         PERIPHS_IO_MUX_SD_DATA3_U
#define GPIO_PIN_REG_11         PERIPHS_IO_MUX_SD_CMD_U
#define GPIO_PIN_REG_12         PERIPHS_IO_MUX_MTDI_U
#define GPIO_PIN_REG_13         PERIPHS_IO_MUX_MTCK_U
#define GPIO_PIN_REG_14         PERIPHS_IO_MUX_MTMS_U
#define GPIO_PIN_REG_15         PERIPHS_IO_MUX_MTDO_U
#define GPIO_PIN_REG_16         PERIPHS_IO_MUX_GPIO16_U
#define GPIO_PIN_REG_17         PERIPHS_IO_MUX_GPIO17_U
#define GPIO_PIN_REG_18         PERIPHS_IO_MUX_GPIO18_U
#define GPIO_PIN_REG_19         PERIPHS_IO_MUX_GPIO19_U
#define GPIO_PIN_REG_20         PERIPHS_IO_MUX_GPIO20_U
#define GPIO_PIN_REG_21         PERIPHS_IO_MUX_GPIO21_U
#define GPIO_PIN_REG_22         PERIPHS_IO_MUX_GPIO22_U
#define GPIO_PIN_REG_23         PERIPHS_IO_MUX_GPIO23_U
#define GPIO_PIN_REG_25         PERIPHS_IO_MUX_GPIO25_U
#define GPIO_PIN_REG_26         PERIPHS_IO_MUX_GPIO26_U
#define GPIO_PIN_REG_27         PERIPHS_IO_MUX_GPIO27_U
#define GPIO_PIN_REG_32         PERIPHS_IO_MUX_GPIO32_U
#define GPIO_PIN_REG_33         PERIPHS_IO_MUX_GPIO33_U
#define GPIO_PIN_REG_34         PERIPHS_IO_MUX_GPIO34_U
#define GPIO_PIN_REG_35         PERIPHS_IO_MUX_GPIO35_U
#define GPIO_PIN_REG_36         PERIPHS_IO_MUX_GPIO36_U
#define GPIO_PIN_REG_37         PERIPHS_IO_MUX_GPIO37_U
#define GPIO_PIN_REG_38         PERIPHS_IO_MUX_GPIO38_U
#define GPIO_PIN_REG_39         PERIPHS_IO_MUX_GPIO39_U

#define GPIO_APP_CPU_INTR_ENA      (BIT(0))
#define GPIO_APP_CPU_NMI_INTR_ENA  (BIT(1))
#define GPIO_PRO_CPU_INTR_ENA      (BIT(2))
#define GPIO_PRO_CPU_NMI_INTR_ENA  (BIT(3))
#define GPIO_SDIO_EXT_INTR_ENA     (BIT(4))

#define GPIO_MODE_DEF_INPUT           (BIT0)
#define GPIO_MODE_DEF_OUTPUT          (BIT1)
#define GPIO_MODE_DEF_OD              (BIT2)

#define GPIO_PIN_COUNT              40
extern const uint32_t GPIO_PIN_MUX_REG[GPIO_PIN_COUNT];
#define GPIO_IS_VALID_GPIO(gpio_num)      ((gpio_num < GPIO_PIN_COUNT && GPIO_PIN_MUX_REG[gpio_num] != 0))   //to decide whether it is a valid GPIO number
#define GPIO_IS_VALID_OUTPUT_GPIO(gpio_num)      ((GPIO_IS_VALID_GPIO(gpio_num)) && (gpio_num < 34))         //to decide whether it can be a valid GPIO number of output mode

typedef enum {
    GPIO_NUM_0 = 0,     /*!< GPIO0, input and output */
    GPIO_NUM_1 = 1,     /*!< GPIO1, input and output */
    GPIO_NUM_2 = 2,     /*!< GPIO2, input and output */
    GPIO_NUM_3 = 3,     /*!< GPIO3, input and output */
    GPIO_NUM_4 = 4,     /*!< GPIO4, input and output */
    GPIO_NUM_5 = 5,     /*!< GPIO5, input and output */
    GPIO_NUM_6 = 6,     /*!< GPIO6, input and output */
    GPIO_NUM_7 = 7,     /*!< GPIO7, input and output */
    GPIO_NUM_8 = 8,     /*!< GPIO8, input and output */
    GPIO_NUM_9 = 9,     /*!< GPIO9, input and output */
    GPIO_NUM_10 = 10,   /*!< GPIO10, input and output */
    GPIO_NUM_11 = 11,   /*!< GPIO11, input and output */
    GPIO_NUM_12 = 12,   /*!< GPIO12, input and output */
    GPIO_NUM_13 = 13,   /*!< GPIO13, input and output */
    GPIO_NUM_14 = 14,   /*!< GPIO14, input and output */
    GPIO_NUM_15 = 15,   /*!< GPIO15, input and output */
    GPIO_NUM_16 = 16,   /*!< GPIO16, input and output */
    GPIO_NUM_17 = 17,   /*!< GPIO17, input and output */
    GPIO_NUM_18 = 18,   /*!< GPIO18, input and output */
    GPIO_NUM_19 = 19,   /*!< GPIO19, input and output */

    GPIO_NUM_21 = 21,   /*!< GPIO21, input and output */
    GPIO_NUM_22 = 22,   /*!< GPIO22, input and output */
    GPIO_NUM_23 = 23,   /*!< GPIO23, input and output */

    GPIO_NUM_25 = 25,   /*!< GPIO25, input and output */
    GPIO_NUM_26 = 26,   /*!< GPIO26, input and output */
    GPIO_NUM_27 = 27,   /*!< GPIO27, input and output */

    GPIO_NUM_32 = 32,   /*!< GPIO32, input and output */
    GPIO_NUM_33 = 33,   /*!< GPIO32, input and output */
    GPIO_NUM_34 = 34,   /*!< GPIO34, input mode only */
    GPIO_NUM_35 = 35,   /*!< GPIO35, input mode only */
    GPIO_NUM_36 = 36,   /*!< GPIO36, input mode only */
    GPIO_NUM_37 = 37,   /*!< GPIO37, input mode only */
    GPIO_NUM_38 = 38,   /*!< GPIO38, input mode only */
    GPIO_NUM_39 = 39,   /*!< GPIO39, input mode only */
    GPIO_NUM_MAX = 40,
} gpio_num_t;

typedef enum {
    GPIO_INTR_DISABLE = 0,     /*!< Disable GPIO interrupt                             */
    GPIO_INTR_POSEDGE = 1,     /*!< GPIO interrupt type : rising edge                  */
    GPIO_INTR_NEGEDGE = 2,     /*!< GPIO interrupt type : falling edge                 */
    GPIO_INTR_ANYEDGE = 3,     /*!< GPIO interrupt type : both rising and falling edge */
    GPIO_INTR_LOW_LEVEL = 4,   /*!< GPIO interrupt type : input low level trigger      */
    GPIO_INTR_HIGH_LEVEL = 5,  /*!< GPIO interrupt type : input high level trigger     */
    GPIO_INTR_MAX,
} gpio_int_type_t;

typedef enum {
    GPIO_MODE_INPUT = GPIO_MODE_DEF_INPUT,                                                         /*!< GPIO mode : input only                           */
    GPIO_MODE_OUTPUT = GPIO_MODE_DEF_OUTPUT,                                                       /*!< GPIO mode : output only mode                     */
    GPIO_MODE_OUTPUT_OD = ((GPIO_MODE_DEF_OUTPUT)|(GPIO_MODE_DEF_OD)),                             /*!< GPIO mode : output only with open-drain mode     */
    GPIO_MODE_INPUT_OUTPUT_OD = ((GPIO_MODE_DEF_INPUT)|(GPIO_MODE_DEF_OUTPUT)|(GPIO_MODE_DEF_OD)), /*!< GPIO mode : output and input with open-drain mode*/
    GPIO_MODE_INPUT_OUTPUT = ((GPIO_MODE_DEF_INPUT)|(GPIO_MODE_DEF_OUTPUT)),                       /*!< GPIO mode : output and input mode                */
} gpio_mode_t;

typedef enum {
    GPIO_PULLUP_DISABLE = 0x0,     /*!< Disable GPIO pull-up resistor */
    GPIO_PULLUP_ENABLE = 0x1,      /*!< Enable GPIO pull-up resistor */
} gpio_pullup_t;

typedef enum {
    GPIO_PULLDOWN_DISABLE = 0x0,   /*!< Disable GPIO pull-down resistor */
    GPIO_PULLDOWN_ENABLE = 0x1,    /*!< Enable GPIO pull-down resistor  */
} gpio_pulldown_t;

/**
 * @brief Configuration parameters of GPIO pad for gpio_config function
 */
typedef struct {
    uint64_t pin_bit_mask;          /*!< GPIO pin: set with bit mask, each bit maps to a GPIO */
    gpio_mode_t mode;               /*!< GPIO mode: set input/output mode                     */
    gpio_pullup_t pull_up_en;       /*!< GPIO pull-up                                         */
    gpio_pulldown_t pull_down_en;   /*!< GPIO pull-down                                       */
    gpio_int_type_t intr_type;      /*!< GPIO interrupt type                                  */
} gpio_config_t;

typedef enum {
    GPIO_PULLUP_ONLY,               /*!< Pad pull up            */
    GPIO_PULLDOWN_ONLY,             /*!< Pad pull down          */
    GPIO_PULLUP_PULLDOWN,           /*!< Pad pull up + pull down*/
    GPIO_FLOATING,                  /*!< Pad floating           */
} gpio_pull_mode_t;

typedef void (*gpio_isr_t)(void*);
typedef intr_handle_t gpio_isr_handle_t;

/**
 * @brief GPIO common configuration
 *
 *        Configure GPIO's Mode,pull-up,PullDown,IntrType
 *
 * @param  pGPIOConfig Pointer to GPIO configure struct
 *
 * @return
 *     - ESP_OK success
 *     - ESP_ERR_INVALID_ARG Parameter error
 *
 */
esp_err_t gpio_config(gpio_config_t *pGPIOConfig);

/**
 * @brief  GPIO set interrupt trigger type
 *
 * @param  gpio_num GPIO number. If you want to set the trigger type of e.g. of GPIO16, gpio_num should be GPIO_NUM_16 (16);
 * @param  intr_type Interrupt type, select from gpio_int_type_t
 *
 * @return
 *     - ESP_OK  Success
 *     - ESP_ERR_INVALID_ARG Parameter error
 *
 */
esp_err_t gpio_set_intr_type(gpio_num_t gpio_num, gpio_int_type_t intr_type);

/**
 * @brief  Enable GPIO module interrupt signal
 *
 * @param  gpio_num GPIO number. If you want to enable an interrupt on e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16);
 *
 * @return
 *     - ESP_OK Success
 *     - ESP_ERR_INVALID_ARG Parameter error
 *
 */
esp_err_t gpio_intr_enable(gpio_num_t gpio_num);

/**
 * @brief  Disable GPIO module interrupt signal
 *
 * @param  gpio_num GPIO number. If you want to disable the interrupt of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16);
 *
 * @return
 *     - ESP_OK success
 *     - ESP_ERR_INVALID_ARG Parameter error
 *
 */
esp_err_t gpio_intr_disable(gpio_num_t gpio_num);

/**
 * @brief  GPIO set output level
 *
 * @param  gpio_num GPIO number. If you want to set the output level of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16);
 * @param  level Output level. 0: low ; 1: high
 *
 * @return
 *     - ESP_OK Success
 *     - ESP_ERR_INVALID_ARG GPIO number error
 *
 */
esp_err_t gpio_set_level(gpio_num_t gpio_num, uint32_t level);

/**
 * @brief  GPIO get input level
 *
 * @param  gpio_num GPIO number. If you want to get the logic level of e.g. pin GPIO16, gpio_num should be GPIO_NUM_16 (16);
 *
 * @return
 *     - 0 the GPIO input level is 0
 *     - 1 the GPIO input level is 1
 *
 */
int gpio_get_level(gpio_num_t gpio_num);

/**
 * @brief	 GPIO set direction
 *
 * Configure GPIO direction,such as output_only,input_only,output_and_input
 *
 * @param  gpio_num  Configure GPIO pins number, it should be GPIO number. If you want to set direction of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16);
 * @param  mode GPIO direction
 *
 * @return
 *     - ESP_OK Success
 *     - ESP_ERR_INVALID_ARG GPIO error
 *
 */
esp_err_t gpio_set_direction(gpio_num_t gpio_num, gpio_mode_t mode);

/**
 * @brief  Configure GPIO pull-up/pull-down resistors
 *
 * Only pins that support both input & output have integrated pull-up and pull-down resistors. Input-only GPIOs 34-39 do not.
 *
 * @param  gpio_num GPIO number. If you want to set pull up or down mode for e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16);
 * @param  pull GPIO pull up/down mode.
 *
 * @return
 *     - ESP_OK Success
 *     - ESP_ERR_INVALID_ARG : Parameter error
 *
 */
esp_err_t gpio_set_pull_mode(gpio_num_t gpio_num, gpio_pull_mode_t pull);

/**
  * @brief Enable GPIO wake-up function.
  *
  * @param gpio_num GPIO number.
  *
  * @param intr_type GPIO wake-up type. Only GPIO_INTR_LOW_LEVEL or GPIO_INTR_HIGH_LEVEL can be used.
  *
  * @return
  *     - ESP_OK Success
  *     - ESP_ERR_INVALID_ARG Parameter error
  */
esp_err_t gpio_wakeup_enable(gpio_num_t gpio_num, gpio_int_type_t intr_type);

/**
  * @brief Disable GPIO wake-up function.
  *
  * @param gpio_num GPIO number
  *
  * @return
  *     - ESP_OK Success
  *     - ESP_ERR_INVALID_ARG Parameter error
  */
esp_err_t gpio_wakeup_disable(gpio_num_t gpio_num);

/**
 * @brief   Register GPIO interrupt handler, the handler is an ISR.
 *          The handler will be attached to the same CPU core that this function is running on.
 *
 * This ISR function is called whenever any GPIO interrupt occurs. See
 * the alternative gpio_install_isr_service() and
 * gpio_isr_handler_add() API in order to have the driver support
 * per-GPIO ISRs.
 *
 * @param  fn  Interrupt handler function.
 * @param  intr_alloc_flags Flags used to allocate the interrupt. One or multiple (ORred)
 *            ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info.
 * @param  arg  Parameter for handler function
 * @param  handle Pointer to return handle. If non-NULL, a handle for the interrupt will be returned here.
 *
 * \verbatim embed:rst:leading-asterisk
 * To disable or remove the ISR, pass the returned handle to the :doc:`interrupt allocation functions </api/system/intr_alloc>`.
 * \endverbatim
 *
 * @return
 *     - ESP_OK Success ;
 *     - ESP_ERR_INVALID_ARG GPIO error
 */
esp_err_t gpio_isr_register(void (*fn)(void*), void * arg, int intr_alloc_flags, gpio_isr_handle_t *handle);

/**
  * @brief Enable pull-up on GPIO.
  *
  * @param gpio_num GPIO number
  *
  * @return
  *     - ESP_OK Success
  *     - ESP_ERR_INVALID_ARG Parameter error
  */
esp_err_t gpio_pullup_en(gpio_num_t gpio_num);

/**
  * @brief Disable pull-up on GPIO.
  *
  * @param gpio_num GPIO number
  *
  * @return
  *     - ESP_OK Success
  *     - ESP_ERR_INVALID_ARG Parameter error
  */
esp_err_t gpio_pullup_dis(gpio_num_t gpio_num);

/**
  * @brief Enable pull-down on GPIO.
  *
  * @param gpio_num GPIO number
  *
  * @return
  *     - ESP_OK Success
  *     - ESP_ERR_INVALID_ARG Parameter error
  */
esp_err_t gpio_pulldown_en(gpio_num_t gpio_num);

/**
  * @brief Disable pull-down on GPIO.
  *
  * @param gpio_num GPIO number
  *
  * @return
  *     - ESP_OK Success
  *     - ESP_ERR_INVALID_ARG Parameter error
  */
esp_err_t gpio_pulldown_dis(gpio_num_t gpio_num);

/**
  * @brief Install the driver's GPIO ISR handler service, which allows per-pin GPIO interrupt handlers.
  *
  * This function is incompatible with gpio_isr_register() - if that function is used, a single global ISR is registered for all GPIO interrupts. If this function is used, the ISR service provides a global GPIO ISR and individual pin handlers are registered via the gpio_isr_register() function.
  *
  * @param intr_alloc_flags Flags used to allocate the interrupt. One or multiple (ORred)
  *            ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info.
  *
  * @return
  *     - ESP_OK Success
  *     - ESP_FAIL Operation fail
  *     - ESP_ERR_NO_MEM No memory to install this service
  */
esp_err_t gpio_install_isr_service(int intr_alloc_flags);

/**
  * @brief Uninstall the driver's GPIO ISR service, freeing related resources.
  */
void gpio_uninstall_isr_service();

/**
  * @brief Add ISR handler for the corresponding GPIO pin.
  *
  * Call this function after using gpio_install_isr_service() to
  * install the driver's GPIO ISR handler service.
  *
  * The pin ISR handlers no longer need to be declared with IRAM_ATTR,
  * unless you pass the ESP_INTR_FLAG_IRAM flag when allocating the
  * ISR in gpio_install_isr_service().
  *
  * This ISR handler will be called from an ISR. So there is a stack
  * size limit (configurable as "ISR stack size" in menuconfig). This
  * limit is smaller compared to a global GPIO interrupt handler due
  * to the additional level of indirection.
  *
  * @param gpio_num GPIO number
  * @param isr_handler ISR handler function for the corresponding GPIO number.
  * @param args parameter for ISR handler.
  *
  * @return
  *     - ESP_OK Success
  *     - ESP_ERR_INVALID_STATE Wrong state, the ISR service has not been initialized.
  *     - ESP_ERR_INVALID_ARG Parameter error
  */
esp_err_t gpio_isr_handler_add(gpio_num_t gpio_num, gpio_isr_t isr_handler, void* args);

/**
  * @brief Remove ISR handler for the corresponding GPIO pin.
  *
  * @param gpio_num GPIO number
  *
  * @return
  *     - ESP_OK Success
  *     - ESP_ERR_INVALID_STATE Wrong state, the ISR service has not been initialized.
  *     - ESP_ERR_INVALID_ARG Parameter error
  */
esp_err_t gpio_isr_handler_remove(gpio_num_t gpio_num);

#ifdef __cplusplus
}
#endif

#endif /* _DRIVER_GPIO_H_ */