text:
title: Flock First Impressions
author: ajordens
layout: post
permalink: /2005/10/flock-first-impressions/
categories:
  - General Discussions
---
Looks like a browser, acts like a browser, must be a browser….right?

So I downloaded [Flock][1]'s developer preview this morning. I'm actually posting this from Flock's internal blog editor so if it works as expected that's +1 for them.  The editor has a few UI oddities but given the 0.5pre designation, those are to be expected.

It looks like an interesting idea and I look forward to future enhancements with the del.icio.us integration.  Many of my del.icio.us tags are dot separated and I'd like the browser to build a favourite's list with drop-downs derived from the tag hierarchy.  There's a firefox plugin already that does this so I don't think this would be overly difficult to implement.  It would also be nice to have the ability to put tags into categories and have them realized as drop-downs within the toolbar.

Overall I like the emphasis on tagged content and I look forward to future releases.  I'm sure I'll have more comments as I continue to experiment with it, but my first impressions are positive.

**Edit: **I'm not sure I like the way the built-in editor html-ized my post, makes it a tad difficult to modify the post from within wordpress. Another interesting feature: Flock recognized when I was logging into wordpress and asked if I wanted to save the password.

**Update: ** Bart (from Flock) has given a [good description][2] of just what Flock is, what it hopes to accomplish, and why it is what it is.

 [1]: http://www.flock.com
 [2]: http://www.decrem.com/bart/2005/10/flock-firefox-and-open-source/


text:
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */

/**
 * @copyright 2013 Couchbase, Inc.
 *
 * @author Filipe Manana  <filipe@couchbase.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 **/

#ifndef _MAPREDUCE_TESTS_H
#define _MAPREDUCE_TESTS_H

#include "config.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "../macros.h"
#include "../../src/views/mapreduce/mapreduce.h"

/* main test function */
void mapreduce_tests(void);
void map_tests(void);
void reduce_tests(void);
void builtin_tests(void);

#endif

redpajama_set_name: RedPajamaGithub


text:
package de.bitbrain.braingdx.tmx;

/**
 * Is thrown when there is a problem with a tiledmap in braingdx.
 *
 * @author Miguel Gonzalez Sanchez
 * @version 1.0.0
 * @since 1.0.0
 */
public class TiledMapException extends RuntimeException {

   private static final long serialVersionUID = 1L;

   public TiledMapException(String message) {
      super(message);
   }

}


text:
import os
import sys
from glob import glob

import versioneer
versioneer.VCS = 'git'
versioneer.style = 'pep440'
versioneer.versionfile_source = 'borg/_version.py'
versioneer.versionfile_build = 'borg/_version.py'
versioneer.tag_prefix = ''
versioneer.parentdir_prefix = 'borgbackup-'  # dirname like 'myproject-1.2.0'

min_python = (3, 2)
if sys.version_info < min_python:
    print("Borg requires Python %d.%d or later" % min_python)
    sys.exit(1)

from setuptools import setup, Extension

crypto_source = 'borg/crypto.pyx'
chunker_source = 'borg/chunker.pyx'
hashindex_source = 'borg/hashindex.pyx'
platform_linux_source = 'borg/platform_linux.pyx'
platform_darwin_source = 'borg/platform_darwin.pyx'
platform_freebsd_source = 'borg/platform_freebsd.pyx'

try:
    from Cython.Distutils import build_ext
    import Cython.Compiler.Main as cython_compiler

    class Sdist(versioneer.cmd_sdist):
        def __init__(self, *args, **kwargs):
            for src in glob('borg/*.pyx'):
                cython_compiler.compile(src, cython_compiler.default_options)
            versioneer.cmd_sdist.__init__(self, *args, **kwargs)

        def make_distribution(self):
            self.filelist.extend([
                'borg/crypto.c',
                'borg/chunker.c', 'borg/_chunker.c',
                'borg/hashindex.c', 'borg/_hashindex.c',
                'borg/platform_linux.c',
                'borg/platform_freebsd.c',
                'borg/platform_darwin.c',
            ])
            super().make_distribution()

except ImportError:
    class Sdist(versioneer.cmd_sdist):
        def __init__(self, *args, **kwargs):
            raise Exception('Cython is required to run sdist')

    crypto_source = crypto_source.replace('.pyx', '.c')
    chunker_source = chunker_source.replace('.pyx', '.c')
    hashindex_source = hashindex_source.replace('.pyx', '.c')
    platform_linux_source = platform_linux_source.replace('.pyx', '.c')
    platform_freebsd_source = platform_freebsd_source.replace('.pyx', '.c')
    platform_darwin_source = platform_darwin_source.replace('.pyx', '.c')
    from distutils.command.build_ext import build_ext
    if not all(os.path.exists(path) for path in [crypto_source, chunker_source, hashindex_source, platform_linux_source, platform_freebsd_source]):
        raise ImportError('The GIT version of Borg needs Cython. Install Cython or use a released version')

def detect_openssl(prefixes):
    for prefix in prefixes:
        filename = os.path.join(prefix, 'include', 'openssl', 'evp.h')
        if os.path.exists(filename):
            with open(filename, 'r') as fd:
                if 'PKCS5_PBKDF2_HMAC(' in fd.read():
                    return prefix

possible_openssl_prefixes = ['/usr', '/usr/local', '/usr/local/opt/openssl', '/usr/local/ssl', '/usr/local/openssl', '/usr/local/borg', '/opt/local']
if os.environ.get('BORG_OPENSSL_PREFIX'):
    possible_openssl_prefixes.insert(0, os.environ.get('BORG_OPENSSL_PREFIX'))
ssl_prefix = detect_openssl(possible_openssl_prefixes)
if not ssl_prefix:
    raise Exception('Unable to find OpenSSL >= 1.0 headers. (Looked here: {})'.format(', '.join(possible_openssl_prefixes)))
include_dirs = [os.path.join(ssl_prefix, 'include')]
library_dirs = [os.path.join(ssl_prefix, 'lib')]

with open('README.rst', 'r') as fd:
    long_description = fd.read()

cmdclass = versioneer.get_cmdclass()
cmdclass.update({'build_ext': build_ext, 'sdist': Sdist})

ext_modules = [
    Extension('borg.crypto', [crypto_source], libraries=['crypto'], include_dirs=include_dirs, library_dirs=library_dirs),
    Extension('borg.chunker', [chunker_source]),
    Extension('borg.hashindex', [hashindex_source])
]
if sys.platform.startswith('linux'):
    ext_modules.append(Extension('borg.platform_linux', [platform_linux_source], libraries=['acl']))
elif sys.platform.startswith('freebsd'):
    ext_modules.append(Extension('borg.platform_freebsd', [platform_freebsd_source]))
elif sys.platform == 'darwin':
    ext_modules.append(Extension('borg.platform_darwin', [platform_darwin_source]))

setup(
    name='borgbackup',
    version=versioneer.get_version(),
    author='The Borg Collective (see AUTHORS file)',
    author_email='borgbackup@librelist.com',
    url='https://borgbackup.github.io/',
    description='Deduplicated, encrypted, authenticated and compressed backups',
    long_description=long_description,
    license='BSD',
    platforms=['Linux', 'MacOS X', 'FreeBSD', ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: BSD License',
        'Operating System :: POSIX :: BSD :: FreeBSD',
        'Operating System :: MacOS :: MacOS X',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Security :: Cryptography',
        'Topic :: System :: Archiving :: Backup',
    ],
    packages=['borg', 'borg.testsuite'],
    entry_points={
        'console_scripts': [
            'borg = borg.archiver:main',
        ]
    },
    cmdclass=cmdclass,
    ext_modules=ext_modules,
    # msgpack pure python data corruption was fixed in 0.4.6.
    # Also, we might use some rather recent API features.
    install_requires=['msgpack-python>=0.4.6']
)


text:
<?php

namespace PHPExiftool\Driver\Tag\NikonCustom;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class ElectronicFrontCurtainShutter extends AbstractTag
{

    protected $Id = '5.3';

    protected $Name = 'ElectronicFront-CurtainShutter';

    protected $FullName = 'NikonCustom::SettingsD810';

    protected $GroupName = 'NikonCustom';

    protected $g0 = 'MakerNotes';

    protected $g1 = 'NikonCustom';

    protected $g2 = 'Camera';

    protected $Type = 'int8u';

    protected $Writable = true;

    protected $Description = 'Electronic Front-Curtain Shutter';

    protected $flag_Permanent = true;

    protected $Values = array(
        0 => array(
            'Id' => 0,
            'Label' => 'Off',
        ),
        8 => array(
            'Id' => 8,
            'Label' => 'On',
        ),
    );
}


text:
<?xml version="1.0" encoding="utf-8"?>
<Template>
  <Unknown5 type="uint32" default="0" description="" />
  <Unknown6 type="uint32" default="0" description="" />
  <Unknown7 type="uint32" default="0" description="" />
  <Unknown8 type="float" default="0" description="" />
  <Unknown9 type="float" default="0" description="" />
  <Unknown10 type="float" default="0" description="" />
  <Collision_Width type="float" default="0" description="" />
  <Collision_Height type="float" default="0" description="" />
  <Collision_Length type="float" default="0" description="" />
  <Extra type="RawByteLength" length="36" />
</Template>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Lychee.Core;
using NUnit.Framework;

namespace Lychee.Tests
{
    public class AttemptTests
    {
        [Test]
        public void FirstAttempt_ForAction_Passes()
        {
            var retry = Attempt.NoMoreThan(5);

            var result = retry.ExecuteAsync(() => { /* no-op */});

            Task.WaitAny(result);

            Assert.IsNull(result.Exception);
            Assert.AreEqual(TaskStatus.RanToCompletion, result.Status);
        }

        [Test]
        public void SecondAttempt_ForAction_Passes()
        {
            var retry = Attempt.NoMoreThan(5);
            var result =
                retry
                    .UsingRetryPolicy(
                        (attempt) => attempt < 1 ? TimeSpan.FromSeconds(0.5) : TimeSpan.FromSeconds(5))
                    .ExecuteAsync(() => Thread.Sleep(TimeSpan.FromMilliseconds(2000)));

            Task.WaitAny(result);

            Assert.IsNull(result.Exception);
            Assert.AreEqual(TaskStatus.RanToCompletion, result.Status);
        }

        [Test]
        public void AcceptedTransientException_ForAction_Passes()
        {
            var retry = Attempt.NoMoreThan(5);
            var simulatedCount = 0;

            var result =
                retry
                    .AllowRetryWhen((e) => e is XmlException)
                    .ExecuteAsync(() =>
                    {
                        /**
                         * fault the first attempt with something accepted as a
                         * transient exception.
                         */
                        if (simulatedCount == 0)
                        {
                            simulatedCount++;
                            throw new XmlException();
                        }
                        /* no-op */
                    });

            Task.WaitAny(result);

            Assert.IsNull(result.Exception);
            Assert.AreEqual(TaskStatus.RanToCompletion, result.Status);
        }

