text:
(function () {
  'use strict';
  angular
    .module('com.module.users')
    .service('UserService', function ($state, CoreService, User, gettextCatalog) {

      this.find = function () {
        return User.find().$promise;
      };

      this.findById = function (id) {
        return User.findById({
          id: id
        }).$promise;
      };

      this.upsert = function (user) {
        return User.upsert(user).$promise
          .then(function () {
            CoreService.toastSuccess(
              gettextCatalog.getString('User saved'),
              gettextCatalog.getString('Your user is safe with us!')
            );
          })
          .catch(function (err) {
            CoreService.toastError(
              gettextCatalog.getString('Error saving user '),
              gettextCatalog.getString('This user could no be saved: ' + err)
            );
          }
        );
      };

      this.delete = function (id, successCb, cancelCb) {
        CoreService.confirm(
          gettextCatalog.getString('Are you sure?'),
          gettextCatalog.getString('Deleting this cannot be undone'),
          function () {
            User.deleteById({id: id}, function () {
              CoreService.toastSuccess(
                gettextCatalog.getString('User deleted'),
                gettextCatalog.getString('Your user is deleted!'));
              successCb();
            }, function (err) {
              CoreService.toastError(
                gettextCatalog.getString('Error deleting user'),
                gettextCatalog.getString('Your user is not deleted! ') + err);
              cancelCb();
            });
          },
          function () {
            cancelCb();
          }
        );
      };

      this.getFormFields = function (formType) {
        var form = [
          {
            key: 'username',
            type: 'input',
            templateOptions: {
              label: gettextCatalog.getString('Username'),
              required: true
            }
          },
          {
            key: 'email',
            type: 'input',
            templateOptions: {
              label: gettextCatalog.getString('Email'),
              required: true
            }
          },
          {
            key: 'firstName',
            type: 'input',
            templateOptions: {
              label: gettextCatalog.getString('Last name'),
              required: true
            }
          },
          {
            key: 'lastName',
            type: 'input',
            templateOptions: {
              label: gettextCatalog.getString('Last name'),
              required: true
            }
          }
        ];
        if (formType === 'add') {
          form.push({
            key: 'password',
            type: 'input',
            templateOptions: {
              label: gettextCatalog.getString('Password'),
              required: true
            }
          });
        }
        if (formType === 'password') {
          form = [
            {
              key: 'password',
              type: 'input',
              templateOptions: {
                label: gettextCatalog.getString('New Password'),
                required: true
              }
            },
            {
              key: 'repassword',
              type: 'input',
              templateOptions: {
                label: gettextCatalog.getString('Re-Enter Password'),
                required: true
              },
              "expressionProperties": {
                "templateOptions.disabled": "!model.password"
              }
            },
          ]
        }
        return form;
      };

    });

})();


text:
puppet-stumpwm
==============

Puppet Stumpwm Module

redpajama_set_name: RedPajamaGithub


text:
define({
  "visible": "Vis oversiktskart som standard",
  "minWidth": "Min. bredde",
  "minHeight": "Min. høyde",
  "maxWidth": "Maks. bredde",
  "maxHeight": "Maks. høyde",
  "minText": "Minimum",
  "maxText": "maksimum",
  "attachText": "Angi i hvilket hjørne av kartet denne widgeten skal legges til i.",
  "expandText": "Utvid widgteten fra start",
  "topLeft": "Øvre venstre",
  "topRight": "Øvre høyre",
  "bottomLeft": "Nedre venstre",
  "bottomRight": "Nedre høyre"
});


text:
using LiteDB.Engine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace LiteDB
{
    public class SharedDataReader : IBsonDataReader
    {
        private readonly IBsonDataReader _reader;
        private readonly Action _dispose;

        private bool _disposed = false;

        public SharedDataReader(IBsonDataReader reader, Action dispose)
        {
            _reader = reader;
            _dispose = dispose;
        }

        public BsonValue this[string field] => _reader[field];

        public string Collection => _reader.Collection;

        public BsonValue Current => _reader.Current;

        public bool HasValues => _reader.HasValues;

        public bool Read() => _reader.Read();

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~SharedDataReader()
        {
            this.Dispose(false);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed) return;

            _disposed = true;

            if (disposing)
            {
                _reader.Dispose();
                _dispose();
            }
        }
    }
}


text:
var _ = require('lodash');

var COMMENT_START = /^\s*\/\*\*/,
  COMMENT_END = /^\s*\*\//;

/**
 * This service reads LESS files and extract jsdoc styles comments.
 * It doesn't parse tags inside comments.
 */
module.exports = function lessFileReader(log) {
  return {
    name: 'lessFileReader',
    defaultPattern: /\.less$/,
    getDocs: function(fileInfo) {
      var isComment = false;
      var commentLines = String(fileInfo.content)
        .trim()
        .replace(/\r\n|\r|\n *\n/g, '\n')
        .split('\n');

      /**
       * Reduce lines to comment blocks
       */
      fileInfo.comments = _.reduce(commentLines, function (commentBlocks, commentLine) {
        if (COMMENT_START.test(commentLine)) {
          isComment = true;
          commentBlocks.push(['*']);
          return commentBlocks;
        }
        if (isComment) {
          if (COMMENT_END.test(commentLine)) {
            commentBlocks[commentBlocks.length - 1].push('*');
            isComment = false;
          } else {
            commentBlocks[commentBlocks.length - 1].push(commentLine);
          }
        }
        return commentBlocks;
      }, []).map(function (block) {
        return {
          type: 'Block',
          value: block.join('\n')
        };
      });

      return [{
        docType: 'lessFile'
      }];
    }
  };
};


text:
'use strict';

var gulp = require('gulp'),
    less = require('gulp-less'),
    livereload = require('gulp-livereload'),
    http = require('http'),
    st = require('st');

gulp.task('less', function() {
  gulp.src('app/styles/*.less')
    .pipe(less())
    .pipe(gulp.dest('dist/styles'))
    .pipe(livereload());
});

gulp.task('watch', ['server'], function() {
  livereload.listen({ basePath: 'dist' });
  gulp.watch('less/*.less', ['less']);
});

gulp.task('server', function(done) {
  http.createServer(
    st({ path: __dirname + '/dist', index: 'index.html', cache: false })
  ).listen(8080, done);
});


text:
<?php

namespace OPNsense\Base\FieldTypes;

use OPNsense\Base\Validators\NetworkValidator;
use OPNsense\Base\Validators\HostValidator;

/**
 * @package OPNsense\Base\FieldTypes
 */
class HostnameField extends BaseField
{
    /**
     * @var bool marks if this is a data node or a container
     */
    protected $internalIsContainer = false;

    /**
     * @var string default validation message string
     */
    protected $internalValidationMessage = "please specify a valid address (IPv4/IPv6) or hostname";

    /**
     * @var null when multiple values could be provided at once, specify the split character
     */
    protected $internalFieldSeparator = null;

    /**
     * @var bool when set, results are returned as list (with all options enabled)
     */
    private $internalAsList = false;

    /**
     * @var bool IP address allowed
     */
    protected $internalIpAllowed = true;

    /**
     * @var bool wildcard (*) enabled
     */
    protected $internalHostWildcardAllowed = false;

    /**
     * @var bool wildcard (*.my.top.level.domain) enabled
     */
    protected $internalFqdnWildcardAllowed = false;

    /**
     * @var bool zone root (@) enabled
     */
    protected $internalZoneRootAllowed = false;

    /**
     * ip addresses allowed
     * @param string $value Y/N
     */
    public function setIpAllowed($value)
    {
        $this->internalIpAllowed = trim(strtoupper($value)) == "Y";
    }

    /**
     * host wildcard (*) allowed
     * @param string $value Y/N
     */
    public function setHostWildcardAllowed($value)
    {
        $this->internalHostWildcardAllowed = trim(strtoupper($value)) == "Y";
    }

    /**
     * fqdn (prefix) wildcard (*.my.top.level.domain) allowed
     * @param string $value Y/N
     */
    public function setFqdnWildcardAllowed($value)
    {
        $this->internalFqdnWildcardAllowed = trim(strtoupper($value)) == "Y";
    }

    /**
     * zone root (@) allowed
     * @param string $value Y/N
     */
    public function setZoneRootAllowed($value)
    {
        $this->internalZoneRootAllowed = trim(strtoupper($value)) == "Y";
    }

    /**
     * always trim hostnames
     * @param string $value
     */
    public function setValue($value)
    {
        parent::setValue(trim($value));
    }

    /**
     * if multiple hostnames maybe provided at once, set separator.
     * @param string $value separator
     */
    public function setFieldSeparator($value)
    {
        $this->internalFieldSeparator = $value;
    }

    /**
     * select if multiple hostnames may be selected at once
     * @param $value boolean value 0/1
     */
    public function setAsList($value)
    {
        $this->internalAsList = trim(strtoupper($value)) == "Y";
    }

    /**
     * get valid options, descriptions and selected value
     * @return array
     */
    public function getNodeData()
    {
        if ($this->internalAsList) {
            // return result as list
            $result = [];
            foreach (explode(',', $this->internalValue) as $net) {
                $result[$net] = array("value" => $net, "selected" => 1);
            }
            return $result;
        } else {
            // normal, single field response
            return $this->internalValue;
        }
    }

    /**
     * retrieve field validators for this field type
     * @return array returns Text/regex validator
     */
    public function getValidators()
    {
        $validators = parent::getValidators();
        if ($this->internalValue != null) {
            $validators[] = new HostValidator(array(
                'message' => $this->internalValidationMessage,
                'split' => $this->internalFieldSeparator,
                'allowip' => $this->internalIpAllowed,
                'hostwildcard' => $this->internalHostWildcardAllowed,
                'fqdnwildcard' => $this->internalFqdnWildcardAllowed,
                'zoneroot' => $this->internalZoneRootAllowed
            ));
        }
        return $validators;
    }
}


text:
require 'spec_helper'

describe 'Turbine::VERSION' do
  it { expect(Turbine::VERSION).to be_a(String) }
end


