text:
import * as columnService from '../column/column.service';
import { Log } from '../infrastructure/log';
import { selectColumn } from '../navigation/navigation.state.selector';
import * as css from '../services/css';
import { Fastdom } from '../services/fastdom';

export class LayoutLet {

  get gridId() {
    return this.plugin.model.grid().id;
  }

  constructor(plugin) {
    const { model, observeReply, disposable } = plugin;
    const styleRow = this.styleRow.bind(this);

    this.plugin = plugin;

    observeReply(model.navigationChanged)
      .subscribe(e => {
        if (e.hasChanges('cell')) {
          const { oldValue, newValue } = e.changes.cell;
          const oldColumn = oldValue ? oldValue.column : {};
          const newColumn = newValue ? newValue.column : {};

          if (oldColumn.key !== newColumn.key && (oldColumn.viewWidth || newColumn.viewWidth)) {
            Fastdom.measure(() => {
              const form = this.updateColumnForm();
              Fastdom.mutate(() => this.invalidateColumns(form));
            });
          }
        }
      });

    observeReply(model.layoutChanged)
      .subscribe(e => {
        if (e.tag.source === 'layout.let') {
          return;
        }

        if (e.hasChanges('columns')) {
          Fastdom.measure(() => {
            const form = this.updateColumnForm();
            Fastdom.mutate(() => this.invalidateColumns(form));
          });
        }
      });

    observeReply(model.rowChanged)
      .subscribe(e => {
        if (e.hasChanges('canResize')) {
          const rows = Array.from(model.style().rows);
          if (e.state.canResize) {
            rows.push(styleRow);
          } else {
            const index = model.style.rows.indexOf(styleRow);
            rows.splice(index, 1);
          }
          model.style({ rows }, { source: 'layout.let' });
        }
      });

    observeReply(model.dataChanged)
      .subscribe(e => {
        if (e.hasChanges('columns')) {
          model.layout({
            columns: new Map(),
          }, {
            source: 'layout.let',
            behavior: 'core',
          });
        }
      });

    observeReply(model.viewChanged)
      .subscribe(e => {
        if (e.hasChanges('columns')) {
          const columns = columnService.flattenColumns(e.state.columns);
          const hasNonDefaultWidth = x => x.width !== null || x.minWidth !== null
					|| x.maxWidth !== null || x.widthMode === 'fit-head';
          if (columns.some(hasNonDefaultWidth)) {
            Fastdom.mutate(() => {
              const { columns } = model.layout();
              this.invalidateColumns(columns);
            });
          }
        }
      });

    disposable.add(() => {
      const sheet = css.sheet(this.gridId, 'column-layout');
      sheet.remove();
    });
  }

  updateColumnForm() {
    const { model, table } = this.plugin;
    const { head } = table;
    const { cells } = head.context.bag;
    const layout = model.layout().columns;

    const form = new Map();
    for (const cell of cells) {
      const { column, rowIndex, columnIndex } = cell;
      if (!column.canResize) {
        continue;
      }

      const { key } = column;
      if (layout.has(key)) {
        const { width } = layout.get(key);
        form.set(key, { width });
      } else {
        const th = head.cell(rowIndex, columnIndex);
        const width = th.width();

        // It can be that clientWidth is zero on start, while css is not applied.
        if (width) {
          form.set(key, { width });
        }
      }
    }

    model.layout({ columns: form }, { source: 'layout.let', behavior: 'core' });

    const column = selectColumn(model.navigation());
    if (column && column.viewWidth) {
      const viewForm = new Map(form);
      const columnForm = form.get(column.key);
      viewForm.set(column.key, { width: columnForm ? Math.max(columnForm.width, column.viewWidth) : column.viewWidth });
      return viewForm;
    }

    return form;
  }

  invalidateColumns(form) {
    Log.info('layout', 'invalidate columns');

    const { table } = this.plugin;
    const columns = table.data.columns();
    const getWidth = columnService.widthFactory(table, form);

    const style = {};
    let { length } = columns;

    while (length--) {
      const column = columns[length];
      const width = getWidth(column.key);
      if (null !== width) {
        const key = css.escape(column.key);
        const size = width + 'px';
        const sizeStyle = {
          'width': size,
          'min-width': size,
          'max-width': size,
        };

        style[`.q-grid-the-${key}`] = sizeStyle;
      }
    }

    const sheet = css.sheet(this.gridId, 'column-layout');
    sheet.set(style);
  }