        [Test]
        public void Attempt_Failure_ForAction_FaultsTask()
        {
            var retry = Attempt
                .NoMoreThan(1)
                .UsingRetryPolicy((i) => TimeSpan.FromMilliseconds(500));

            var result = retry.ExecuteAsync(() => Thread.Sleep(TimeSpan.FromMilliseconds(10000)));

            Task.WaitAny(result);
            Assert.AreEqual(TaskStatus.Faulted, result.Status);
            Assert.IsTrue(result.Exception != null && result.Exception.InnerException is TimeoutException);
        }

        [Test]
        public void FirstAttempt_ForFunction_Passes()
        {
            var retry = Attempt.NoMoreThan(5);

            var result = retry.ExecuteAsync(() => "test");

            Task.WaitAny(result);

            Assert.IsNull(result.Exception);
            Assert.AreEqual(TaskStatus.RanToCompletion, result.Status);
            Assert.AreEqual("test", result.Result);
        }

        [Test]
        public void SecondAttempt_ForFunction_Passes()
        {
            var retry = Attempt.NoMoreThan(5);
            var result =
                retry
                    .UsingRetryPolicy(
                        (attempt) => attempt < 1 ? TimeSpan.FromSeconds(0.5) : TimeSpan.FromSeconds(5))
                    .ExecuteAsync(() =>
                    {
                        Thread.Sleep(TimeSpan.FromMilliseconds(2000));
                        return "test";
                    });

            Task.WaitAny(result);

            Assert.IsNull(result.Exception);
            Assert.AreEqual(TaskStatus.RanToCompletion, result.Status);
            Assert.AreEqual("test", result.Result);
        }

        [Test]
        public void Attempt_Failure_ForFunction_FaultsTask()
        {
            var retry = Attempt
                .NoMoreThan(1)
                .UsingRetryPolicy((i) => TimeSpan.FromMilliseconds(500));

            var result = retry.ExecuteAsync(() =>
            {
                Thread.Sleep(TimeSpan.FromMilliseconds(10000));
                return "test";
            });

            Task.WaitAny(result);
            Assert.AreEqual(TaskStatus.Faulted, result.Status);
            Assert.IsTrue(result.Exception != null && result.Exception.InnerException is TimeoutException);
        }

        [Test]
        public void AcceptedTransientException_ForFunction_Passes()
        {
            var retry = Attempt.NoMoreThan(5);
            var simulatedCount = 0;

            var result =
                retry
                    .AllowRetryWhen((e) => e is XmlException)
                    .ExecuteAsync(() =>
                    {
                        /**
                         * fault the first attempt with something accepted as a
                         * transient exception.
                         */
                        if (simulatedCount == 0)
                        {
                            simulatedCount++;
                            throw new XmlException();
                        }
                        return "test";
                    });

            Task.WaitAny(result);

            Assert.IsNull(result.Exception);
            Assert.AreEqual(TaskStatus.RanToCompletion, result.Status);
            Assert.AreEqual("test", result.Result);
        }
    }
}


text:
layout: default
description: It is recommended to check the following list of incompatible changes before upgrading to ArangoDB 3.6
---
Incompatible changes in ArangoDB 3.6
====================================

It is recommended to check the following list of incompatible changes **before**
upgrading to ArangoDB 3.6, and adjust any client programs if necessary.

The following incompatible changes have been made in ArangoDB 3.6:

Restricted ranges for date/time values in AQL
---------------------------------------------

ArangoDB 3.6 enforces valid date ranges for working with date/time in AQL.
The valid date ranges for any AQL date/time function are:

- for string date/time values: `"0000-01-01T00:00:00.000Z"` (including) up to
  `"9999-12-31T23:59:59.999Z"` (including)
- for numeric date/time values: -62167219200000 (including) up to
  253402300799999 (including). These values are the numeric equivalents of
  `"0000-01-01T00:00:00.000Z"` and `"9999-12-31T23:59:59.999Z"`.

Any date/time values outside the given range that are passed into an AQL date
function will make the function return `null` and trigger a warning in the
query, which can optionally be escalated to an error and stop the query.

Any date/time operations that produce date/time outside the valid ranges stated
above will make the function return `null` and trigger a warning too. Example:

```js
DATE_SUBTRACT("2018-08-22T10:49:00+02:00", 100000, "years") // null
```

Startup options
---------------

The following startup options have been removed in ArangoDB 3.6:

- `--vst.maxsize`: this option was used in previous versions to control the
  maximum size (in bytes) of VelocyPack chunks when using the VelocyStream
  (VST) protocol. This is now handled automatically by the server and does not
  need any configuration.

Deprecation of MMFiles Storage Engine
-------------------------------------

The MMFiles storage engine is deprecated starting with version
3.6.0 and it will be removed in a future release.
{%- assign ver = "3.7" | version: "<=" %}{% if ver %}
To change your MMFiles storage engine deployment to RocksDB, see:
[Switch storage engine](administration-engine-switch-engine.html)
{% endif %}

We recommend to switch to RocksDB even before the removal of MMFiles.
RocksDB is the default [storage engine](architecture-storage-engines.html)
since v3.4.0.

Requests statistics
-------------------

<small>Introduced in: v3.6.5</small>

Previous versions of ArangoDB excluded all requests made to the web interface at
`/_admin/aardvark` from the requests statistics if the request was made for the
`_system` database. Requests for all other endpoints or requests to the same
endpoint for any non-system database were already counted.
ArangoDB now treats all incoming requests to the web interface in the same
way as requests to other endpoints, so the request counters may show higher
values than before in case the web interface was used a lot on the
`_system` database.


text:
import {Validate} from '~/src/util/Validate'

export class PlatformApi {

  constructor() {
    this.onTickHandlers = []
    this.onLogHandlers = []
    this.onInputHandlers = []
    this.onProbeChangeHandlers = []
  }

  setTick(tick) {
    Validate.isNumber(tick)

    this.onTickHandlers.forEach(h=>h(tick))
  }

  onTick(handler) {
    this.onTickHandlers.push(handler)
  }

  log(msg) {
    this.onLogHandlers.forEach(h=>h(msg))
  }

  onLog(handler) {
    this.onLogHandlers.push(handler)
  }

  input(str) {
    this.onInputHandlers.forEach(h=>h(str))
  }

  onInput(handler) {
    this.onInputHandlers.push(handler)
  }

  probeChange(name, oldValue, value) {
    this.onProbeChangeHandlers.forEach(h=>h(name, oldValue, value))
  }

  onProbeChange(handler) {
    this.onProbeChangeHandlers.push(handler)
  }
}


text:
import { NewQuestionnaireForm } from "./form";
import { NewQuestionnaireTypeSelector } from "./type";

export { NewQuestionnaireForm, NewQuestionnaireTypeSelector };


text:
package com.beanframework.platform.sysconfig.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.Table;

import com.beanframework.platform.core.base.BaseDomain;
import com.beanframework.platform.sysconfig.SysConfigConstants;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = SysConfigConstants.TABLE_CONFIG)
public class SysConfig extends BaseDomain {

	/**
	 *
	 */
	private static final long serialVersionUID = 2500661400995007868L;

	@Column(unique = true)
	private String name;
	private String value;
	private String description;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

}


text:
namespace cmd_cmakemaker {
TEST(cmd_cmakemaker, TestTargetWriter) {
}
}


text:
#pragma once

#include "envoy/network/filter.h"
#include "envoy/stats/scope.h"

#include "source/common/common/logger.h"

#include "absl/container/flat_hash_map.h"
#include "contrib/kafka/filters/network/source/external/request_metrics.h"
#include "contrib/kafka/filters/network/source/external/response_metrics.h"
#include "contrib/kafka/filters/network/source/parser.h"
#include "contrib/kafka/filters/network/source/request_codec.h"
#include "contrib/kafka/filters/network/source/response_codec.h"

namespace Envoy {
namespace Extensions {
namespace NetworkFilters {
namespace Kafka {
namespace Broker {

/**
 * Utility class that merges both request & response callbacks.
 */
class KafkaCallback : public RequestCallback, public ResponseCallback {};

using KafkaCallbackSharedPtr = std::shared_ptr<KafkaCallback>;

/**
 * Request callback responsible for updating state of related response decoder.
 * When a request gets successfully parsed, the response decoder registers a new incoming request.
 * When request could not be recognized, we can extract the header, so we can register the
 * expected response (decoder will not be able to capable of decoding the response, but at least we
 * will not break the communication between client and broker).
 */
class Forwarder : public RequestCallback {
public:
  /**
   * Binds forwarder to given response decoder.
   */
  Forwarder(ResponseDecoder& response_decoder) : response_decoder_{response_decoder} {};

  // RequestCallback
  void onMessage(AbstractRequestSharedPtr request) override;
  void onFailedParse(RequestParseFailureSharedPtr parse_failure) override;

private:
  ResponseDecoder& response_decoder_;
};

/**
 * Single access point for all Kafka-related metrics.
 * Implements Kafka message callback, so decoders can refer to it when parse results appear.
 * This interface was extracted to facilitate mock injection in unit tests.
 */
class KafkaMetricsFacade : public KafkaCallback {
public:
  /**
   * To be invoked when exceptions occur while processing a request.
   */
  virtual void onRequestException() PURE;

  /**
   * To be invoked when exceptions occur while processing a response.
   */
  virtual void onResponseException() PURE;
};

using KafkaMetricsFacadeSharedPtr = std::shared_ptr<KafkaMetricsFacade>;

/**
 * Metrics facade implementation that actually uses rich request/response metrics.
 * Keeps requests' arrival timestamps (by correlation id) and uses them calculate response
 * processing time.
 */
class KafkaMetricsFacadeImpl : public KafkaMetricsFacade {
public:
  /**
   * Creates facade that keeps prefixed metrics in given scope, and uses given time source to
   * compute processing durations.
   */
  KafkaMetricsFacadeImpl(Stats::Scope& scope, TimeSource& time_source,
                         const std::string& stat_prefix);

  /**
   * Visible for testing.
   */
  KafkaMetricsFacadeImpl(TimeSource& time_source, RichRequestMetricsSharedPtr request_metrics,
                         RichResponseMetricsSharedPtr response_metrics);

  // RequestCallback
  void onMessage(AbstractRequestSharedPtr request) override;
  void onFailedParse(RequestParseFailureSharedPtr parse_failure) override;

  // ResponseCallback
  void onMessage(AbstractResponseSharedPtr response) override;
  void onFailedParse(ResponseMetadataSharedPtr parse_failure) override;

  // KafkaMetricsFacade
  void onRequestException() override;
  void onResponseException() override;

