text:
var React = require('react-native');
var {
  StyleSheet,
  PropTypes,
  NativeModules,
  requireNativeComponent,

  // Once these are exposed, use them
  // LayoutPropTypes,
  // StyleSheetPropType,
  // NativeMethodsMixin,
  // RCTDeviceEventEmitter,
} = React;

// These are not yet exposed by the react-native package, so we must
// continue requiring them this way, which will cause warnings.
var LayoutPropTypes = require('react-native/Libraries/StyleSheet/LayoutPropTypes');
var StyleSheetPropType = require('react-native/Libraries/StyleSheet/StyleSheetPropType');
var NativeMethodsMixin = require('react-native/Libraries/ReactIOS/NativeMethodsMixin');
var RCTDeviceEventEmitter = require('react-native/Libraries/Device/RCTDeviceEventEmitter');

var { FBLoginManager } = NativeModules;

var FBLogin = React.createClass({
  statics: {
    Events: FBLoginManager.Events,
  },

  propTypes: {
    style: StyleSheetPropType(LayoutPropTypes),
    permissions: PropTypes.array, // default: ["public_profile", "email"]
    loginBehavior: PropTypes.number, // default: Native
    onLogin: PropTypes.func,
    onLogout: PropTypes.func,
    onLoginFound: PropTypes.func,
    onLoginNotFound: PropTypes.func,
    onError: PropTypes.func,
    onCancel: PropTypes.func,
    onPermissionsMissing: PropTypes.func,
  },

  getInitialState: function(){
    return {
      credentials: null,
      subscriptions: [],
    };
  },

  mixins: [NativeMethodsMixin],

  componentWillMount: function(){
    var _this = this;
    var subscriptions = this.state.subscriptions;

    // For each event key in FBLoginManager constantsToExport
    // Create listener and call event handler from props
    // e.g.  this.props.onError, this.props.onLogin
    Object.keys(FBLoginManager.Events).forEach(function(event){
      subscriptions.push(RCTDeviceEventEmitter.addListener(
        FBLoginManager.Events[event],
        (eventData) => {
          // event handler defined? call it and pass along any event data
          var eventHandler = _this.props["on"+event];
          eventHandler && eventHandler(eventData);
        }
      ));
    })

    // Add listeners to state
    this.setState({ subscriptions : subscriptions });
  },

  componentWillUnmount: function(){
    var subscriptions = this.state.subscriptions;
    subscriptions.forEach(function(subscription){
      subscription.remove();
    });
  },

  componentDidMount: function(){
    var _this = this;
    FBLoginManager.getCredentials(function(error, data){
      if (!error) {
        _this.setState({ credentials : data.credentials });
      } else {
        _this.setState({ credentials : null });
      }
    });
  },

  render: function() {
    var props = {
      ...this.props,
      style: ([styles.base, this.props.style]),
    };

    return <RCTFBLogin {...props} />
  },
});

var RCTFBLogin = requireNativeComponent('RCTFBLogin', FBLogin);

var styles = StyleSheet.create({
  base: {
    width: 175,
    height: 30,
  },
});

module.exports = FBLogin;


text:
require 'spec_helper'

describe Mobx do
  it 'initializes state on init' do
    expect(Thread.current['mobx']).to_not be_nil
  end

  it 'detects being in transaction' do
    block = proc do
      expect(Mobx.in?(:transaction)).to be_truthy
    end

    expect(block).to receive(:call).and_call_original
    Mobx::Transaction.call(block)
  end

  it 'detects being in autorun block' do
    block = proc do
      expect(Mobx.in?(:autorun)).to be_truthy
    end
    expect(block).to receive(:call).and_call_original

    autorun = Mobx::Autorun.new(block)
    Mobx.wrapped(:autorun, autorun, &block)
  end
end

redpajama_set_name: RedPajamaGithub


text:
Contributors
==============

Elio Maisonneuve, Author


text:
package com.google.edwmigration.dumper.application.dumper.connector;

import com.google.common.base.MoreObjects;
import com.google.common.base.Predicates;
import com.google.common.io.ByteSource;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import com.google.edwmigration.dumper.application.dumper.MetadataDumper;
import com.google.edwmigration.dumper.application.dumper.task.AbstractTask;
import com.google.edwmigration.dumper.common.io.ZipArchiveEntryByteSource;
import com.google.edwmigration.dumper.plugin.lib.dumper.spi.CoreMetadataDumpFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.junit.Assert.*;
import com.google.edwmigration.dumper.plugin.lib.dumper.spi.MetadataDumperConstants;
import com.google.edwmigration.dumper.test.SystemPropertyValue;
import com.google.edwmigration.dumper.test.TestUtils;

/**
 *
 * @author matt
 */