  styleRow(row, context) {
    const { model } = this.plugin;
    const { layout } = model;

    const form = layout().rows;
    const style = form.get(row);
    if (style) {
      const { minHeight } = model.row();
      if (minHeight > style.height){
        return;
      }

      context.class(`resized-${style.height}px`, { height: style.height + 'px' });
    }
  }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('cbh_chembl_model_extension', '0025_auto_20150807_0933'),
    ]

    operations = [
        migrations.AddField(
            model_name='cbhcompoundbatch',
            name='big_image',
            field=models.TextField(default=b''),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='cbhcompoundbatch',
            name='image',
            field=models.TextField(default=b''),
            preserve_default=True,
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
package com.dtflys.test.http;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dtflys.forest.backend.HttpBackend;
import com.dtflys.forest.config.ForestConfiguration;
import com.dtflys.forest.converter.json.ForestFastjsonConverter;
import com.dtflys.test.http.client.PostClient;
import com.dtflys.test.mock.PostJsonMockServer;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.junit.Assert.assertNotNull;

/**
 * @author gongjun[jun.gong@thebeastshop.com]
 * @since 2017-05-11 16:55
 */
public class TestPostJsonClient extends BaseClientTest {

    private final static Logger log = LoggerFactory.getLogger(TestPostJsonClient.class);

    @Rule
    public PostJsonMockServer server = new PostJsonMockServer(this);

    private static ForestConfiguration configuration;

    private static PostClient postClient;

    @BeforeClass
    public static void prepareClient() {
        configuration = ForestConfiguration.configuration();
        configuration.setVariableValue("port", PostJsonMockServer.port);
        ForestFastjsonConverter fastjsonConverter = new ForestFastjsonConverter();
        fastjsonConverter.setSerializerFeature(SerializerFeature.SortField);
        configuration.setJsonConverter(fastjsonConverter);
    }

    public TestPostJsonClient(HttpBackend backend) {
        super(backend, configuration);
        postClient = configuration.createInstance(PostClient.class);
    }

    @Before
    public void prepareMockServer() {
        server.initServer();
    }

    @Test
    public void testJsonPost() {
        String result = postClient.postJson("foo", "123456&&++===", "中文名");
        log.info("response: " + result);
        assertNotNull(result);
        Assert.assertEquals(PostJsonMockServer.EXPECTED, result);
    }

    @Test
    public void testJsonPost2() {
        String result = postClient.postJson2("foo", "123456&&++===", "中文名");
        log.info("response: " + result);
        assertNotNull(result);
        Assert.assertEquals(PostJsonMockServer.EXPECTED, result);
    }

    @Test
    public void testJsonPost3() {
        String result = postClient.postJson3("foo", "123456&&++===", "中文名");
        log.info("response: " + result);
        assertNotNull(result);
        Assert.assertEquals(PostJsonMockServer.EXPECTED, result);
    }

    @Test
    public void testJsonPost4() {
        String result = postClient.postJson4("foo", "123456&&++===", "中文名");
        log.info("response: " + result);
        assertNotNull(result);
        Assert.assertEquals(PostJsonMockServer.EXPECTED, result);
    }

/*
    @Test
    public void testJsonPost5() {
        SimpleUser user = new SimpleUser();
        user.setUsername("foo");
        user.setPassword("123456");
        String result = postClient.postJson5(user);
        log.info("response: " + result);
        assertNotNull(result);
        Assert.assertEquals(PostJsonMockServer.EXPECTED, result);
    }

    @Test
    public void testJsonPost6() {
        SimpleUser user = new SimpleUser();
        user.setUsername("foo");
        user.setPassword("123456");
        String result = postClient.postJson6(user);
        log.info("response: " + result);
        assertNotNull(result);
        Assert.assertEquals(PostJsonMockServer.EXPECTED, result);
    }
*/

}


text:
import { mergeWith } from "lodash";
export = mergeWith;


text:
const assert = require('chai').assert;
const AWS = require('aws-sdk-mock');
const alert = require('../util/alert');

describe('Alert Util', () => {
    it('should alert if aws key is present', () => {
        process.env.SNS_ALERT_TOPIC_ARN = 'foo';
        process.env.AWS_ACCESS_KEY_ID = 'bar';
        process.env.AWS_SECRET_ACCESS_KEY = 'baz';
        process.env.AWS_REGION = 'us-west-2';
        const mock = AWS.mock('SNS', 'publish');
        alert('foo', 'bar');
        assert.deepEqual(mock.stub.getCall(0).args[0], { TopicArn: process.env.SNS_ALERT_TOPIC_ARN, Message: 'bar', Subject: 'foo' });
    });
    it('should not alert if no aws key', () => {
        delete process.env.SNS_ALERT_TOPIC_ARN;
        assert.isFalse(alert('foo', 'bar'));
    });
});


text:
from __future__ import print_function
import time, sys, signal, atexit
from upm import pyupm_sm130 as sensorObj

def main():
    # Instantiate a UART based SM130 RFID Module using defaults
    sensor = sensorObj.SM130()

    ## Exit handlers ##
    # This stops python from printing a stacktrace when you hit control-C
    def SIGINTHandler(signum, frame):
        raise SystemExit

    # This function lets you run code on exit
    def exitHandler():
        print("Exiting")
        sys.exit(0)

    # Register exit handlers
    atexit.register(exitHandler)
    signal.signal(signal.SIGINT, SIGINTHandler)

    # Set the baud rate, 19200 baud is the default.
    if (sensor.setBaudRate(19200)):
        print("Failed to set baud rate")
        sys.exit(0)

    print("Resetting...")
    sensor.reset()

    print("Firmware revision: " + sensor.getFirmwareVersion())

    print("Waiting up to 5 seconds for a tag...")

    if (sensor.waitForTag(5000)):
        print("Found tag, UID:", end=' ')
        print(sensor.string2HexString(sensor.getUID()))
        print("Tag Type:", end=' ')
        print(sensor.tag2String(sensor.getTagType()))
    else:
        # error
        print("waitForTag failed: " + sensor.getLastErrorString())

if __name__ == '__main__':
    main()


text:
import json
import logging

import netaddr

from powergslb.server.http.handler.abstract import AbstractContentHandler

import powergslb.monitor

__all__ = ['PowerDNSContentHandler']

class PowerDNSContentHandler(AbstractContentHandler):
    """
    PowerDNS content handler
    """

    def _filter_records(self, qtype_records):
        records = []
        for qtype in qtype_records:

            fallback_records = {}
            live_records = {}

            for record in qtype_records[qtype]:
                if not self._is_in_view(record):
                    continue

                if record['fallback']:
                    if record['weight'] not in fallback_records:
                        fallback_records[record['weight']] = []

                    fallback_records[record['weight']].append(record)

                if record['id'] not in powergslb.monitor.get_status():
                    if record['weight'] not in live_records:
                        live_records[record['weight']] = []

                    live_records[record['weight']].append(record)

            if live_records:
                filtered_records = live_records[max(live_records)]
            elif fallback_records:
                filtered_records = fallback_records[max(fallback_records)]
            else:
                filtered_records = []

            if not filtered_records:
                continue

            if filtered_records[0]['persistence']:
                records.append(self._remote_ip_persistence(filtered_records))
            else:
                records.extend(filtered_records)

        return records

    def _get_lookup(self):
        v3_format = True
        if self.dirs[2].endswith('.'):
            v3_format = False
            self.dirs[2] = self.dirs[2].rstrip('.')

        records = self.database.gslb_records(*self.dirs[2:])
        qtype_records = self._split_records(records, v3_format)
        filtered_records = self._filter_records(qtype_records)
        return self._strip_records(filtered_records, v3_format)

    def _is_in_view(self, record):
        result = False
        try:
            result = bool(netaddr.smallest_matching_cidr(self.remote_ip, record.get('rule').split()))
        except (AttributeError, netaddr.AddrFormatError, ValueError) as e:
            logging.error('{}: record id {} view rule invalid: {}: {}'.format(
                type(self).__name__, record['id'], type(e).__name__, e))

        return result

    def _remote_ip_persistence(self, records):
        persistence_value = netaddr.IPAddress(self.remote_ip).value >> records[0]['persistence']
        return records[hash(persistence_value) % len(records)]

    def _split_records(self, records, v3_format=False):
        qtype_records = {}
        for record in records:
            if v3_format and record['qtype'] in ['MX', 'SRV']:
                content_split = record['content'].split()
                try:
                    record['priority'] = int(content_split[0])
                    record['content'] = ' '.join(content_split[1:])
                except (KeyError, ValueError) as e:
                    logging.error('{}: record id {} priority missing or invalid: {}: {}'.format(
                        type(self).__name__, record['id'], type(e).__name__, e))
                    continue

            if record['qtype'] not in qtype_records:
                qtype_records[record['qtype']] = []

            qtype_records[record['qtype']].append(record)

        return qtype_records

    @staticmethod
    def _strip_records(records, v3_format=False):
        result = []
        for record in records:
            if v3_format and record['qtype'] in ['MX', 'SRV']:
                names = ['qname', 'qtype', 'content', 'ttl', 'priority']
                values = [record['qname'], record['qtype'], record['content'], record['ttl'], record['priority']]
            else:
                names = ['qname', 'qtype', 'content', 'ttl']
                values = [record['qname'], record['qtype'], record['content'], record['ttl']]

            result.append(dict(zip(names, values)))

        return result

    def content(self):
        if len(self.dirs) == 4 and self.dirs[1] == 'lookup':
            content = {'result': self._get_lookup()}
        else:
            content = {'result': False}

        return json.dumps(content, separators=(',', ':'))


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>CustomAsyncPolicy | @uirouter/react</title>
	<meta name="description" content="Documentation for @uirouter/react">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					@uirouter/react

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals

					Menu

					@uirouter/react

					@uirouter/core/resolve/interface

					CustomAsyncPolicy

Interface CustomAsyncPolicy

Hierarchy

						CustomAsyncPolicy

Callable

__call(data: any): Promise<any>

Defined in @uirouter/core/src/resolve/interface.ts:206

Parameters

data: any

Returns Promise<any>

						UIRouter<wbr>React

						Services

						State<wbr>Service

						State<wbr>Registry

						Transition<wbr>Service

						Url<wbr>Service

						Url<wbr>Config

						Url<wbr>Rules

						Interfaces

						React<wbr>State<wbr>Declaration

						Components

						UIRouter

						UIView

						UISref

						UISref<wbr>Active

						React <wbr>Hooks

						use<wbr>Router

						use<wbr>Sref

						use<wbr>Sref<wbr>Active

						use<wbr>Sref<wbr>Active<wbr>Exact

						use<wbr>Transition<wbr>Hook

						use<wbr>Current<wbr>State<wbr>And<wbr>Params

						use<wbr>OnState<wbr>Changed

						use<wbr>IsActive

						Other

						Transition

						Trace

						Custom<wbr>Async<wbr>Policy

						Provider<wbr>Like

						Resolvable<wbr>Literal

						Resolve<wbr>Policy

						Policy<wbr>Async

						Policy<wbr>When

						resolve<wbr>Policies

Legend

Generated using TypeDoc


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

namespace YamlDotNet.Serialization.TypeInspectors
{
    /// <summary>
    /// Returns the properties of a type that are both readable and writable.
    /// </summary>
    public sealed class ReadableAndWritablePropertiesTypeInspector : TypeInspectorSkeleton
    {
        private readonly ITypeInspector _innerTypeDescriptor;

        public ReadableAndWritablePropertiesTypeInspector(ITypeInspector innerTypeDescriptor)
        {
            _innerTypeDescriptor = innerTypeDescriptor;
        }

        public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object container)
        {
            return _innerTypeDescriptor.GetProperties(type, container)
                .Where(p => p.CanWrite);
        }
    }
}


text:
namespace NetCoreApp21
{
  using System.Globalization;

  using Localization.AspNetCore.TagHelpers;

  using Microsoft.AspNetCore.Builder;
  using Microsoft.AspNetCore.Hosting;
  using Microsoft.AspNetCore.Http;
  using Microsoft.AspNetCore.Localization;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.AspNetCore.Mvc.Razor;
  using Microsoft.Extensions.Configuration;
  using Microsoft.Extensions.DependencyInjection;

  public class Startup
  {
    public Startup(IConfiguration configuration)
    {
      Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
#pragma warning disable CA1822 // Mark members as static

    public void ConfigureServices(IServiceCollection services)
#pragma warning restore CA1822 // Mark members as static
    {
      services.AddLocalization(options => options.ResourcesPath = "Localization");

      services.Configure<CookiePolicyOptions>(options =>
      {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
      });

      services
        .AddMvc()
        .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
        .AddDataAnnotationsLocalization()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

      // The following configuration is optional, this just sets the default values
      services.Configure<LocalizeTagHelperOptions>(options =>
      {
        options.HtmlEncodeByDefault = true;
        options.NewLineHandling = NewLineHandling.Auto;
        options.TrimWhitespace = true;
      });

      // We configure it here, so we can use DI to get the options in the view
      services.Configure<RequestLocalizationOptions>(options =>
      {
        var supportedCultures = new[]
        {
          "en",
          "nb"
        };

        options.AddSupportedCultures(supportedCultures)
               .AddSupportedUICultures(supportedCultures)
               .SetDefaultCulture(supportedCultures[0]);
      });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
#pragma warning disable CA1822 // Mark members as static

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
#pragma warning restore CA1822 // Mark members as static
    {
      app.UseRequestLocalization();

      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }
      else
      {
        app.UseExceptionHandler("/Home/Error");
      }

      app.UseStaticFiles();
      app.UseCookiePolicy();

#pragma warning disable IDE0053 // Use expression body for lambda expressions
      app.UseMvc(routes =>
#pragma warning restore IDE0053 // Use expression body for lambda expressions
      {
        routes.MapRoute(
                  name: "default",
                  template: "{controller=Home}/{action=Index}/{id?}");
      });
    }
  }
}


text:
import mahotas

class ZernikeMoments:
	def __init__(self, radius):
		# store the size of the radius that will be
		# used when computing moments
		self.radius = radius

	def describe(self, image):
		# return the Zernike moments for the image
		return mahotas.features.zernike_moments(image, self.radius)


text:
<?php

namespace Quartet\Haydn\Set;

use Quartet\Haydn\Set;

class ProductSet extends AbstractOperationalSet
{
    /**
     * {@inheritdoc}
     */
    protected function iterate() {
        $this->a->rewind();
        foreach ($this->a->getIterator() as $r1) {
            $this->b->rewind();
            foreach ($this->b->getIterator() as $r2) {
                yield array_merge($r1, $r2);
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function count()
    {
        return $this->a->count() * $this->b->count();
    }
}


text:
import os, os.path, sys, shutil, re, itertools
from collections import namedtuple
from distutils.command.build_ext import build_ext as _build_ext
from distutils.command.build import build as _build

from distutils.core import setup
from distutils.core import Extension

pack_name = 'rpy2'
pack_version = __import__('rpy').__version__

package_prefix='.'
if sys.version_info >= (3,):
    print("Using 2to3 to translate Python2-only idioms into Python3 code. Please wait...")
    # Python 3 and we need to translate code
    package_prefix = os.path.join('build', 'python3_rpy')
    from distutils import filelist, dir_util, file_util, util#, log
    #log.set_verbosity(1)
    fl = filelist.FileList()
    tmp = open("MANIFEST.in")
    for line in tmp:
        line = line.rstrip()
        if line != '':
            fl.process_template_line(line)
    tmp.close()
    dir_util.create_tree(package_prefix, fl.files)
    outfiles_2to3 = []
    #dist_script = os.path.join("build", "src", "distribute_setup.py")
    for f in fl.files:
        outf, copied = file_util.copy_file(f, os.path.join(package_prefix, f),
                                           update=1)
        if copied and outf.endswith(".py"): #and outf != dist_script:
            outfiles_2to3.append(outf)
        if copied and outf.endswith('api_tests.txt'):
            # XXX support this in distutils as well
            from lib2to3.main import main
            main('lib2to3.fixes', ['-wd', os.path.join(package_prefix,
                                                       'tests', 'api_tests.txt')])

    util.run_2to3(outfiles_2to3)

    # arrange setup to use the copy
    sys.path.insert(0, package_prefix)
    src_root = package_prefix
    print('done.')
else:
    from distutils.core import setup
from distutils.core import Extension

class build(_build):
    user_options = _build.user_options + \
        [
        #('r-autoconfig', None,
        # "guess all configuration paths from " +\
        #     "the R executable found in the PATH " +\
        #     "(this overrides r-home)"),
        ('r-home=', None,
         "full path for the R home to compile against " +\
             "(see r-autoconfig for an automatic configuration)"),
        ('r-home-lib=', None,
         "full path for the R shared lib/ directory " +\
             "(<r-home>/lib otherwise)"),
        ('r-home-modules=', None,
         "full path for the R shared modules/ directory " +\
             "(<r-home>/modules otherwise)")
        ]
    boolean_options = _build.boolean_options #+ \
        #['r-autoconfig', ]

    def initialize_options(self):
        _build.initialize_options(self)
        self.r_autoconfig = None
        self.r_home = None
        self.r_home_lib = None
        self.r_home_modules = None

class build_ext(_build_ext):
    """
    -DRPY_STRNDUP          : definition of strndup()
    -DRPY_VERBOSE
    -DRPY_DEBUG_PRESERV
    -DRPY_DEBUG_PROMISE    : evaluation of promises
    -DRPY_DEBUG_OBJECTINIT : initialization of PySexpObject
    -DRPY_DEBUG_CONSOLE    : console I/O
    -DRPY_DEBUG_COBJECT    : SexpObject passed as a CObject
    -DRPY_DEBUG_GRDEV
    """
    user_options = _build_ext.user_options + \
        [
        #('r-autoconfig', None,
        #  "guess all configuration paths from " +\
        #      "the R executable found in the PATH " +\
        #      "(this overrides r-home)"),
        ('r-home=', None,
         "full path for the R home to compile against " +\
             "(see r-autoconfig for an automatic configuration)"),
        ('r-home-lib=', None,
         "full path for the R shared lib/ directory" +\
             "(<r-home>/lib otherwise)"),
        ('r-home-modules=', None,
         "full path for the R shared modules/ directory" +\
             "(<r-home>/modules otherwise)")]

    boolean_options = _build_ext.boolean_options #+ \
        #['r-autoconfig', ]

    def initialize_options(self):
        _build_ext.initialize_options(self)
        self.r_autoconfig = None
        self.r_home = None
        self.r_home_lib = None
        self.r_home_modules = None

    def finalize_options(self):
        self.set_undefined_options('build',
                                   #('r_autoconfig', 'r_autoconfig'),
                                   ('r_home', 'r_home'))
        _build_ext.finalize_options(self)
        if self.r_home is None:
            tmp = os.popen("R RHOME")
            self.r_home = tmp.readlines()
            tmp.close()
            if len(self.r_home) == 0:
                raise SystemExit("Error: Tried to guess R's HOME but no R command in the PATH.")

    #Twist if 'R RHOME' spits out a warning
            if self.r_home[0].startswith("WARNING"):
                self.r_home = self.r_home[1]
            else:
                self.r_home = self.r_home[0]
            #self.r_home = [self.r_home, ]

        if self.r_home is None:
            raise SystemExit("Error: --r-home not specified.")
        else:
            self.r_home = self.r_home.split(os.pathsep)

        rversions = []
        for r_home in self.r_home:
            r_home = r_home.strip()
        rversion = get_rversion(r_home)
        if cmp_version(rversion[:2], [2, 8]) == -1:
            raise SystemExit("Error: R >= 2.8 required.")
        rversions.append(rversion)

        config = RConfig()
        for about in ('--ldflags', '--cppflags',
                      'LAPACK_LIBS', 'BLAS_LIBS'):
            if sys.platform == "win32":
                config += get_rconfig(r_home, about, True)
            else:
                config += get_rconfig(r_home, about)
        print(config.__repr__())

        self.include_dirs.extend(config._include_dirs)
        self.libraries.extend(config._libraries)
        self.library_dirs.extend(config._library_dirs)

        if self.r_home_modules is None:
            self.library_dirs.extend([os.path.join(r_home, 'modules'), ])
        else:
            self.library_dirs.extends([self.r_home_modules, ])

        #for e in self.extensions:
        #    self.extra_link_args.extra_link_args(config.extra_link_args)
        #    e.extra_compile_args.extend(extra_link_args)

    def run(self):
        _build_ext.run(self)

def get_rversion(r_home):
    r_exec = os.path.join(r_home, 'bin', 'R')
    # Twist if Win32
    if sys.platform == "win32":
        rp = os.popen3('"'+r_exec+'" --version')[2]
    else:
        rp = os.popen('"'+r_exec+'" --version')
    rversion = rp.readline()
    #Twist if 'R RHOME' spits out a warning
    if rversion.startswith("WARNING"):
        rversion = rp.readline()
    m = re.match('^R version ([^ ]+) .+$', rversion)
    rversion = m.groups()[0]
    rversion = rversion.split('.')
    rversion[0] = int(rversion[0])
    rversion[1] = int(rversion[1])
    rp.close()
    return rversion

def cmp_version(x, y):
    if (x[0] < y[0]):
        return -1
    if (x[0] > y[0]):
        return 1
    if (x[0] == y[0]):
        if len(x) == 1 or len(y) == 1:
            return 0
        return cmp_version(x[1:], y[1:])

class RConfig(object):
    _include_dirs = None
    _libraries = None
    _library_dirs = None
    _extra_link_args = None
    _frameworks = None
    _framework_dirs = None

    def __init__(self,
                 include_dirs = tuple(), libraries = tuple(),
                 library_dirs = tuple(), extra_link_args = tuple(),
                 frameworks = tuple(),
                 framework_dirs = tuple()):
        for k in ('include_dirs', 'libraries',
                  'library_dirs', 'extra_link_args'):
            v = locals()[k]
            if not isinstance(v, tuple):
                if isinstance(v, str):
                    v = [v, ]
            v = tuple(set(v))
            self.__dict__['_'+k] = v
        # frameworks are specific to OSX
        for k in ('framework_dirs', 'frameworks'):
            v = locals()[k]
            if not isinstance(v, tuple):
                if isinstance(v, str):
                    v = [v, ]
            v = tuple(set(v))
            self.__dict__['_'+k] = v
            self.__dict__['_'+'extra_link_args'] = tuple(set(v + self.__dict__['_'+'extra_link_args']))

    @staticmethod
    def from_string(string, allow_empty = False):
        possible_patterns = ('^-L(?P<library_dirs>[^ ]+)$',
                             '^-l(?P<libraries>[^ ]+)$',
                             '^-I(?P<include_dirs>[^ ]+)$',
                             '^(?P<framework_dirs>-F[^ ]+?)$',
                             '^(?P<frameworks>-framework [^ ]+)$',
                             '^(?P<extra_link_args>-Wl[^ ]+)$')
        pp = [re.compile(x) for x in possible_patterns]
        # sanity check of what is returned into rconfig
        rconfig_m = None
        span = (0, 0)
        rc = RConfig()

        for substring in re.split('(?<!-framework) ', string):
            ok = False
            for pattern in pp:
                rconfig_m = pattern.match(substring)
                if rconfig_m is not None:
                    rc += RConfig(**rconfig_m.groupdict())
                    span = rconfig_m.span()
                    ok = True
                    break
                elif rconfig_m is None:

                    if allow_empty:
                        if sys.platform == 'win32':
                            if (rconfig == ''):
                                print(cmd + '\nreturned an empty string.\n')
                            else:
                                print('\nreturned an empty string.\n')
                        rc += RConfig()
                        ok = True
                        break
                    else:
                        # if the configuration points to an existing library,
                        # use it
                        if os.path.exists(string):
                            rc += RConfig(libraries = substring)
                            ok = True
                            break
            if not ok:
                raise ValueError('Invalid substring\n' + substring
                                 + '\nin string\n' + string)
        return rc

    def __repr__(self):
        s = 'Configuration for R as a library:' + os.linesep
        s += os.linesep.join(
            ['  ' + x + ': ' + self.__dict__['_'+x].__repr__() \
                 for x in ('include_dirs', 'libraries',
                           'library_dirs', 'extra_link_args')])
        s += os.linesep + ' # OSX-specific (included in extra_link_args)' + os.linesep
        s += os.linesep.join(
            ['  ' + x + ': ' + self.__dict__['_'+x].__repr__() \
                 for x in ('framework_dirs', 'frameworks')]
            )

        return s

    def __add__(self, config):
        assert isinstance(config, RConfig)
        res = RConfig(include_dirs = self._include_dirs + \
                          config._include_dirs,
                      libraries = self._libraries + config._libraries,
                      library_dirs = self._library_dirs + \
                          config._library_dirs,
                      extra_link_args = self._extra_link_args + \
                          config._extra_link_args,
                      frameworks = self._frameworks + config._frameworks,
                      framework_dirs = self._framework_dirs + config._framework_dirs)
        return res

def get_rconfig(r_home, about, allow_empty = False):
    r_exec = os.path.join(r_home, 'bin', 'R')
    cmd = '"'+r_exec+'" CMD config '+about
    rp = os.popen(cmd)
    rconfig = rp.readline()
    #Twist if 'R RHOME' spits out a warning
    if rconfig.startswith("WARNING"):
        rconfig = rp.readline()
    rconfig = rconfig.strip()
    rc = RConfig.from_string(rconfig, allow_empty = allow_empty)
    rp.close()
    return rc

def getRinterface_ext():
    #r_libs = [os.path.join(RHOME, 'lib'), os.path.join(RHOME, 'modules')]
    r_libs = []
    extra_link_args = []

    #FIXME: crude way (will break in many cases)
    #check how to get how to have a configure step
    define_macros = []

    if sys.platform == 'win32':
        define_macros.append(('Win32', 1))
    else:
        define_macros.append(('R_INTERFACE_PTRS', 1))
        define_macros.append(('HAVE_POSIX_SIGJMP', 1))
        define_macros.append(('RIF_HAS_RSIGHAND', 1))

    define_macros.append(('CSTACK_DEFNS', 1))

    if sys.byteorder == 'big':
        define_macros.append(('RPY_BIGENDIAN', 1))
    else:
        pass

    include_dirs = []

    rinterface_ext = Extension(
            name = pack_name + '.rinterface._rinterface',
            sources = [ \
            #os.path.join('rpy', 'rinterface', 'embeddedr.c'),
            #os.path.join('rpy', 'rinterface', 'r_utils.c'),
            #os.path.join('rpy', 'rinterface', 'buffer.c'),
            #os.path.join('rpy', 'rinterface', 'sequence.c'),
            #os.path.join('rpy', 'rinterface', 'sexp.c'),
            os.path.join(package_prefix,
                         'rpy', 'rinterface', '_rinterface.c')
                       ],
            depends = [os.path.join(package_prefix,
                                    'rpy', 'rinterface', 'embeddedr.h'),
                       os.path.join(package_prefix,
                                    'rpy', 'rinterface', 'r_utils.h'),
                       os.path.join(package_prefix,
                                    'rpy', 'rinterface', 'buffer.h'),
                       os.path.join(package_prefix,
                                    'rpy', 'rinterface', 'sequence.h'),
                       os.path.join(package_prefix,
                                    'rpy', 'rinterface', 'sexp.h'),
                       os.path.join(package_prefix,
                                    'rpy', 'rinterface', 'rpy_rinterface.h'),
                       os.path.join(package_prefix,
                                    'rpy', 'rinterface', 'rpy_device.h')
                       ],
            include_dirs = [os.path.join(package_prefix,
                                         'rpy', 'rinterface'),] + include_dirs,
            libraries = ['R', ],
            library_dirs = r_libs,
            define_macros = define_macros,
            runtime_library_dirs = r_libs,
            #extra_compile_args=['-O0', '-g'],
            #extra_link_args = extra_link_args
            )

    rpy_device_ext = Extension(
        pack_name + '.rinterface.rpy_device',
            [
            os.path.join('rpy', 'rinterface', 'rpy_device.c'),
             ],
            include_dirs = include_dirs +
                            [os.path.join('rpy', 'rinterface'), ],
            libraries = ['R', ],
            library_dirs = r_libs,
            define_macros = define_macros,
            runtime_library_dirs = r_libs,
            #extra_compile_args=['-O0', '-g'],
            extra_link_args = extra_link_args
        )

    return [rinterface_ext, rpy_device_ext]

if __name__ == '__main__':
    rinterface_exts = []
    ri_ext = getRinterface_ext()
    rinterface_exts.append(ri_ext)

    pack_dir = {pack_name: os.path.join(package_prefix, 'rpy')}

    import distutils.command.install
    for scheme in distutils.command.install.INSTALL_SCHEMES.values():
        scheme['data'] = scheme['purelib']

    setup(
        #install_requires=['distribute'],
        cmdclass = {'build': build,
                    'build_ext': build_ext},
        name = pack_name,
        version = pack_version,
        description = """
About rpy2
==========

Rpy2 is a Python interface to the R language, mainly constitutued
of a low-level interface (rpy2.rinterface) close to R's C-level API
and a high-level interface with convenience classes and features
(rpy2.robjects).

The high-level interface is implemented using the low-level interface
and other high-level interfaces are possible. The original rpy interface
can be implemented with the low-level interface (rpy2.rpy_classic)

""",
        url = "http://rpy.sourceforge.net",
        license = "AGPLv3.0 (except rpy2.rinterface: LGPL)",
        author = "Laurent Gautier",
        author_email = "lgautier@gmail.com",
        ext_modules = rinterface_exts[0],
        package_dir = pack_dir,
        packages = [pack_name,
                    pack_name + '.rlike',
                    pack_name + '.rlike.tests',
                    pack_name + '.rinterface',
                    pack_name + '.rinterface.tests',
                    pack_name + '.robjects',
                    pack_name + '.robjects.tests',
                    pack_name + '.robjects.lib',
                    pack_name + '.interactive',
                    pack_name + '.interactive.tests'
                    ],
        classifiers = ['Programming Language :: Python',
                       'Programming Language :: Python :: 2',
                       'Programming Language :: Python :: 3',
                       'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
                       'License :: OSI Approved :: GNU Affero General Public License v3',
                       'Intended Audience :: Developers',
                       'Intended Audience :: Science/Research',
                       'Development Status :: 5 - Production/Stable'
                       ],
        data_files = [(os.path.join('rpy2', 'images'),
                       [os.path.join('doc', 'source', 'rpy2_logo.png')])],

        #[pack_name + '.rinterface_' + x for x in rinterface_rversions] + \
            #[pack_name + '.rinterface_' + x + '.tests' for x in rinterface_rversions]
        )


text:
import 'babel-polyfill'
import 'whatwg-fetch' // Polyfills window.fetch

import L from 'leaflet'
import Tangram from 'tangram' // via browserify-shim
import 'leaflet-hash'

const locations = {
  'Oakland': [37.8044, -122.2708, 15],
  'New York': [40.70531887544228, -74.00976419448853, 15],
  'Seattle': [47.5937, -122.3215, 15],
  'Philadelphia': [39.95200, -75.16400, 18]
}

// Parse URL hash, expecting leaflet-hash format
// #[zoom],[lat],[lng]
const urlHash = window.location.hash.slice(1, window.location.hash.length).split('/')

// Map start location is Philadelphia, unless the hash changes it
let mapStartLocation = locations['Philadelphia']

if (urlHash.length === 3) {
  // Converts values from strings
  mapStartLocation = [urlHash[1], urlHash[2], urlHash[0]].map(Number)
}

// Instatiate Leaflet map and Tangram
const map = L.map('map', {
  'keyboardZoomOffset': .05
}).setView(mapStartLocation.slice(0, 3), mapStartLocation[2])

const layer = Tangram.leafletLayer({
  scene: 'scene/curblines.yaml',
  attribution: '© OpenStreetMap contributors | Mapzen'
}).addTo(map);

let scene = layer.scene
let hash = new L.Hash(map)

// Hashes update parent if iframed
window.addEventListener('hashchange', function () {
  parent.postMessage(window.location.hash, '*')
})

// Debug
window.layer = layer
window.scene = scene
window.map = map


text:
<?php
session_start(); //Iniciamos la Sesion o la Continuamos
?>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Unibox</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/modern-business.css" rel="stylesheet">

    <link href="font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

            <?php
                $valor_sesion = $_SESSION["var_sesion"];
                echo"Bienvenido $valor_sesion";
            ?>

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        Toggle navigation

                    </button>
                    Inicio

                            Perfil

                        Registrar Cursos

                            Cerrar Sesion

Cargar Archivo

                  <form method="post" action="uploader.php" role="form" enctype="multipart/form-data" class="form form-horizontal">

                            Nombre:
                            <input  type="text" class="form-control" name="nombre">

                            Asignatura:
                            <input type="text" class="form-control" name="asignatura">

                            Descripción:
                            <input type="text" class="form-control" name="descripcion">

                            Tipo De Archivo

                            <input type="radio" name="tipo" value="1">Ayuda

                            <input type="radio" name="tipo" value="2">Exámenes

                            <input type="radio" name="tipo" value="3">Talleres

                            <input type="radio" name="tipo" value="4">Otros

                            Archivo
                            <input type="file" name="archivo"/>

                            <input type="submit" value="Subir Archivo" name="boton" id="cargar"/>

                </form>

Copyright © Unibox


text:
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^product/(?P<pid>\d+)/object/add$', views.new_object, name='new_object'),
    url(r'^product/(?P<pid>\d+)/object/(?P<ttid>\d+)/edit$', views.edit_object, name='edit_object'),
    url(r'^product/(?P<pid>\d+)/object/view$', views.view_objects, name='view_objects'),
    url(r'^product/(?P<pid>\d+)/object/(?P<ttid>\d+)/delete$', views.delete_object,
        name='delete_object'),
]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Smellyriver.TankInspector.Pro.Data.Tank;
using Smellyriver.TankInspector.Pro.UserInterface.Modularity;
using Smellyriver.TankInspector.Common.Wpf.Input;

namespace Smellyriver.TankInspector.Pro.StatComparer
{
    class ComparisonSelectorFlyoutVM
    {
        public event EventHandler Closed;

        public bool IsProceed { get; private set; }

        private readonly List<AvailableComparisonVMBase> _availableComparisons;
        public IEnumerable<AvailableComparisonVMBase> AvailableComparisons { get { return _availableComparisons; } }

        public AvailableComparisonVMBase SelectedComparison { get; set; }

        public ICommand OKCommand { get; private set; }
        public ICommand CancelCommand { get; private set; }

        public TankUnikey[] TankKeys { get; private set; }

        public ComparisonSelectorFlyoutVM(TankUnikey[] keys)
        {
            this.TankKeys = keys;

            _availableComparisons = new List<AvailableComparisonVMBase>();
            this.InitializeAvailableComparisons();

            this.OKCommand = new RelayCommand<AvailableComparisonVMBase>(this.Proceed, this.CanProceed);
            this.CancelCommand = new RelayCommand(this.Cancel);
        }

        private void Cancel()
        {
            this.Close();
        }

        private bool CanProceed(AvailableComparisonVMBase selected)
        {
            return this.SelectedComparison != null;
        }

        private void Proceed(AvailableComparisonVMBase selected)
        {
            this.IsProceed = true;
            this.Close();
        }

        private void Close()
        {
            if (this.Closed != null)
                this.Closed(this, EventArgs.Empty);
        }

        private void InitializeAvailableComparisons()
        {
            _availableComparisons.Add(new NewComparisonVM());

            var documents = DockingViewManager.Instance
                                              .DocumentManager
                                              .Documents
                                              .Where(d => d.Content is StatComparisonDocumentView);

            foreach (var document in documents)
            {
                _availableComparisons.Add(new AvailableComparisonVM(document));
            }

            var activeDocument = DockingViewManager.Instance.DocumentManager.ActiveDocument;
            if (activeDocument != null && activeDocument.Content is StatComparisonDocumentView)
            {
                this.SelectedComparison = _availableComparisons.OfType<AvailableComparisonVM>()
                                                               .Where(c => c.DocumentVM == ((StatComparisonDocumentView)activeDocument.Content).ViewModel)
                                                               .FirstOrDefault();
            }

            if (this.SelectedComparison == null)
                this.SelectedComparison = _availableComparisons[0];
        }
    }
}


text:
<?php

namespace Google\Cloud\Samples\Iap;

use Google\Cloud\TestUtils\TestTrait;
use PHPUnit\Framework\TestCase;

/**
 * Unit Tests for IAP commands.
 */
class iapTest extends TestCase
{
    use TestTrait;

    public function testRequestAndValidate()
    {
        // Make a request to our IAP URL, which returns the IAP's JWT Assertion.
        $output = $this->runFunctionSnippet('make_iap_request', [
            'url' => $this->requireEnv('IAP_URL'),
            'clientId' => $this->requireEnv('IAP_CLIENT_ID')
        ]);

        // Verify an ID token was returned
        $this->assertStringContainsString('Printing out response body:', $output);
        list($_, $iapJwt) = explode(':', $output);

        $projectNumber = $this->requireEnv('IAP_PROJECT_NUMBER');
        $projectId = $this->requireEnv('IAP_PROJECT_ID');

        // Now validate the JWT using the validation command
        $output = $this->runFunctionSnippet('validate_jwt', [
            $iapJwt,
            sprintf('/projects/%s/apps/%s', $projectNumber, $projectId),
        ]);
        $this->assertStringContainsString('Printing user identity information from ID token payload:', $output);
        $this->assertStringContainsString('sub: accounts.google.com', $output);
        $this->assertStringContainsString('email:', $output);
    }

    public function testInvalidJwt()
    {
        $output = $this->runFunctionSnippet('validate_jwt', [
            'fake_j.w.t',
            'fake_expected_audience'
        ]);
        $this->assertStringContainsString('Failed to validate JWT:', $output);
    }
}


text:
#region License

#endregion

#region Imports

using System;
using System.Reflection;
using System.Reflection.Emit;
using Spring.Proxy;

#endregion

namespace Spring.Web.Support
{
    /// <summary>
    /// This MethodBuilder emits a Callback-call before calling the base method
    /// </summary>
    /// <author>Erich Eichinger</author>
    internal class SupportsWebDependencyInjectionMethodBuilder : BaseProxyMethodBuilder
    {
        private FieldInfo _appContextField;
        private MethodInfo _callbackMethod;

        /// <summary>
        /// Initializes a new instance of a SupportsWebDependencyInjectionMethodBuilder
        /// </summary>
        public SupportsWebDependencyInjectionMethodBuilder(TypeBuilder typeBuilder, IProxyTypeGenerator proxyGenerator,
                                                           FieldInfo appContextField, MethodInfo callbackMethod)
            : base(typeBuilder, proxyGenerator, true)
        {
            _appContextField = appContextField;
            _callbackMethod = callbackMethod;
        }

        /// <summary>
        /// Inserts a call to a callback-method before actually calling the base-method.
        /// </summary>
        /// <param name="il">The IL generator to use</param>
        /// <param name="method">The method to proxy</param>
        /// <param name="interfaceMethod">The interface definition of this method, if applicable</param>
        protected override void GenerateMethod(ILGenerator il, MethodInfo method, MethodInfo interfaceMethod)
        {
            this.GenerateCallbackMethodCall(il, method, interfaceMethod);
            base.GenerateMethod(il, method, interfaceMethod);
        }

        /// <summary>
        /// Emits the callback invocation.
        /// </summary>
        private void GenerateCallbackMethodCall(ILGenerator il, MethodInfo method, MethodInfo interfaceMethod)
        {
            // setup parameters for call

            // IApplicationContext is always first parameter!
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, _appContextField);

            // lookup parameters needed for callback - they are matched by type in order!
            ParameterInfo[] callbackParams = _callbackMethod.GetParameters();
            ParameterInfo[] paramArray = method.GetParameters();

            Type returnType = _callbackMethod.ReturnType;
            int replaceArgumentIndex = -1;

            for (int j = 1; j < callbackParams.Length; j++)
            {
                for (int i = 0; i < paramArray.Length; i++)
                {
                    // remember the parameter to assign the value returned from the callback to
                    if (paramArray[i].ParameterType == returnType)
                    {
                        replaceArgumentIndex = i;
                    }

                    if (paramArray[i].ParameterType == callbackParams[j].ParameterType)
                    {
                        il.Emit(OpCodes.Ldarg_S, i + 1);
                        break;
                    }
                }
            }

            // invoke static(!) callback
            il.EmitCall(OpCodes.Call, _callbackMethod, null);
            // if callback has a result, store the result back into the first matching argument
            if (replaceArgumentIndex > -1)
            {
                il.Emit(OpCodes.Starg_S, (byte)replaceArgumentIndex+1);
            }
            return;
        }
    }
}


text:
package com.lidroid.xutils.db.converter;

import com.lidroid.xutils.db.sqlite.ColumnDbType;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Author: wyouflf
 * Date: 13-11-4
 * Time: 下午10:27
 */
public class ColumnConverterFactory {

    private ColumnConverterFactory() {
    }

    public static ColumnConverter getColumnConverter(Class columnType) {
        if (columnType_columnConverter_map.containsKey(columnType.getName())) {
            return columnType_columnConverter_map.get(columnType.getName());
        } else if (ColumnConverter.class.isAssignableFrom(columnType)) {
            try {
                ColumnConverter columnConverter = (ColumnConverter) columnType.newInstance();
                if (columnConverter != null) {
                    columnType_columnConverter_map.put(columnType.getName(), columnConverter);
                }
                return columnConverter;
            } catch (Throwable e) {
            }
        }
        return null;
    }

    public static ColumnDbType getDbColumnType(Class columnType) {
        ColumnConverter converter = getColumnConverter(columnType);
        if (converter != null) {
            return converter.getColumnDbType();
        }
        return ColumnDbType.TEXT;
    }

    public static void registerColumnConverter(Class columnType, ColumnConverter columnConverter) {
        columnType_columnConverter_map.put(columnType.getName(), columnConverter);
    }

    public static boolean isSupportColumnConverter(Class columnType) {
        if (columnType_columnConverter_map.containsKey(columnType.getName())) {
            return true;
        } else if (ColumnConverter.class.isAssignableFrom(columnType)) {
            try {
                ColumnConverter columnConverter = (ColumnConverter) columnType.newInstance();
                if (columnConverter != null) {
                    columnType_columnConverter_map.put(columnType.getName(), columnConverter);
                }
                return columnConverter == null;
            } catch (Throwable e) {
            }
        }
        return false;
    }

    private static final ConcurrentHashMap<String, ColumnConverter> columnType_columnConverter_map;

    static {
        columnType_columnConverter_map = new ConcurrentHashMap<String, ColumnConverter>();

        BooleanColumnConverter booleanColumnConverter = new BooleanColumnConverter();
        columnType_columnConverter_map.put(boolean.class.getName(), booleanColumnConverter);
        columnType_columnConverter_map.put(Boolean.class.getName(), booleanColumnConverter);

        ByteArrayColumnConverter byteArrayColumnConverter = new ByteArrayColumnConverter();
        columnType_columnConverter_map.put(byte[].class.getName(), byteArrayColumnConverter);

        ByteColumnConverter byteColumnConverter = new ByteColumnConverter();
        columnType_columnConverter_map.put(byte.class.getName(), byteColumnConverter);
        columnType_columnConverter_map.put(Byte.class.getName(), byteColumnConverter);

        CharColumnConverter charColumnConverter = new CharColumnConverter();
        columnType_columnConverter_map.put(char.class.getName(), charColumnConverter);
        columnType_columnConverter_map.put(Character.class.getName(), charColumnConverter);

        DateColumnConverter dateColumnConverter = new DateColumnConverter();
        columnType_columnConverter_map.put(Date.class.getName(), dateColumnConverter);

        DoubleColumnConverter doubleColumnConverter = new DoubleColumnConverter();
        columnType_columnConverter_map.put(double.class.getName(), doubleColumnConverter);
        columnType_columnConverter_map.put(Double.class.getName(), doubleColumnConverter);

        FloatColumnConverter floatColumnConverter = new FloatColumnConverter();
        columnType_columnConverter_map.put(float.class.getName(), floatColumnConverter);
        columnType_columnConverter_map.put(Float.class.getName(), floatColumnConverter);

        IntegerColumnConverter integerColumnConverter = new IntegerColumnConverter();
        columnType_columnConverter_map.put(int.class.getName(), integerColumnConverter);
        columnType_columnConverter_map.put(Integer.class.getName(), integerColumnConverter);

        LongColumnConverter longColumnConverter = new LongColumnConverter();
        columnType_columnConverter_map.put(long.class.getName(), longColumnConverter);
        columnType_columnConverter_map.put(Long.class.getName(), longColumnConverter);

        ShortColumnConverter shortColumnConverter = new ShortColumnConverter();
        columnType_columnConverter_map.put(short.class.getName(), shortColumnConverter);
        columnType_columnConverter_map.put(Short.class.getName(), shortColumnConverter);

        SqlDateColumnConverter sqlDateColumnConverter = new SqlDateColumnConverter();
        columnType_columnConverter_map.put(java.sql.Date.class.getName(), sqlDateColumnConverter);

        StringColumnConverter stringColumnConverter = new StringColumnConverter();
        columnType_columnConverter_map.put(String.class.getName(), stringColumnConverter);
    }
}


text:
<!DOCTYPE html>

        <title>Test Runner</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <link rel="stylesheet" type="text/css" href="../logger/graphicalLogger.css"></link>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Pap. 7: 5 (1943)

#### Original name
Ascochyta kashmeriana Padwick & Merh

### Remarks
null


text:
(function (root) {

    /**
     * ForceOAuth constructor
     *
     * @param loginURL string Login url, typically it is: https://login.salesforce.com/
     * @param consumerKey string Consumer Key from Setup | Develop | Remote Access
     * @param callbackURL string Callback URL from Setup | Develop | Remote Access
     * @param successCallback function Function that will be called on successful login, it accepts single argument with forcetk.Client instance
     * @param errorCallback function Function that will be called when login process fails, it accepts single argument with error object
     *
     * @constructor
     */
    root.ForceOAuth = function (loginURL, consumerKey, callbackURL, successCallback, errorCallback, proxyUrl) {

        if (typeof loginURL !== 'string') throw new TypeError('loginURL should be of type String');
        this.loginURL = loginURL;

        if (typeof consumerKey !== 'string') throw new TypeError('consumerKey should be of type String');
        this.consumerKey = consumerKey;

        if (typeof callbackURL !== 'string') throw new TypeError('callbackURL should be of type String');
        this.callbackURL = callbackURL;

        if (typeof successCallback !== 'function') throw new TypeError('successCallback should of type Function');
        this.successCallback = successCallback;

        if (typeof errorCallback !== 'undefined' && typeof errorCallback !== 'function')
            throw new TypeError('errorCallback should of type Function');
        this.errorCallback = errorCallback;

    };

    root.ForceOAuth.prototype = {

        /**
         * Starts OAuth login process.
         */
        login: function login() {
            var that = this;

            var winHeight = 524,
              winWidth = 674,
              centeredY = window.screenY + (window.outerHeight / 2 - winHeight / 2),
              centeredX = window.screenX + (window.outerWidth / 2 - winWidth / 2);

            var authUrl = that.loginURL + 'services/oauth2/authorize?'
                + '&response_type=token&client_id=' + encodeURIComponent(that.consumerKey)
                + '&redirect_uri=' + encodeURIComponent(that.callbackURL);

            var loginWindow = window.open(authUrl,
                'Login to Salesforce', 'height=' + winHeight + ',width=' + winWidth
                + ',toolbar=1,scrollbars=1,status=1,resizable=1,location=0,menuBar=0'
                + ',left=' + centeredX + ',top=' + centeredY);

            if (loginWindow) {
                // Creating an interval to detect popup window location change event
                var interval = setInterval(function () {
                    if (loginWindow.closed) {
                        // Clearing interval if popup was closed
                        clearInterval(interval);
                    } else {
                        var loc = loginWindow.location.href;
                        if (typeof loc !== 'undefined' && loc.indexOf(that.callbackURL) == 0) {
                            loginWindow.close();
                            that.oauthCallback(loginWindow.location.hash);
                        }
                    }
                }, 250);

                loginWindow.focus();
            }
        },

        logout: function logout(logoutCallback) {

        },

        oauthCallback: function oauthCallback(locHash) {
            var fragment = (locHash || window.location.hash).split("#")[1];
            this.oauthResponse = {};

            if (fragment) {
                this.oauthResponse['response'] = fragment;
                var nvps = fragment.split('&');
                for (var nvp in nvps) {
                    var parts = nvps[nvp].split('=');

                    //Note some of the values like refresh_token might have '=' inside them
                    //so pop the key(first item in parts) and then join the rest of the parts with =
                    var key = parts.shift();
                    var val = parts.join('=');
                    this.oauthResponse[key] = decodeURIComponent(val);
                }
            }

            if (typeof this.oauthResponse.access_token === 'undefined') {

                if (this.errorCallback)
                    this.errorCallback({code: 0, message: 'Unauthorized - no OAuth response!'});
                else
                    console.log('ERROR: No OAuth response!')

            } else {

                if (this.successCallback) {
                    this.successCallback(this.oauthResponse);
                    window.location.hash = "";
                } else
                    console.log('INFO: OAuth login successful!')
            }
        }
    };
})(this);


text:
var AnythingStream = require('./anything');

// ArrayStream wraps an array-like object into a Readable stream.
// The only requirement is that the object needs have a numeric 'length'
// property.
//
// Since arrays may contain null/undefined values, it is necessary to inherit
// from the AnythingStream class
var ArrayStream = AnythingStream.extend({
  constructor: function ArrayStream(array) {
    // Need to set 'objectMode' to enable pushing arbitrary objects
    AnythingStream.call(this);

    this._array = array;
    this._length = array.length;
    this._i = 0;
  },

  _read: function() {
    this.push(this._array[this._i++]);
  },

  _done: function() {
    return this._i >= this._length;
  }
});

module.exports = function array(arr) {
  return new ArrayStream(arr);
};


text:
layout: docwithnav-trendz
assignees:
- vparomskiy
title: Bar & Histogram
description: Bar Chart and Histogram
---

* TOC
{:toc}

Details about basic Bar chart you can find in [Line Chart Configuration](/docs/trendz/visualizations-line/)
Main concept for line and bar charts are the same. In this tutorial we will focus on differences.

## Video Tutorial

## Horizontal Bars

By default bar chart is vertical. In some cases it is required to show data using vertical bars. For making it:

* Open View Settings
* Enable **Horizontal Bar** mode

![image](/images/trendz/bar-horizontal.png)
![image](/images/trendz/bar-horizontal-conf.png)

**Note** horizontal mode available only when **Y-axis** contains one field. When multiple fields added to **Y-axis** and there are fields
in **Series** section - horizontal bar would not display.

## Stacked Bars

When bar chart contains multiple timeseries or series fields - each seria showed independently. And it is possible to enable
stacked mode for bar charts. Here are few examples: stacking disabled, stacking enabled and 100% stacked bars.

![image](/images/trendz/bar-stack-off.png)
![image](/images/trendz/bar-stack-onn.png)
![image](/images/trendz/bar-stack-100.png)

You can control stack options in View Settings

![image](/images/trendz/bar-stack-conf.png)

## Group By telemetry value

This option used when you need to group and aggregate data based on telemetry field value.
For example we have machine that produce different cups. Machine submit telemetry that contains info:

* How many products were produced (amount)
* What type of product was produced (product category)
* How many resources were utilised (energy)

Raw payload format is the following:

{% highlight javascript %}
  {
    "ts": 1540892498884,
    "amount": 12,
    "product": "glass",
    "energy": 218,
  }
{% endhighlight %}

What we want to find - how many products with different types were produced. Or how much energy was consumed for producing products
of certain type.

In both cases we need to group telemetry by **product** value and then apply required aggregation (in our case - SUM):

* Add **product** field into **Series** section and select **UNIQ** aggregation - in this step we will group telemetry.
* Add **product** field into **Y-axis** section and select **SUM** aggregation - in this step we apply aggregation for each group.
* Add **Machine** field into **X-axis** section - we will see a breakdown for each machine

Now we now how much products in different categories were produced by different machines.

![image](/images/trendz/bar-group-ts.png)

## Labels
You can add/hide labels from the bar chart using checkbex in View Settings.

![image](/images/trendz/bar-labels.png)


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Globalization;
using System.Linq;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;

namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
    /// <summary>
    /// Represents light bulb menu item for code fixes.
    /// </summary>
    internal sealed class CodeFixSuggestedAction : SuggestedActionWithNestedFlavors, ITelemetryDiagnosticID<string>
    {
        private readonly CodeFix _fix;

        public CodeFixSuggestedAction(
            IThreadingContext threadingContext,
            SuggestedActionsSourceProvider sourceProvider,
            Workspace workspace,
            ITextBuffer subjectBuffer,
            CodeFix fix,
            object provider,
            CodeAction action,
            SuggestedActionSet fixAllFlavors)
            : base(threadingContext, sourceProvider, workspace, subjectBuffer,
                   provider, action, fixAllFlavors)
        {
            _fix = fix;
        }

        public string GetDiagnosticID()
        {
            var diagnostic = _fix.PrimaryDiagnostic;

            // we log diagnostic id as it is if it is from us
            if (diagnostic.Descriptor.CustomTags.Any(t => t == WellKnownDiagnosticTags.Telemetry))
            {
                return diagnostic.Id;
            }

            // if it is from third party, we use hashcode
            return diagnostic.GetHashCode().ToString(CultureInfo.InvariantCulture);
        }

        protected override DiagnosticData GetDiagnostic()
        {
            return _fix.GetPrimaryDiagnosticData();
        }
    }
}


text:
/***********************************************************************
    created:    30/5/2013
    author:     Timotei Dolean
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#ifndef _Sample_Form_Navigation_h_
#define _Sample_Form_Navigation_h_

#include "SampleBase.h"
#include "NavigationStrategies.h"

class FormNavigationSample : public Sample
{
public:
    FormNavigationSample();

    virtual bool initialise(CEGUI::GUIContext* gui_context);
    virtual void deinitialise();

private:
    void createForm(CEGUI::FrameWindow* wnd);

    CEGUI::Window* createWidget(const CEGUI::String& type, float position_x, float position_y, const CEGUI::String& text = "");
    bool resetForm(const CEGUI::EventArgs& e);
    bool disableConfirmButton(const CEGUI::EventArgs& e);
    std::map<int, CEGUI::String> getNavigationMappings();

    CEGUI::DefaultWindow*       d_root;
    CEGUI::ToggleButton*        d_isGameMasterCheckbox;
    CEGUI::Window*              d_confirmButton;
    std::vector<CEGUI::Window*> d_editboxes;
    LinearNavigationStrategy*   d_navigationStrategy;
    CEGUI::WindowNavigator*     d_windowNavigator;
};

#endif  // end of guard _Sample_Form_Navigation_h_


text:
package com.github.gauthierj.dsm.webapi.client;

import com.github.gauthierj.dsm.webapi.client.apiinfo.ApiInfo;
import com.github.gauthierj.dsm.webapi.client.apiinfo.ApiInfoService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;

public abstract class AbstractDsmServiceImpl {

    @Autowired
    private ApiInfoService apiInfoService;

    @Autowired
    private DsmWebapiClient dsmWebapiClient;

    private final String apiId;

    private ApiInfo apiInfo;

    public AbstractDsmServiceImpl(String apiId) {
        this.apiId = apiId;
    }

    @PostConstruct
    public final void init() {
        apiInfo = apiInfoService.findOne(apiId);
    }

    public DsmWebapiClient getDsmWebapiClient() {
        return dsmWebapiClient;
    }

    public ApiInfoService getApiInfoService() {
        return apiInfoService;
    }

    public String getApiId() {
        return apiId;
    }

    public ApiInfo getApiInfo() {
        return apiInfo;
    }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta name="description" content="">
		<meta name="author" content="">
		<title>Funnel</title>
		<link href='http://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'>
		<link href="css/bootstrap.css" rel="stylesheet">
		<link href="css/app.css" rel="stylesheet">


text:
from cupy.binary import elementwise  # NOQA
from cupy.binary import packing  # NOQA


text:
<!--- Texts inside this are invisible and will not be displayed on the issue -->
### Scenario/Intent
<!--- What you are trying to achieve but can't? -->

---
#### Steps to Reproduce
<!--- What are the complete steps needed to do in order to reproduce your problem? -->

#### Expected Result
<!--- What do you expect to happen after taking the steps above? -->

#### Actual Result
<!--- What actually happens after the steps above? -->

---
#### Environment Details
 - **OneView Java SDK:**
    <Version of the oneview-sdk-java module for which you are encountering the issue>
 - **OneView Appliance Version:**
    <Version of the OneView appliance you are interacting with>
 - **OneView Client API Version:**
    <OnewView API version listed in your configuration file>
 - **Java Version:**
    <Version of Java in your environment>
 - **Platform:**
    <OS distribution and release version>

---
#### Attachments and Screenshots
<!--- (Optional) Drag and drop logs, screenshots and any other relevant files here -->


text:
Would you work with a plumber that only works with a screwdriver? Even if this guy told you "I'm the
master of screwdrivers, I nailed this skill over the past year".

No, you wouldn't. But, you hire developpers that only knows React.

## "We need RxJS/Redux/XState/TS/..."

> Dev1: How should I handle my 3 steps form?
> Dev2: This is a state machine problem. You can use Xstate to solve this problems.

> Dev1: We should use TypeScript so Backend and Frontend can share model. If the Backend model
> change, the Frontend model will not break. That will fix our problem.
> Me: How many issues related to BE data model did we had over the past 6 months?
> Dev1: One.

Because of our ego, we love to make overcomplicated things. Focus on the right things.


text:
{% extends "base.html" %}
{% load i18n %}

{% block title %}{% trans "Log in" %}{% endblock %}
{% block breadcrumbs %}

Home

Login[1]

{% endblock %}
{% block pagename %}Log in (step 1){% endblock %}
{% block content %}
    <form method="post" action="">
        {% csrf_token %}

Email:

{{ form.email }}

            <input type="submit" class="active btn btn-lg" name="login"
                   value="{% trans 'Send Pin Code' %}"/>

Password:

{{ form.password }}

Pin Code:

{{ form.sms_code }}

            <input type="submit" class="active btn btn-lg btn-success"
                   name="login" value="{% trans 'Login' %}"/>

        <input type="hidden" name="next" value="{{ next }}"/>
        <input type="hidden" name="pin_code" value="{{ form.pin_code }}"/>
    </form>

{% trans "Forgot your password?" %} {% trans "Reset it" %}.

{% trans "Not a member?" %} {% trans "Register" %}.

{% endblock %}

{% comment %}
**registration/login.html**

It's your responsibility to provide the login form in a template called
registration/login.html by default. This template gets passed four
template context variables:

``form``
    A Form object representing the login form. See the forms
    documentation for more on Form objects.

``next``
    The URL to redirect to after successful login. This may contain a
    query string, too.

``site``
    The current Site, according to the SITE_ID setting. If you don't
    have the site framework installed, this will be set to an instance
    of RequestSite, which derives the site name and domain from the
    current HttpRequest.

``site_name``
    An alias for site.name. If you don't have the site framework
    installed, this will be set to the value of
    request.META['SERVER_NAME']. For more on sites, see The
    "sites" framework.
{% endcomment %}


text:
/**
 * \file TS9OverdriveFilter.h
 */

#ifndef ATK_DISTORTION_TS9OVERDRIVEFILTER_H
#define ATK_DISTORTION_TS9OVERDRIVEFILTER_H

#include <memory>

#include <ATK/Core/TypedBaseFilter.h>
#include <ATK/Distortion/config.h>

namespace ATK
{
  template<typename Function, int max_iterations, bool check_convergence>
  class ScalarNewtonRaphson;

  /// TS9 filter, based on a trapezoidal rule
  template<typename DataType_>
  class ATK_DISTORTION_EXPORT TS9OverdriveFilter final : public TypedBaseFilter<DataType_>
  {
    class TS9OverdriveFunction;
  protected:
    /// Simplify parent calls
    using Parent = TypedBaseFilter<DataType_>;
    using typename Parent::DataType;
    using Parent::converted_inputs;
    using Parent::outputs;
    using Parent::input_sampling_rate;
    using Parent::output_sampling_rate;

    using Parent::input_delay;
    using Parent::output_delay;
  public:
    /*!
    * @brief Constructor
    * @param nb_channels is the number of input and output channels
    */
    TS9OverdriveFilter();
    /// Destructor
    ~TS9OverdriveFilter();

    void set_drive(DataType_ drive);
    DataType_ get_drive() const;

  protected:
    void setup() final;
    void process_impl(gsl::index size) const final;
    DataType drive = 0.5;

  private:
    static const int num_iterations = 30;
    std::unique_ptr<ScalarNewtonRaphson<TS9OverdriveFunction, num_iterations, true> > optimizer;
  };
}

#endif


text:
import React from 'react';
import PropTypes from 'prop-types';
import ballFactory from '../utils/ballFactory';

const QueueItems = (props) => {

  let ballObjects = ballFactory().buildBallObjects(props.queueSize);
  let items = [];

  for (let i = 0; i < 20; i++) {
    let ball = (<div key={i + 1} className={`ball ${ballObjects[i].clazzName}`}/>);
    items.push(ball);
  }

  return (

{items}

  );
};

QueueItems.propTypes = {
  queueSize: PropTypes.number.isRequired
};

export default QueueItems;


text:
using UnityEngine;
using System.Collections;

public class PressAnyKeyToLoadScene : MonoBehaviour {

    public string sceneName;

	// Update is called once per frame
	void Update () {
	    if (Input.anyKey)
            Application.LoadLevel(sceneName);
	}
}


text:
This demo is an integration test for testing local registration an discovery.

Local registration and discovery is a mechanism that do not using Service Center,
`Microservice` and `MicroserviceInstance` are constructed from configuration file.


text:
package org.keycloak.authentication;

/**
 * Set of error codes that can be thrown by an Authenticator, FormAuthenticator, or FormAction
 *
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public enum AuthenticationFlowError {
    EXPIRED_CODE,
    INVALID_CLIENT_SESSION,
    INVALID_USER,
    INVALID_CREDENTIALS,
    CREDENTIAL_SETUP_REQUIRED,
    USER_DISABLED,
    USER_CONFLICT,
    USER_TEMPORARILY_DISABLED,
    INTERNAL_ERROR,
    UNKNOWN_USER,
    FORK_FLOW,
    UNKNOWN_CLIENT,
    CLIENT_NOT_FOUND,
    CLIENT_DISABLED,
    CLIENT_CREDENTIALS_SETUP_REQUIRED,
    INVALID_CLIENT_CREDENTIALS,

    IDENTITY_PROVIDER_NOT_FOUND,
    IDENTITY_PROVIDER_DISABLED,
    IDENTITY_PROVIDER_ERROR
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Can. J. Bot. 54(24): 2852 (1976)

#### Original name
Cryptosporium pinicola Linder

### Remarks
null