text:
#pragma once
#include <aws/polly/Polly_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/polly/model/LanguageCode.h>
#include <aws/core/utils/DateTime.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace Polly
{
namespace Model
{

  /**
   *
Contains metadata describing the lexicon such as the number of lexemes,
   * language code, and so on. For more information, see Managing
   * Lexicons.

See Also:
   AWS
   * API Reference

   */
  class AWS_POLLY_API LexiconAttributes
  {
  public:
    LexiconAttributes();
    LexiconAttributes(const Aws::Utils::Json::JsonValue& jsonValue);
    LexiconAttributes& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
Phonetic alphabet used in the lexicon. Valid values are ipa and
     * x-sampa.

     */
    inline const Aws::String& GetAlphabet() const{ return m_alphabet; }

    /**
     *
Phonetic alphabet used in the lexicon. Valid values are ipa and
     * x-sampa.

     */
    inline void SetAlphabet(const Aws::String& value) { m_alphabetHasBeenSet = true; m_alphabet = value; }

    /**
     *
Phonetic alphabet used in the lexicon. Valid values are ipa and
     * x-sampa.

     */
    inline void SetAlphabet(Aws::String&& value) { m_alphabetHasBeenSet = true; m_alphabet = std::move(value); }

    /**
     *
Phonetic alphabet used in the lexicon. Valid values are ipa and
     * x-sampa.

     */
    inline void SetAlphabet(const char* value) { m_alphabetHasBeenSet = true; m_alphabet.assign(value); }

    /**
     *
Phonetic alphabet used in the lexicon. Valid values are ipa and
     * x-sampa.

     */
    inline LexiconAttributes& WithAlphabet(const Aws::String& value) { SetAlphabet(value); return *this;}

    /**
     *
Phonetic alphabet used in the lexicon. Valid values are ipa and
     * x-sampa.

     */
    inline LexiconAttributes& WithAlphabet(Aws::String&& value) { SetAlphabet(std::move(value)); return *this;}

    /**
     *
Phonetic alphabet used in the lexicon. Valid values are ipa and
     * x-sampa.

     */
    inline LexiconAttributes& WithAlphabet(const char* value) { SetAlphabet(value); return *this;}

    /**
     *
Language code that the lexicon applies to. A lexicon with a language code
     * such as "en" would be applied to all English languages (en-GB, en-US, en-AUS,
     * en-WLS, and so on.

     */
    inline const LanguageCode& GetLanguageCode() const{ return m_languageCode; }

    /**
     *
Language code that the lexicon applies to. A lexicon with a language code
     * such as "en" would be applied to all English languages (en-GB, en-US, en-AUS,
     * en-WLS, and so on.

     */
    inline void SetLanguageCode(const LanguageCode& value) { m_languageCodeHasBeenSet = true; m_languageCode = value; }

    /**
     *
Language code that the lexicon applies to. A lexicon with a language code
     * such as "en" would be applied to all English languages (en-GB, en-US, en-AUS,
     * en-WLS, and so on.

     */
    inline void SetLanguageCode(LanguageCode&& value) { m_languageCodeHasBeenSet = true; m_languageCode = std::move(value); }

    /**
     *
Language code that the lexicon applies to. A lexicon with a language code
     * such as "en" would be applied to all English languages (en-GB, en-US, en-AUS,
     * en-WLS, and so on.

     */
    inline LexiconAttributes& WithLanguageCode(const LanguageCode& value) { SetLanguageCode(value); return *this;}

    /**
     *
Language code that the lexicon applies to. A lexicon with a language code
     * such as "en" would be applied to all English languages (en-GB, en-US, en-AUS,
     * en-WLS, and so on.

     */
    inline LexiconAttributes& WithLanguageCode(LanguageCode&& value) { SetLanguageCode(std::move(value)); return *this;}

    /**
     *
Date lexicon was last modified (a timestamp value).

     */
    inline const Aws::Utils::DateTime& GetLastModified() const{ return m_lastModified; }

    /**
     *
Date lexicon was last modified (a timestamp value).

     */
    inline void SetLastModified(const Aws::Utils::DateTime& value) { m_lastModifiedHasBeenSet = true; m_lastModified = value; }

    /**
     *
Date lexicon was last modified (a timestamp value).

     */
    inline void SetLastModified(Aws::Utils::DateTime&& value) { m_lastModifiedHasBeenSet = true; m_lastModified = std::move(value); }

    /**
     *
Date lexicon was last modified (a timestamp value).

     */
    inline LexiconAttributes& WithLastModified(const Aws::Utils::DateTime& value) { SetLastModified(value); return *this;}

    /**
     *
Date lexicon was last modified (a timestamp value).

     */
    inline LexiconAttributes& WithLastModified(Aws::Utils::DateTime&& value) { SetLastModified(std::move(value)); return *this;}

    /**
     *
Amazon Resource Name (ARN) of the lexicon.

     */
    inline const Aws::String& GetLexiconArn() const{ return m_lexiconArn; }

    /**
     *
Amazon Resource Name (ARN) of the lexicon.

     */
    inline void SetLexiconArn(const Aws::String& value) { m_lexiconArnHasBeenSet = true; m_lexiconArn = value; }

    /**
     *
Amazon Resource Name (ARN) of the lexicon.

     */
    inline void SetLexiconArn(Aws::String&& value) { m_lexiconArnHasBeenSet = true; m_lexiconArn = std::move(value); }

    /**
     *
Amazon Resource Name (ARN) of the lexicon.

     */
    inline void SetLexiconArn(const char* value) { m_lexiconArnHasBeenSet = true; m_lexiconArn.assign(value); }

    /**
     *
Amazon Resource Name (ARN) of the lexicon.

     */
    inline LexiconAttributes& WithLexiconArn(const Aws::String& value) { SetLexiconArn(value); return *this;}

    /**
     *
Amazon Resource Name (ARN) of the lexicon.

     */
    inline LexiconAttributes& WithLexiconArn(Aws::String&& value) { SetLexiconArn(std::move(value)); return *this;}

    /**
     *
Amazon Resource Name (ARN) of the lexicon.

     */
    inline LexiconAttributes& WithLexiconArn(const char* value) { SetLexiconArn(value); return *this;}

    /**
     *
Number of lexemes in the lexicon.

     */
    inline int GetLexemesCount() const{ return m_lexemesCount; }

    /**
     *
Number of lexemes in the lexicon.

     */
    inline void SetLexemesCount(int value) { m_lexemesCountHasBeenSet = true; m_lexemesCount = value; }

    /**
     *
Number of lexemes in the lexicon.

     */
    inline LexiconAttributes& WithLexemesCount(int value) { SetLexemesCount(value); return *this;}

    /**
     *
Total size of the lexicon, in characters.

     */
    inline int GetSize() const{ return m_size; }

    /**
     *
Total size of the lexicon, in characters.

     */
    inline void SetSize(int value) { m_sizeHasBeenSet = true; m_size = value; }

    /**
     *
Total size of the lexicon, in characters.

     */
    inline LexiconAttributes& WithSize(int value) { SetSize(value); return *this;}

  private:
    Aws::String m_alphabet;
    bool m_alphabetHasBeenSet;
    LanguageCode m_languageCode;
    bool m_languageCodeHasBeenSet;
    Aws::Utils::DateTime m_lastModified;
    bool m_lastModifiedHasBeenSet;
    Aws::String m_lexiconArn;
    bool m_lexiconArnHasBeenSet;
    int m_lexemesCount;
    bool m_lexemesCountHasBeenSet;
    int m_size;
    bool m_sizeHasBeenSet;
  };

} // namespace Model
} // namespace Polly
} // namespace Aws


text:
package com.ibasco.agql.protocols.valve.steam.webapi.pojos;

import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 *
StoreAppPriceInfo class.

 *
 * @author Rafael Luis Ibasco
 */
public class StoreAppPriceInfo {

    private String currency;

    @SerializedName("initial")
    private int initialPrice;

    @SerializedName("final")
    private int finalPrice;

    @SerializedName("discount_percent")
    private int discountPercent;

    /** {@inheritDoc} */
    @Override
    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.NO_CLASS_NAME_STYLE)
                .append("currency", getCurrency())
                .append("initialPrice", getInitialPrice())
                .append("finalPrice", getFinalPrice())
                .append("discountPct", getDiscountPercent())
                .toString();
    }

    /**
     *
Getter for the field currency.

     *
     * @return a {@link java.lang.String} object
     */
    public String getCurrency() {
        return currency;
    }

    /**
     *
Setter for the field currency.

     *
     * @param currency
     *         a {@link java.lang.String} object
     */
    public void setCurrency(String currency) {
        this.currency = currency;
    }

    /**
     *
Getter for the field initialPrice.

     *
     * @return a int
     */
    public int getInitialPrice() {
        return initialPrice;
    }

    /**
     *
Setter for the field initialPrice.

     *
     * @param initialPrice
     *         a int
     */
    public void setInitialPrice(int initialPrice) {
        this.initialPrice = initialPrice;
    }

    /**
     *
Getter for the field finalPrice.

     *
     * @return a int
     */
    public int getFinalPrice() {
        return finalPrice;
    }

    /**
     *
Setter for the field finalPrice.

     *
     * @param finalPrice
     *         a int
     */
    public void setFinalPrice(int finalPrice) {
        this.finalPrice = finalPrice;
    }

    /**
     *
Getter for the field discountPercent.

     *
     * @return a int
     */
    public int getDiscountPercent() {
        return discountPercent;
    }

    /**
     *
Setter for the field discountPercent.

     *
     * @param discountPercent
     *         a int
     */
    public void setDiscountPercent(int discountPercent) {
        this.discountPercent = discountPercent;
    }
}


text:
class Test {
  StringBuilder test() {
      StringBuilder stringBuilder = new StringBuilder();
      stringBuilder.append("foo");
      stringBuilder.append("bar");
      return stringBuilder;
  }
}


text:
<?php

namespace Magento\CatalogSearch\Model\Adapter\Mysql\Aggregation;

use Magento\Catalog\Model\Product;
use Magento\Customer\Model\Session;
use Magento\Eav\Model\Config;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\App\ScopeResolverInterface;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\DB\Select;
use Magento\Framework\Search\Adapter\Mysql\Aggregation\DataProviderInterface;
use Magento\Framework\Search\Request\BucketInterface;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class DataProvider implements DataProviderInterface
{
    /**
     * @var Config
     */
    private $eavConfig;

    /**
     * @var Resource
     */
    private $resource;

    /**
     * @var ScopeResolverInterface
     */
    private $scopeResolver;

    /**
     * @var Session
     */
    private $customerSession;

    /**
     * @var AdapterInterface
     */
    private $connection;

    /**
     * @param Config $eavConfig
     * @param ResourceConnection $resource
     * @param ScopeResolverInterface $scopeResolver
     * @param Session $customerSession
     */
    public function __construct(
        Config $eavConfig,
        ResourceConnection $resource,
        ScopeResolverInterface $scopeResolver,
        Session $customerSession
    ) {
        $this->eavConfig = $eavConfig;
        $this->resource = $resource;
        $this->connection = $resource->getConnection();
        $this->scopeResolver = $scopeResolver;
        $this->customerSession = $customerSession;
    }

    /**
     * {@inheritdoc}
     */
    public function getDataSet(
        BucketInterface $bucket,
        array $dimensions,
        Table $entityIdsTable
    ) {
        $currentScope = $this->scopeResolver->getScope($dimensions['scope']->getValue())->getId();

        $attribute = $this->eavConfig->getAttribute(Product::ENTITY, $bucket->getField());

        $select = $this->getSelect();

        if ($attribute->getAttributeCode() == 'price') {
            /** @var \Magento\Store\Model\Store $store */
            $store = $this->scopeResolver->getScope($currentScope);
            if (!$store instanceof \Magento\Store\Model\Store) {
                throw new \RuntimeException('Illegal scope resolved');
            }
            $table = $this->resource->getTableName('catalog_product_index_price');
            $select->from(['main_table' => $table], null)
                ->columns([BucketInterface::FIELD_VALUE => 'main_table.min_price'])
                ->where('main_table.customer_group_id = ?', $this->customerSession->getCustomerGroupId())
                ->where('main_table.website_id = ?', $store->getWebsiteId());
        } else {
            $currentScopeId = $this->scopeResolver->getScope($currentScope)
                ->getId();
            $table = $this->resource->getTableName(
                'catalog_product_index_eav' . ($attribute->getBackendType() == 'decimal' ? '_decimal' : '')
            );
            $select->from(['main_table' => $table], ['value'])
                ->where('main_table.attribute_id = ?', $attribute->getAttributeId())
                ->where('main_table.store_id = ? ', $currentScopeId);
        }

        $select->joinInner(
            ['entities' => $entityIdsTable->getName()],
            'main_table.entity_id  = entities.entity_id',
            []
        );

        return $select;
    }

    /**
     * {@inheritdoc}
     */
    public function execute(Select $select)
    {
        return $this->connection->fetchAssoc($select);
    }

    /**
     * @return Select
     */
    private function getSelect()
    {
        return $this->connection->select();
    }
}