public abstract class AbstractConnectorExecutionTest extends AbstractConnectorTest {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractConnectorExecutionTest.class);

    protected final static String SUBPROJECT = "compilerworks-application-dumper";

    private final static Path JDBC_DRIVERS = new File(TestUtils.getTestResourcesDir(SUBPROJECT), "jdbc-drivers/").toPath();

    // -Dtest.dumper to run dumper agains real databases. Off by default for jenkins.
    private static class IsDumperTest {

        public static final String NAME = "test.dumper";
        private static final boolean VALUE = SystemPropertyValue.get(NAME);
    }

    public static boolean isDumperTest() {
        if (IsDumperTest.VALUE)
            LOG.debug("Running dumpers against database, -Dtest-sys-prop.{}=false to disable", IsDumperTest.NAME);
        else
            LOG.debug("NOT running dumpers against database, -Dtest-sys-prop.{}=true to enable", IsDumperTest.NAME);
        return IsDumperTest.VALUE;
    }

    public boolean run(@Nonnull String... args) throws Exception {
        if (!isDumperTest()) {
            final int N = args.length;
            String[] dryRunArgs = Arrays.copyOf(args, N + 1);
            dryRunArgs[N] = "--dry-run";
            runDumper(dryRunArgs);
            return false;
        } else {
            runDumper(args);
            return true;
        }
    }

    // TODO: take multiple baseName to load multiple jar
    @CheckForNull
    static protected List<String> findJdbcDrivers(@Nonnull String baseName) throws IOException {
        //LOG.debug(baseName + " IN " + JDBC_DRIVERS.toString());
        return Files.find(JDBC_DRIVERS, 1, (path, attr) -> {
            String name = path.getFileName().toString();
            return name.startsWith(baseName) && name.endsWith(".jar");
        }).map(p -> p.toAbsolutePath().toString()).collect(Collectors.toList());
    }

    public void runDumper(@Nonnull String... args) throws Exception {
        MetadataDumper dumper = new MetadataDumper();
        dumper.run(args);
    }

    protected static class ZipEntryValidator<E extends Enum<E>> {

        private final String entryName;
        private final Class<E> headerEnumClass;
        private E[] headerRequired = null;
        private boolean headerStrict = false;
        private Consumer<CSVRecord> recordConsumer = new Consumer<CSVRecord>() {
            private boolean seen = false;

            @Override
            public void accept(CSVRecord t) {
                if (seen)
                    return;
                seen = true;
                LOG.debug(entryName + ": Sample record: " + t);
            }
        };
        private int recordCountMin = 1;
        private int recordCountMax = Integer.MAX_VALUE;

        public ZipEntryValidator(String entryName, Class<E> headerEnumClass) {
            this.entryName = entryName;
            this.headerEnumClass = headerEnumClass;
        }

        @SafeVarargs
        @SuppressWarnings("varargs")
        public final ZipEntryValidator<E> withHeaderRequired(E... headerRequired) {
            this.headerRequired = headerRequired;
            return this;
        }

        public ZipEntryValidator<E> withHeaderStrict() {
            this.headerStrict = true;
            return this;
        }

        public ZipEntryValidator<E> withRecordConsumer(Consumer<CSVRecord> recordConsumer) {
            this.recordConsumer = recordConsumer;
            return this;
        }

        public ZipEntryValidator<E> withRecordCount(int min, int max) {
            this.recordCountMin = min;
            this.recordCountMax = max;
            return this;
        }

        public ZipEntryValidator<E> withRecordCountIgnored() {
            return withRecordCount(0, Integer.MAX_VALUE);
        }

        public void run(@Nonnull ByteSource zipEntryByteSource) throws Exception {
            try (BufferedReader reader = zipEntryByteSource.asCharSource(
                    StandardCharsets.UTF_8).openBufferedStream()) {
                CSVParser parser = new CSVParser(reader, AbstractTask.FORMAT.withFirstRecordAsHeader());

                Map<String, Integer> headerMap = parser.getHeaderMap();
                LOG.debug(zipEntryByteSource + ": CSV header map: {}", headerMap);

                if (headerStrict) {
                    // Assert that all fields in CSV are valid header fields.
                    for (Map.Entry<String, Integer> entry : headerMap.entrySet()) {
                        E field = Enum.valueOf(headerEnumClass, entry.getKey());
                        assertEquals(field.ordinal(), (int) entry.getValue());
                    }
                }

                // Assert that all valid header fields are in the CSV.
                if (headerRequired != null) {
                    for (E headerItem : headerRequired)
                        assertTrue("Header map contains " + headerItem, headerMap.containsKey(headerItem.name()));
                }

                // Ensure presence of at least one record.
                int numRecords = 0;
                for (CSVRecord record : parser) {
                    // Ensure each record maps a value to each header field (with no extraneous record fields).
                    assertEquals(headerMap.size(), record.size());

                    if (headerRequired != null) {
                        for (E headerItem : headerRequired)
                            assertTrue(record.isMapped(headerItem.name()));
                    }

                    numRecords++;
                    if (recordConsumer != null)
                        recordConsumer.accept(record);
                }
                LOG.debug(zipEntryByteSource + ": Number of records: {}", numRecords);
                if (numRecords < recordCountMin || numRecords > recordCountMax)
                    fail("Record count out of range: " + numRecords + " not in [" + recordCountMin + ", " + recordCountMax + "]");
            }
        }
    }

    protected static class ZipValidator {

        private final Set<String> expectedEntries = new HashSet<>();
        private final Set<String> allowedEntries = new HashSet<>();
        @Nonnull
        private Predicate<? super String> allowedEntriesPredicate = Predicates.alwaysFalse();
        private final List<ZipEntryValidator<?>> entryValidators = new ArrayList<>();
        private String format;

        public ZipValidator() {
            expectedEntries.add(MetadataDumperConstants.VERSION_ZIP_ENTRY_NAME);
            expectedEntries.add(MetadataDumperConstants.ARGUMENTS_ZIP_ENTRY_NAME);
            expectedEntries.add(MetadataDumperConstants.FORMAT_ZIP_ENTRY_NAME);
            expectedEntries.add(CoreMetadataDumpFormat.CompilerWorksDumpMetadataTaskFormat.ZIP_ENTRY_NAME);
        }

        @Nonnull
        public ZipValidator withFormat(@Nonnull String format) {
            this.format = format;
            return this;
        }

        /**
         * Specify names of files that are required to be in the zip file.
         */
        @Nonnull
        public ZipValidator withExpectedEntries(@Nonnull String... expectedEntries) {
            Collections.addAll(this.expectedEntries, expectedEntries);
            return this;
        }

        /**
         * Specify names of files that are allowed to be in the zip file, but whose absence is not an error.
         *
         * This predicate is considered additionally and separately to the explicitly allowed names.
         */
        @Nonnull
        public ZipValidator withAllowedEntries(@Nonnull Predicate<? super String> allowedEntries) {
            this.allowedEntriesPredicate = MoreObjects.firstNonNull(allowedEntries, Predicates.alwaysFalse());
            return this;
        }

        /**
         * Specify names of files that are allowed to be in the zip file, but whose absence is not an error.
         *
         * These explicitly allowed names are considered additionally and separately to the predicate.
         * The set of names is additive.
         */
        @Nonnull
        public ZipValidator withAllowedEntries(@Nonnull String... allowedEntries) {
            Collections.addAll(this.allowedEntries, allowedEntries);
            return this;
        }

        @Nonnull
        public <E extends Enum<E>> ZipEntryValidator<E> withEntryValidator(@Nonnull String entryName, @Nonnull Class<E> headerEnumClass) {
            withAllowedEntries(entryName);
            ZipEntryValidator<E> entryValidator = new ZipEntryValidator<>(entryName, headerEnumClass);
            entryValidators.add(entryValidator);
            return entryValidator;
        }

        public void run(@Nonnull ZipFile zipFile, @Nonnull String zipName) throws Exception {
            // Assert that all entries in zip are valid entries.
            for (ZipArchiveEntry entry : Collections.list(zipFile.getEntries())) {
                // if (!expectedEntries.contains(entry.getName()))
                // LOG.warn("Unexpected entry " + entry.getName());
                assertTrue("Unexpected entry " + entry.getName(),
                        expectedEntries.contains(entry.getName()) || allowedEntries.contains(entry.getName()) || allowedEntriesPredicate.test(entry.getName()));
            }

            // Assert that all valid entries are in the zip.
            for (String expectedEntry : expectedEntries) {
                ZipArchiveEntry zipEntry = zipFile.getEntry(expectedEntry);
                assertNotNull("Missing required entry " + expectedEntry, zipEntry);
            }

            FORMAT:
            {
                YAML:
                {
                    ZipArchiveEntryByteSource source = ZipArchiveEntryByteSource.forZipEntryNameOrNull(zipName, zipFile, CoreMetadataDumpFormat.CompilerWorksDumpMetadataTaskFormat.ZIP_ENTRY_NAME);
                    if (source == null)
                        break YAML;
                    try (Reader reader = source.asCharSource(StandardCharsets.UTF_8).openStream()) {
                        CoreMetadataDumpFormat.CompilerWorksDumpMetadataTaskFormat.Root root = CoreMetadataDumpFormat.MAPPER.readValue(reader, CoreMetadataDumpFormat.CompilerWorksDumpMetadataTaskFormat.Root.class);
                        String format = root.format;
                        LOG.debug("Format is " + format);
                        if (this.format != null)
                            assertEquals("Format was wrong.", this.format, format);
                    }
                    break FORMAT;
                }
                TEXT:
                {
                    ZipArchiveEntryByteSource source = ZipArchiveEntryByteSource.forZipEntryNameOrNull(zipName, zipFile, MetadataDumperConstants.FORMAT_ZIP_ENTRY_NAME);
                    if (source == null)
                        break TEXT;
                    String format = source.asCharSource(StandardCharsets.UTF_8).readFirstLine();
                    LOG.debug("Format is " + format);
                    if (this.format != null)
                        assertEquals("Format was wrong.", this.format, format);
                    break FORMAT;
                }
            }

            for (ZipEntryValidator<?> entryValidator : entryValidators) {
                entryValidator.run(ZipArchiveEntryByteSource.forZipEntryName(zipName, zipFile, entryValidator.entryName));
            }
        }

        public void run(@Nonnull File zipFile) throws Exception {
            run(new ZipFile(zipFile), zipFile.getPath());
        }
    }
}


text:
<?php
namespace Icecave\Pasta\AST\Func;

use Phake;
use PHPUnit_Framework_TestCase;
use Icecave\Pasta\AST\Expr\QualifiedIdentifier;

class ObjectTypeHintTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->typeName = QualifiedIdentifier::fromString('thing');
        $this->node = Phake::partialMock(__NAMESPACE__ . '\ObjectTypeHint', $this->typeName);
    }

    public function testTypeName()
    {
        $this->assertSame($this->typeName, $this->node->typeName());
    }

    public function testSetTypeName()
    {
        $typeName = QualifiedIdentifier::fromString('other');
        $this->node->setTypeName($typeName);
        $this->assertSame($typeName, $this->node->typeName());
    }
}


text:
from uliweb import Middleware
from uliweb.orm import begin_sql_monitor, close_sql_monitor

class SQLMonitorMiddle(Middleware):
    ORDER = 90

    def process_request(self, request):
        from uliweb import settings

        if 'sqlmonitor' in request.GET or settings.ORM.SQL_MONITOR:
            self.monitor = begin_sql_monitor(settings.ORM.get('SQL_MONITOR_LENGTH', 70), record_details=False)

    def process_response(self, request, response):
        from uliweb import settings

        if 'sqlmonitor' in request.GET or settings.ORM.SQL_MONITOR:
            self.monitor.print_(request.path)
            close_sql_monitor(self.monitor)
        return response

    def process_exception(self, request, exception):
        from uliweb import settings

        if 'sqlmonitor' in request.GET or settings.ORM.SQL_MONITOR:
            self.monitor.print_(request.path)
            close_sql_monitor(self.monitor)


text:
/**
 * @file Mocks out Apps Script's UrlFetchApp, using the fibers library to
 * emulate concurrent executions.
 */

var Future = require('fibers/future');

var MockUrlFetchApp = function() {
  this.delayFunction = () => 0;
  this.resultFunction = () => '';
};

MockUrlFetchApp.prototype.fetch = function(url, optOptions) {
  var delay = this.delayFunction();
  var result = this.resultFunction(url, optOptions);
  if (delay) {
    sleep(delay).wait();
  }
  return {
    getContentText: () => result,
    getResponseCode: () => 200
  };
};

function sleep(ms) {
  var future = new Future();
  setTimeout(function() {
    future.return();
  }, ms);
  return future;
}

module.exports = MockUrlFetchApp;


text:
// ---------------------------------------------------------------------------------------------------
// <copyright file="LinkTestType.cs" company="Elephant Insurance Services, LLC">
//     Copyright (c) 2015 All Right Reserved
// </copyright>
// <author>Vyom Sharma</author>
// <date>2015-08-05</date>
// <summary>
//     The LinkTestType enum
// </summary>
// ---------------------------------------------------------------------------------------------------

namespace Elephant.Hank.Resources.Enum
{
    /// <summary>
    /// The LinkTestType enum
    /// </summary>
    public enum LinkTestType
    {
        /// <summary>
        /// for simple test step
        /// </summary>
        TestStep = 0,

        /// <summary>
        /// for shared test as test step
        /// </summary>
        SharedTest = 1,

        /// <summary>
        /// for test itself as test step
        /// </summary>
        SharedWebsiteTest = 2,

        /// <summary>
        /// for simple test step
        /// </summary>
        SqlTestStep = 3,

        /// <summary>
        /// /// for Api Test Step
        /// </summary>
        ApiTestStep = 4
    }
}


text:
export RAILS_ENV=test

for version in 3.1
do
  echo "Testing Rails version " $version
  rm Gemfile.lock
  if [ -f Gemfile.lock.$version ];
  then
    echo Reusing Gemfile.lock.$version
    cp Gemfile.lock.$version Gemfile.lock
  fi
  rm spec/dummy/db/test.sqlite3
  export RAILS_VERSION=$version
  spec/ci.rb
  cp Gemfile.lock Gemfile.lock.$version
done


text:
export * from '../AsyncCreatable';
export { default } from '../AsyncCreatable';


text:
package org.onosproject.evpnrouteservice;

import java.util.Objects;

import static com.google.common.base.MoreObjects.toStringHelper;

/**
 * Represents Route target of vpn instance.
 */
public final class VpnRouteTarget {
    private final String routeTarget;