  absl::flat_hash_map<int32_t, MonotonicTime>& getRequestArrivalsForTest();

private:
  TimeSource& time_source_;
  absl::flat_hash_map<int32_t, MonotonicTime> request_arrivals_;
  RichRequestMetricsSharedPtr request_metrics_;
  RichResponseMetricsSharedPtr response_metrics_;
};

/**
 * Implementation of Kafka broker-level filter.
 * Uses two decoders - request and response ones, that are connected using Forwarder instance.
 * There's also a KafkaMetricsFacade, that is listening on codec events.
 *
 *        +---------------------------------------------------+
 *        |                                                   |
 *        |               +--------------+                    |
 *        |   +---------->+RequestDecoder+----------------+   |
 *        |   |           +-------+------+                |   |
 *        |   |                   |                       |   |
 *        |   |                   |                       |   |
 *        |   |                   v                       v   v
 * +------+---+------+       +----+----+        +---------+---+----+
 * |KafkaBrokerFilter|       |Forwarder|        |KafkaMetricsFacade|
 * +----------+------+       +----+----+        +---------+--------+
 *            |                   |                       ^
 *            |                   |                       |
 *            |                   v                       |
 *            |           +-------+-------+               |
 *            +---------->+ResponseDecoder+---------------+
 *                        +---------------+
 */
class KafkaBrokerFilter : public Network::Filter, private Logger::Loggable<Logger::Id::kafka> {
public:
  /**
   * Main constructor.
   * Creates decoders that eventually update prefixed metrics stored in scope, using time source for
   * duration calculation.
   */
  KafkaBrokerFilter(Stats::Scope& scope, TimeSource& time_source, const std::string& stat_prefix);

  /**
   * Visible for testing.
   */
  KafkaBrokerFilter(KafkaMetricsFacadeSharedPtr metrics, ResponseDecoderSharedPtr response_decoder,
                    RequestDecoderSharedPtr request_decoder);

  // Network::ReadFilter
  Network::FilterStatus onNewConnection() override;
  void initializeReadFilterCallbacks(Network::ReadFilterCallbacks& callbacks) override;
  Network::FilterStatus onData(Buffer::Instance& data, bool end_stream) override;

  // Network::WriteFilter
  Network::FilterStatus onWrite(Buffer::Instance& data, bool end_stream) override;

  RequestDecoderSharedPtr getRequestDecoderForTest();
  ResponseDecoderSharedPtr getResponseDecoderForTest();

private:
  /**
   * Helper delegate constructor.
   * Passes metrics facade as argument to decoders.
   */
  KafkaBrokerFilter(const KafkaMetricsFacadeSharedPtr& metrics);

  const KafkaMetricsFacadeSharedPtr metrics_;
  const ResponseDecoderSharedPtr response_decoder_;
  const RequestDecoderSharedPtr request_decoder_;
};

} // namespace Broker
} // namespace Kafka
} // namespace NetworkFilters
} // namespace Extensions
} // namespace Envoy


text:
package de.l3s.eumssi.webservices;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import de.l3s.eumssi.core.StoryDistribution;
import de.l3s.eumssi.dao.DatabaseManager;
import de.l3s.eumssi.dao.SolrDBManager;
import de.l3s.eumssi.model.*;
import de.l3s.eumssi.service.ContentHandling;

import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;

import org.apache.struts2.ServletActionContext;
import org.json.JSONArray;

/** eg.
 * http://pharos.l3s.uni-hannover.de:8485/EventSense/webresources/WebService/getWordCloud/json/text/news/germany
 * @author giangbinhtran
 *
 */
@Path("/WebService")
public class RestfulService {

	@GET
	@Path("/getNews/json/{fields}/{sources}/{keyword}")
	@Produces(MediaType.APPLICATION_JSON)
	public List<Event> getNews(@PathParam("keyword") String keyword,
			@PathParam("fields") String fields, @PathParam("sources") String sources) {
		SolrDBManager db = new SolrDBManager();
		List<Event> events = new ArrayList<Event> ();
		ArrayList<String> searchField = formSearchField(fields);						//search field
		//Debug
		ArrayList<String> S = new ArrayList<String> ();
		if (sources.contains("video")) S.add("Video");
		if (sources.contains("news")) S.add("NewsArticle");
		try{
			int maxNumOfEventsToDisplay = Integer.parseInt(db.conf.getProperty("visualization_MaxTimelineSize"));
			events = db.searchByKeyword(keyword, S, searchField, maxNumOfEventsToDisplay);
		}catch(Exception e){
			e.printStackTrace();
		}
		return events;

	}

	@GET
	@Path("/getOccurence/json/{fields}/{sources}/{keyword}")
	@Produces(MediaType.APPLICATION_JSON)
	public String getCooccurences(@PathParam("keyword") String keyword,
			@PathParam("fields") String fields, @PathParam("sources") String sources) {
		SolrDBManager db = new SolrDBManager();
		JSONArray coocc = null;
		ArrayList<String> searchField = formSearchField(fields);
		ArrayList<String> S = new ArrayList<String> ();
		if (sources.contains("video")) S.add("Video");
		if (sources.contains("news")) S.add("NewsArticle");

		try{

			int maxNumOfWordsToDisplay = Integer.parseInt(db.conf.getProperty("visualization_MaxWordCloudSize"));
			int maxNumOfEvents = Integer.parseInt(db.conf.getProperty("visualization_MaxDocForClouds"));

			StoryDistribution distr = db.getDistribution(keyword, S, searchField, maxNumOfEvents);
			coocc = distr.getCoOccurenceOfTopTerms(maxNumOfWordsToDisplay);

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

		}
		return coocc.toString();
	}

	@GET
	@Path("/getWordCloud/json/{fields}/{sources}/{keyword}")
	@Produces(MediaType.APPLICATION_JSON)
	public String getWordCloud(@PathParam("keyword") String keyword,
			@PathParam("fields") String fields, @PathParam("sources") String sources) {
		SolrDBManager db = new SolrDBManager();
		JSONArray tfjson = null;
		ArrayList<String> searchField = formSearchField(fields);
		ArrayList<String> S = new ArrayList<String> ();
		if (sources.contains("video")) S.add("Video");
		if (sources.contains("news")) S.add("NewsArticle");

		try{

			int maxNumOfWordsToDisplay = Integer.parseInt(db.conf.getProperty("visualization_MaxWordCloudSize"));
			int maxNumOfEvents = Integer.parseInt(db.conf.getProperty("visualization_MaxDocForClouds"));

			StoryDistribution distr = db.getDistribution(keyword, S, searchField, maxNumOfEvents);
			tfjson =  distr.getTermFrequencies(maxNumOfWordsToDisplay);

			System.out.println("Finish generating wordcloud");

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

		}
		return tfjson.toString();
	}

	private ArrayList<String> formSearchField(String fields) {
		ArrayList<String> searchFields = new ArrayList<String> ();
		if (fields.contains("headline")) searchFields.add("meta.source.headline");
		if (fields.contains("text"))searchFields.add("meta.source.text");
		if (fields.contains("transcript")) searchFields.add("meta.extracted.audio_transcript");
		return searchFields;
	}
}


text:
module Haskell99Pointfree.P34
    (
    ) where

import Control.Applicative

--simple, ineffective solution for large numbers
p34_1 :: Int -> Int
p34_1 = ( length  .)    . filter . ( (== 1) . )  . gcd    <*>  enumFromTo 1 . subtract 1


text:
package com.camunda.fox.rest.impl;

import java.util.logging.Logger;

import javax.inject.Inject;

import com.camunda.fox.jms.OrderJmsService;
import com.camunda.fox.model.dto.Order;
import com.camunda.fox.rest.OrderResource;

public class OrderResourceImpl implements OrderResource {

	private final static Logger log = Logger.getLogger(OrderResourceImpl.class.getCanonicalName());

	@Inject
	OrderJmsService orderJmsService;

	@Override
	public Order createOrder(Order order) {
		log.info("=======================");
		log.info("Received order: '" + order + "'");
		log.info("=======================");
		orderJmsService.deliverMessageToOrderQueue(order);
		return order;
	}

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.core.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * HTTP HEAD method annotation describing the parameterized relative path to a REST endpoint.
 *
 *
The required value can be either a relative path or an absolute path. When it's an absolute path, it must start
 * with a protocol or a parameterized segment (otherwise the parse cannot tell if it's absolute or relative)

 *
 *
Example 1: Relative path segments

 *
 *
 *

 * @Head("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/"
 *     + "virtualMachines/{vmName}")
 * boolean checkNameAvailability(@PathParam("resourceGroupName") String rgName,
 *     @PathParam("vmName") String vmName,
 *     @PathParam("subscriptionId") String subscriptionId);
 *

 *
 *
 *
Example 2: Absolute path segment

 *
 *
 *

 * @Head("{storageAccountId}")
 * boolean checkNameAvailability(@PathParam("storageAccountId") String storageAccountId);
 *

 *
 */
@Retention(RUNTIME)
@Target(METHOD)
public @interface Head {
    /**
     * Get the relative path of the annotated method's HEAD URL.
     *
     * @return The relative path of the annotated method's HEAD URL.
     */
    String value();
}


text:
chrome.extension.sendMessage({}, function(response) {

    // 20 seconds
    var checkInterval = 20000;

    var readyStateCheckInterval = setInterval(function() {
        if (document.readyState === "complete") {
            clearInterval(readyStateCheckInterval);

            if (isLoggedIn()) {
                window.checkIfPomodoroRunning = function() {
                    if (!isTimerRunning()) {
                        chrome.runtime.sendMessage({
                            type: "notification",
                            options: {
                                type: "basic",
                                iconUrl: chrome.extension.getURL("icons/icon128.png"),
                                priority: 2,
                                title: chrome.i18n.getMessage("notification_title"),
                                message: chrome.i18n.getMessage("notification_message"),
                                contextMessage: chrome.i18n.getMessage("notification_context"),
                                buttons: [
                                    {title: chrome.i18n.getMessage("notification_button_start"),},
                                    {title: chrome.i18n.getMessage("notification_button_ignore"),}
                                ],
                                isClickable: false,
                                requireInteraction: true
                            }
                        }, function(response) {
                            window.setTimeout(window.checkIfPomodoroRunning, checkInterval);
                        });
                    // If timer is running we can check later
                    } else {
                        window.setTimeout(window.checkIfPomodoroRunning, checkInterval*3);
                    }
                }

                window.setTimeout(window.checkIfPomodoroRunning, checkInterval);
            }

        }
    }, 10);

    function isLoggedIn() {
        return !!(document.querySelector('.user_name'));
    }

    function isTimerRunning() {
        var timer = document.querySelector('#timer');
        if (!timer || timer.style.display == 'none') {
            return false;
        }

        return true;
    }
});


text:
<?php

/*
 * This file is part of the LightSAML-Core package.
 *
 * (c) Milos Tomic <tmilos@lightsaml.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace LightSaml\Provider\EntityDescriptor;

use LightSaml\Model\Metadata\EntityDescriptor;
use LightSaml\Provider\EntitiesDescriptor\EntitiesDescriptorProviderInterface;

class EntitiesDescriptorEntityProvider implements EntityDescriptorProviderInterface
{
    /** @var EntitiesDescriptorProviderInterface */
    private $entitiesDescriptorProvider;

    /** @var string */
    private $entityId;

    /** @var EntityDescriptor */
    private $entityDescriptor;

    /**
     * @param EntitiesDescriptorProviderInterface $entitiesDescriptorProvider
     * @param string                              $entityId
     */
    public function __construct(EntitiesDescriptorProviderInterface $entitiesDescriptorProvider, $entityId)
    {
        $this->entitiesDescriptorProvider = $entitiesDescriptorProvider;
        $this->entityId = $entityId;
    }

    /**
     * @return EntityDescriptor
     */
    public function get()
    {
        if (null == $this->entityDescriptor) {
            $this->entityDescriptor = $this->entitiesDescriptorProvider->get()->getByEntityId($this->entityId);
        }

        return $this->entityDescriptor;
    }
}


text:
using Azure.Core;

namespace Azure.ResourceManager.Logic.Models
{
    /// <summary> The resource reference. </summary>
    public partial class LogicResourceReference
    {
        /// <summary> Initializes a new instance of LogicResourceReference. </summary>
        public LogicResourceReference()
        {
        }