text:
package org.bbelovic.devel.testing;

/**
 *
 *
 */
public class MathOperations {

    private MathOperations() {
        // private constructor, since this is going to be utility class
    }

    public static Integer stringToInteger(final String integerString) {
        int sum = 0;
        int length = integerString.length();
        int start = 0;
        boolean negative = false;
        if (integerString.charAt(0) == '-') {
            start = 1;
            negative = true;
        }
        for (int i = start; i < length; i++) {
            sum *= 10;
            sum += (integerString.charAt(i) - '0');
        }
        return (negative) ? Integer.valueOf(-sum) : Integer.valueOf(sum);
    }

    public static String integerToString(Integer input) {
        int size = (input < 0) ? getSize(-input) + 1 : getSize(input);

        boolean negative = false;
        if (input < 0) {
            input = -input;
            negative = true;
        }

        char [] buf = new char [size];
        while (true) {
            buf [--size] = digitTable [input % 10];
            input /= 10;
            if (input == 0) break;
        }
        if (negative) buf [--size] = '-';
        return String.valueOf(buf);
    }

    private static final int [] sizeTable = {9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 99999999, Integer.MAX_VALUE};
    private static final char [] digitTable = {'0', '1', '2', '3', '4', '5', '6', '7','8', '9'};

    private static int getSize(int x) {
        for (int i = 0; ; i++) {
            if (x <= sizeTable[i])
                return i+1;
        }

    }
}


text:
namespace GG
{
	bool Camera::DepthCompare( const Camera * a, const Camera * b )
	{
		if( a == nullptr || b == nullptr )
			return false;

		return a->getDepth() < b->getDepth();
	}

	Camera::Camera() :
		_enabled(true),
		_depth(0),
		_layer(0)
	{
		setPerspective( Angle::FromDegrees(60.0f), 1.333f, 0.1f, 100 );
		setViewport( 0, 0, 1, 1 );
		setClearColor( Vector4( 0, 0, 0, 1 ) );
	}

	Camera::~Camera()
	{
	}

	inline void Camera::setEnabled( bool enabled )
	{
		_enabled = enabled;
	}

	inline bool Camera::isEnabled( ) const
	{
		return _enabled;
	}

	inline void Camera::setRenderLayer( int32 layer )
	{
		_layer = layer;
	}

	inline int32 Camera::getRenderLayer( ) const
	{
		return _layer;
	}

	inline void Camera::setDepth( int16 depth )
	{
		_depth = depth;
	}

	inline int16 Camera::getDepth() const
	{
		return _depth;
	}

	void Camera::setClearColor( const Vector4 & clearColor )
	{
		if( clearColor == _cachedClearColor )
			return;

		_cachedClearColor = clearColor;
	}

	Vector4 Camera::getClearColor( ) const
	{
		return _cachedClearColor;
	}

	void Camera::setClearMode( uint clearMode )
	{
		_clearMode = clearMode;
	}

	uint Camera::getClearMode( ) const
	{
		return _clearMode;
	}

	void Camera::setViewport( float x, float y, float width, float height )
	{
		_cachedViewport = Vector4( x, y, width, height );
	}

	Vector4 Camera::getViewport() const
	{
		return _cachedViewport;
	}

	void Camera::setPerspective( const Angle & fovy, float aspect, float zNear, float zFar )
	{
		_projectionMat = glm::perspective(fovy.toRadians(), aspect, zNear, zFar);
	}

	void Camera::setOrthogonal( float left, float right, float bottom, float top, float zNear, float zFar )
	{
		_projectionMat = glm::ortho(left, right, bottom, top, zNear, zFar);
	}

	Matrix4 Camera::getViewMatrix( ) const
	{
		const SceneNode * n = getEntity()->getSceneNode();
		if( n != nullptr )
		{

			return glm::inverse(n->modelToWorldMatrix());
		}
		else
		{
			TRACE_WARNING( "Camera is not attached to a scene node!" );
		}

		return _viewMat;
	}

	Matrix4 Camera::getProjectionMatrix( ) const
	{
		return _projectionMat;
	}

}


text:
package com.handcraftedbits.arquillian.extension.incontainerurl.test;

import java.net.URL;
import javax.inject.Inject;

import com.handcraftedbits.arquillian.extension.incontainerurl.api.InContainerResource;
import com.handcraftedbits.arquillian.extension.incontainerurl.test.util.DeploymentTestUtil;
import com.handcraftedbits.arquillian.extension.incontainerurl.test.verification.DeploymentVerificationBean;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
public final class SingleDeploymentTest {
     private static final String DEPLOYMENT_NAME = "deployment";

     @SuppressWarnings("unused")
     @InContainerResource
     private URL url;

     @Inject
     private DeploymentVerificationBean verificationBean;

     @Deployment
     public static WebArchive createDeployment () {
          return DeploymentTestUtil.createDeployment(SingleDeploymentTest.DEPLOYMENT_NAME);
     }

     @Test
     public void testDeploymentURL () throws Exception {
          DeploymentTestUtil.verifyDeployment(SingleDeploymentTest.DEPLOYMENT_NAME, this.verificationBean, this.url);
     }

     @Test
     public void testDeploymentURLAsParameter (@InContainerResource final URL url) throws Exception {
          DeploymentTestUtil.verifyDeployment(SingleDeploymentTest.DEPLOYMENT_NAME, this.verificationBean, url);
     }

     @Test
     @RunAsClient
     public void testDeploymentURLMissingForClient () {
          Assert.assertNull(this.url);
     }
}


text:
// Copyright (c) 2017 Pavol Kovalik. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace PowerBuild.Logging
{
    using System;
    using System.Collections.Concurrent;
    using System.Management.Automation;

    internal class PSEventSink : MarshalByRefObject, IPSEventSink
    {
        private readonly BlockingCollection<object> _eventActions = new BlockingCollection<object>();
        private ConsoleColor _backgroundColor;
        private PSCmdlet _cmdlet;
        private ConsoleColor _foregroundColor;

        public PSEventSink(PSCmdlet cmdlet)
        {
            _cmdlet = cmdlet;
            _backgroundColor = cmdlet.Host.UI.RawUI.BackgroundColor;
            _foregroundColor = cmdlet.Host.UI.RawUI.ForegroundColor;
        }

        private enum MessageType
        {
            Host,
            Verbose,
            Warning
        }

        public void ColorReset()
        {
            _eventActions.Add(new SetColor(_foregroundColor));
        }

        public void ColorSet(ConsoleColor color)
        {
            _eventActions.Add(new SetColor(color));
        }

        public void CompleteWriting()
        {
            _eventActions.CompleteAdding();
        }

        public void ConsumeEvents()
        {
            var color = _foregroundColor;

            foreach (var eventAction in _eventActions.GetConsumingEnumerable())
            {
                switch (eventAction)
                {
                    case Message message when message.Type == MessageType.Verbose:
                        _cmdlet.WriteVerbose(message.Text);
                        break;

                    case Message message when message.Type == MessageType.Host:
                        _cmdlet.Host.UI.Write(color, _backgroundColor, message.Text);
                        break;

                    case Message message when message.Type == MessageType.Warning:
                        _cmdlet.WriteWarning(message.Text);
                        break;

                    case SetColor setColor:
                        color = setColor.Color;
                        break;

                    case ErrorMessage error:
                        _cmdlet.WriteError(error.Error);
                        break;
                }
            }
        }

        public void WriteError(ErrorRecord error)
        {
            _eventActions.Add(new ErrorMessage(error));
        }

        public void WriteHost(string message)
        {
            _eventActions.Add(new Message(MessageType.Host, message));
        }

        public void WriteVerbose(string message)
        {
            _eventActions.Add(new Message(MessageType.Verbose, message));
        }

        public void WriteWarning(string message)
        {
            _eventActions.Add(new Message(MessageType.Warning, message));
        }

        private class ErrorMessage
        {
            public ErrorMessage(ErrorRecord error)
            {
                Error = error;
            }

            public ErrorRecord Error { get; }
        }

        private class Message
        {
            public Message(MessageType type, string text)
            {
                Text = text;
                Type = type;
            }

            public string Text { get; }

            public MessageType Type { get; }
        }

        private class SetColor
        {
            public SetColor(ConsoleColor color)
            {
                Color = color;
            }

            public ConsoleColor Color { get; }
        }
    }
}


text:
namespace Azure.ResourceManager.Monitor.Models
{
    /// <summary> The UnknownRuleAction. </summary>
    internal partial class UnknownRuleAction : AlertRuleAction
    {
        /// <summary> Initializes a new instance of UnknownRuleAction. </summary>
        /// <param name="odataType"> specifies the type of the action. There are two types of actions: RuleEmailAction and RuleWebhookAction. </param>
        internal UnknownRuleAction(string odataType) : base(odataType)
        {
            OdataType = odataType ?? "Unknown";
        }
    }
}


text:
using System.Collections.Generic;

namespace Stripe.Tests.test_data
{
    public static class stripe_charge_update_options
    {
        public static StripeChargeUpdateOptions Valid()
        {
            return new StripeChargeUpdateOptions
            {
                Description = "Gangster Pancakes (syrup@og.com)",
                Metadata = new Dictionary<string, string>
                {
                    { "A", "Value-A" },
                    { "B", "Value-B" },
                    { "C", "Value-C" }
                },
                ReceiptEmail = "syrup@og.com"
            };
        }
    }
}


text:
package processors

import (
	"bytes"
	"encoding/csv"
	"errors"
	"fmt"
	"io"
	"strings"

	"github.com/buger/jsonparser"
	"github.com/gravwell/ingest/v3/config"
	"github.com/gravwell/ingest/v3/entry"
)

const (
	JsonExtractProcessor    string = `jsonextract`
	JsonArraySplitProcessor string = `jsonarraysplit`
)

var (
	ErrMissStrictConflict   = errors.New("Strict-Extraction and Passthrough-Misses are mutually exclusive")
	ErrMissingExtractions   = errors.New("Extractions specifications missing")
	ErrInvalidExtractions   = errors.New("Invalid Extractions")
	ErrInvalidKeyname       = errors.New("Invalid keyname")
	ErrDuplicateKey         = errors.New("Duplicate extraction key")
	ErrDuplicateKeyname     = errors.New("Duplicate keys")
	ErrSingleArraySplitOnly = errors.New("jsonarraysplit only supports a single extraction")
)

type JsonExtractConfig struct {
	Passthrough_Misses bool
	Strict_Extraction  bool
	Force_JSON_Object  bool
	Extractions        string
}

func JsonExtractLoadConfig(vc *config.VariableConfig) (c JsonExtractConfig, err error) {
	err = vc.MapTo(&c)
	return
}

// JsonExtractor
type JsonExtractor struct {
	nocloser
	JsonExtractConfig
	bldr builder
}