    /**
     * Constructor to initialize parameters.
     *
     * @param routeTarget route target
     */
    private VpnRouteTarget(String routeTarget) {
        this.routeTarget = routeTarget;
    }

    /**
     * Creates the vpn route target.
     *
     * @param routeTarget route target
     * @return route target
     */
    public static VpnRouteTarget routeTarget(String routeTarget) {
        return new VpnRouteTarget(routeTarget);
    }

    /**
     * get the route target.
     *
     * @return route target
     */
    public String getRouteTarget() {
        return routeTarget;
    }

    @Override
    public int hashCode() {
        return Objects.hash(routeTarget);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj instanceof VpnRouteTarget) {
            VpnRouteTarget other = (VpnRouteTarget) obj;
            return Objects.equals(routeTarget, other.routeTarget);
        }
        return false;
    }

    @Override
    public String toString() {
        return toStringHelper(this).add("routeTarget", routeTarget).toString();
    }
}


text:
/**
 * @file qentry.c Linked-list Data Structure API
 *
 * @code
 *   [Code sample - String]
 *
 *   // init a linked-list.
 *   qentry_t *entry = qEntry();
 *
 *   // insert a string element
 *   entry->putstr(entry, "str", "hello world", true);
 *
 *   // get the string.
 *   char *str = entry->getstr(entry, "str", false);
 *   if(str != NULL) {
 *     printf("str = %s\n", str);
 *     free(str);
 *   }
 *
 *   // print out all elements in the list.
 *   entry->print(entry, stdout, false);
 *
 *   // free the list.
 *   entry->free(entry);
 *
 *   [Result]
 * @endcode
 */

#ifdef ENABLE_FASTCGI
#include "fcgi_stdio.h"
#else
#include <stdio.h>
#endif
#include <stdlib.h>
#include <stdbool.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include "qdecoder.h"
#include "internal.h"

/*
 * Member method protos
 */
#ifndef _DOXYGEN_SKIP

#define _VAR        '$'
#define _VAR_OPEN   '{'
#define _VAR_CLOSE  '}'
#define _VAR_CMD    '!'
#define _VAR_ENV    '%'

static bool _put(qentry_t *entry, const char *name, const void *data,
                 size_t size, bool replace);
static bool _putstr(qentry_t *entry, const char *name, const char *str,
                    bool replace);
static bool _putstrf(qentry_t *entry, bool replace, const char *name,
                     const char *format, ...);
static bool _putint(qentry_t *entry, const char *name, int num, bool replace);

static void *_get(qentry_t *entry, const char *name, size_t *size, bool newmem);
static void *_getlast(qentry_t *entry, const char *name, size_t *size,
                      bool newmem);
static char *_getstr(qentry_t *entry, const char *name, bool newmem);
static char *_getstrf(qentry_t *entry, bool newmem, const char *namefmt, ...);
static char *_getstrlast(qentry_t *entry, const char *name, bool newmem);

static int _getint(qentry_t *entry, const char *name);
static int _getintlast(qentry_t *entry, const char *name);

static void *_caseget(qentry_t *entry, const char *name, size_t *size,
                      bool newmem);
static char *_casegetstr(qentry_t *entry, const char *name, bool newmem);
static int _casegetint(qentry_t *entry, const char *name);

static bool _getnext(qentry_t *entry, qentobj_t *obj, const char *name,
                     bool newmem);

static int _size(qentry_t *entry);
static int _remove(qentry_t *entry, const char *name);
static bool _truncate(qentry_t *entry);
static bool _reverse(qentry_t *entry);

static bool _save(qentry_t *entry, const char *filepath);
static int _load(qentry_t *entry, const char *filepath);

static bool _print(qentry_t *entry, FILE *out, bool print_data);
static bool _free(qentry_t *entry);

#endif

/**
 * Create new qentry_t linked-list object
 *
 * @return a pointer of malloced qentry_t structure in case of successful,
 *         otherwise returns NULL.
 *
 * @code
 *   qentry_t *entry = qEntry();
 * @endcode
 */
qentry_t *qEntry(void)
{
    qentry_t *entry = (qentry_t *)malloc(sizeof(qentry_t));
    if (entry == NULL) return NULL;

    memset((void *)entry, 0, sizeof(qentry_t));

    // member methods
    entry->put          = _put;
    entry->putstr       = _putstr;
    entry->putstrf      = _putstrf;
    entry->putint       = _putint;

    entry->get          = _get;
    entry->getlast      = _getlast;
    entry->getstr       = _getstr;
    entry->getstrf      = _getstrf;
    entry->getstrlast   = _getstrlast;

    entry->getint       = _getint;
    entry->getintlast   = _getintlast;

    entry->caseget      = _caseget;
    entry->casegetstr   = _casegetstr;
    entry->casegetint   = _casegetint;

    entry->getnext      = _getnext;

    entry->size         = _size;
    entry->remove       = _remove;
    entry->truncate     = _truncate;
    entry->reverse      = _reverse;

    entry->save         = _save;
    entry->load         = _load;

    entry->print        = _print;
    entry->free         = _free;

    return entry;
}

/**
 * qentry_t->put(): Store object into linked-list structure.
 *
 * @param   entry   qentry_t pointer
 * @param   name    key name.
 * @param   object  object pointer
 * @param   size    size of the object
 * @param   replace in case of false, just insert. in case of true, remove all
 *          same key then insert object if found.
 *
 * @return  true if successful, otherwise returns false.
 */
static bool _put(qentry_t *entry, const char *name,
                 const void *data, size_t size, bool replace)
{
    // check arguments
    if (entry == NULL || name == NULL || data == NULL || size <= 0) {
        return false;
    }

    // duplicate name
    char *dup_name = strdup(name);
    if (dup_name == NULL) return false;

    // duplicate object
    void *dup_data = malloc(size);
    if (dup_data == NULL) {
        free(dup_name);
        return false;
    }
    memcpy(dup_data, data, size);

    // make new object entry
    qentobj_t *obj = (qentobj_t *)malloc(sizeof(qentobj_t));
    if (obj == NULL) {
        free(dup_name);
        free(dup_data);
        return false;
    }
    obj->name = dup_name;
    obj->data = dup_data;
    obj->size = size;
    obj->next = NULL;

    // if replace flag is set, remove same key
    if (replace == true) _remove(entry, dup_name);

    // make chain link
    if (entry->first == NULL) entry->first = entry->last = obj;
    else {
        entry->last->next = obj;
        entry->last = obj;
    }

    entry->num++;

    return true;
}

/**
 * qentry_t->putstr(): Add string object into linked-list structure.
 *
 * @param   entry   qentry_t pointer
 * @param   name    key name.
 * @param   str string value
 * @param   replace in case of false, just insert. in case of true, remove all
 *                  same key then insert object if found.
 *
 * @return  true if successful, otherwise returns false.
 */
static bool _putstr(qentry_t *entry, const char *name, const char *str,
                    bool replace)
{
    size_t size = (str!=NULL) ? (strlen(str) + 1) : 0;
    return _put(entry, name, (const void *)str, size, replace);
}

/**
 * qentry_t->putstrf(): Add formatted string object into linked-list structure.
 *
 * @param   entry   qentry_t pointer
 * @param   replace in case of false, just insert. in case of true, remove all
 *                  same key then insert object if found.
 * @param   name    key name.
 * @param   format  formatted value string
 *
 * @return  true if successful, otherwise returns false.
 */
static bool _putstrf(qentry_t *entry, bool replace, const char *name,
                     const char *format, ...)
{
    char *str;
    DYNAMIC_VSPRINTF(str, format);
    if (str == NULL) return false;

    bool ret = _putstr(entry, name, str, replace);
    free(str);

    return ret;
}

/**
 * qentry_t->putint(): Add integer object into linked-list structure.
 *
 * @param   entry   qentry_t pointer
 * @param   name    key name.
 * @param   num number value
 * @param   replace in case of false, just insert. in case of true, remove all
 *                  same key then insert object if found.
 *
 * @return  true if successful, otherwise returns false.
 */
static bool _putint(qentry_t *entry, const char *name, int num, bool replace)
{
    char str[20+1];
    if (snprintf(str, 20+1, "%d", num) >= 20+1) str[20] = '\0';
    return _put(entry, name, (void *)str, strlen(str) + 1, replace);
}

/**
 * qentry_t->get(): Find object with given name
 *
 * @param   entry   qentry_t pointer
 * @param   name    key name
 * @param   size    if size is not NULL, object size will be stored.
 * @param   newmem  whether or not to allocate memory for the data.
 *
 * @return  a pointer of data if key is found, otherwise returns NULL.
 *
 * @code
 *   qentry_t *entry = qEntry();
 *   (...codes...)
 *
 *   // with newmem flag unset
 *   size_t size;
 *   const char *data = entry->get(entry, "key_name", &size, false);
 *
 *   // with newmem flag set
 *   size_t size;
 *   char *data = entry->get(entry, "key_name", &size, true);
 *   if(data != NULL) free(data);
 * @endcode
 *
 * @note
 * If newmem flag is set, returned data will be malloced and should be
 * deallocated by user. Otherwise returned pointer will point internal buffer
 * directly and should not be de-allocated by user. In thread-safe mode, newmem
 * flag always should be true.
 */
static void *_get(qentry_t *entry, const char *name, size_t *size, bool newmem)
{
    if (entry == NULL || name == NULL) return NULL;

    void *data = NULL;
    qentobj_t *obj;
    for (obj = entry->first; obj; obj = obj->next) {
        if (!strcmp(obj->name, name)) {
            if (size != NULL) *size = obj->size;

            if (newmem == true) {
                data = malloc(obj->size);
                memcpy(data, obj->data, obj->size);
            } else {
                data = obj->data;
            }

            break;
        }
    }

    return data;
}