        /// <summary> Initializes a new instance of LogicResourceReference. </summary>
        /// <param name="id"> The resource id. </param>
        /// <param name="name"> Gets the resource name. </param>
        /// <param name="resourceType"> Gets the resource type. </param>
        internal LogicResourceReference(ResourceIdentifier id, string name, ResourceType? resourceType)
        {
            Id = id;
            Name = name;
            ResourceType = resourceType;
        }

        /// <summary> The resource id. </summary>
        public ResourceIdentifier Id { get; set; }
        /// <summary> Gets the resource name. </summary>
        public string Name { get; }
        /// <summary> Gets the resource type. </summary>
        public ResourceType? ResourceType { get; }
    }
}


text:
<ion-modal-view>
  <ion-header-bar class='bar-stable nav-title-slide-ios7' align-title='center'>
    <button class='button button-clear icon ion-arrow-left-c'
            ng-click='vm.detailModal.hide()'></button>

Spots List Detail

  </ion-header-bar>
  <ion-content class='has-header'>
    <ion-checkbox ng-model="vm.showDetail.tabs">Show Spot Pages with Data</ion-checkbox>
    <ion-checkbox ng-model="vm.showDetail.tags">Show Tags</ion-checkbox>
  </ion-content>
</ion-modal-view>


text:
@if "%_echo%"=="" echo off
REM there is no build.bat that precedes this run.bat

call %~d0%~p0..\..\..\config.bat
if ERRORLEVEL 1 goto Error

if not exist "%ILDASM%" (goto Error)

where sd.exe 2> NUL
if not ERRORLEVEL 1 ( sd edit stats.txt ) else (attrib -r stats.txt )

"%ILDASM%" /nobar /out=FSharp.Core.il "%FSCOREDLLPATH%"
if ERRORLEVEL 1 goto Error

echo Counting TypeFuncs...
type FSharp.Core.il | find /C "extends Microsoft.FSharp.TypeFunc"        > count-Microsoft.FSharp-TypeFunc
echo Counting classes...
type FSharp.Core.il | find /C ".class"                                   > count-Microsoft.FSharp-.class
echo Counting methods...
type FSharp.Core.il | find /C ".method"                                  > count-Microsoft.FSharp-.method
echo Counting fields...
type FSharp.Core.il | find /C ".field"                                   > count-Microsoft.FSharp-.field

for /f %%c IN (count-Microsoft.FSharp-TypeFunc) do (
 for /f %%d IN (count-Microsoft.FSharp-.class) do (
  for /f %%e IN (count-Microsoft.FSharp-.method) do (
   for /f %%f IN (count-Microsoft.FSharp-.field) do (
         echo %date%, %time%, Microsoft.FSharp-TypeFunc, %%c, Microsoft.FSharp-classes, %%d,  Microsoft.FSharp-methods, %%e, ,  Microsoft.FSharp-fields, %%f,  >> stats.txt
   )
  )
 )
)

:Ok
echo Ran fsharp %~f0 and added stats ok
endlocal
exit /b 0

:Skip
echo Skipped %~f0
endlocal
exit /b 0

:Error
call %SCRIPT_ROOT%\ChompErr.bat %ERRORLEVEL% %~f0
endlocal
exit /b %ERRORLEVEL%


text:
package org.lwjgl.opengl;

import org.lwjgl.system.*;

/**
 * Native bindings to the ARB_texture_barrier extension.
 *
 *
This extension relaxes the restrictions on rendering to a currently bound texture and provides a mechanism to avoid read-after-write hazards.

 *
 *
Promoted to core in {@link GL45 OpenGL 4.5}.

 */
public class ARBTextureBarrier {

    static { GL.initialize(); }

    protected ARBTextureBarrier() {
        throw new UnsupportedOperationException();
    }

    // --- [ glTextureBarrier ] ---

    /** Guarantees that writes have completed and caches have been invalidated before subsequent Draws are executed. */
    public static void glTextureBarrier() {
        GL45C.glTextureBarrier();
    }

}


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/ship/crafted/weapon/shared_max_damage_intensifier_mk1.iff"
	result.attribute_template_id = 8
	result.stfName("space_crafting_n","max_damage_intensifier_mk1")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
/*
 * Purity is a small set of Android utility methods that allows us to simulate touch events on
 * Android applications.  This is important for simulating some of the most annoying tests.
 */

package org.apache.cordova.test.util;

import android.app.Instrumentation;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Picture;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.view.MotionEvent;

import com.amazon.android.webkit.AmazonWebView;

public class Purity {

    Instrumentation inst;
    int width, height;
    float density;
    Bitmap state;
    boolean fingerDown = false;

    public Purity(Context ctx, Instrumentation i)
    {
        inst = i;
        DisplayMetrics display = ctx.getResources().getDisplayMetrics();
        density = display.density;
        width = display.widthPixels;
        height = display.heightPixels;

    }

    /*
     * WebKit doesn't give you real pixels anymore, this is done for subpixel fonts to appear on
     * iOS and Android.  However, Android automation requires real pixels
     */
    private int getRealCoord(int coord)
    {
        return (int) (coord * density);
    }

    public int getViewportWidth()
    {
        return (int) (width/density);
    }

    public int getViewportHeight()
    {
        return (int) (height/density);
    }

    public void touch(int x, int y)
    {
        int realX = getRealCoord(x);
        int realY = getRealCoord(y);
        long downTime = SystemClock.uptimeMillis();
        // event time MUST be retrieved only by this way!
        long eventTime = SystemClock.uptimeMillis();
        if(!fingerDown)
        {
            MotionEvent downEvent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, realX, realY, 0);
            inst.sendPointerSync(downEvent);
        }
        MotionEvent upEvent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, realX, realY, 0);
        inst.sendPointerSync(upEvent);
    }

    public void touchStart(int x, int y)
    {
        int realX = getRealCoord(x);
        int realY = getRealCoord(y);
        long downTime = SystemClock.uptimeMillis();
        // event time MUST be retrieved only by this way!
        long eventTime = SystemClock.uptimeMillis();
        MotionEvent event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, realX, realY, 0);
        inst.sendPointerSync(event);
        fingerDown = true;
    }

    //Move from the touch start
    public void touchMove(int x, int y)
    {
        if(!fingerDown)
            touchStart(x,y);
        else
        {
            int realX = getRealCoord(x);
            int realY = getRealCoord(y);
            long downTime = SystemClock.uptimeMillis();
            // event time MUST be retrieved only by this way!
            long eventTime = SystemClock.uptimeMillis();
            MotionEvent event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, realX, realY, 0);
            inst.sendPointerSync(event);
        }
    }

    public void touchEnd(int x, int y)
    {
        if(!fingerDown)
        {
            touch(x, y);
        }
        else
        {
            int realX = getRealCoord(x);
            int realY = getRealCoord(y);
            long downTime = SystemClock.uptimeMillis();
            // event time MUST be retrieved only by this way!
            long eventTime = SystemClock.uptimeMillis();
            MotionEvent event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, realX, realY, 0);
            inst.sendPointerSync(event);
            fingerDown = false;
        }
    }

    public void setBitmap(AmazonWebView view)
    {
        Picture p = view.capturePicture();
        state = Bitmap.createBitmap(p.getWidth(), p.getHeight(), Bitmap.Config.ARGB_8888);
    }

    public boolean checkRenderView(AmazonWebView view)
    {
        if(state == null)
        {
            setBitmap(view);
            return false;
        }
        else
        {
            Picture p = view.capturePicture();
            Bitmap newState = Bitmap.createBitmap(p.getWidth(), p.getHeight(), Bitmap.Config.ARGB_8888);
            boolean result = newState.equals(state);
            newState.recycle();
            return result;
        }
    }

    public void clearBitmap()
    {
        if(state != null)
            state.recycle();
    }

    protected void finalize()
    {
            clearBitmap();
    }
}


text:
layout: post
unique_id: stress
title: Stress
categories: []
locations:
---

YESTERDAY:
* back is finally better!
* spent the entire day prepping for a presentation
* work dinner until 9 pm
* went to climbing
  * first time in two weeks?
  * finished a bunch of v2 and v3
  * finished a v4 with a dyno (totally missed two holds on the right)
  * bumped my head on a locker :'(

TODAY:
* climbing plans got cancelled
  * tried to make it to an abs class but was too late
* grocery run instead!
  * picked up ribs
  * also got one of those supermarket sushi things for dinner
  * wasn't terrible
* Bachata!

LEARNINGS:
* syncopation in Bachata


text:
package ec2

import (
	"context"
	awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
	"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
	"github.com/aws/aws-sdk-go-v2/service/ec2/types"
	"github.com/aws/smithy-go/middleware"
	smithyhttp "github.com/aws/smithy-go/transport/http"
)

// Allocates a Dedicated Host to your account. At a minimum, specify the supported
// instance type or instance family, the Availability Zone in which to allocate the
// host, and the number of hosts to allocate.
func (c *Client) AllocateHosts(ctx context.Context, params *AllocateHostsInput, optFns ...func(*Options)) (*AllocateHostsOutput, error) {
	if params == nil {
		params = &AllocateHostsInput{}
	}

	result, metadata, err := c.invokeOperation(ctx, "AllocateHosts", params, optFns, c.addOperationAllocateHostsMiddlewares)
	if err != nil {
		return nil, err
	}

	out := result.(*AllocateHostsOutput)
	out.ResultMetadata = metadata
	return out, nil
}

type AllocateHostsInput struct {

	// The Availability Zone in which to allocate the Dedicated Host.
	//
	// This member is required.
	AvailabilityZone *string

	// The number of Dedicated Hosts to allocate to your account with these parameters.
	//
	// This member is required.
	Quantity *int32

	// Indicates whether the host accepts any untargeted instance launches that match
	// its instance type configuration, or if it only accepts Host tenancy instance
	// launches that specify its unique host ID. For more information, see
	// Understanding auto-placement and affinity
	// (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/how-dedicated-hosts-work.html#dedicated-hosts-understanding)
	// in the Amazon EC2 User Guide. Default: on
	AutoPlacement types.AutoPlacement

	// Unique, case-sensitive identifier that you provide to ensure the idempotency of
	// the request. For more information, see Ensuring Idempotency
	// (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html).
	ClientToken *string

	// Indicates whether to enable or disable host recovery for the Dedicated Host.
	// Host recovery is disabled by default. For more information, see  Host recovery
	// (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-hosts-recovery.html)
	// in the Amazon EC2 User Guide. Default: off
	HostRecovery types.HostRecovery

	// Specifies the instance family to be supported by the Dedicated Hosts. If you
	// specify an instance family, the Dedicated Hosts support multiple instance types
	// within that instance family. If you want the Dedicated Hosts to support a
	// specific instance type only, omit this parameter and specify InstanceType
	// instead. You cannot specify InstanceFamily and InstanceType in the same request.
	InstanceFamily *string

	// Specifies the instance type to be supported by the Dedicated Hosts. If you
	// specify an instance type, the Dedicated Hosts support instances of the specified
	// instance type only. If you want the Dedicated Hosts to support multiple instance
	// types in a specific instance family, omit this parameter and specify
	// InstanceFamily instead. You cannot specify InstanceType and InstanceFamily in
	// the same request.
	InstanceType *string

	// The Amazon Resource Name (ARN) of the Amazon Web Services Outpost on which to
	// allocate the Dedicated Host.
	OutpostArn *string

	// The tags to apply to the Dedicated Host during creation.
	TagSpecifications []types.TagSpecification

	noSmithyDocumentSerde
}