func NewJsonExtractor(cfg JsonExtractConfig) (*JsonExtractor, error) {
	if cfg.Passthrough_Misses && cfg.Strict_Extraction {
		return nil, ErrMissStrictConflict
	}
	keys, keynames, err := cfg.getKeyData()
	if err != nil {
		return nil, err
	}
	return &JsonExtractor{
		JsonExtractConfig: cfg,
		bldr: builder{
			forceJson: cfg.Force_JSON_Object,
			bb:        bytes.NewBuffer(nil),
			keys:      keys,
			keynames:  keynames,
		},
	}, nil
}

func (j *JsonExtractor) Config(v interface{}) (err error) {
	if v == nil {
		err = ErrNilConfig
	} else if cfg, ok := v.(JsonExtractConfig); ok {
		j.JsonExtractConfig = cfg
	} else {
		err = fmt.Errorf("Invalid configuration, unknown type type %T", v)
	}
	return
}

func (je *JsonExtractor) Process(ent *entry.Entry) (rset []*entry.Entry, err error) {
	if ent == nil {
		return
	}
	if err = je.bldr.extract(ent.Data); err != nil {
		je.bldr.reset()
		return
	}
	data, cnt := je.bldr.render()
	if je.Strict_Extraction && cnt != len(je.bldr.keynames) {
		return nil, nil //just dropping the entry
	} else if cnt == 0 && je.Passthrough_Misses {
		rset = []*entry.Entry{ent}
	} else if len(data) > 0 {
		ent.Data = data
		rset = []*entry.Entry{ent}
	}
	return
}

func (jec JsonExtractConfig) getKeyData() (keys [][]string, keynames []string, err error) {
	if len(jec.Extractions) == 0 {
		err = ErrMissingExtractions
		return
	}
	r := csv.NewReader(strings.NewReader(jec.Extractions))
	r.Comma = ',' // space
	r.TrimLeadingSpace = true
	var flds []string
	if flds, err = r.Read(); err != nil {
		return
	}
	for _, key := range flds {
		var keyname string
		if len(key) == 0 {
			continue
		}
		bits := strings.Split(key, `.`)
		if keyname = bits[len(bits)-1]; len(keyname) == 0 {
			err = ErrInvalidKeyname
			return
		}
		if inStringSliceSet(keys, bits) {
			err = ErrDuplicateKey
			return
		} else if inStringSet(keynames, keyname) {
			err = ErrDuplicateKeyname
			return
		}
		keys = append(keys, bits)
		keynames = append(keynames, keyname)
	}
	if len(keys) == 0 || len(keynames) == 0 || len(keys) != len(keynames) {
		err = ErrInvalidExtractions
	}
	return
}

func inStringSliceSet(set [][]string, key []string) bool {
	for _, x := range set {
		if len(x) != len(key) {
			continue
		}
		var miss bool
		for i := range x {
			if key[i] != x[i] {
				miss = true
				break
			}
		}
		if !miss {
			return true // it matched
		}
	}
	return false
}

func inStringSet(set []string, key string) bool {
	for _, x := range set {
		if x == key {
			return true
		}
	}
	return false
}

type builder struct {
	comma     bool
	forceJson bool
	cnt       int
	bb        *bytes.Buffer
	keys      [][]string
	keynames  []string
}

func (b *builder) extract(data []byte) error {
	if len(b.keys) > 1 || b.forceJson {
		return b.extractJson(data)
	}
	return b.extractObject(data)
}

// Extracting a single field and not rewrapping in JSON with a key name
func (b *builder) extractObject(data []byte) error {
	v, _, _, err := jsonparser.Get(data, b.keys[0]...)
	if err != nil {
		if err == jsonparser.KeyPathNotFoundError {
			err = nil
		}
	} else {
		//got a successful extraction
		b.cnt++
		b.bb.Write(v)
	}
	return err
}

// extract and handle data as a JSON object
func (b *builder) extractJson(data []byte) error {
	for i, keys := range b.keys {
		v, dt, _, err := jsonparser.Get(data, keys...)
		if err != nil {
			if err == jsonparser.KeyPathNotFoundError {
				continue
			}
			return err
		}
		if dt != jsonparser.NotExist {
			if !b.comma {
				b.bb.WriteString("{")
			} else {
				b.bb.WriteString(",")
			}
			addData(b.keynames[i], dt, v, b.bb)
			b.cnt++
			b.comma = true
		}
	}
	return nil
}

func (b *builder) render() (r []byte, cnt int) {
	if b.cnt == 0 {
		return
	}
	if len(b.keys) > 1 || b.forceJson {
		io.WriteString(b.bb, "}")
	}
	r = append([]byte{}, b.bb.Bytes()...) //force allocation
	cnt = b.cnt
	b.reset()
	return
}

func (b *builder) reset() {
	b.bb.Reset()
	b.comma = false
	b.cnt = 0
}

func addData(key string, dt jsonparser.ValueType, v []byte, bb *bytes.Buffer) {
	if dt == jsonparser.String {
		fmt.Fprintf(bb, `"%s":"%s"`, key, string(v))
	} else {
		fmt.Fprintf(bb, `"%s":`, key)
		bb.Write(v)
	}
}

type JsonArraySplitConfig struct {
	Passthrough_Misses bool
	Extraction         string
	Force_JSON_Object  bool
}

func JsonArraySplitLoadConfig(vc *config.VariableConfig) (c JsonArraySplitConfig, err error) {
	err = vc.MapTo(&c)
	return
}

func (jasc JsonArraySplitConfig) getKeyData() (key []string, keyname string, err error) {
	if len(jasc.Extraction) == 0 {
		err = ErrMissingExtractions
		return
	}
	r := csv.NewReader(strings.NewReader(jasc.Extraction))
	r.Comma = ' ' // space
	r.TrimLeadingSpace = true
	var flds []string
	if flds, err = r.Read(); err != nil {
		return
	}
	if len(flds) != 1 {
		err = ErrSingleArraySplitOnly
		return
	}
	if key = strings.Split(flds[0], `.`); len(key) == 0 {
		err = ErrMissingExtractions
		return
	}
	keyname = key[len(key)-1]
	return
}

type JsonArraySplitter struct {
	nocloser
	JsonArraySplitConfig
	key     []string
	keyname string
}

func NewJsonArraySplitter(cfg JsonArraySplitConfig) (*JsonArraySplitter, error) {
	key, keyname, err := cfg.getKeyData()
	if err != nil {
		return nil, err
	}
	return &JsonArraySplitter{
		JsonArraySplitConfig: cfg,
		key:                  key,
		keyname:              keyname,
	}, nil
}

func (j *JsonArraySplitter) Config(v interface{}) (err error) {
	if v == nil {
		err = ErrNilConfig
	} else if cfg, ok := v.(JsonArraySplitConfig); ok {
		j.JsonArraySplitConfig = cfg
	} else {
		err = fmt.Errorf("Invalid configuration, unknown type type %T", v)
	}
	return
}

func (je *JsonArraySplitter) Process(ent *entry.Entry) (rset []*entry.Entry, err error) {
	cb := func(v []byte, dt jsonparser.ValueType, off int, lerr error) {
		if len(v) == 0 {
			return
		}
		if r, ok := je.genEntry(dt, ent, v); ok {
			rset = append(rset, r)
		}
		return
	}
	if ent == nil {
		return
	}
	if _, err = jsonparser.ArrayEach(ent.Data, cb, je.key...); err != nil {
		if err == jsonparser.KeyPathNotFoundError {
			if je.Passthrough_Misses && rset == nil {
				rset = []*entry.Entry{ent}
			}
			err = nil
		}
	}
	return
}

func (je *JsonArraySplitter) genEntry(dt jsonparser.ValueType, ent *entry.Entry, v []byte) (r *entry.Entry, ok bool) {
	if ent == nil || v == nil {
		return
	}
	if len(v) != 0 {
		ok = true
		r = &entry.Entry{
			Tag: ent.Tag,
			SRC: ent.SRC,
			TS:  ent.TS,
		}
		if !je.Force_JSON_Object {
			r.Data = v
		} else if dt == jsonparser.String {
			r.Data = []byte(fmt.Sprintf(`{"%s":"%s"}`, je.keyname, string(v)))
		} else {
			r.Data = []byte(fmt.Sprintf(`{"%s":%s}`, je.keyname, string(v)))
		}
	}
	return
}


text:
This extension adds suggestions for product search.

## Demo

![](screenshot.png)

## Getting Started
### Installation

Add the Spree Autosuggest gem to your `Gemfile`:
  ```ruby
  gem 'spree_autosuggest'
  ```

### Usage

  ```sh
  $ bundle install
  $ rails g spree_autosuggest:install
  ```

In order to add all Taxon & Product names to the autosuggest database run:
  ```sh
  rake spree_autosuggest:seed
  ```
## Contributing

Please read [Code of Conduct](CODE-OF-CONDUCT.md) and [Contributing Guidelines](CONTRIBUTING.md) for submitting pull requests to us.

## Authors

* [Aleksey Demidov](https://github.com/ademidov)
* [Alexander Balashov](https://github.com/divineforest)

See also the list of [contributors](https://github.com/evrone/spree_autosuggest/graphs/contributors) who participated in this project.

## License

This project is licensed under the [MIT License](LICENSE).


text:
**Overview**:

  For this scenario, we have been asked to write an application that will be used to provide information about baseball player statistics.  Approach this problem as if it is an application going to production.  We don't expect it to be perfect (no production code is), but we also don't want you to hack together a throw-away script.  This should be representative of something that you would be comfortable releasing to a production environment.  Also, spend whatever amount of time you think is reasonable.  If you don't get all the requirements completed, that's ok.  Just do the best you can with the time that you have available.  You may use whatever gems, frameworks and tools that you think are appropriate, just provide any special setup instructions when you submit your solution.

**Assumptions**:

All requests currently are based on data in the hitting file.  Future requests of the system will require data from a pitching file as well. Consider this in the design.

**Requirements**:

When the application is run, use the provided data and calculate the following results and write them to STDOUT.

1) Most improved batting average( hits / at-bats) from 2009 to 2010.  Only include players with at least 200 at-bats.
2) Slugging percentage for all players on the Oakland A's (teamID = OAK) in 2007.
3) Who was the AL and NL triple crown winner for 2011 and 2012.  If no one won the crown, output "(No winner)"

**Formulas**:
Batting average = hits / at-bats
Slugging percentage = ((Hits – doubles – triples – home runs) + (2 * doubles) + (3 * triples) + (4 * home runs)) / at-bats
Triple crown winner – The player that had the highest batting average AND the most home runs AND the most RBI in their league. It's unusual for someone to win this, but there was a winner in 2012. "Officially" the batting title (highest league batting average) is based on a minimum of 502 plate appearances. The provided dataset does not include plate appearances. It also does not include walks so plate appearances cannot be calculated. Instead, use a constraint of a minimum of 400 at-bats to determine those eligible for the league batting title.

**Data**:

All the necessary data is available in the two csv files attached:

Batting-07-12.csv – Contains all the batting statistics from 2007-2012.

**Column header key**:

AB – at-bats

H – hits

2B – doubles

3B – triples

HR – home runs

RBI – runs batted in

Master-small.csv – Contains the demographic data for all baseball players in history through 2012.

Please note: We are looking for you to demonstrate you knowledge related to common software practices to include reusability, portability, and encapsulation – to name a few. Work submitted should be in project form and implemented as you were implementing any production solution.