/**
 * qentry_t->getlast(): Find lastest matched object with given name.
 *
 * @param   entry   qentry_t pointer
 * @param   name    key name
 * @param   size    if size is not NULL, object size will be stored.
 * @param   newmem  whether or not to allocate memory for the data.
 *
 * @return  a pointer of malloced data if key is found, otherwise returns NULL.
 *
 * @note
 * If you have multiple objects with same name. this method can be used to
 * find out lastest matched object.
 */
static void *_getlast(qentry_t *entry, const char *name, size_t *size,
                      bool newmem)
{
    if (entry == NULL || name == NULL) return NULL;

    qentobj_t *lastobj = NULL;
    qentobj_t *obj;
    for (obj = entry->first; obj; obj = obj->next) {
        if (!strcmp(name, obj->name)) lastobj = obj;
    }

    void *data = NULL;
    if (lastobj != NULL) {
        if (size != NULL) *size = lastobj->size;
        if (newmem == true) {
            data = malloc(lastobj->size);
            memcpy(data, lastobj->data, lastobj->size);
        } else {
            data = lastobj->data;
        }
    }

    return data;
}

/**
 * qentry_t->getstr():  Find string object with given name.
 *
 * @param   entry   qentry_t pointer
 * @param   name    key name
 * @param   newmem  whether or not to allocate memory for the data.
 *
 * @return  a pointer of malloced data if key is found, otherwise returns NULL.
 */
static char *_getstr(qentry_t *entry, const char *name, bool newmem)
{
    return (char *)_get(entry, name, NULL, newmem);
}

/**
 * qentry_t->_getstrf():  Find string object with given formatted name.
 *
 * @param   entry   qentry_t pointer
 * @param   newmem  whether or not to allocate memory for the data.
 * @param   namefmt formatted name string
 *
 * @return  a pointer of malloced data if key is found, otherwise returns NULL.
 */
static char *_getstrf(qentry_t *entry, bool newmem, const char *namefmt, ...)
{
    char *name;
    DYNAMIC_VSPRINTF(name, namefmt);
    if (name == NULL) return NULL;

    char *data = (char *)_get(entry, name, NULL, newmem);
    free(name);

    return data;
}

/**
 * qentry_t->getstrlast(): Find lastest matched string object with given name.
 *
 * @param   entry   qentry_t pointer
 * @param   name    key name
 * @param   newmem  whether or not to allocate memory for the data.
 *
 * @return  a pointer of malloced data if key is found, otherwise returns NULL.
 */
static char *_getstrlast(qentry_t *entry, const char *name, bool newmem)
{
    return (char *)_getlast(entry, name, NULL, newmem);
}

/**
 * qentry_t->getint(): Find integer object with given name.
 *
 * @param   entry   qentry_t pointer
 * @param   name    key name
 *
 * @return  a integer value of the integer object, otherwise returns 0.
 */
static int _getint(qentry_t *entry, const char *name)
{
    int n = 0;
    char *str = _get(entry, name, NULL, true);
    if (str != NULL) {
        n = atoi(str);
        free(str);
    }
    return n;
}

/**
 * qentry_t->getintlast(): Find lastest matched integer object with given name.
 *
 * @param   entry   qentry_t pointer
 * @param   name    key name
 *
 * @return  a integer value of the object.
 */
static int _getintlast(qentry_t *entry, const char *name)
{
    char *str =_getlast(entry, name, NULL, true);
    int n = 0;
    if (str != NULL) {
        n = atoi(str);
        free(str);
    }
    return n;

}

/**
 * qentry_t->caseget(): Find object with given name. (case-insensitive)
 *
 * @param   entry   qentry_t pointer
 * @param   name    key name
 * @param   size    if size is not NULL, object size will be stored.
 * @param   newmem  whether or not to allocate memory for the data.
 *
 * @return  a pointer of malloced data if key is found, otherwise returns NULL.
 */
static void *_caseget(qentry_t *entry, const char *name, size_t *size,
                      bool newmem)
{
    if (entry == NULL || name == NULL) return NULL;

    void *data = NULL;
    qentobj_t *obj;
    for (obj = entry->first; obj; obj = obj->next) {
        if (!strcasecmp(name, obj->name)) {
            if (size != NULL) *size = obj->size;
            if (newmem == true) {
                data = malloc(obj->size);
                memcpy(data, obj->data, obj->size);
            } else {
                data = obj->data;
            }

            break;
        }
    }

    return data;
}

/**
 * qentry_t->casegetstr(): Find string object with given name in
 * case-insensitive way.
 *
 * @param   entry   qentry_t pointer
 * @param   name    key name
 * @param   newmem  whether or not to allocate memory for the data.
 *
 * @return  a pointer of malloced data if key is found, otherwise returns NULL.
 */
static char *_casegetstr(qentry_t *entry, const char *name, bool newmem)
{
    return (char *)_caseget(entry, name, NULL, newmem);
}

/**
 * qentry_t->casegetint(): Find integer object with given name in
 * case-insensitive way.
 *
 * @param   entry   qentry_t pointer
 * @param   name    key name
 *
 * @return  a integer value of the object.
 */
static int _casegetint(qentry_t *entry, const char *name)
{
    char *str =_caseget(entry, name, NULL, true);
    int n = 0;
    if (str != NULL) {
        n = atoi(str);
        free(str);
    }
    return n;
}

/**
 * qentry_t->getnext(): Get next object structure.
 *
 * @param   entry   qentry_t pointer
 * @param   obj found data will be stored in this object
 * @param   name    key name, if key name is NULL search every key in the list.
 * @param   newmem  whether or not to allocate memory for the data.
 *
 * @return  true if found otherwise returns false
 *
 * @note
 * obj should be filled with 0 by using memset() before first call.
 * If newmem flag is true, user should de-allocate obj.name and obj.data
 * resources.
 *
 * @code
 *   qentry_t *entry = qEntry();
 *   entry->putstr(entry, "key1", "hello world 1", false);
 *   entry->putstr(entry, "key2", "hello world 2", false);
 *   entry->putstr(entry, "key3", "hello world 3", false);
 *
 *   qentobj_t obj;
 *   memset((void*)&obj, 0, sizeof(obj)); // must be cleared before call
 *   while(entry->getnext(entry, &obj, NULL, false) == true) {
 *     printf("NAME=%s, DATA=%s", SIZE=%zu", obj.name, obj.data, obj.size);
 *   }
 *
 *   // with newmem flag
 *   qentobj_t obj;
 *   memset((void*)&obj, 0, sizeof(obj)); // must be cleared before call
 *   while(entry->getnext(entry, &obj, NULL, true) == true) {
 *     printf("NAME=%s, DATA=%s", SIZE=%zu", obj.name, obj.data, obj.size);
 *     free(obj.name);
 *     free(obj.data);
 *   }
 * @endcode
 */
static bool _getnext(qentry_t *entry, qentobj_t *obj, const char *name,
                     bool newmem)
{
    if (entry == NULL || obj == NULL) return NULL;

    // if obj->name is NULL, it means this is first call.
    if (obj->name == NULL) obj->next = entry->first;

    qentobj_t *cont;
    bool ret = false;
    for (cont = obj->next; cont; cont = cont->next) {
        if (name != NULL && strcmp(cont->name, name)) continue;

        if (newmem == true) {
            obj->name = strdup(cont->name);
            obj->data = malloc(cont->size);
            memcpy(obj->data, cont->data, cont->size);
        } else {
            obj->name = cont->name;
            obj->data = cont->data;
        }
        obj->size = cont->size;
        obj->next = cont->next;

        ret = true;
        break;
    }

    return ret;
}

/**
 * qentry_t->size(): Get total number of stored objects
 *
 * @param   entry   qentry_t pointer
 *
 * @return  total number of stored objects.
 */
static int _size(qentry_t *entry)
{
    if (entry == NULL) return 0;

    return entry->num;
}

/**
 * qentry_t->remove(): Remove matched objects as given name.
 *
 * @param   entry   qentry_t pointer
 * @param   name    key name
 *
 * @return  a number of removed objects.
 */
static int _remove(qentry_t *entry, const char *name)
{
    if (entry == NULL || name == NULL) return 0;

    int removed = 0;
    qentobj_t *prev, *obj;
    for (prev = NULL, obj = entry->first; obj;) {
        if (!strcmp(obj->name, name)) { // found
            // copy next chain
            qentobj_t *next = obj->next;

            // adjust counter
            entry->num--;
            removed++;

            // remove entry itself
            free(obj->name);
            free(obj->data);
            free(obj);

            // adjust chain links
            if (next == NULL) entry->last = prev;  // if the object is last one
            if (prev == NULL) entry->first = next; // if the object is first one
            else prev->next = next;       // if the object is middle or last one

            // set next entry
            obj = next;
        } else {
            // remember prev object
            prev = obj;

            // set next entry
            obj = obj->next;
        }
    }

    return removed;
}

/**
 * qentry_t->truncate(): Truncate qentry_t
 *
 * @param   entry   qentry_t pointer
 *
 * @return  always returns true.
 */
static bool _truncate(qentry_t *entry)
{
    if (entry == NULL) return false;

    qentobj_t *obj;
    for (obj = entry->first; obj;) {
        qentobj_t *next = obj->next;
        free(obj->name);
        free(obj->data);
        free(obj);
        obj = next;
    }

    entry->num = 0;
    entry->first = NULL;
    entry->last = NULL;

    return true;
}

/**
 * qentry_t->reverse(): Reverse-sort internal stored object.
 *
 * @param   entry   qentry_t pointer
 *
 * @return  true if successful otherwise returns false.
 *
 * @note
 * This method can be used to improve look up performance.
 * if your application offen looking for last stored object.
 */