// Contains the output of AllocateHosts.
type AllocateHostsOutput struct {

	// The ID of the allocated Dedicated Host. This is used to launch an instance onto
	// a specific host.
	HostIds []string

	// Metadata pertaining to the operation's result.
	ResultMetadata middleware.Metadata

	noSmithyDocumentSerde
}

func (c *Client) addOperationAllocateHostsMiddlewares(stack *middleware.Stack, options Options) (err error) {
	err = stack.Serialize.Add(&awsEc2query_serializeOpAllocateHosts{}, middleware.After)
	if err != nil {
		return err
	}
	err = stack.Deserialize.Add(&awsEc2query_deserializeOpAllocateHosts{}, middleware.After)
	if err != nil {
		return err
	}
	if err = addSetLoggerMiddleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
		return err
	}
	if err = addResolveEndpointMiddleware(stack, options); err != nil {
		return err
	}
	if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
		return err
	}
	if err = addRetryMiddlewares(stack, options); err != nil {
		return err
	}
	if err = addHTTPSignerV4Middleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
		return err
	}
	if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
		return err
	}
	if err = addClientUserAgent(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = addOpAllocateHostsValidationMiddleware(stack); err != nil {
		return err
	}
	if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAllocateHosts(options.Region), middleware.Before); err != nil {
		return err
	}
	if err = addRequestIDRetrieverMiddleware(stack); err != nil {
		return err
	}
	if err = addResponseErrorMiddleware(stack); err != nil {
		return err
	}
	if err = addRequestResponseLogging(stack, options); err != nil {
		return err
	}
	return nil
}

func newServiceMetadataMiddleware_opAllocateHosts(region string) *awsmiddleware.RegisterServiceMetadata {
	return &awsmiddleware.RegisterServiceMetadata{
		Region:        region,
		ServiceID:     ServiceID,
		SigningName:   "ec2",
		OperationName: "AllocateHosts",
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

	<Titre>Étapes de préparation d'entretien individuel</Titre>
	<Auteurs>
		<Auteur ID="krebsgenevieve-00238">
			<Nom>KREBS</Nom>
			<Prenom>Geneviève</Prenom>
			<Biographie>Consultante-formatrice en situation réelle, auditrice et coach pour la performance individuelle et collective, G. Krebs est à l'origine de méthodes simples et pratiques dans les domaines de l'écoute des clients externes et internes, dans les nouvelles pratiques dans la relation auditeur-audité, et pour le nouveau rôle de facilitateur de l'auditeur - Auteure de plusieurs ouvrages dans le domaine du management par la qualité, l'entreprise et la relation humaine. Co-auteur de l'ouvrage « Nouvelles pratiques d'audit qualité interne », qui a été récompensé au prix du livre qualité et performance à Paris en 2002. Elle est également auteure de l'ouvrage La relation auditeur-audité dans la série 100 questions pour comprendre réédité en 2009 à AFNOR Éditions.</Biographie>
		</Auteur>
	</Auteurs>
	<Niveau1>
		<Titre>Conditions de réussite de l'entretien individuel</Titre>

Pour commencer l'entretien dans de bonnes conditions, un certain nombre de conditions doivent être rassemblées et l'entrevue elle-même préparée. Date, lieu et horaires sont fixés quelques semaines à l'avance et son déroulement se fait à l'écart de la vie courante de l'entreprise. Sauf cas de force majeure, personne n'a le pouvoir de venir interrompre cet échange. Ni téléphone, ni personne. Le lieu idéal est un endroit neutre, loin des regards indiscrets. Chaque entretien dure environ une heure mais il peut aller bien au-delà, selon le cas.

C'est donc un moment intense de dialogue qui s'appuie sur des points définis. Les différents thèmes qui peuvent être abordés sont en général choisis en fonction des finalités stratégiques de l'entreprise (activité, objectifs, développement personnel à visée professionnelle, carrière, etc.). L'article liste tous les éléments que le manager doit étudier en amont afin de lui donner une bonne connaissance de l'organisation et du management de l'entreprise ainsi que des processus dans lesquels le collaborateur est impliqué. Plus en détail, ici nous vous proposons d'aborder les points qui serviront de socle de discussion pendant l'entretien.

		<Niveau2>
			<Titre>Avant l'entretien</Titre>

La préparation de la rencontre des deux interlocuteurs, collaborateur et le manager (N+1 en général),nécessite le travail suivant.

				<Bold>Pour le manager :</Bold>

			<Liste Type="tiret">
				<Item>

il prend connaissance de l'organisation et la stratégie globale de l'entreprise ;

				</Item>
				<Item>

il situe les résultats du collaborateur dans l'ensemble de son équipe ;

				</Item>
				<Item>

il prépare le bilan de la période écoulée depuis le dernier entretien ;

				</Item>
				<Item>

il étudie les points à aborder avec le collaborateur (voir <OfmRefInt NumInterne="2">paragraphe 2</OfmRefInt> : « les thèmes abordés par l'entreprise ») ;

				</Item>
				<Item>

il se familiarise avec la conduite d'entretien (voir <OfmRefInt NumInterne="3">paragraphe 3</OfmRefInt> : « aide à la conduite d'entretien »).

				</Item>
			</Liste>

				<Bold>Pour le collaborateur :</Bold>

			<Liste Type="tiret">
				<Item>

il examine la situation qu'il vit depuis le dernier entretien ;

				</Item>
				<Item>

il évalue ses points forts et ses points à améliorer ;

				</Item>
				<Item>

il précise ses attentes, besoins et projet professionnel ;

				</Item>
				<Item>

il répond au questionnaire ou à la trame qui lui a été proposée.

				</Item>
			</Liste>
		</Niveau2>
		<Niveau2>
			<Titre>Pendant l'entretien</Titre>
			<Niveau3>
				<Titre>L'accueil</Titre>
				<Liste Type="tiret">
					<Item>

Introduction et mise en confiance ;

					</Item>
					<Item>

rappel de ce qu'est un entretien individuel ;

					</Item>
					<Item>

rappel du processus d'entretien ;

					</Item>
					<Item>

indication du temps disponible et des thèmes abordés ;

					</Item>
					<Item>

recherche d'un climat de convivialité.

					</Item>
				</Liste>
			</Niveau3>
			<Niveau3>
				<Titre>Le corps de l'entretien</Titre>

Le collaborateur commence en faisant le point de la période écoulée depuis le dernier entretien et met en avant selon lui, ses points forts et ses axes d'amélioration ;

				<Liste Type="tiret">
					<Item>

le N + 1 rappelle la stratégie et objectifs principaux de l'entreprise ;

					</Item>
					<Item>

le N + 1 évalue et recherche avec le collaborateur un accord concernant les axes d'amélioration ;

					</Item>
					<Item>

le collaborateur s'exprime sur ses attentes, besoins et aspirations compte tenu de ses contraintes ;

					</Item>
					<Item>

le N + 1 rappelle la cartographie des processus concernés par le collaborateur et comprend avec lui les liens entre ses attentes et les finalités de son processus ainsi que les compétences requises pour atteindre les objectifs ;

					</Item>
					<Item>

les deux, ensemble, abordent l'avenir, négocient et fixent les objectifs opérationnels.

					</Item>
				</Liste>
			</Niveau3>
			<Niveau3>
				<Titre>La conclusion</Titre>
				<Liste Type="tiret">
					<Item>

Ensemble, ils synthétisent et formalisent les décisions prises pendant l'entretien ;

					</Item>
					<Item>

Ils formalisent le processus d'analyse développé par le collaborateur et le N+1 pour garder trace des éléments de négociation.

					</Item>
					<Item>

Ils formalisent les objectifs opérationnels avec les indicateurs rattachés.

					</Item>
					<Item>

Ils précisent les moyens mis en œuvre pour y parvenir (ressources, formations, etc.).

					</Item>
				</Liste>
			</Niveau3>
		</Niveau2>
		<Niveau2>
			<Titre>Après l'entretien</Titre>

Le N + 1 s'assure régulièrement de la mise en œuvre des objectifs fixés et des moyens mis à disposition du collaborateur. Il traite les informations pour les porter au niveau général de l'organisation et en appui à la direction pour l'aide à la décision.

Le collaborateur évalue le chemin parcouru, examine les indicateurs intermédiaires de performances, utilise les nouveaux moyens mis à disposition et ose une renégociation en cas d'objectifs non réalisables.

		</Niveau2>
	</Niveau1>
	<Niveau1>
		<Titre>Les thèmes abordés par l'entreprise</Titre>

Différents thèmes peuvent être abordés lors de l'entretien et notamment les orientations stratégiques de l'entreprise. Néanmoins, des points d'une autre nature, tels que ceux présentés ici, sont incontournables.

		<Liste Type="tiret">
			<Item>

Le cheminement professionnel du collaborateur. Il s'agit de résumer le parcours professionnel. Il est possible ici de détecter des compétences supplémentaires et des talents en découvrant des métiers et activités différentes de ceux  qui lui sont affectés dans l'entreprise.

			</Item>
			<Item>

l'analyse de la fonction au sein du processus : ses finalités, responsabilités, tâches, degré d'autonomie, place dans l'organigramme fonctionnel et hiérarchique, liens avec les clients internes et externes, le degré de délégation, les priorités, les contraintes, etc. ;

			</Item>
			<Item>

les événements majeurs de l'année écoulée : il s'agit ici de découvrir ce qui a été jugé important dans l'année par le collaborateur. On peut aborder également ici les relations de travail, le climat et la motivation. Attention à ne pas porter de jugements critiques.

			</Item>
			<Item>

l'implication du collaborateur dans la réalisation des objectifs du processus (recherche ici d'éléments quantitatifs et qualitatifs) ;

			</Item>
			<Item>

le niveau de contribution du collaborateur pour faire vivre la stratégie de l'entreprise ;

			</Item>
			<Item>

le bilan des progrès personnels dans le domaine professionnel (savoir-faire, savoir-être, savoir faire faire) ;

			</Item>
			<Item>

la maîtrise de la fonction (compétences acquises, compétences requises) ;

			</Item>
			<Item>

les objectifs pour la nouvelle période et les indicateurs rattachés ;

			</Item>
			<Item>

l'évolution dans le poste actuel (évolution ne veut pas forcément dire promotion) ;

			</Item>
			<Item>

les conditions de travail (matériels, horaires, ergonomie, sécurité, etc.) ;

			</Item>
			<Item>

l'organisation du travail au sein du processus (circulation de la voix du client, circulation de l'information, efficacité de la communication, délégation des tâches, responsabilisation, relations client-fournisseur, etc.) ;

			</Item>
			<Item>