## Installation

Download application from github to your local directory:

    $ git clone git@github.com:sbrmnn/sport_stats.git

Change directory to the application's root:

    $ cd sport_stats

Install development environment gems.

    $ bundle install

Build the application:

    $ rake build

Install application:

    $ rake install

## Usage

Run Code (must be run within the application's root directory):

    $ sport_stats

Run Tests (must be run within the application's root directory):

    $ rspec spec/


text:
using System.Data.Entity;
using SimpleSSO.Domain.System;

namespace SimpleSSO.EFRepositories
{
    partial class SimpleDbContext
    {
        public DbSet<User> Users { get; set; }

        public DbSet<App> Apps { get; set; }

        public DbSet<Role> Roles { get; set; }

        private void MapSystemModuleEntities(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().ToTable("Sys_User");
        }
    }
}


text:
package io.github.bonigarcia.seljup;

import com.google.gson.internal.LinkedTreeMap;

import io.github.bonigarcia.seljup.BrowsersTemplate.Browser;

/**
 * Browser builder.
 *
 * @author Boni Garcia
 * @since 2.2.0
 */
public class BrowserBuilder {

    String type;
    String version;
    String remoteUrl;
    String[] arguments;
    String[] preferences;
    Object capabilities;

    public BrowserBuilder(String type) {
        this.type = type;
    }

    public static BrowserBuilder chrome() {
        return new BrowserBuilder("chrome");
    }

    public static BrowserBuilder chromeMobile() {
        return new BrowserBuilder("chrome-mobile");
    }

    public static BrowserBuilder firefox() {
        return new BrowserBuilder("firefox");
    }

    public static BrowserBuilder edge() {
        return new BrowserBuilder("edge");
    }

    public static BrowserBuilder opera() {
        return new BrowserBuilder("opera");
    }

    public static BrowserBuilder safari() {
        return new BrowserBuilder("safari");
    }

    public static BrowserBuilder iexplorer() {
        return new BrowserBuilder("iexplorer");
    }

    public static BrowserBuilder chromeInDocker() {
        return new BrowserBuilder("chrome-in-docker");
    }

    public static BrowserBuilder firefoxInDocker() {
        return new BrowserBuilder("firefox-in-docker");
    }

    public static BrowserBuilder operaInDocker() {
        return new BrowserBuilder("opera-in-docker");
    }

    public static BrowserBuilder edgeInDocker() {
        return new BrowserBuilder("edge-in-docker");
    }

    public static BrowserBuilder safariInDocker() {
        return new BrowserBuilder("safari-in-docker");
    }

    public BrowserBuilder version(String version) {
        this.version = version;
        return this;
    }

    public BrowserBuilder remoteUrl(String url) {
        this.remoteUrl = url;
        return this;
    }

    public BrowserBuilder arguments(String[] arguments) {
        this.arguments = arguments;
        return this;
    }

    public BrowserBuilder preferences(String[] preferences) {
        this.preferences = preferences;
        return this;
    }

    public BrowserBuilder capabilities(
            LinkedTreeMap<String, String> capabilities) {
        this.capabilities = capabilities;
        return this;
    }

    public Browser build() {
        return new Browser(type, version, remoteUrl, arguments, preferences,
                capabilities);
    }

}


text:
import { Component, OnInit, Input, OnDestroy } from '@angular/core';
import {Subscription} from 'rxjs/Subscription';

import { UserService } from '../../core';
import { UserDetailsDTO } from '../../model/models';

@Component({

  selector: 'app-usernav',
  templateUrl: 'usernav.component.html',
  styleUrls: ['usernav.component.css']
})
export class UsernavComponent implements OnInit {

  user: UserDetailsDTO;

  constructor(private _userService: UserService) { }

  ngOnInit() {
    this._userService.login$.subscribe(user => {
      this.user = user;
    });
  }

  logOut(){
    this._userService.logOut();
  }

}


text:
A simple mobile web app to learn German.
[Just click here and test it by yourself !](https://thinow.github.io/genau)

## What does contain this repository ?

This repository contains only the user interface of the app.
If you want to access to the API, please go to the [genau-api](https://github.com/thinow/genau-api) repository.

## Made with love... and React

Ok maybe love is not enough, hopefully I could rely on powerful tools :
- [react](https://www.npmjs.com/package/react)
- [redux](https://www.npmjs.com/package/react-redux)
- [saga](https://www.npmjs.com/package/react-saga)
- [material-ui](https://www.npmjs.com/package/material-ui)
- [jest](https://www.npmjs.com/package/jest)
- [webpack](https://www.npmjs.com/package/webpack)

## Do you want to contribute ?

Thanks to GitHub (I just love [what you are doing guys](https://github.com/about) :heart:), to contribute is quite easy !

```bash
# Clone this project
git clone git@github.com:thinow/genau.git

# Change directory
cd genau

# Fetch the npm dependencies
npm install

# Run the development server
npm run start

# Run the tests
npm run test
```

You can send me your modifications [by creating a pull request](https://github.com/thinow/genau/pulls).

## How to report a bug ?

If you've seen any problem by using the app, please [create a new issue](https://github.com/thinow/genau/issues/new). Many thanks !

## License
This project is licensed under the terms of the [MIT license](https://raw.githubusercontent.com/thinow/genau/master/LICENSE)


text:
package suppressed;
class NewSuppress {
  void barr() {
    String str = "";
    st<caret>r = str;
  }
}


text:
opera.isReady(function() {

	function onMessage(message) {
		var currentTab = opera.extension.tabs.getFocused();
		switch (message.data.action) {
		case 'send_to_phone':
			var pageData = message.data.data || {};
			if (currentTab) {
				var data = {
					'title': pageData.title || currentTab.title,
					'url': pageData.link || currentTab.url,
					'sel': null
				};
				sendToPhone(data, function(statusMsg) {
					opera.extension.broadcastMessage({
						'action': statusMsg
					});
				});
			} else {
				opera.extension.broadcastMessage({
					'action': 'no_tab_access'
				});
			}
			break;
		case 'open_tab':
			if (message.data.data && message.data.data.url) {
				opera.extension.tabs.create({
					'url': message.data.data.url,
					'focused': true
				});
			}
			break;
		case 'close_tab':
			if (currentTab) currentTab.close();
			break;
		}
	}
	var onMessage = window['onMessage'] = onMessage;
	opera.extension.addEventListener('message', onMessage, false);

});


text:
.class public interface abstract Lcom/android/server/display/WifiDisplayController$Listener;
.super Ljava/lang/Object;
.source "WifiDisplayController.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/display/WifiDisplayController;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "Listener"
.end annotation

# virtual methods
.method public abstract onDisplayChanged(Landroid/hardware/display/WifiDisplay;)V
.end method

.method public abstract onDisplayConnected(Landroid/hardware/display/WifiDisplay;Landroid/view/Surface;III)V
.end method

.method public abstract onDisplayConnecting(Landroid/hardware/display/WifiDisplay;)V
.end method

.method public abstract onDisplayConnectionFailed()V
.end method

.method public abstract onDisplayDisconnected()V
.end method

.method public abstract onDisplayDisconnecting()V
.end method

.method public abstract onDisplaySessionInfo(Landroid/hardware/display/WifiDisplaySessionInfo;)V
.end method

.method public abstract onFeatureStateChanged(I)V
.end method

.method public abstract onScanFinished()V
.end method

.method public abstract onScanResults([Landroid/hardware/display/WifiDisplay;)V
.end method

.method public abstract onScanStarted()V
.end method


text:
require "set"
require "securerandom"

module Zeitwerk
  class Loader
    require_relative "loader/callbacks"
    include Callbacks
    include RealModName

    # @sig String
    attr_reader :tag

    # @sig #camelize
    attr_accessor :inflector

    # @sig #call | #debug | nil
    attr_accessor :logger

    # Absolute paths of the root directories. Stored in a hash to preserve
    # order, easily handle duplicates, and also be able to have a fast lookup,
    # needed for detecting nested paths.
    #
    #   "/Users/fxn/blog/app/assets"   => true,
    #   "/Users/fxn/blog/app/channels" => true,
    #   ...
    #
    # This is a private collection maintained by the loader. The public
    # interface for it is `push_dir` and `dirs`.
    #
    # @private
    # @sig Hash[String, true]
    attr_reader :root_dirs

    # Absolute paths of files or directories that have to be preloaded.
    #
    # @private
    # @sig Array[String]
    attr_reader :preloads

    # Absolute paths of files, directories, or glob patterns to be totally
    # ignored.
    #
    # @private
    # @sig Set[String]
    attr_reader :ignored_glob_patterns

    # The actual collection of absolute file and directory names at the time the
    # ignored glob patterns were expanded. Computed on setup, and recomputed on
    # reload.
    #
    # @private
    # @sig Set[String]
    attr_reader :ignored_paths

    # Absolute paths of directories or glob patterns to be collapsed.
    #
    # @private
    # @sig Set[String]
    attr_reader :collapse_glob_patterns

    # The actual collection of absolute directory names at the time the collapse
    # glob patterns were expanded. Computed on setup, and recomputed on reload.
    #
    # @private
    # @sig Set[String]
    attr_reader :collapse_dirs

    # Maps real absolute paths for which an autoload has been set ---and not
    # executed--- to their corresponding parent class or module and constant
    # name.
    #
    #   "/Users/fxn/blog/app/models/user.rb"          => [Object, :User],
    #   "/Users/fxn/blog/app/models/hotel/pricing.rb" => [Hotel, :Pricing]
    #   ...
    #
    # @private
    # @sig Hash[String, [Module, Symbol]]
    attr_reader :autoloads

    # We keep track of autoloaded directories to remove them from the registry
    # at the end of eager loading.
    #
    # Files are removed as they are autoloaded, but directories need to wait due
    # to concurrency (see why in Zeitwerk::Loader::Callbacks#on_dir_autoloaded).
    #
    # @private
    # @sig Array[String]
    attr_reader :autoloaded_dirs

    # Stores metadata needed for unloading. Its entries look like this:
    #
    #   "Admin::Role" => [".../admin/role.rb", [Admin, :Role]]
    #
    # The cpath as key helps implementing unloadable_cpath? The real file name
    # is stored in order to be able to delete it from $LOADED_FEATURES, and the
    # pair [Module, Symbol] is used to remove_const the constant from the class
    # or module object.
    #
    # If reloading is enabled, this hash is filled as constants are autoloaded
    # or eager loaded. Otherwise, the collection remains empty.
    #
    # @private
    # @sig Hash[String, [String, [Module, Symbol]]]
    attr_reader :to_unload

    # Maps constant paths of namespaces to arrays of corresponding directories.
    #
    # For example, given this mapping:
    #
    #   "Admin" => [
    #     "/Users/fxn/blog/app/controllers/admin",
    #     "/Users/fxn/blog/app/models/admin",
    #     ...
    #   ]
    #
    # when `Admin` gets defined we know that it plays the role of a namespace and
    # that its children are spread over those directories. We'll visit them to set
    # up the corresponding autoloads.
    #
    # @private
    # @sig Hash[String, Array[String]]
    attr_reader :lazy_subdirs

    # Absolute paths of files or directories not to be eager loaded.
    #
    # @private
    # @sig Set[String]
    attr_reader :eager_load_exclusions

    # @private
    # @sig Mutex
    attr_reader :mutex

    # @private
    # @sig Mutex
    attr_reader :mutex2

    def initialize
      @initialized_at = Time.now

      @tag       = SecureRandom.hex(3)
      @inflector = Inflector.new
      @logger    = self.class.default_logger

      @root_dirs              = {}
      @preloads               = []
      @ignored_glob_patterns  = Set.new
      @ignored_paths          = Set.new
      @collapse_glob_patterns = Set.new
      @collapse_dirs          = Set.new
      @autoloads              = {}
      @autoloaded_dirs        = []
      @to_unload              = {}
      @lazy_subdirs           = {}
      @eager_load_exclusions  = Set.new

      # TODO: find a better name for these mutexes.
      @mutex        = Mutex.new
      @mutex2       = Mutex.new
      @setup        = false
      @eager_loaded = false

      @reloading_enabled = false

      Registry.register_loader(self)
    end

    # Sets a tag for the loader, useful for logging.
    #
    # @param tag [#to_s]
    # @sig (#to_s) -> void
    def tag=(tag)
      @tag = tag.to_s
    end

    # Absolute paths of the root directories. This is a read-only collection,
    # please push here via `push_dir`.
    #
    # @sig () -> Array[String]
    def dirs
      root_dirs.keys.freeze
    end

    # Pushes `path` to the list of root directories.
    #
    # Raises `Zeitwerk::Error` if `path` does not exist, or if another loader in
    # the same process already manages that directory or one of its ascendants
    # or descendants.
    #
    # @raise [Zeitwerk::Error]
    # @sig (String | Pathname, Module) -> void
    def push_dir(path, namespace: Object)
      # Note that Class < Module.
      unless namespace.is_a?(Module)
        raise Error, "#{namespace.inspect} is not a class or module object, should be"
      end

      abspath = File.expand_path(path)
      if dir?(abspath)
        raise_if_conflicting_directory(abspath)
        root_dirs[abspath] = namespace
      else
        raise Error, "the root directory #{abspath} does not exist"
      end
    end

    # You need to call this method before setup in order to be able to reload.
    # There is no way to undo this, either you want to reload or you don't.
    #
    # @raise [Zeitwerk::Error]
    # @sig () -> void
    def enable_reloading
      mutex.synchronize do
        break if @reloading_enabled

        if @setup
          raise Error, "cannot enable reloading after setup"
        else
          @reloading_enabled = true
        end
      end
    end

    # @sig () -> bool
    def reloading_enabled?
      @reloading_enabled
    end

    # Files or directories to be preloaded instead of lazy loaded.
    #
    # @sig (*(String | Pathname | Array[String | Pathname])) -> void
    def preload(*paths)
      mutex.synchronize do
        expand_paths(paths).each do |abspath|
          preloads << abspath
          do_preload_abspath(abspath) if @setup
        end
      end
    end

    # Configure files, directories, or glob patterns to be totally ignored.
    #
    # @sig (*(String | Pathname | Array[String | Pathname])) -> void
    def ignore(*glob_patterns)
      glob_patterns = expand_paths(glob_patterns)
      mutex.synchronize do
        ignored_glob_patterns.merge(glob_patterns)
        ignored_paths.merge(expand_glob_patterns(glob_patterns))
      end
    end

    # Configure directories or glob patterns to be collapsed.
    #
    # @sig (*(String | Pathname | Array[String | Pathname])) -> void
    def collapse(*glob_patterns)
      glob_patterns = expand_paths(glob_patterns)
      mutex.synchronize do
        collapse_glob_patterns.merge(glob_patterns)
        collapse_dirs.merge(expand_glob_patterns(glob_patterns))
      end
    end

    # Sets autoloads in the root namespace and preloads files, if any.
    #
    # @sig () -> void
    def setup
      mutex.synchronize do
        break if @setup

        actual_root_dirs.each do |root_dir, namespace|
          set_autoloads_in_dir(root_dir, namespace)
        end
        do_preload

        @setup = true
      end
    end

    # Removes loaded constants and configured autoloads.
    #
    # The objects the constants stored are no longer reachable through them. In
    # addition, since said objects are normally not referenced from anywhere
    # else, they are eligible for garbage collection, which would effectively
    # unload them.
    #
    # @private
    # @sig () -> void
    def unload
      mutex.synchronize do
        # We are going to keep track of the files that were required by our
        # autoloads to later remove them from $LOADED_FEATURES, thus making them
        # loadable by Kernel#require again.
        #
        # Directories are not stored in $LOADED_FEATURES, keeping track of files
        # is enough.
        unloaded_files = Set.new

        autoloads.each do |realpath, (parent, cname)|
          if parent.autoload?(cname)
            unload_autoload(parent, cname)
          else
            # Could happen if loaded with require_relative. That is unsupported,
            # and the constant path would escape unloadable_cpath? This is just
            # defensive code to clean things up as much as we are able to.
            unload_cref(parent, cname)   if cdef?(parent, cname)
            unloaded_files.add(realpath) if ruby?(realpath)
          end
        end

        to_unload.each_value do |(realpath, (parent, cname))|
          unload_cref(parent, cname)   if cdef?(parent, cname)
          unloaded_files.add(realpath) if ruby?(realpath)
        end

        unless unloaded_files.empty?
          # Bootsnap decorates Kernel#require to speed it up using a cache and
          # this optimization does not check if $LOADED_FEATURES has the file.
          #
          # To make it aware of changes, the gem defines singleton methods in
          # $LOADED_FEATURES:
          #
          #   https://github.com/Shopify/bootsnap/blob/master/lib/bootsnap/load_path_cache/core_ext/loaded_features.rb
          #
          # Rails applications may depend on bootsnap, so for unloading to work
          # in that setting it is preferable that we restrict our API choice to
          # one of those methods.
          $LOADED_FEATURES.reject! { |file| unloaded_files.member?(file) }
        end

        autoloads.clear
        autoloaded_dirs.clear
        to_unload.clear
        lazy_subdirs.clear

        Registry.on_unload(self)
        ExplicitNamespace.unregister(self)

        @setup        = false
        @eager_loaded = false
      end
    end

    # Unloads all loaded code, and calls setup again so that the loader is able
    # to pick any changes in the file system.
    #
    # This method is not thread-safe, please see how this can be achieved by
    # client code in the README of the project.
    #
    # @raise [Zeitwerk::Error]
    # @sig () -> void
    def reload
      if reloading_enabled?
        unload
        recompute_ignored_paths
        recompute_collapse_dirs
        setup
      else
        raise ReloadingDisabledError, "can't reload, please call loader.enable_reloading before setup"
      end
    end

    # Eager loads all files in the root directories, recursively. Files do not
    # need to be in `$LOAD_PATH`, absolute file names are used. Ignored files
    # are not eager loaded. You can opt-out specifically in specific files and
    # directories with `do_not_eager_load`.
    #
    # @sig () -> void
    def eager_load
      mutex.synchronize do
        break if @eager_loaded

        queue = []
        actual_root_dirs.each do |root_dir, namespace|
          queue << [namespace, root_dir] unless eager_load_exclusions.member?(root_dir)
        end

        while to_eager_load = queue.shift
          namespace, dir = to_eager_load

          ls(dir) do |basename, abspath|
            next if eager_load_exclusions.member?(abspath)

            if ruby?(abspath)
              if cref = autoloads[File.realpath(abspath)]
                cref[0].const_get(cref[1], false)
              end
            elsif dir?(abspath) && !root_dirs.key?(abspath)
              if collapse_dirs.member?(abspath)
                queue << [namespace, abspath]
              else
                cname = inflector.camelize(basename, abspath)
                queue << [namespace.const_get(cname, false), abspath]
              end
            end
          end
        end

        autoloaded_dirs.each do |autoloaded_dir|
          Registry.unregister_autoload(autoloaded_dir)
        end
        autoloaded_dirs.clear

        @eager_loaded = true
      end
    end

    # Let eager load ignore the given files or directories. The constants
    # defined in those files are still autoloadable.
    #
    # @sig (*(String | Pathname | Array[String | Pathname])) -> void
    def do_not_eager_load(*paths)
      mutex.synchronize { eager_load_exclusions.merge(expand_paths(paths)) }
    end

    # Says if the given constant path would be unloaded on reload. This
    # predicate returns `false` if reloading is disabled.
    #
    # @sig (String) -> bool
    def unloadable_cpath?(cpath)
      to_unload.key?(cpath)
    end

    # Returns an array with the constant paths that would be unloaded on reload.
    # This predicate returns an empty array if reloading is disabled.
    #
    # @sig () -> Array[String]
    def unloadable_cpaths
      to_unload.keys.freeze
    end

    # Logs to `$stdout`, handy shortcut for debugging.
    #
    # @sig () -> void
    def log!
      @logger = ->(msg) { puts msg }
    end

    # @private
    # @sig (String) -> bool
    def manages?(dir)
      dir = dir + "/"
      ignored_paths.each do |ignored_path|
        return false if dir.start_with?(ignored_path + "/")
      end

      root_dirs.each_key do |root_dir|
        return true if root_dir.start_with?(dir) || dir.start_with?(root_dir + "/")
      end

      false
    end

    # --- Class methods ---------------------------------------------------------------------------

    class << self
      # @sig #call | #debug | nil
      attr_accessor :default_logger

      # @private
      # @sig Mutex
      attr_accessor :mutex

      # This is a shortcut for
      #
      #   require "zeitwerk"
      #   loader = Zeitwerk::Loader.new
      #   loader.tag = File.basename(__FILE__, ".rb")
      #   loader.inflector = Zeitwerk::GemInflector.new(__FILE__)
      #   loader.push_dir(__dir__)
      #
      # except that this method returns the same object in subsequent calls from
      # the same file, in the unlikely case the gem wants to be able to reload.
      #
      # @sig () -> Zeitwerk::Loader
      def for_gem
        called_from = caller_locations(1, 1).first.path
        Registry.loader_for_gem(called_from)
      end

      # Broadcasts `eager_load` to all loaders.
      #
      # @sig () -> void
      def eager_load_all
        Registry.loaders.each(&:eager_load)
      end

      # Returns an array with the absolute paths of the root directories of all
      # registered loaders. This is a read-only collection.
      #
      # @sig () -> Array[String]
      def all_dirs
        Registry.loaders.flat_map(&:dirs).freeze
      end
    end

    self.mutex = Mutex.new

    private # -------------------------------------------------------------------------------------

    # @sig () -> Array[String]
    def actual_root_dirs
      root_dirs.reject do |root_dir, _namespace|
        !dir?(root_dir) || ignored_paths.member?(root_dir)
      end
    end

    # @sig (String, Module) -> void
    def set_autoloads_in_dir(dir, parent)
      ls(dir) do |basename, abspath|
        begin
          if ruby?(basename)
            basename[-3..-1] = ''
            cname = inflector.camelize(basename, abspath).to_sym
            autoload_file(parent, cname, abspath)
          elsif dir?(abspath)
            # In a Rails application, `app/models/concerns` is a subdirectory of
            # `app/models`, but both of them are root directories.
            #
            # To resolve the ambiguity file name -> constant path this introduces,
            # the `app/models/concerns` directory is totally ignored as a namespace,
            # it counts only as root. The guard checks that.
            unless root_dirs.key?(abspath)
              cname = inflector.camelize(basename, abspath).to_sym
              if collapse_dirs.member?(abspath)
                set_autoloads_in_dir(abspath, parent)
              else
                autoload_subdir(parent, cname, abspath)
              end
            end
          end
        rescue ::NameError => error
          path_type = ruby?(abspath) ? "file" : "directory"

          raise NameError.new(<<~MESSAGE, error.name)
            #{error.message} inferred by #{inflector.class} from #{path_type}

              #{abspath}

            Possible ways to address this:

              * Tell Zeitwerk to ignore this particular #{path_type}.
              * Tell Zeitwerk to ignore one of its parent directories.
              * Rename the #{path_type} to comply with the naming conventions.
              * Modify the inflector to handle this case.
          MESSAGE
        end
      end
    end

    # @sig (Module, Symbol, String) -> void
    def autoload_subdir(parent, cname, subdir)
      if autoload_path = autoload_for?(parent, cname)
        cpath = cpath(parent, cname)
        register_explicit_namespace(cpath) if ruby?(autoload_path)
        # We do not need to issue another autoload, the existing one is enough
        # no matter if it is for a file or a directory. Just remember the
        # subdirectory has to be visited if the namespace is used.
        (lazy_subdirs[cpath] ||= []) << subdir
      elsif !cdef?(parent, cname)
        # First time we find this namespace, set an autoload for it.
        (lazy_subdirs[cpath(parent, cname)] ||= []) << subdir
        set_autoload(parent, cname, subdir)
      else
        # For whatever reason the constant that corresponds to this namespace has
        # already been defined, we have to recurse.
        set_autoloads_in_dir(subdir, parent.const_get(cname))
      end
    end

    # @sig (Module, Symbol, String) -> void
    def autoload_file(parent, cname, file)
      if autoload_path = autoload_for?(parent, cname)
        # First autoload for a Ruby file wins, just ignore subsequent ones.
        if ruby?(autoload_path)
          log("file #{file} is ignored because #{autoload_path} has precedence") if logger
        else
          promote_namespace_from_implicit_to_explicit(
            dir:    autoload_path,
            file:   file,
            parent: parent,
            cname:  cname
          )
        end
      elsif cdef?(parent, cname)
        log("file #{file} is ignored because #{cpath(parent, cname)} is already defined") if logger
      else
        set_autoload(parent, cname, file)
      end
    end

    # `dir` is the directory that would have autovivified a namespace. `file` is
    # the file where we've found the namespace is explicitly defined.
    #
    # @sig (dir: String, file: String, parent: Module, cname: Symbol) -> void
    def promote_namespace_from_implicit_to_explicit(dir:, file:, parent:, cname:)
      autoloads.delete(dir)
      Registry.unregister_autoload(dir)

      set_autoload(parent, cname, file)
      register_explicit_namespace(cpath(parent, cname))
    end

    # @sig (Module, Symbol, String) -> void
    def set_autoload(parent, cname, abspath)
      # $LOADED_FEATURES stores real paths since Ruby 2.4.4. We set and save the
      # real path to be able to delete it from $LOADED_FEATURES on unload, and to
      # be able to do a lookup later in Kernel#require for manual require calls.
      #
      # We freeze realpath because that saves allocations in Module#autoload.
      # See #125.
      realpath = File.realpath(abspath).freeze
      parent.autoload(cname, realpath)
      if logger
        if ruby?(realpath)
          log("autoload set for #{cpath(parent, cname)}, to be loaded from #{realpath}")
        else
          log("autoload set for #{cpath(parent, cname)}, to be autovivified from #{realpath}")
        end
      end

      autoloads[realpath] = [parent, cname]
      Registry.register_autoload(self, realpath)

      # See why in the documentation of Zeitwerk::Registry.inceptions.
      unless parent.autoload?(cname)
        Registry.register_inception(cpath(parent, cname), realpath, self)
      end
    end

    # @sig (Module, Symbol) -> String?
    def autoload_for?(parent, cname)
      strict_autoload_path(parent, cname) || Registry.inception?(cpath(parent, cname))
    end

    # The autoload? predicate takes into account the ancestor chain of the
    # receiver, like const_defined? and other methods in the constants API do.
    #
    # For example, given
    #
    #   class A
    #     autoload :X, "x.rb"
    #   end
    #
    #   class B < A
    #   end
    #
    # B.autoload?(:X) returns "x.rb".
    #
    # We need a way to strictly check in parent ignoring ancestors.
    #
    # @sig (Module, Symbol) -> String?
    if method(:autoload?).arity == 1
      def strict_autoload_path(parent, cname)
        parent.autoload?(cname) if cdef?(parent, cname)
      end
    else
      def strict_autoload_path(parent, cname)
        parent.autoload?(cname, false)
      end
    end

    # This method is called this way because I prefer `preload` to be the method
    # name to configure preloads in the public interface.
    #
    # @sig () -> void
    def do_preload
      preloads.each do |abspath|
        do_preload_abspath(abspath)
      end
    end

    # @sig (String) -> void
    def do_preload_abspath(abspath)
      if ruby?(abspath)
        do_preload_file(abspath)
      elsif dir?(abspath)
        do_preload_dir(abspath)
      end
    end

    # @sig (String) -> void
    def do_preload_dir(dir)
      ls(dir) do |_basename, abspath|
        do_preload_abspath(abspath)
      end
    end

    # @sig (String) -> bool
    def do_preload_file(file)
      log("preloading #{file}") if logger
      require file
    end

    # @sig (Module, Symbol) -> String
    def cpath(parent, cname)
      parent.equal?(Object) ? cname.to_s : "#{real_mod_name(parent)}::#{cname}"
    end

    # @sig (String) { (String, String) -> void } -> void
    def ls(dir)
      Dir.foreach(dir) do |basename|
        next if basename.start_with?(".")

        abspath = File.join(dir, basename)
        next if ignored_paths.member?(abspath)

        # We freeze abspath because that saves allocations when passed later to
        # File methods. See #125.
        yield basename, abspath.freeze
      end
    end

    # @sig (String) -> bool
    def ruby?(path)
      path.end_with?(".rb")
    end

    # @sig (String) -> bool
    def dir?(path)
      File.directory?(path)
    end

    # @sig (String | Pathname | Array[String | Pathname]) -> Array[String]
    def expand_paths(paths)
      paths.flatten.map! { |path| File.expand_path(path) }
    end

    # @sig (Array[String]) -> Array[String]
    def expand_glob_patterns(glob_patterns)
      # Note that Dir.glob works with regular file names just fine. That is,
      # glob patterns technically need no wildcards.
      glob_patterns.flat_map { |glob_pattern| Dir.glob(glob_pattern) }
    end

    # @sig () -> void
    def recompute_ignored_paths
      ignored_paths.replace(expand_glob_patterns(ignored_glob_patterns))
    end

    # @sig () -> void
    def recompute_collapse_dirs
      collapse_dirs.replace(expand_glob_patterns(collapse_glob_patterns))
    end

    # @sig (String) -> void
    def log(message)
      method_name = logger.respond_to?(:debug) ? :debug : :call
      logger.send(method_name, "Zeitwerk@#{tag}: #{message}")
    end

    # @sig (Module, Symbol) -> bool
    def cdef?(parent, cname)
      parent.const_defined?(cname, false)
    end

    # @sig (String) -> void
    def register_explicit_namespace(cpath)
      ExplicitNamespace.register(cpath, self)
    end

    # @sig (String) -> void
    def raise_if_conflicting_directory(dir)
      self.class.mutex.synchronize do
        Registry.loaders.each do |loader|
          if loader != self && loader.manages?(dir)
            require "pp"
            raise Error,
              "loader\n\n#{pretty_inspect}\n\nwants to manage directory #{dir}," \
              " which is already managed by\n\n#{loader.pretty_inspect}\n"
            EOS
          end
        end
      end
    end

    # @sig (Module, Symbol) -> void
    def unload_autoload(parent, cname)
      parent.__send__(:remove_const, cname)
      log("autoload for #{cpath(parent, cname)} removed") if logger
    end

    # @sig (Module, Symbol) -> void
    def unload_cref(parent, cname)
      parent.__send__(:remove_const, cname)
      log("#{cpath(parent, cname)} unloaded") if logger
    end
  end
end


text:
//
//  Copyright 2017  DRIVE BY WIRE
//
//    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.
using System;
namespace DriveByWire.Oirts.Core
{
    /// <summary>
    /// iRacing defines these variable types.
    /// </summary>
    public enum VariableType
    {
        /// <summary>
        /// Represents a char value. Length: 1 byte
        /// </summary>
        IRSDK_CHAR = 0,

        /// <summary>
        /// Represents a boolean value. Length: 1 byte
        /// </summary>
        IRSDK_BOOL,

        /// <summary>
        /// Represents an integer value. Length: 4 bytes
        /// </summary>
        IRSDK_INT,

        /// <summary>
        /// Represents a bitfield. Length: 4 bytes
        /// </summary>
        IRSDK_BITFIELD,

        /// <summary>
        /// Represents a float value. Length: 4 bytes
        /// </summary>
        IRSDK_FLOAT,

        /// <summary>
        /// Represents a double value. Length: 8 bytes
        /// </summary>
        IRSDK_DOUBLE
    }
}


text:
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Results;
using Exceptionless.Api.Controllers;
using Exceptionless.Api.Tests.Utility;
using Exceptionless.Core.Authorization;
using Exceptionless.Core.Extensions;
using Exceptionless.Core.Jobs;
using Exceptionless.Core.Messaging.Models;
using Exceptionless.Core.Models;
using Exceptionless.Core.Queues.Models;
using Exceptionless.Core.Repositories;
using Exceptionless.Helpers;
using Exceptionless.Tests.Utility;
using Foundatio.Messaging;
using Foundatio.Metrics;
using Foundatio.Queues;
using Foundatio.Repositories.Models;
using Microsoft.Owin;
using Nest;
using Newtonsoft.Json;
using Nito.AsyncEx;
using Xunit;

namespace Exceptionless.Api.Tests.Controllers {
    public class EventControllerTests {
        private static bool _databaseReset;
        private static bool _sampleOrganizationsAdded;
        private static bool _sampleProjectsAdded;

        private readonly IElasticClient _client = IoC.GetInstance<IElasticClient>();
        private readonly EventController _eventController = IoC.GetInstance<EventController>();
        private readonly IEventRepository _eventRepository = IoC.GetInstance<IEventRepository>();
        private readonly IQueue<EventPost> _eventQueue = IoC.GetInstance<IQueue<EventPost>>();
        private readonly IOrganizationRepository _organizationRepository = IoC.GetInstance<IOrganizationRepository>();
        private readonly IProjectRepository _projectRepository = IoC.GetInstance<IProjectRepository>();

        [Fact]
        public async Task CanPostStringAsync() {
            await ResetAsync();

            try {
                _eventController.Request = CreateRequestMessage(new ClaimsPrincipal(new User { EmailAddress = TestConstants.UserEmail, Id = TestConstants.UserId, OrganizationIds = new[] { TestConstants.OrganizationId }, Roles = new[] { AuthorizationRoles.Client }}.ToIdentity(TestConstants.ProjectId)), false, false);

                var metricsClient = IoC.GetInstance<IMetricsClient>() as InMemoryMetricsClient;
                Assert.NotNull(metricsClient);

                Assert.True(await metricsClient.WaitForCounterAsync("eventpost.enqueued", work: async () => {
                    var actionResult = await _eventController.PostAsync(Encoding.UTF8.GetBytes("simple string"));
                    Assert.IsType<StatusCodeResult>(actionResult);
                }));

                Assert.Equal(1, (await _eventQueue.GetQueueStatsAsync()).Enqueued);
                Assert.Equal(0, (await _eventQueue.GetQueueStatsAsync()).Completed);

                var processEventsJob = IoC.GetInstance<EventPostsJob>();
                await processEventsJob.RunAsync();

                Assert.Equal(1, (await _eventQueue.GetQueueStatsAsync()).Completed);
                Assert.Equal(1, await EventCountAsync());
            } finally {
                await RemoveAllEventsAsync();
            }
        }

        [Fact]
        public async Task CanPostCompressedStringAsync() {
            await ResetAsync();

            try {
                _eventController.Request = CreateRequestMessage(new ClaimsPrincipal(new User { EmailAddress = TestConstants.UserEmail, Id = TestConstants.UserId, OrganizationIds = new[] { TestConstants.OrganizationId }, Roles = new[] { AuthorizationRoles.Client } }.ToIdentity(TestConstants.ProjectId)), true, false);
                var actionResult = await _eventController.PostAsync(await Encoding.UTF8.GetBytes("simple string").CompressAsync());
                Assert.IsType<StatusCodeResult>(actionResult);
                Assert.Equal(1, (await _eventQueue.GetQueueStatsAsync()).Enqueued);
                Assert.Equal(0, (await _eventQueue.GetQueueStatsAsync()).Completed);

                var processEventsJob = IoC.GetInstance<EventPostsJob>();
                await processEventsJob.RunAsync();

                Assert.Equal(1, (await _eventQueue.GetQueueStatsAsync()).Completed);
                Assert.Equal(1, await EventCountAsync());
            } finally {
                await RemoveAllEventsAsync();
            }
        }

        [Fact]
        public async Task CanPostSingleEventAsync() {
            await ResetAsync();

            try {
                _eventController.Request = CreateRequestMessage(new ClaimsPrincipal(new User { EmailAddress = TestConstants.UserEmail, Id = TestConstants.UserId, OrganizationIds = new[] { TestConstants.OrganizationId }, Roles = new[] { AuthorizationRoles.Client } }.ToIdentity(TestConstants.ProjectId)), true, false);
                var actionResult = await _eventController.PostAsync(await Encoding.UTF8.GetBytes("simple string").CompressAsync());
                Assert.IsType<StatusCodeResult>(actionResult);
                Assert.Equal(1, (await _eventQueue.GetQueueStatsAsync()).Enqueued);
                Assert.Equal(0, (await _eventQueue.GetQueueStatsAsync()).Completed);

                var processEventsJob = IoC.GetInstance<EventPostsJob>();
                await processEventsJob.RunAsync();

                Assert.Equal(1, (await _eventQueue.GetQueueStatsAsync()).Completed);
                Assert.Equal(1, await EventCountAsync());
            } finally {
                await RemoveAllEventsAsync();
            }
        }

        [Fact]
        public async Task CanPostManyEventsAsync() {
            await ResetAsync();

            const int batchSize = 250;
            const int batchCount = 10;

            try {
                var countdown = new AsyncCountdownEvent(batchCount);
                var messageSubscriber = IoC.GetInstance<IMessageSubscriber>();
                messageSubscriber.Subscribe<ExtendedEntityChanged>(ch => {
                    if (ch.ChangeType != ChangeType.Added || ch.Type != typeof(PersistentEvent).Name)
                        return;

                    if (countdown.CurrentCount >= batchCount)
                        throw new ApplicationException("Too many change notifications.");

                    countdown.Signal();
                });

                await Run.InParallelAsync(batchCount, async i => {
                    _eventController.Request = CreateRequestMessage(new ClaimsPrincipal(new User { EmailAddress = TestConstants.UserEmail, Id = TestConstants.UserId, OrganizationIds = new[] { TestConstants.OrganizationId }, Roles = new[] { AuthorizationRoles.Client } }.ToIdentity(TestConstants.ProjectId)), true, false);
                    var events = new RandomEventGenerator().Generate(batchSize);
                    var compressedEvents = await Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(events)).CompressAsync();
                    var actionResult = await _eventController.PostAsync(compressedEvents, version: 2, userAgent: "exceptionless/2.0.0.0");
                    Assert.IsType<StatusCodeResult>(actionResult);
                });

                await _client.RefreshAsync();
                Assert.Equal(batchCount, (await _eventQueue.GetQueueStatsAsync()).Enqueued);
                Assert.Equal(0, (await _eventQueue.GetQueueStatsAsync()).Completed);

                var processEventsJob = IoC.GetInstance<EventPostsJob>();
                var sw = Stopwatch.StartNew();
                await processEventsJob.RunUntilEmptyAsync();
                sw.Stop();
                Trace.WriteLine(sw.Elapsed);

                await _client.RefreshAsync();
                Assert.Equal(batchCount, (await _eventQueue.GetQueueStatsAsync()).Completed);
                var minimum = batchSize * batchCount;
                Assert.InRange(await EventCountAsync(), minimum, minimum * 2);
            } finally {
                await _eventQueue.DeleteQueueAsync();
            }
        }

        private HttpRequestMessage CreateRequestMessage(ClaimsPrincipal user, bool isCompressed, bool isJson, string charset = "utf-8") {
            var request = new HttpRequestMessage();

            var context = new OwinContext();
            context.Request.User = Thread.CurrentPrincipal = user;
            request.SetOwinContext(context);
            request.SetConfiguration(new HttpConfiguration());
            request.Content = new HttpMessageContent(new HttpRequestMessage(HttpMethod.Post, "/api/v2/events"));
            if (isCompressed)
                request.Content.Headers.ContentEncoding.Add("gzip");
            request.Content.Headers.ContentType.MediaType = isJson ? "application/json" : "text/plain";
            request.Content.Headers.ContentType.CharSet = charset;

            return request;
        }

        private bool _isReset;
        private async Task ResetAsync() {
            if (!_isReset) {
                _isReset = true;
                await ResetDatabaseAsync();
                await AddSamplesAsync();
            }

            await _eventQueue.DeleteQueueAsync();
            await RemoveAllEventsAsync();
        }

        private async Task ResetDatabaseAsync(bool force = false) {
            if (_databaseReset && !force)
                return;

            await RemoveAllEventsAsync();
            await RemoveAllProjectsAsync();
            await RemoveAllOrganizationsAsync();

            _databaseReset = true;
        }

        public async Task RemoveAllOrganizationsAsync() {
            await _client.RefreshAsync();
            await _organizationRepository.RemoveAllAsync();
            await _client.RefreshAsync();
            _sampleOrganizationsAdded = false;
        }

        public async Task RemoveAllProjectsAsync() {
            await _client.RefreshAsync();
            await _projectRepository.RemoveAllAsync();
            await _client.RefreshAsync();
            _sampleProjectsAdded = false;
        }

        public async Task RemoveAllEventsAsync() {
            await _client.RefreshAsync();
            await _eventRepository.RemoveAllAsync();
            await _client.RefreshAsync();
        }

        public async Task<long> EventCountAsync() {
            await _client.RefreshAsync();
            return await _eventRepository.CountAsync();
        }

        public async Task AddSampleProjectsAsync() {
            if (_sampleProjectsAdded)
                return;

            await _projectRepository.AddAsync(ProjectData.GenerateSampleProjects());
            await _client.RefreshAsync();
            _sampleProjectsAdded = true;
        }

        public async Task AddSampleOrganizationsAsync() {
            if (_sampleOrganizationsAdded)
                return;

            await _organizationRepository.AddAsync(OrganizationData.GenerateSampleOrganizations());
            await _client.RefreshAsync();
            _sampleOrganizationsAdded = true;
        }

        public async Task AddSamplesAsync() {
            await AddSampleProjectsAsync();
            await AddSampleOrganizationsAsync();
        }
    }
}


text:
<!doctype html>

<meta charset="utf-8">
<link href="../layout.css" charset="utf-8" type="text/css" rel="stylesheet"></link>
<title>SDL_atomic_t</title>

SDL_atomic_t

A structure representing an atomic integer value.

Data Fields

int	value	the atomic integer value

Code Examples

Remarks

SDL_atomic_t is a structure so people don't accidentally use numeric operations on it. Instead, you should use the atomic operation functions to work with the integer value.

Related Functions

SDL_AtomicAdd

SDL_AtomicCAS

SDL_AtomicDecRef

SDL_AtomicGet

SDL_AtomicIncRef

SDL_AtomicSet


text:
using namespace std;

//|---------------------- SkyboxPlugin --------------------------------------
//|--------------------------------------------------------------------------

///////////////////////// SkyboxPlugin::Constructor /////////////////////////
SkyboxPlugin::SkyboxPlugin()
{
}

///////////////////////// SkyboxPlugin::Destructor //////////////////////////
SkyboxPlugin::~SkyboxPlugin()
{
  shutdown();
}

///////////////////////// SkyboxPlugin::initialise //////////////////////////
bool SkyboxPlugin::initialise(QStringList const &arguments, QString *errormsg)
{
  auto viewfactory = Studio::Core::instance()->find_object<Studio::ViewFactory>();

  viewfactory->register_factory("SkyBox", this);

  auto actionmanager = Studio::Core::instance()->find_object<Studio::ActionManager>();

  auto create = new QAction("SkyBox", this);

  actionmanager->register_action("Skybox.Create", create);

  actionmanager->container("Content.Menu.Create")->add_back(create);

  auto contentmanager = Studio::Core::instance()->find_object<Studio::ContentManager>();

  contentmanager->register_creator("SkyBox", this);

  auto buildmanager = Studio::Core::instance()->find_object<Studio::BuildManager>();

  buildmanager->register_builder("SkyBox", this);

  auto packmanager = Studio::Core::instance()->find_object<Studio::PackManager>();

  packmanager->register_packer("SkyBox", this);

  return true;
}

///////////////////////// SkyboxPlugin::shutdown ////////////////////////////
void SkyboxPlugin::shutdown()
{
}

///////////////////////// SkyboxPlugin::create_view /////////////////////////
QWidget *SkyboxPlugin::create_view(QString const &type)
{
  return new SkyboxEditor;
}

///////////////////////// SkyboxPlugin::create //////////////////////////////
bool SkyboxPlugin::create(QString const &type, QString const &path, QJsonObject metadata)
{
  SkyboxDocument::create(path.toStdString());

  return true;
}

///////////////////////// SkyboxPlugin::hash ////////////////////////////////
bool SkyboxPlugin::hash(Studio::Document *document, size_t *key)
{
  SkyboxDocument::hash(document, key);

  return true;
}

///////////////////////// SkyboxPlugin::build ///////////////////////////////
bool SkyboxPlugin::build(Studio::Document *document, QString const &path)
{
  SkyboxDocument::build(document, path.toStdString());

  return true;
}

///////////////////////// SkyboxPlugin::pack /////////////////////////////////
bool SkyboxPlugin::pack(Studio::PackerState &asset, ofstream &fout)
{
  SkyboxDocument::pack(asset, fout);

  return true;
}