static bool _reverse(qentry_t *entry)
{
    if (entry == NULL) return false;

    qentobj_t *prev, *obj;
    for (prev = NULL, obj = entry->first; obj;) {
        qentobj_t *next = obj->next;
        obj->next = prev;
        prev = obj;
        obj = next;
    }

    entry->last = entry->first;
    entry->first = prev;

    return true;
}

/**
 * qentry_t->save(): Save qentry_t as plain text format
 *
 * @param   entry   qentry_t pointer
 * @param   filepath save file path
 *
 * @return  true if successful, otherwise returns false.
 */
static bool _save(qentry_t *entry, const char *filepath)
{
    if (entry == NULL) return false;

    FILE *fd;
    if ((fd = fopen(filepath, "w")) < 0) {
        DEBUG("qentry_t->save(): Can't open file %s", filepath);
        return false;
    }

    // change mode
    fchmod(fileno(fd), DEF_FILE_MODE);

    fprintf(fd, "# Generated by " _Q_PRGNAME ".\n");
    fprintf(fd, "# %s\n", filepath);

    qentobj_t *obj;
    for (obj = entry->first; obj; obj = obj->next) {
        char *encval = _q_urlencode(obj->data, obj->size);
        fprintf(fd, "%s=%s\n", obj->name, encval);
        free(encval);
    }

    fclose(fd);

    return true;
}

/**
 * qentry_t->load(): Load and append entries from given filepath
 *
 * @param   entry   qentry_t pointer
 * @param   filepath save file path
 *
 * @return  a number of loaded entries.
 */
static int _load(qentry_t *entry, const char *filepath)
{
    if (entry == NULL) return 0;

    FILE *fp = fopen(filepath, "r");
    if (fp == NULL) return 0;

    int cnt;
    for (cnt = 0; ; cnt++) {
        char *line = _q_fgetline(fp, MAX_LINEBUF);
        if (line == NULL) break;

        // parse & store
        char *data = line;
        char *name  = _q_makeword(data, '=');
        _q_strtrim(data);
        _q_strtrim(name);

        size_t size = _q_urldecode(data);
        _put(entry, name, data, size, false);
    }

    return cnt;
}

/**
 * qentry_t->print(): Print out stored objects for debugging purpose.
 *
 * @param   entry       qentry_t pointer
 * @param   out         output stream FILE descriptor such like stdout, stderr.
 * @param   print_data  true for printing out object value, false for disable
 *                      printing out object value.
 */
static bool _print(qentry_t *entry, FILE *out, bool print_data)
{
    if (entry == NULL || out == NULL) return false;

    qentobj_t *obj;
    for (obj = entry->first; obj; obj = obj->next) {
        fprintf(out, "%s=%s (%zu)\n",
                obj->name, (print_data?(char *)obj->data:"(data)"), obj->size);
    }

    return true;
}

/**
 * qentry_t->free(): Free qentry_t
 *
 * @param   entry   qentry_t pointer
 *
 * @return  always returns true.
 */
static bool _free(qentry_t *entry)
{
    if (entry == NULL) return false;

    _truncate(entry);

    free(entry);
    return true;
}


text:
double cabs(double complex z)
{
	return hypot(creal(z), cimag(z));
}


text:
<?php

namespace phpFastCache\Drivers;

use phpFastCache\Core\DriverAbstract;

/**
 * Class ssdb
 * @package phpFastCache\Drivers
 */
class ssdb extends DriverAbstract
{

    /**
     * @var bool
     */
    private $checked_ssdb = false;

    /**
     * phpFastCache_ssdb constructor.
     * @param array $config
     */
    public function __construct($config = array())
    {
        $this->setup($config);
        if (!$this->checkdriver() && !isset($config[ 'skipError' ])) {
            $this->fallback = true;
        }
    }

    /**
     * @return bool
     */
    public function checkdriver()
    {
        // Check memcache
        $this->required_extension('SSDB');
        if (class_exists('SimpleSSDB')) {
            return true;
        }
        $this->fallback = true;
        return false;
    }

    /**
     * @return bool
     */
    public function connectServer()
    {

        $server = isset($this->config[ 'ssdb' ]) ? $this->config[ 'ssdb' ] : array(
          'host' => "127.0.0.1",
          'port' => 8888,
          'password' => '',
          'timeout' => 2000,
        );

        if ($this->checked_ssdb === false) {
            $host = $server[ 'host' ];
            $port = isset($server[ 'port' ]) ? (int)$server[ 'port' ] : 8888;
            $password = isset($server[ 'password' ]) ? $server[ 'password' ] : '';
            $timeout = !empty($server[ 'timeout' ]) ? (int)$server[ 'timeout' ] : 2000;
            $this->instant = new \SimpleSSDB($host, $port, $timeout);
            if (!empty($password)) {
                $this->instant->auth($password);
            }
            $this->checked_ssdb = true;
            if (!$this->instant) {
                $this->fallback = true;
                return false;
            } else {
                return true;
            }
        }

        return true;
    }

    /**
     * @param $keyword
     * @param string $value
     * @param int $time
     * @param array $option
     * @return bool
     */
    public function driver_set($keyword, $value = '', $time = 300, $option = array())
    {
        if ($this->connectServer()) {
            if (isset($option[ 'skipExisting' ]) && $option[ 'skipExisting' ] == true) {
                $x = $this->instant->get($keyword);
                if ($x === false) {
                    return false;
                } elseif (!is_null($x)) {
                    return true;
                }
            }
            $value = $this->encode($value);
            return $this->instant->setx($keyword, $value, $time);
        } else {
            return $this->backup()->set($keyword, $value, $time, $option);
        }
    }

    /**
     * @param $keyword
     * @param array $option
     * @return mixed|null
     */
    public function driver_get($keyword, $option = array())
    {
        if ($this->connectServer()) {
            // return null if no caching
            // return value if in caching'
            $x = $this->instant->get($keyword);
            if ($x == false) {
                return null;
            } else {
                return $this->decode($x);
            }
        } else {
            $this->backup()->get($keyword, $option);
        }
    }

    /**
     * @param $keyword
     * @param array $option
     */
    public function driver_delete($keyword, $option = array())
    {
        if ($this->connectServer()) {
            $this->instant->del($keyword);
        }
    }

    /**
     * @param array $option
     * @return array
     */
    public function driver_stats($option = array())
    {
        if ($this->connectServer()) {
            $res = array(
              'info' => '',
              'size' => $this->instant->dbsize(),
              'data' => $this->instant->info(),
            );

            return $res;
        }

        return array();
    }

    /**
     * @param array $option
     * @return bool
     */
    public function driver_clean($option = array())
    {
        //Is not supported, only support command line operations
        return false;
    }

    /**
     * @param $keyword
     * @return bool
     */
    public function driver_isExisting($keyword)
    {
        if ($this->connectServer()) {
            $x = $this->instant->exists($keyword);
            return !($x == null);
        } else {
            return $this->backup()->isExisting($keyword);
        }
    }
}


text:
package org.projectfloodlight.openflow.protocol.ver14;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.projectfloodlight.openflow.protocol.OFPortState;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import java.util.EnumSet;
import java.util.Collections;

public class OFPortStateSerializerVer14 {

    public final static int LINK_DOWN_VAL = 0x1;
    public final static int BLOCKED_VAL = 0x2;
    public final static int LIVE_VAL = 0x4;

    public static Set<OFPortState> readFrom(ByteBuf bb) throws OFParseError {
        try {
            return ofWireValue(bb.readInt());
        } catch (IllegalArgumentException e) {
            throw new OFParseError(e);
        }
    }

    public static void writeTo(ByteBuf bb, Set<OFPortState> set) {
        bb.writeInt(toWireValue(set));
    }

    public static void putTo(Set<OFPortState> set, PrimitiveSink sink) {
        sink.putInt(toWireValue(set));
    }

    public static Set<OFPortState> ofWireValue(int val) {
        EnumSet<OFPortState> set = EnumSet.noneOf(OFPortState.class);

        if((val & LINK_DOWN_VAL) != 0)
            set.add(OFPortState.LINK_DOWN);
        if((val & BLOCKED_VAL) != 0)
            set.add(OFPortState.BLOCKED);
        if((val & LIVE_VAL) != 0)
            set.add(OFPortState.LIVE);
        return Collections.unmodifiableSet(set);
    }

    public static int toWireValue(Set<OFPortState> set) {
        int wireValue = 0;

        for(OFPortState e: set) {
            switch(e) {
                case LINK_DOWN:
                    wireValue |= LINK_DOWN_VAL;
                    break;
                case BLOCKED:
                    wireValue |= BLOCKED_VAL;
                    break;
                case LIVE:
                    wireValue |= LIVE_VAL;
                    break;
                default:
                    throw new IllegalArgumentException("Illegal enum value for type OFPortState in version 1.4: " + e);
            }
        }
        return wireValue;
    }

}


text:
require 'spec_helper'