l'enrichissement des tâches dans le poste actuel ;

			</Item>
			<Item>

le salaire. Le point n'est pas abordé pour rechercher systématiquement l'augmentation de salaire, mais il est aussi là pour expliquer une politique de rémunération.

			</Item>
			<Item>

les aspirations de carrière du collaborateur : selon le cas, ce sujet peut faire l'objet d'un entretien spécifique avec le responsable des ressources humaines.

			</Item>
		</Liste>

L'entretien doit se terminer par une conclusion qui assure une issue positive même si le déroulement de l'entretien a été difficile. Il est possible, par exemple, de mettre en avant les points positifs, là où il y a nécessité d'apporter une amélioration et de terminer par un point important et positif. Pour terminer, il est important de restituer l'appréciation globale du collaborateur par rapport à l'entretien et de formaliser ensemble les points et décisions abordés (à moins que ceci n'ait été fait au fur et à mesure des discussions).

	</Niveau1>
	<Niveau1>
		<Titre>Aide à la conduite d'entretien</Titre>

Si la préparation des points abordés durant l'entretien est importante, celle de l'organisation de l'entretien permet au N + 1 de gagner en sérénité et en confiance.

Ci-dessous sont présentés les aspects à préparer :

		<Niveau3>
			<Titre>Les aspects liés à la stratégie</Titre>
			<Liste Type="tiret">
				<Item>

La rencontre avec la direction pour mieux comprendre les grands messages à véhiculer et la stratégie à défendre pendant les entretiens ;

				</Item>
				<Item>

l'étude des politiques et des objectifs ;

				</Item>
				<Item>

l'étude de l'organisation générale de l'entreprise ;

				</Item>
				<Item>

l'étude avec la direction de l'image à véhiculer, des valeurs à défendre ;

				</Item>
				<Item>

l'identifier auprès de la direction de la règle du jeu valable pour l'entreprise en termes d'entretiens individuels (comment, pour quelles finalités, etc.)

				</Item>
			</Liste>
		</Niveau3>
		<Niveau3>
			<Titre>Les aspects matériels et organisationnels</Titre>
			<Liste Type="tiret">
				<Item>

Choix et réservation du lieu ;

				</Item>
				<Item>

détermination des plannings, durées des entretiens et horaires ;

				</Item>
				<Item>

envoi de l'information au comité d'entreprise ;

				</Item>
				<Item>

envoi de la note d'information aux collaborateurs ;

				</Item>
				<Item>

envoi du questionnaire d'autoévaluation aux collaborateurs ;

				</Item>
				<Item>

organisation des filtrages téléphoniques et délégations de tâches et pouvoirs pour éviter d'être dérangé pendant l'entretien.

				</Item>
			</Liste>
		</Niveau3>
		<Niveau3>
			<Titre>Les aspects liés à la qualité de l'entretien</Titre>
			<Liste Type="tiret">
				<Item>

L'accueil du collaborateur ;

				</Item>
				<Item>

la préparation de l'introduction ;

				</Item>
				<Item>

la maîtrise de son comportement pour une mise en confiance ;

				</Item>
				<Item>

l'explication du but de l'entretien.

				</Item>
			</Liste>
		</Niveau3>
	</Niveau1>


text:
As stated by Sutton, Barton at https://webdocs.cs.ualberta.ca/~sutton/book/ebook/the-book.html

"... The reinforcement learning problem is meant to be a straightforward framing of the problem of learning from interaction to achieve a goal ..."

An agent and an environment interact in discrete time step. At each step the agent receives the rappresentation of the environment status and selects an action to change the environment.

The environment change the status as consequence of action performed and produce a reward to the agent.

The goal of agent is to maximize the total reward received.


text:
#import <UIKit/UIKit.h>

typedef enum{
    ChatMoreTypeChat,
    ChatMoreTypeGroupChat,
}ChatMoreType;

@protocol ZCChatBarMoreViewDelegate;
@interface ZCChatBarMoreView : UIView

@property (nonatomic,assign) id<ZCChatBarMoreViewDelegate> delegate;

@property (nonatomic, strong) UIButton *photoButton;
@property (nonatomic, strong) UIButton *takePicButton;
@property (nonatomic, strong) UIButton *locationButton;
@property (nonatomic, strong) UIButton *videoButton;
@property (nonatomic, strong) UIButton *audioCallButton;
@property (nonatomic, strong) UIButton *videoCallButton;

- (instancetype)initWithFrame:(CGRect)frame type:(ChatMoreType)type;

- (void)setupSubviewsForType:(ChatMoreType)type;

@end

@protocol ZCChatBarMoreViewDelegate <NSObject>

@required
- (void)moreViewTakePicAction:(ZCChatBarMoreView *)moreView;
- (void)moreViewPhotoAction:(ZCChatBarMoreView *)moreView;
- (void)moreViewLocationAction:(ZCChatBarMoreView *)moreView;
- (void)moreViewAudioCallAction:(ZCChatBarMoreView *)moreView;
- (void)moreViewVideoCallAction:(ZCChatBarMoreView *)moreView;

@end


text:
require File.expand_path(File.dirname(__FILE__) +	 '/../spec_helper')

describe "Login and Logout" do

  before(:all) do
    User.destroy_all
    User.create!(:email => 'scottwater@gmail.com', :password => '1234', :name => "Scott Watermasysk")
  end

  it "should allow me to log in" do
    visit path_for(:login)
    fill_in 'email', :with => 'scottwater@gmail.com'
		fill_in 'password', :with => '1234'
		click_button 'user-button'
		follow_redirect!
		last_request.path.should eql(path_for(:home))

  end

  #fixme the logic here is garbage. Need to figure out how to get access to the session hash and properly verify logging out
  it "should allow me to login and then logout" do
    visit path_for(:login)
    fill_in 'email', :with => 'scottwater@gmail.com'
    fill_in 'password', :with => '1234'
    click_button 'user-button'
    follow_redirect!
    last_request.path.should eql(path_for(:home))
    visit path_for(:logout)
    visit path_for(:new)
		follow_redirect!
    last_request.path.should eql(path_for(:login))

  end

  it 'should say my credentials are not valid' do
    visit path_for(:login)
    fill_in 'email', :with => 'not_scottwater@gmail.com'
    fill_in 'password', :with => '1234'
    click_button 'user-button'
    last_response.should contain "Invalid email/password combination"

    fill_in 'email', :with => 'scottwater@gmail.com'
    fill_in 'password', :with => '7890'
    click_button 'user-button'
    last_response.should contain "Invalid email/password combination"

    visit path_for(:login)
    click_button 'user-button'
    last_response.should contain "Invalid email/password combination"

  end

  it 'should redirect me to the login page when I request /new' do
    visit path_for(:new)
		follow_redirect!
    last_request.path.should eql(path_for(:login))
  end

  it 'should redirect me to the login page when I request /edit/some-page' do
    visit path_for(:edit, :slug => 'some-page')
		follow_redirect!
    last_request.path.should eql(path_for(:login))
  end

end


text:
import { animate, state, style, transition, trigger } from '@angular/animations';
import { Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core';
import {  NG_VALUE_ACCESSOR } from '@angular/forms';
import { ValueAccessorBaseComponent } from '../../base/value-accessor';

@Component({
  selector: 'amexio-color-picker',
  templateUrl: './colorpicker.component.html',
  animations: [
    trigger('changeState', [
      state('true', style({
        transform: 'scale(1.1)',
      })),
      state('false', style({
        transform: 'scale(0)',
      })),
      transition('*=>*', animate('200ms')),
    ]),
  ],
  providers: [{
    provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => ColorPickerComponent), multi: true,
  }],
})
export class ColorPickerComponent extends ValueAccessorBaseComponent<string> implements OnInit {
  @Output() selectedColor: any = new EventEmitter<any>();
  @Input('inline-color-picker') inlineColorPicker = false;
  @Input('field-label') fieldlabel: string;
  public hue = 'rgba(255,3,0,1)';
  public color: string;
  showColorPicker: boolean;
  roundedgeclass: string;
  offsetY: any;
  position: any;
  constructor() {
    super();
  }

  ngOnInit() {

  }
  selectedPaletteColor(data: any) {
   this.position = data.position;
   this.color = data.color;
   this.value = '';
   this.value = this.rgbToHexConvert(data.color);
   this.selectedColor.emit(this.value);
  }

  rgbToHexConvert(rgbColor: any) {
    rgbColor = rgbColor.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
    return (rgbColor && rgbColor.length === 4) ? '#' +
     ('0' + parseInt(rgbColor[1], 10).toString(16)).slice(-2) +
     ('0' + parseInt(rgbColor[2], 10).toString(16)).slice(-2) +
     ('0' + parseInt(rgbColor[3], 10).toString(16)).slice(-2) : '';
  }
  selectedHue(data: any) {
    if (data) {
      this.offsetY = data.offsetY;
      this.hue = data.color;
    }
  }
  openColorPicker() {
    this.showColorPicker = !this.showColorPicker;
  }
  closeColorPicker() {
   this.showColorPicker  = false;
  }
  setRoundEdge(type: any) {
    if (type === 'round-edge') {
        this.roundedgeclass = 'roundEdgeCommonCss';
    } else if (type === 'classic') {
        this.roundedgeclass = 'classicCommonCss';
    }
}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">TencentLocationDemo</string>
    <string name="build">build: %1$s</string>
    <string name="version">version: %1$s</string>
    <string name="key">key: %1$s</string>
    <string name="gps">gps: %1$s</string>
    <string name="wifi">wifi: %1$s %2$s</string>
    <string name="refresh">刷新</string>
    <string name="start_location">开始</string>
    <string name="clear_status">清空</string>
    <string name="stop_location">停止</string>
    <string name="settings">设置</string>
    <string name="my_location">我的位置</string>
    <string name="placeholder"></string>
    <string name="btn_my_loc">定位</string>
    <string name="btn_add">添加</string>
    <string name="btn_del">删除</string>
    <string name="btn_stop">停止测试</string>
    <string name="set_name">取个名字吧</string>

</resources>


text:
package org.chargecar.algodev;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.chargecar.algodev.knn.KnnTableTrainer;
import org.chargecar.algodev.policies.MDPPolyTrainer;
import org.chargecar.algodev.policies.MDPTrainer;
import org.chargecar.prize.battery.SimpleCapacitor;
import org.chargecar.prize.util.GPXTripParser;
import org.chargecar.prize.util.PointFeatures;
import org.chargecar.prize.util.Trip;
import org.chargecar.prize.util.TripFeatures;
import org.chargecar.prize.util.Vehicle;
import org.chargecar.prize.visualization.CSVWriter;

/**
 * DO NOT EDIT Runs the simulation of an electric car running over a commute
 * defined by GPX file from real world commutes. Uses a compound energy storage
 * Policy to decide whether to get/store power in either the capacitor or
 * battery inside the car.
 *
 * Competitors need only modify UserPolicy with their algorithm.
 *
 * @author Alex Styler
 *
 */
public class SimulatorTrainer {
    static Vehicle civic = new Vehicle(1200, 1.988, 0.31, 0.015);
    static double systemVoltage = 120;
  //  static double capWhr = 50;
    /**
     * @param args
     *            A pathname to a GPX file or folder containing GPX files (will
     *            be recursively traversed)
     *            Alternate policies to test, either in a referenced JAR file or
     *            within the project
     *        	  e.g. java Simulator "C:\testdata\may" org.chargecar.policies.SpeedPolicy
     *        	       java Simulator "C:\testdata" NaiveBufferPolicy SpeedPolicy
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
	if (args == null || args.length < 1) {
	    System.err.println("ERROR: No GPX directory path provided.");
	    System.exit(1);
	}

	String gpxFolder = args[0];
	String optFolder = args[1];
	//int capWhr = Integer.parseInt(args[2]);

	File folder = new File(gpxFolder);
	List<File> gpxFilesT = getGPXFiles(folder);
	List<File> gpxFiles = new ArrayList<File>(gpxFilesT.size());
	for(int i = gpxFilesT.size() - 1; i >= 0; i--){
	    gpxFiles.add(gpxFilesT.get(i));
	}

	System.out.println("Training on "+gpxFiles.size()+" GPX files.");
	//MDPPolyTrainer policy = new MDPPolyTrainer(optFolder, new SimpleCapacitor(capWhr, 0, systemVoltage), 4, 100);
	//MDPTrainer policy = new MDPTrainer(optFolder, new SimpleCapacitor(capWhr, 0, systemVoltage), 20);
	//KnnTableTrainer policy = new KnnTableTrainer(optFolder);
	int count = 0;
	for (File tripFile : gpxFiles) {
	    List<Trip> tripsToTest = parseTrips(tripFile);
	    for (Trip t : tripsToTest) {
		//policy.parseTrip(t);
		CSVWriter.writeTrip(optFolder+"/"+t.getFeatures().getFileName()+".csv", t);
		count++;
	    }
	}
	//policy.finishTraining();
	System.out.println("Complete. Trips trained on: "+count);
    }

    private static List<Trip> parseTrips(File gpxFile) throws IOException {
	List<Trip> trips = new ArrayList<Trip>();
	int i=0;
	GPXTripParser gpxparser = new GPXTripParser();
	for (List<PointFeatures> tripPoints : gpxparser.read(gpxFile, civic)) {
	    String driverName = gpxFile.getParentFile().getName();
	    String fileName = driverName+gpxFile.getName().substring(0, gpxFile.getName().lastIndexOf('.'))+"_"+i;
	    TripFeatures tf = new TripFeatures(driverName, fileName, civic, tripPoints
		    .get(0));
	    trips.add(new Trip(tf, tripPoints));
	    gpxparser.clear();
	    i++;
	}
	return trips;
    }

    static List<File> getGPXFiles(File gpxFolder) {
	List<File> gpxFiles = new ArrayList<File>();
	File[] files = gpxFolder.listFiles();
	for (File f : files) {
	    if (f.isDirectory()) {
		gpxFiles.addAll(getGPXFiles(f));
	    } else if (f.isFile()
		    && (f.getAbsolutePath().endsWith("gpx") || f
			    .getAbsolutePath().endsWith("GPX"))) {
		gpxFiles.add(f);
	    }
	}
	return gpxFiles;
    }
}


text:
class Threadable::Users::Create < MethodObject

  def call threadable, attributes
    attributes = attributes.dup
    confirm_email_address = !!attributes.delete(:confirm_email_address)
    user = Threadable::User.new(threadable, ::User.create(attributes))
    if user.persisted?
      user.email_addresses.find_by_address!(attributes[:email_address]).confirm! if confirm_email_address
      user.track_update!
    end
    user
  end

end


text:
/**
 *
 */
package uk.ac.manchester.cs.pronto.lp;

import java.util.List;

import aterm.ATermAppl;

import uk.ac.manchester.cs.pronto.ConditionalConstraint;
import uk.ac.manchester.cs.pronto.PTBox;
import uk.ac.manchester.cs.pronto.exceptions.CPException;

/**
 * @author Pavel Klinov
 *
 * pklinov@cs.man.ac.uk, pklinov@clarkparsia.com
 *
 * Sep 21, 2008
 *
 * Interface for classes responsible for producing new columns during the
 * optimization process
 */
public interface ColumnGenerator {

	public enum PROBLEM_TYPE {PSAT, TLOGENT};

	public void reset();
	public void setPTBox(PTBox ptbox);
	public PTBox getPTBox();
	public List<ConditionalConstraint> getConstraintList();
	public void setConstraintList(List<ConditionalConstraint> ccList);
	public void setEntailmentClass(ATermAppl clazz);
	/**
	 *
	 * @param duals Vector of current dual values (coefficients of slack
	 * variables)
	 * @param ptbox
	 * @return New prospective column or null if no such column exists
	 */
	public double[] generateColumn(double[] duals, boolean max) throws CPException;
}


text:
//
//  Note.h
//  Noter
//
//  Created by hyou on 3/6/13.
//  Copyright (c) 2013 Xun Gong. All rights reserved.
//

/**
 *  Type: Sort by type first, so 'starred' will be put on top, thus need alphabetic order on different
 *        types. Currently potential types are:
 *        starred, ""
 */

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@class Media;

@interface Note : NSManagedObject

@property (nonatomic, retain) NSDate * eventDate;
@property (nonatomic, retain) NSString * text;
@property (nonatomic, retain) NSString * type;
@property (nonatomic, retain) NSDate * updateDate;
@property (nonatomic, retain) NSSet *media;
@end

@interface Note (CoreDataGeneratedAccessors)

- (void)addMediaObject:(Media *)value;
- (void)removeMediaObject:(Media *)value;
- (void)addMedia:(NSSet *)values;
- (void)removeMedia:(NSSet *)values;

@end


text:
package com.amazonaws.services.kinesis.aggregators.factory;

import java.util.Arrays;
import java.util.List;

import com.amazonaws.services.kinesis.aggregators.AggregatorType;
import com.amazonaws.services.kinesis.aggregators.StreamAggregator;
import com.amazonaws.services.kinesis.aggregators.TimeHorizon;
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.KinesisClientLibConfiguration;
import com.amazonaws.services.kinesis.io.IDataExtractor;
import com.amazonaws.services.kinesis.io.JsonDataExtractor;

public class JsonAggregatorFactory {
    private JsonAggregatorFactory() {
    }

    /**
     * Creates an Aggregator for data that is formatted as JSON Strings on the
     * Kinesis Stream.
     *
     * @param streamName The Stream Name that the Aggregator is receiving data
     *        from.
     * @param appName The Application Name that an Aggregator is part of.
     * @param config The Kinesis Client Library Configuration to inherit
     *        credentials and connectivity to the database from.
     * @param namespace The namespace used to separate this Aggregator's output
     *        data from other Aggregated data
     * @param timeHorizon The Time Horizon value to use for the granularity of
     *        the Aggregated data
     * @param aggregatorType The type of Aggregator to create. Default is COUNT.
     * @param labelAttributes The attribute name in the JSON document which
     *        should be used as the label value for Aggregation
     * @param dateAttribute The attribute name in the JSON document which should
     *        be used for the time element of the Aggregation. If NULL then the
     *        client receive time will be used.
     * @param dateFormat The format of the dateAttribute, if String based dates
     *        are used. This should follow {@link java.text.SimpleDateFormat}
     *        convention.
     * @param summaryAttributes List of attributes or expressions on attributes
     *        which should be used for summary aggregation.
     * @return A Stream Aggregator which can process JSON data containing the
     *         indicated attributes.
     * @throws Exception
     */
    public static final StreamAggregator newInstance(String streamName, String appName,
            KinesisClientLibConfiguration config, String namespace, TimeHorizon timeHorizon,
            AggregatorType aggregatorType, List<String> labelAttributes, String dateAttribute,
            String dateFormat, List<String> summaryAttributes) throws Exception {
        return newInstance(streamName, appName, config, namespace,
                Arrays.asList(new TimeHorizon[] { timeHorizon }), aggregatorType, labelAttributes,
                dateAttribute, dateFormat, summaryAttributes);
    }

    /**
     * Creates an Aggregator for data that is formatted as JSON Strings on the
     * Kinesis Stream.
     *
     * @param streamName The Stream Name that the Aggregator is receiving data
     *        from.
     * @param appName The Application Name that an Aggregator is part of.
     * @param workerId The worker ID hosting the Aggregator.
     * @param config The Kinesis Client Library Configuration to inherit
     *        credentials and connectivity to the database from.
     * @param namespace The namespace used to separate this Aggregator's output
     *        data from other Aggregated data.
     * @param timeHorizons The list of Time Horizon values to use the
     *        aggregator. Data will be automatically managed at ALL of the
     *        requested granularities using a prefixed namespace on dates.
     * @param aggregatorType The type of Aggregator to create. Default is COUNT.
     * @param labelAttributes The attribute name in the JSON document which
     *        should be used as the label value for Aggregation.
     * @param dateAttribute The attribute name in the JSON document which should
     *        be used for the time element of the Aggregation. If NULL then the
     *        client receive time will be used.
     * @param dateFormat The format of the dateAttribute, if String based dates
     *        are used. This should follow {@link java.text.SimpleDateFormat}
     *        convention.
     * @param summaryAttributes List of attributes or expressions on attributes
     *        which should be used for summary aggregation.
     * @return A Stream Aggregator which can process JSON data containing the
     *         indicated attributes.
     * @throws Exception
     */
    public static final StreamAggregator newInstance(String streamName, String appName,
            KinesisClientLibConfiguration config, String namespace, List<TimeHorizon> timeHorizons,
            AggregatorType aggregatorType, List<String> labelAttributes, String dateAttribute,
            String dateFormat, List<String> summaryAttributes) throws Exception {
        IDataExtractor dataExtractor = new JsonDataExtractor(labelAttributes).withDateValueAttribute(
                dateAttribute).withSummaryAttributes(summaryAttributes).withDateFormat(dateFormat);
        dataExtractor.setAggregatorType(aggregatorType);
        return new StreamAggregator(streamName, appName, namespace, config, dataExtractor).withTimeHorizon(
                timeHorizons).withAggregatorType(aggregatorType);
    }
}


text:
<Alloy>
	<Tab title="Principal">
		<Window	id="win">
			<TextField id="fecha" editable="false"></TextField>
			<Button id="calendarIcon" backgroundImage="/blue-calendar-icon.png"></Button>

			<TextField id="hora" editable="false"></TextField>
			<Button id="clockIcon" backgroundImage="/blue-clock-icon.png"></Button>

			<Picker id="mensaje" type="Titanium.UI.PICKER_TYPE_PLAIN">
				<PickerRow title="Mensaje Uno"></PickerRow>
				<PickerRow title="Mensaje Dos"></PickerRow>
				<PickerRow title="Mensaje Tres"></PickerRow>
			</Picker>
			<Button id="mensajeIcon" backgroundImage="/blue-balloon-plus-icon.png"></Button>