describe ProjectPostObserver do
  describe 'after_create' do
    context "notify contributions" do
      let(:project) { create(:project) }
      let(:project_post) { create(:project_post) }

      it "should satisfy expectations" do
        ProjectPostWorker.should_receive(:perform_async).with(project_post.id)
        project_post.save
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingTranslation">
    <string name="intro_slide1_title">Začínáme</string>
    <string name="intro_slide1_desc">Vítejte v andOTP! Tento průvodce Vám pomůže s úvodním nastavením.
        Prosím dávejte pozor a čtěte pečlivě, jinak můžete přijít o data!
        \n\nŽádné obavy, kteroukoli volbu můžete následně změnit v Nastavení.</string>
    <string name="intro_slide2_desc">K zajištění bezpečnosti Vašich účtů je andOTP ukládá
        výhradně do šifrovaných datových souborů.
        Zde můžete zvolit, která metoda šifrování se bude používat.</string>
    <string name="intro_slide2_desc_keystore">KeyStore je komponenta systému Android sloužící k
        bezpečnému ukládání kryptografických klíčů. Výhodou je, že klíče jsou uloženy
        odděleně od dat, tato funkce může využívat hardwarovou podporu šifrování
        (je-li v zařízení k dispozici). Nicméně tím, že klíče nejsou ukládány s daty, zabraňuje tato metoda
        použití externích zálohovacích řešení (například Titanium).
        Pokud zvolíte tuto možnost, musíte se spolehnout na vlastní zálohovací funkce poskytované
        andOTP. \n\nVarování: O KeyStore je známo,
        že dělá dost problémů, prosím používejte jej jen v případě, že opravdu musíte.
        Pokud Vám nevadí zadávání hesla / PINu při každém spuštění
         andOTP, doporučuje se raději použít šifrování založené na hesle.</string>
    <string name="intro_slide2_desc_password">Tato metoda zašifruje data pomocí klíče
        generovaného z PINu nebo hesla. Hlavní výhodou je, že bude fungovat s externími zálohovacími
        nástroji (např. Titanium) a je méně náchylná k selhání než KeyStore.
        Budete ale muset zadat své přihlašovací údaje při každém spuštěn
         andOTP.</string>
    <string name="intro_slide3_desc_keystore">Zde si můžete nastavit bezpečnostní zámek
        andOTP. Pokud jste zvolili šifrování pomocí Android KeyStore,
        je tento krok volitelný.</string>
    <string name="intro_slide3_desc_password">Zde si můžete nastavit bezpečnostní zámek
        andOTP. Vzhledem k volbě šifrování pomocí Hesla/PINu je třeba nastavit
        heslo či PIN pro pokračování.</string>
    <string name="intro_slide3_warn_no_password">Prosím, nastavte heslo pro pokračování!</string>
    <string name="intro_slide3_warn_no_pin">Prosím, nastavte PIN pro pokračování!</string>
    <string name="intro_slide3_warn_confirm_password">Před pokračováním, prosím, potvrďte své heslo!</string>
    <string name="intro_slide3_warn_password_mismatch">Passwords must match!</string>
    <string name="intro_slide3_warn_confirm_pin">Před pokračováním, prosím, potvrďte svůj PIN!</string>
    <string name="intro_slide3_warn_pin_mismatch">Pins must match!</string>
    <string name="intro_slide4_title">Hotovo</string>
    <string name="intro_slide4_title_failed">Setup failed</string>
    <string name="intro_slide4_title_progress">Please wait</string>
    <string name="intro_slide4_desc_failed">Failed to set a password, this intro will be shown again
        the next time!</string>
    <string name="intro_slide4_desc">Vaše nastavení bylo uloženo, od teď můžete začít používat
        andOTP!</string>
    <string name="intro_slide4_desc_progress">Your settings are being saved and the encryption key is being
        generated, please wait…</string>
    <string name="intro_slide_android_backup_desc">Android sync is a feature built in to android used to back up app data to a 3rd party service (usually Google). Backups are always encrypted and unaccessible to 3rd parties without your master password. Requires use of Password encryption method.</string>
</resources>


text:
using SFML.Window;
using SFML.System;
using SFML.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Iris
{
    class NetPlayer : Actor
    {
        Animation idle, running, jumpUp, jumpDown, backpedal;
        public Vector2f oldPosition;
        public int animPadding; //Wait a slight bit before changing animations since position may be unreliable
        public int weaponIndex = 0;

        public NetPlayer(Deathmatch dm, long UID)
        : base(dm)
        {
            model = MainGame.Char1Model;
            this.UID = UID;
            idle = new Animation(Content.GetTexture(model.idleFile), 4, 120, 1);
            running = new Animation(Content.GetTexture(model.runFile), 6, 60, 2);
            backpedal = new Animation(Content.GetTexture(model.runFile), 6, 60, 2, false);
            jumpUp = new Animation(Content.GetTexture(model.jumpUpFile), 1, 60, 0);
            jumpDown = new Animation(Content.GetTexture(model.jumpDownFile), 3, 60, -5);
            animation = idle;

            Texture = Content.GetTexture("idle.png");
            Alive = true;
            //.Color = Color.Red;

            weapons = new List<Weapon>()
            {
                new Revolver(this),
                new Shotgun(this),
                new MachineGun(this),
                new BombWeapon(this),
            };
        }

        public override void Update()
        {
            HandleDeath();
            base.Update();

            if (!Alive)
                return;
            this.weapon = weapons[weaponIndex];
            animation.Update();
            HandleAnimationSetting();
            CheckProjectiles();

            oldPosition = Pos;
        }

        public override void Draw()
        {
            if (!Alive)
                return;

            Core = Pos - new Vector2f(-1, 35);
            this.Texture = animation.Texture;
            Render.renderStates = Actor.shader;
            Texture pistolHand = Content.GetTexture(model.pistolHand);
            Texture weaponTexture = weapon.texture;

            if (ouchTimer > 0)
            {
                shader.Shader.SetParameter("ouch", 1f);
            }
            else
            {
                shader.Shader.SetParameter("ouch", 0f);
            }

            shader.Shader.SetParameter("sampler", pistolHand);
            Render.Draw(pistolHand, Core, Color.White, new Vector2f(2, 4), 1, AimAngle, 1, Facing == -1);
            shader.Shader.SetParameter("sampler", weaponTexture);
            Render.Draw(weaponTexture, Core, Color.White, new Vector2f(2, 4), 1, AimAngle, 1, Facing == -1);
            shader.Shader.SetParameter("sampler", Texture);
            Render.DrawAnimation(Texture, this.Pos, Color.White, new Vector2f(Texture.Size.X / (animation.Count * 4),
                Texture.Size.Y - animation.YOffset), Facing, animation.Count, animation.Frame, 1);
            Render.renderStates = null;

            //Render.DrawString(Content.GetFont("Font1.ttf"), Name, Core - new Vector2f(0, 40), Color.White, .3f, true, 1);

            if (!Name.Equals(null))
                Render.DrawString(Content.GetFont("PixelSix.ttf"), Name, this.Core - new Vector2f(0, 40), Color.White, .3f, true, 1);

            base.Draw();
        }

        public void CheckProjectiles()
        {
            for (int i = 0; i < MainGame.dm.Projectiles.Count; i++)
            {
                if (Helper.Distance(MainGame.dm.Projectiles[i].Pos, Core) < 20)
                {
                    this.Killer = MainGame.dm.Projectiles[i].Owner;
                    MainGame.dm.Projectiles[i].Destroy();
                    ouchTimer = 10;
                }
            }
        }

        public override void UpdateCollisionBox()
        {
            collisionBox.Left = (int)Pos.X - 9;
            collisionBox.Top = (int)Pos.Y - 55;
            collisionBox.Width = 18;
            collisionBox.Height = 55;

            base.UpdateCollisionBox();
        }

        public void HandleDeath()
        {
            if (Alive)
            {
                if (Health <= 0)
                {
                    Alive = false;
                    for (int i = 0; i < MainGame.gibCount; i++)
                    {
                        int gibNum = MainGame.rand.Next(1, 4);
                        Gib g = new Gib(new Texture(Content.GetTexture("gib" + gibNum + ".png")), Core - new Vector2f(0, 4) +
                            new Vector2f(MainGame.rand.Next(-4, 5), MainGame.rand.Next(-4, 5)), (float)MainGame.rand.NextDouble() * 4.5f,
                            Helper.angleBetween(Core, Core - new Vector2f(0, 4)) + (float)Math.PI + (float)(i - 5 / 10f) + (float)MainGame.rand.NextDouble());
                        g.addVel = new Vector2f(Velocity.X / 15, Velocity.Y / 35); //Trauma
                        MainGame.dm.GameObjects.Add(g);
                    }

                    MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibHead.png")), Core - new Vector2f(0, 4), 3,
                        Helper.angleBetween(Core, Core - new Vector2f(0, 4)) + (float)Math.PI));

                    MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibBody.png")), Core - new Vector2f(0, 1), 2,
                        Helper.angleBetween(Core, Core - new Vector2f(1, 2)) + (float)Math.PI));

                    MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibUpperLeg.png")), Core + new Vector2f(0, 1), 3.2f,
                        Helper.angleBetween(Core, Core - new Vector2f(.5f, 1)) + (float)Math.PI));

                    MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibUpperLeg.png")), Core + new Vector2f(0, 1), 3.2f,
                        Helper.angleBetween(Core, Core - new Vector2f(-.5f, 1)) + (float)Math.PI));

                    MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibLowerLeg.png")), Core + new Vector2f(0, 1), 3.2f,
                        Helper.angleBetween(Core, Core - new Vector2f(.15f, 3)) + (float)Math.PI));

                    MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibLowerLeg.png")), Core + new Vector2f(0, 1), 3.2f,
                        Helper.angleBetween(Core, Core - new Vector2f(-.20f, 2)) + (float)Math.PI));

                    MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibArm.png")), Core + new Vector2f(0, 1), 3.2f,
                        Helper.angleBetween(Core, Core - new Vector2f(.04f, 3)) + (float)Math.PI));

                    MainGame.dm.GameObjects.Add(new Gib(new Texture(Content.GetTexture("gibArm.png")), Core + new Vector2f(0, 1), 3.2f,
                        Helper.angleBetween(Core, Core - new Vector2f(-.55f, 2)) + (float)Math.PI));
                }
            }
        }

        public void HandleAnimationSetting()
        {
            OnGround = false;
            if (dm.MapCollide((int)this.Pos.X, (int)this.Pos.Y + 1, CollideTypes.HardOrSoft))
                OnGround = true;
            animPadding--;

            if (animPadding <= -5)
            {
                //if (Helper.Distance(oldPosition,Pos) < 2)
                animation = idle;
                if (OnGround) //On Ground
                {
                    if (Facing == 1)
                    {
                        if (oldPosition.X - Pos.X < -.2f)
                        {
                            animation = running;
                            animPadding = 5;
                        }
                        if (oldPosition.X - Pos.X > .2f)
                        {
                            animation = backpedal;
                            animPadding = 5;
                        }

                    }
                    if (Facing == -1)
                    {
                        if (oldPosition.X - Pos.X < -.2f)
                        {
                            animation = backpedal;
                            animPadding = 5;
                        }
                        if (oldPosition.X - Pos.X > .2f)
                        {
                            animation = running;
                            animPadding = 5;
                        }

                    }
                }
                if (!OnGround) // Not on Ground
                {
                    if ((oldPosition.Y - Pos.Y) > 2)
                    {
                        animation = jumpUp;
                        animPadding = 5;
                    }
                    if ((oldPosition.Y - Pos.Y) < 2)
                    {
                        animation = jumpDown;
                        animPadding = 5;
                    }
                }
            }
        }

        public override void OnProjectileHit(Projectile hit)
        {
            hit.Destroy();
            //Probably wont do anything
            base.OnProjectileHit(hit);
        }

        public void UpdateToCurrentModel()
        {
            idle = new Animation(Content.GetTexture(model.idleFile), 4, 120, 1);
            running = new Animation(Content.GetTexture(model.runFile), 6, 60, 2);
            backpedal = new Animation(Content.GetTexture(model.runFile), 6, 60, 2, false);
            jumpUp = new Animation(Content.GetTexture(model.jumpUpFile), 1, 60, 0);
            jumpDown = new Animation(Content.GetTexture(model.jumpDownFile), 3, 60, -5);
        }
    }
}