			<Picker id="destino" type="Titanium.UI.PICKER_TYPE_PLAIN">
				<PickerRow title="Lista Uno"></PickerRow>
				<PickerRow title="Lista Dos"></PickerRow>
				<PickerRow title="Lista Tres"></PickerRow>
			</Picker>
			<Button id="destinoIcon" backgroundImage="/blue-user-icon.png"></Button>

			<TextField id="lugar" editable="true"></TextField>
			<Button id="lugarIcon" backgroundImage="/blue-home-icon.png"></Button>

			<Button id="enviar">Enviar</Button>
		</Window>
	</Tab>
</Alloy>


text:
/* Test for bogus diagnostics for dremf definition.  Although this
   definition is formally incorrect in ISO C, a GNU extension permits
   a prototype followed by unpromoted types in a function definition,
   so it should be permitted when the function is built in.  Bug
   16666.  */
/* { dg-do compile } */
/* { dg-options "" } */

float dremf (float, float);

float
dremf (x, y)
     float x, y;
{
  return x + y;
}


text:
package net.andreho.haxxor.cgen.instr.local.store;

import net.andreho.haxxor.cgen.HxCodeStream;
import net.andreho.haxxor.cgen.HxComputationContext;
import net.andreho.haxxor.cgen.HxFrame;
import net.andreho.haxxor.cgen.HxInstructionType;
import net.andreho.haxxor.cgen.HxInstructionTypes;
import net.andreho.haxxor.cgen.instr.abstr.LocalAccessInstruction;

/**
 *
Created by a.hofmann on 03.03.2016.

 */
public class LSTORE
  extends LocalAccessInstruction {

  public LSTORE(int var) {
    super(var);
  }

  @Override
  public HxInstructionType getInstructionType() {
    return HxInstructionTypes.Store.LSTORE;
  }

  @Override
  public void visit(HxCodeStream codeStream) {
    codeStream.LSTORE(getLocalIndex());
  }

  @Override
  public void compute(final HxComputationContext context, final HxFrame frame) {
    context.getExecutor().visit(context, this, frame);
  }

  @Override
  public LSTORE clone() {
    return clone(getLocalIndex());
  }

  @Override
  public LSTORE clone(final int var) {
    return new LSTORE(var);
  }
}


text:
using JetBrains.ReSharper.FeaturesTestFramework.Intentions;
using NUnit.Framework;
using ReSharper.ContractExtensions.ContextActions;

namespace ReSharper.ContractExtensions.Tests.Postconditions
{
        [TestFixture]
    public class EnsuresContextActionExecuteForIndexersTest : CSharpContextActionExecuteTestBase<EnsuresContextAction>
    {
        protected override string RelativeTestDataPath
        {
            get { return "Intentions/ContextActions/Ensures/IndexerFixes"; }
        }

        protected override string ExtraPath
        {
            get { return "Ensures\\IndexerFixes"; }
        }

        [TestCase("ExecuteOnGetter")]
        [TestCase("ExecuteOnIndexerDeclaration")]
        [TestCase("ExecuteOnReturn")]
        public void TestExecution(string testStr)
        {
            DoOneTest(testStr);
        }
    }

    [TestFixture]
    public class EnsuresContextActionExecuteTest : CSharpContextActionExecuteTestBase<EnsuresContextAction>
    {
        protected override string RelativeTestDataPath
        {
            get { return "Intentions/ContextActions/Ensures"; }
        }

        protected override string ExtraPath
        {
            get { return "Ensures"; }
        }

        [TestCase("Execution")]

        [TestCase("ExecutionWithAbstractClass")]
        [TestCase("ExecutionWithInterface")]

        [TestCase("ExecutionWithExistingUsing")]
        [TestCase("ExecutionWithGenerics")]
        [TestCase("ExecutionWithRequires")]
        public void TestExecution(string testSrc)
        {
            DoOneTest(testSrc);
        }
    }
}


text:
#ifndef OPENSIM_CONTACT_GEOMETRY_SET_H_
#define OPENSIM_CONTACT_GEOMETRY_SET_H_

#include "OpenSim/Simulation/Model/ModelComponentSet.h"
#include "ContactGeometry.h"

namespace OpenSim {
//=============================================================================
//=============================================================================
/**
 * A class for holding a set of ContactGeometry components.
 *
 * @authors Peter Eastman
 */
class OSIMSIMULATION_API ContactGeometrySet
:   public ModelComponentSet<ContactGeometry> {
OpenSim_DECLARE_CONCRETE_OBJECT(ContactGeometrySet,
                                ModelComponentSet<ContactGeometry>);

public:
    /** Use Super's constructors. @see ModelComponentSet */
    using Super::Super;

    // default copy, assignment operator, and destructor

//=============================================================================
};  // END of class ContactGeometrySet
//=============================================================================
//=============================================================================

} // end of namespace OpenSim

#endif // OPENSIM_CONTACT_GEOMETRY_SET_H_


text:
@implementation ANTestViewModel

@end


text:
var dataItems = [ 2, 4, 8, 16, 32, 64 ];
var NUM_ITEMS = dataItems.length;

function sendNextItem(items, index) {
  // Build message
  var key = 'AppKeyItem' + index;
  var dict = {};
  dict[key] = items[index];

  // Send the message
  Pebble.sendAppMessage(dict, function() {
    // Use success callback to increment index
    index++;

    if(index < NUM_ITEMS) {
      // Send next item
      sendNextItem(items, index);
    }
  }, function() {
    console.log('Item transmission failed: ' + index);
  });
}

function sendList(items) {
  var index = 0;
  sendNextItem(items, index);
}

Pebble.addEventListener('ready', function() {
  console.log('PebbleKit JS ready!');

  // Begin list transmission
  sendList(dataItems);
});

Pebble.addEventListener('appmessage', function(e) {
  var dict = e.payload;

  for(var index = 0; index < NUM_ITEMS; index++) {
    var key = 'AppKeyItem' + index;
    if(dict[key] !== undefined) {
      // This key was received
      console.log('C sent item: ' + dict[key]);
    }
  }
});


text:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using CIB.Exchange.Coinbase.DTO;
using CIB.Exchange.Model;
using Newtonsoft.Json;

namespace CIB.Exchange.Coinbase
{
    public class CoinbaseExchangeGateway : IExchangeGateway
    {
        private string PublicApiUrl = "https://api.gdax.com/";
        private string TickerApi = "/products/{0}/ticker";
        private string OrderBookApi = "/products/{0}/book?level=2";
        private string FullOrderBookApi = "/products/{0}/book?level=3";

        //private const int OrderBookDepth = 10;
        public string Name => "GDAX";

        public List<Quote> GetQuote(IEnumerable<CurrencyPair> tickers)
        {
            var result = new List<Quote>();
            foreach (var ticker in tickers)
            {
                result.Add(GetQuote(ticker));
            }
            return result;
        }

        private Quote GetQuote(CurrencyPair ticker)
        {
            var convertTicker = CoinbaseConverter.ConvertTicker(ticker);
            var api = string.Format(TickerApi, convertTicker);
            var json = QueryPublic(api).Result;
            var result = JsonConvert.DeserializeObject<CoinbaseQuote>(json);

            if (result.message == null)
                return ToDomain(ticker, result);

            throw new NotImplementedException();
        }

        private Quote ToDomain(CurrencyPair ticker, CoinbaseQuote result)
        {
            //var convertTicker = CoinbaseConverter.ConvertTicker(ticker);
            //var cexioQuote = result.SingleOrDefault(r => r.pair == convertTicker);
            return new Quote("GDAX", ticker, decimal.Parse(result.bid), decimal.Parse(result.ask), DateTime.Parse(result.time));
        }

        private async Task<string> QueryPublic(string requestUri)
        {
            var client = new HttpClient();
            client.BaseAddress = new Uri(PublicApiUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("User-Agent", ".NET Foundation Repository Reporter");
            var response = await client.GetAsync(requestUri);
            using (HttpContent content = response.Content)
            {
                return await content.ReadAsStringAsync();
            }
        }

        public OrderBook GetOrderBook(CurrencyPair ticker)
        {
            var convertTicker = CoinbaseConverter.ConvertTicker(ticker);
            var api = string.Format(OrderBookApi, convertTicker);

            var json = QueryPublic(api).Result;
            var result = JsonConvert.DeserializeObject<CoinbaseOrderBook1>(json);

            return new OrderBook(ticker, ConvertToDomain(result.asks, result.bids), DateTime.UtcNow);
            //if (string.IsNullOrEmpty(result.error))
            //{
            //}
            //throw new NotImplementedException();
        }

        public CoinbaseFullOrderBook GetFullOrderBook(CurrencyPair ticker)
        {
            var convertTicker = CoinbaseConverter.ConvertTicker(ticker);
            var api = string.Format(FullOrderBookApi, convertTicker);

            var json = QueryPublic(api).Result;
            return JsonConvert.DeserializeObject<CoinbaseFullOrderBook>(json);
        }

        private IEnumerable<OrderBookLevel> ConvertToDomain(List<List<decimal>> asks, List<List<decimal>> bids)
        {
            var depth = Math.Min(asks.Count, bids.Count);
            for (int i = 0; i < depth; i++)
            {
                var ask = asks[i];
                var bid = bids[i];
                yield return new OrderBookLevel(ask[0], ask[1], bid[0], bid[1]);
            }
        }

        public AccountBalance GetBalance()
        {
            throw new NotImplementedException();
        }

        public OrderStatus AddOrder(Order order)
        {
            throw new NotImplementedException();
        }

        public OrderStatus CancelOrder(Order order)
        {
            throw new NotImplementedException();
        }
    }

    //public class CoinbaseOrderBook
    //{
    //        public long sequence { get; set; }
    //        public List<List<decimal>> bids { get; set; }
    //        public List<List<decimal>> asks { get; set; }
    //}

    //internal class CoinbaseQuote
    //{
    //    public string message { get; set; }
    //    public int trade_id { get; set; }
    //    public string price { get; set; }
    //    public string size { get; set; }
    //    public string bid { get; set; }
    //    public string ask { get; set; }
    //    public string volume { get; set; }
    //    public string time { get; set; }

    //}

    //internal class CoinbaseConverter
    //{
    //    public static string ConvertTicker(CurrencyPair arg)
    //    {
    //        return arg.Base + "-" + arg.Quote;
    //    }
    //}
}


text:
/* jslint node: true */

'use strict';

var EventEmitter = require('events').EventEmitter,
    util = require('util'),
    Busboy = require('busboy');

function TransferManager(storage) {
    EventEmitter.call(this);

    this.storage = storage;
}

util.inherits(TransferManager, EventEmitter);

TransferManager.prototype.pipeFile = function pipeFile(id) {
    var sender, receiver, busboy;

    sender = this.storage.get(id, 'sender');
    receiver = this.storage.get(id, 'receiver');

    busboy = new Busboy({
        headers: sender.request.headers
    });

    busboy.on('file', function onFile(fieldname, file, filename) {
        filename = filename.toLowerCase();

        receiver.response.setHeader(
            'content-disposition',
            'attachment; filename="' + filename + '"'
        );

        file.pipe(receiver.response);
    });

    receiver.request.on('end', function onEnd() {
        sender.response.end();

        this.emit('pipeFileComplete', id);
    }.bind(this));

    sender.request.pipe(busboy);
};

module.exports = TransferManager;