text:
<?php

namespace Payum\Paypal\ProHosted\Nvp\Action\Api;

use ArrayAccess;
use Payum\Core\Action\ActionInterface;
use Payum\Core\ApiAwareInterface;
use Payum\Core\ApiAwareTrait;
use Payum\Core\Bridge\Spl\ArrayObject;
use Payum\Core\Exception\LogicException;
use Payum\Core\Exception\RequestNotSupportedException;
use Payum\Paypal\ProHosted\Nvp\Api;
use Payum\Paypal\ProHosted\Nvp\Request\Api\GetTransactionDetails;

class GetTransactionDetailsAction implements ActionInterface, ApiAwareInterface
{
    use ApiAwareTrait;

    public function __construct()
    {
        $this->apiClass = Api::class;
    }

    public function execute($request)
    {
        /** @var GetTransactionDetails $request */
        RequestNotSupportedException::assertSupports($this, $request);
        $model = ArrayObject::ensureArrayObject($request->getModel());

        if (null == $model['txn_id']) {
            throw new LogicException('TRANSACTIONID must be set.');
        }

        $fields = new ArrayObject([]);

        $fields['TRANSACTIONID'] = $model['txn_id'];

        $result = $this->api->getTransactionDetails((array) $fields);

        $model->replace($result);
    }

    public function supports($request)
    {
        return $request instanceof GetTransactionDetails &&
            $request->getModel() instanceof ArrayAccess;
    }
}


text:
var webpack = require('webpack');
var path = require('path');

module.exports = {

  entry: [
  'webpack-dev-server/client?http://localhost:9090',
  'webpack/hot/only-dev-server',
  './src/app'
  ],

  output: {
    path:       __dirname + '/build/',
    filename:   'app.js',
    publicPath: 'http://localhost:9090/build/'
  },

  module: {
    loaders: [
      { test: path.join(__dirname, 'src'), loaders: ['react-hot', 'babel-loader']}
    ]
  },

  resolve: {
    extensions: ['', '.js', '.jsx']
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ]
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
    public class SynthesizedStaticConstructorTests : CompilingTestBase
    {
        [Fact]
        public void NoStaticMembers()
        {
            var source = @"
class C
{
    int i1;
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);
            Assert.False(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.True(IsBeforeFieldInit(typeSymbol));
        }

        [Fact]
        public void NoStaticFields()
        {
            var source = @"
class C
{
    int i1;

    static void Goo() { }
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);
            Assert.False(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.True(IsBeforeFieldInit(typeSymbol));
        }

        [Fact]
        public void NoStaticInitializers()
        {
            var source = @"
class C
{
    int i1;
    static int s1;

    static void Goo() { }
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);
            Assert.False(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.True(IsBeforeFieldInit(typeSymbol));
        }

        [Fact]
        public void StaticInitializers()
        {
            var source = @"
class C
{
    int i1;
    static int s1 = 1;

    static void Goo() { }
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);
            Assert.True(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.True(IsBeforeFieldInit(typeSymbol));
        }

        [Fact]
        public void ConstantInitializers()
        {
            var source = @"
class C
{
    int i1;
    const int s1 = 1;

    static void Goo() { }
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);
            Assert.False(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.True(IsBeforeFieldInit(typeSymbol));
        }

        [Fact]
        public void SourceStaticConstructorNoStaticMembers()
        {
            var source = @"
class C
{
    static C() { }

    int i1;
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);
            Assert.False(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.False(IsBeforeFieldInit(typeSymbol));
        }

        [Fact]
        public void SourceStaticConstructorNoStaticFields()
        {
            var source = @"
class C
{
    static C() { }

    int i1;

    static void Goo() { }
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);
            Assert.False(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.False(IsBeforeFieldInit(typeSymbol));
        }

        [Fact]
        public void SourceStaticConstructorNoStaticInitializers()
        {
            var source = @"
class C
{
    static C() { }

    int i1;
    static int s1;

    static void Goo() { }
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);
            Assert.False(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.False(IsBeforeFieldInit(typeSymbol));
        }

        [Fact]
        public void SourceStaticConstructorStaticInitializers()
        {
            var source = @"
class C
{
    static C() { }

    int i1;
    static int s1 = 1;

    static void Goo() { }
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);
            Assert.False(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.False(IsBeforeFieldInit(typeSymbol));
        }

        [Fact]
        public void SourceStaticConstructorConstantInitializers()
        {
            var source = @"
class C
{
    static C() { }

    int i1;
    const int s1 = 1;

    static void Goo() { }
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);
            Assert.False(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.False(IsBeforeFieldInit(typeSymbol));
        }

        [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")]
        [Fact]
        public void SourceStaticConstructorConstantInitializersDecimal01()
        {
            var source = @"
class C
{
    const decimal dec1 = 12345;
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);
            Assert.False(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.True(IsBeforeFieldInit(typeSymbol));
        }

        [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")]
        [Fact]
        public void SourceStaticConstructorConstantInitializersDecimal02()
        {
            var source = @"
class C
{
    static C() { }

    const decimal dec1 = 12345;
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);
            Assert.False(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.False(IsBeforeFieldInit(typeSymbol));
        }

        [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")]
        [Fact]
        public void SourceStaticConstructorConstantInitializersDecimal03()
        {
            var source = @"
class C
{
    decimal dec1 = 12345;
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);
            Assert.False(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.True(IsBeforeFieldInit(typeSymbol));
        }

        [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")]
        [Fact]
        public void SourceStaticConstructorConstantInitializersDecimal04()
        {
            var source = @"
class C
{
    static C() { }

    decimal dec1 = 12345;
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);
            Assert.False(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.False(IsBeforeFieldInit(typeSymbol));
        }

        [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")]
        [Fact]
        public void SourceStaticConstructorConstantInitializersDecimal05()
        {
            var source = @"
class C
{
    static int s1 = 1;
    const decimal dec1 = 12345;
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);
            Assert.True(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.True(IsBeforeFieldInit(typeSymbol));
        }

        [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")]
        [Fact]
        public void StaticConstructorNullInitializer()
        {
            var source = @"
#nullable enable
class C
{
    static string s1 = null!;
}";

            var typeSymbol = CompileAndExtractTypeSymbol(source);

            // Although we do not emit the synthesized static constructor, the source type symbol will still appear to have one
            Assert.True(HasSynthesizedStaticConstructor(typeSymbol));
            Assert.True(IsBeforeFieldInit(typeSymbol));
        }

        private static SourceNamedTypeSymbol CompileAndExtractTypeSymbol(string source)
        {
            var compilation = CreateCompilation(source);
            var typeSymbol = (SourceNamedTypeSymbol)compilation.GlobalNamespace.GetMembers("C").Single();
            return typeSymbol;
        }

        private static bool HasSynthesizedStaticConstructor(NamedTypeSymbol typeSymbol)
        {
            foreach (var member in typeSymbol.GetMembers(WellKnownMemberNames.StaticConstructorName))
            {
                if (member.IsImplicitlyDeclared)
                {
                    return true;
                }
            }
            return false;
        }

        private static bool IsBeforeFieldInit(NamedTypeSymbol typeSymbol)
        {
            return ((Microsoft.Cci.ITypeDefinition)typeSymbol).IsBeforeFieldInit;
        }
    }
}


text:
package main

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"os"
	"strings"

	"golang.org/x/crypto/bcrypt"

	"github.com/dexidp/dex/pkg/log"
	"github.com/dexidp/dex/server"
	"github.com/dexidp/dex/storage"
	"github.com/dexidp/dex/storage/etcd"
	"github.com/dexidp/dex/storage/kubernetes"
	"github.com/dexidp/dex/storage/memory"
	"github.com/dexidp/dex/storage/sql"
)

// Config is the config format for the main application.
type Config struct {
	Issuer    string    `json:"issuer"`
	Storage   Storage   `json:"storage"`
	Web       Web       `json:"web"`
	Telemetry Telemetry `json:"telemetry"`
	OAuth2    OAuth2    `json:"oauth2"`
	GRPC      GRPC      `json:"grpc"`
	Expiry    Expiry    `json:"expiry"`
	Logger    Logger    `json:"logger"`

	Frontend server.WebConfig `json:"frontend"`

	// StaticConnectors are user defined connectors specified in the ConfigMap
	// Write operations, like updating a connector, will fail.
	StaticConnectors []Connector `json:"connectors"`

	// StaticClients cause the server to use this list of clients rather than
	// querying the storage. Write operations, like creating a client, will fail.
	StaticClients []storage.Client `json:"staticClients"`

	// If enabled, the server will maintain a list of passwords which can be used
	// to identify a user.
	EnablePasswordDB bool `json:"enablePasswordDB"`

	// StaticPasswords cause the server use this list of passwords rather than
	// querying the storage. Cannot be specified without enabling a passwords
	// database.
	StaticPasswords []password `json:"staticPasswords"`
}

//Validate the configuration
func (c Config) Validate() error {
	// Fast checks. Perform these first for a more responsive CLI.
	checks := []struct {
		bad    bool
		errMsg string
	}{
		{c.Issuer == "", "no issuer specified in config file"},
		{!c.EnablePasswordDB && len(c.StaticPasswords) != 0, "cannot specify static passwords without enabling password db"},
		{c.Storage.Config == nil, "no storage supplied in config file"},
		{c.Web.HTTP == "" && c.Web.HTTPS == "", "must supply a HTTP/HTTPS  address to listen on"},
		{c.Web.HTTPS != "" && c.Web.TLSCert == "", "no cert specified for HTTPS"},
		{c.Web.HTTPS != "" && c.Web.TLSKey == "", "no private key specified for HTTPS"},
		{c.GRPC.TLSCert != "" && c.GRPC.Addr == "", "no address specified for gRPC"},
		{c.GRPC.TLSKey != "" && c.GRPC.Addr == "", "no address specified for gRPC"},
		{(c.GRPC.TLSCert == "") != (c.GRPC.TLSKey == ""), "must specific both a gRPC TLS cert and key"},
		{c.GRPC.TLSCert == "" && c.GRPC.TLSClientCA != "", "cannot specify gRPC TLS client CA without a gRPC TLS cert"},
	}

	var checkErrors []string

	for _, check := range checks {
		if check.bad {
			checkErrors = append(checkErrors, check.errMsg)
		}
	}
	if len(checkErrors) != 0 {
		return fmt.Errorf("invalid Config:\n\t-\t%s", strings.Join(checkErrors, "\n\t-\t"))
	}
	return nil
}

type password storage.Password

func (p *password) UnmarshalJSON(b []byte) error {
	var data struct {
		Email       string `json:"email"`
		Username    string `json:"username"`
		UserID      string `json:"userID"`
		Hash        string `json:"hash"`
		HashFromEnv string `json:"hashFromEnv"`
	}
	if err := json.Unmarshal(b, &data); err != nil {
		return err
	}
	*p = password(storage.Password{
		Email:    data.Email,
		Username: data.Username,
		UserID:   data.UserID,
	})
	if len(data.Hash) == 0 && len(data.HashFromEnv) > 0 {
		data.Hash = os.Getenv(data.HashFromEnv)
	}
	if len(data.Hash) == 0 {
		return fmt.Errorf("no password hash provided")
	}

	// If this value is a valid bcrypt, use it.
	_, bcryptErr := bcrypt.Cost([]byte(data.Hash))
	if bcryptErr == nil {
		p.Hash = []byte(data.Hash)
		return nil
	}

	// For backwards compatibility try to base64 decode this value.
	hashBytes, err := base64.StdEncoding.DecodeString(data.Hash)
	if err != nil {
		return fmt.Errorf("malformed bcrypt hash: %v", bcryptErr)
	}
	if _, err := bcrypt.Cost(hashBytes); err != nil {
		return fmt.Errorf("malformed bcrypt hash: %v", err)
	}
	p.Hash = hashBytes
	return nil
}

// OAuth2 describes enabled OAuth2 extensions.
type OAuth2 struct {
	ResponseTypes []string `json:"responseTypes"`
	// If specified, do not prompt the user to approve client authorization. The
	// act of logging in implies authorization.
	SkipApprovalScreen bool `json:"skipApprovalScreen"`
	// If specified, show the connector selection screen even if there's only one
	AlwaysShowLoginScreen bool `json:"alwaysShowLoginScreen"`
	// This is the connector that can be used for password grant
	PasswordConnector string `json:"passwordConnector"`
}

// Web is the config format for the HTTP server.
type Web struct {
	HTTP           string   `json:"http"`
	HTTPS          string   `json:"https"`
	TLSCert        string   `json:"tlsCert"`
	TLSKey         string   `json:"tlsKey"`
	AllowedOrigins []string `json:"allowedOrigins"`
}

// Telemetry is the config format for telemetry including the HTTP server config.
type Telemetry struct {
	HTTP string `json:"http"`
}

// GRPC is the config for the gRPC API.
type GRPC struct {
	// The port to listen on.
	Addr        string `json:"addr"`
	TLSCert     string `json:"tlsCert"`
	TLSKey      string `json:"tlsKey"`
	TLSClientCA string `json:"tlsClientCA"`
	Reflection  bool   `json:"reflection"`
}

// Storage holds app's storage configuration.
type Storage struct {
	Type   string        `json:"type"`
	Config StorageConfig `json:"config"`
}

// StorageConfig is a configuration that can create a storage.
type StorageConfig interface {
	Open(logger log.Logger) (storage.Storage, error)
}

var storages = map[string]func() StorageConfig{
	"etcd":       func() StorageConfig { return new(etcd.Etcd) },
	"kubernetes": func() StorageConfig { return new(kubernetes.Config) },
	"memory":     func() StorageConfig { return new(memory.Config) },
	"sqlite3":    func() StorageConfig { return new(sql.SQLite3) },
	"postgres":   func() StorageConfig { return new(sql.Postgres) },
	"mysql":      func() StorageConfig { return new(sql.MySQL) },
}

// UnmarshalJSON allows Storage to implement the unmarshaler interface to
// dynamically determine the type of the storage config.
func (s *Storage) UnmarshalJSON(b []byte) error {
	var store struct {
		Type   string          `json:"type"`
		Config json.RawMessage `json:"config"`
	}
	if err := json.Unmarshal(b, &store); err != nil {
		return fmt.Errorf("parse storage: %v", err)
	}
	f, ok := storages[store.Type]
	if !ok {
		return fmt.Errorf("unknown storage type %q", store.Type)
	}

	storageConfig := f()
	if len(store.Config) != 0 {
		data := []byte(os.ExpandEnv(string(store.Config)))
		if err := json.Unmarshal(data, storageConfig); err != nil {
			return fmt.Errorf("parse storage config: %v", err)
		}
	}
	*s = Storage{
		Type:   store.Type,
		Config: storageConfig,
	}
	return nil
}

// Connector is a magical type that can unmarshal YAML dynamically. The
// Type field determines the connector type, which is then customized for Config.
type Connector struct {
	Type string `json:"type"`
	Name string `json:"name"`
	ID   string `json:"id"`

	Config server.ConnectorConfig `json:"config"`
}

// UnmarshalJSON allows Connector to implement the unmarshaler interface to
// dynamically determine the type of the connector config.
func (c *Connector) UnmarshalJSON(b []byte) error {
	var conn struct {
		Type string `json:"type"`
		Name string `json:"name"`
		ID   string `json:"id"`

		Config json.RawMessage `json:"config"`
	}
	if err := json.Unmarshal(b, &conn); err != nil {
		return fmt.Errorf("parse connector: %v", err)
	}
	f, ok := server.ConnectorsConfig[conn.Type]
	if !ok {
		return fmt.Errorf("unknown connector type %q", conn.Type)
	}

	connConfig := f()
	if len(conn.Config) != 0 {
		data := []byte(os.ExpandEnv(string(conn.Config)))
		if err := json.Unmarshal(data, connConfig); err != nil {
			return fmt.Errorf("parse connector config: %v", err)
		}
	}
	*c = Connector{
		Type:   conn.Type,
		Name:   conn.Name,
		ID:     conn.ID,
		Config: connConfig,
	}
	return nil
}

// ToStorageConnector converts an object to storage connector type.
func ToStorageConnector(c Connector) (storage.Connector, error) {
	data, err := json.Marshal(c.Config)
	if err != nil {
		return storage.Connector{}, fmt.Errorf("failed to marshal connector config: %v", err)
	}

	return storage.Connector{
		ID:     c.ID,
		Type:   c.Type,
		Name:   c.Name,
		Config: data,
	}, nil
}

// Expiry holds configuration for the validity period of components.
type Expiry struct {
	// SigningKeys defines the duration of time after which the SigningKeys will be rotated.
	SigningKeys string `json:"signingKeys"`

	// IdTokens defines the duration of time for which the IdTokens will be valid.
	IDTokens string `json:"idTokens"`

	// AuthRequests defines the duration of time for which the AuthRequests will be valid.
	AuthRequests string `json:"authRequests"`
}

// Logger holds configuration required to customize logging for dex.
type Logger struct {
	// Level sets logging level severity.
	Level string `json:"level"`

	// Format specifies the format to be used for logging.
	Format string `json:"format"`
}