text:
require 'test_helper'

describe Rack::Cache::MetaStore::Redis do
  before do
    @store        = ::Rack::Cache::MetaStore::Redis.resolve   uri('redis://127.0.0.1')
    @entity_store = ::Rack::Cache::EntityStore::Redis.resolve uri('redis://127.0.0.1:6380')
    @request  = mock_request('/', {})
    @response = mock_response(200, {}, ['hello world'])
  end

  after do
    @store.cache.flushall
    @entity_store.cache.flushall
  end

  it "respects the default_tll options" do
    @store = ::Rack::Cache::MetaStore::Redis.new({ :host => "localhost" }, { :default_ttl => 120 })
    @store.default_ttl.must_equal(120)

    @entity_store = ::Rack::Cache::EntityStore::Redis.new({ :host => "localhost" }, { :default_ttl => 120 })
    @entity_store.default_ttl.must_equal(120)
  end

  it "properly delegates the TTL to redis" do
    key = '/test/'
    @store = ::Rack::Cache::MetaStore::Redis.new({ :host => "localhost" }, { :default_ttl => 120 })

    @store.write(key, [[{},{}]])
    assert @store.cache.ttl(key) <= 120

    @entity_store = ::Rack::Cache::EntityStore::Redis.new({ :host => "localhost" }, { :default_ttl => 120 })
    key, size = @entity_store.write(['She rode to the devil,'])
    assert @entity_store.cache.ttl(key) <= 120
  end

  it "has the class referenced by homonym constant" do
    ::Rack::Cache::MetaStore::REDIS.must_equal(::Rack::Cache::MetaStore::Redis)
  end

  it "instantiates the store" do
    @store.must_be_kind_of(::Rack::Cache::MetaStore::Redis)
  end

  it "resolves the connection uri" do
    cache = Rack::Cache::MetaStore::Redis.resolve(uri("redis://127.0.0.1")).cache
    cache.must_be_kind_of(::Redis::Store)
    cache.to_s.must_equal("Redis Client connected to 127.0.0.1:6379 against DB 0")

    cache = Rack::Cache::MetaStore::Redis.resolve(uri("redis://127.0.0.1:6380")).cache
    cache.to_s.must_equal("Redis Client connected to 127.0.0.1:6380 against DB 0")

    cache = Rack::Cache::MetaStore::Redis.resolve(uri("redis://127.0.0.1/13")).cache
    cache.to_s.must_equal("Redis Client connected to 127.0.0.1:6379 against DB 13")

    # cache = Rack::Cache::MetaStore::Redis.resolve(uri("redis://:secret@127.0.0.1")).cache
    # cache.id.must_equal("redis://127.0.0.1:6379/0")
    # cache.client.password.must_equal('secret')

    cache = Rack::Cache::MetaStore::Redis.resolve(uri("redis://127.0.0.1:6380/0/metastore")).cache
    cache.to_s.must_equal("Redis Client connected to 127.0.0.1:6380 against DB 0 with namespace metastore")
  end

  # Low-level implementation methods ===========================================

  it 'writes a list of negotation tuples with #write' do
    # lambda {
      @store.write('/test', [[{}, {}]])
    # }.wont_raise Exception
  end

  it 'reads a list of negotation tuples with #read' do
    @store.write('/test', [[{},{}],[{},{}]])
    tuples = @store.read('/test')
    tuples.must_equal([ [{},{}], [{},{}] ])
  end

  it 'reads an empty list with #read when nothing cached at key' do
    @store.read('/nothing').must_be_empty
  end

  it 'removes entries for key with #purge' do
    @store.write('/test', [[{},{}]])
    @store.read('/test').wont_be_empty

    @store.purge('/test')
    @store.read('/test').must_be_empty
  end

  it 'succeeds when purging non-existing entries' do
    @store.read('/test').must_be_empty
    @store.purge('/test')
  end

  it 'returns nil from #purge' do
    @store.write('/test', [[{},{}]])
    @store.purge('/test').must_be_nil
    @store.read('/test').must_equal([])
  end

  %w[/test http://example.com:8080/ /test?x=y /test?x=y&p=q].each do |key|
    it "can read and write key: '#{key}'" do
      # lambda {
        @store.write(key, [[{},{}]])
      # }.wont_raise Exception
      @store.read(key).must_equal([[{},{}]])
    end
  end

  it "can read and write fairly large keys" do
    key = "b" * 4096
    # lambda {
      @store.write(key, [[{},{}]])
    # }.wont_raise Exception
    @store.read(key).must_equal([[{},{}]])
  end

  it "allows custom cache keys from block" do
    request = mock_request('/test', {})
    request.env['rack-cache.cache_key'] =
      lambda { |request| request.path_info.reverse }
    @store.cache_key(request).must_equal('tset/')
  end

  it "allows custom cache keys from class" do
    request = mock_request('/test', {})
    request.env['rack-cache.cache_key'] = Class.new do
      def self.call(request); request.path_info.reverse end
    end
    @store.cache_key(request).must_equal('tset/')
  end

  it 'does not blow up when given a non-marhsalable object with an ALL_CAPS key' do
    store_simple_entry('/bad', { 'SOME_THING' => Proc.new {} })
  end

  it 'takes a ttl parameter for #write' do
    @store.write('/foo', [[{},{}]], 123)
    data = @store.read('/foo')
    data.must_equal([[{},{}]])
  end

  # Abstract methods ===========================================================

  it 'stores a cache entry' do
    cache_key = store_simple_entry
    @store.read(cache_key).wont_be_empty
  end

  it 'sets the X-Content-Digest response header before storing' do
    cache_key = store_simple_entry
    req, res = @store.read(cache_key).first
    res['X-Content-Digest'].must_equal('a94a8fe5ccb19ba61c4c0873d391e987982fbbd3')
  end

  it 'finds a stored entry with #lookup' do
    store_simple_entry
    response = @store.lookup(@request, @entity_store)
    response.wont_be_nil
    response.must_be_kind_of(Rack::Cache::Response)
  end

  it 'does not find an entry with #lookup when none exists' do
    req = mock_request('/test', {'HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'})
    @store.lookup(req, @entity_store).must_be_nil
  end

  it "canonizes urls for cache keys" do
    store_simple_entry(path='/test?x=y&p=q')

    hits_req = mock_request(path, {})
    miss_req = mock_request('/test?p=x', {})

    @store.lookup(hits_req, @entity_store).wont_be_nil
    @store.lookup(miss_req, @entity_store).must_be_nil
  end

  it 'does not find an entry with #lookup when the body does not exist' do
    store_simple_entry
    @response.headers['X-Content-Digest'].wont_be_nil
    @entity_store.purge(@response.headers['X-Content-Digest'])
    @store.lookup(@request, @entity_store).must_be_nil
  end

  it 'restores response headers properly with #lookup' do
    store_simple_entry
    response = @store.lookup(@request, @entity_store)
    response.headers.
      must_equal(@response.headers.merge('Content-Length' => '4'))
  end

  it 'restores response body from entity store with #lookup' do
    store_simple_entry
    response = @store.lookup(@request, @entity_store)
    body = '' ; response.body.each {|p| body << p}
    body.must_equal('test')
  end

  it 'invalidates meta and entity store entries with #invalidate' do
    store_simple_entry
    @store.invalidate(@request, @entity_store)
    response = @store.lookup(@request, @entity_store)
    response.must_be_kind_of(Rack::Cache::Response)
    response.wont_be :fresh?
  end

  it 'succeeds quietly when #invalidate called with no matching entries' do
    req = mock_request('/test', {})
    @store.invalidate(req, @entity_store)
    @store.lookup(@request, @entity_store).must_be_nil
  end

  # Vary =======================================================================

  it 'does not return entries that Vary with #lookup' do
    req1 = mock_request('/test', {'HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'})
    req2 = mock_request('/test', {'HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam'})
    res = mock_response(200, {'Vary' => 'Foo Bar'}, ['test'])
    @store.store(req1, res, @entity_store)

    @store.lookup(req2, @entity_store).must_be_nil
  end

  it 'stores multiple responses for each Vary combination' do
    req1 = mock_request('/test', {'HTTP_FOO' => 'Foo',   'HTTP_BAR' => 'Bar'})
    res1 = mock_response(200, {'Vary' => 'Foo Bar'}, ['test 1'])
    key = @store.store(req1, res1, @entity_store)

    req2 = mock_request('/test', {'HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam'})
    res2 = mock_response(200, {'Vary' => 'Foo Bar'}, ['test 2'])
    @store.store(req2, res2, @entity_store)

    req3 = mock_request('/test', {'HTTP_FOO' => 'Baz',   'HTTP_BAR' => 'Boom'})
    res3 = mock_response(200, {'Vary' => 'Foo Bar'}, ['test 3'])
    @store.store(req3, res3, @entity_store)

    slurp(@store.lookup(req3, @entity_store).body).must_equal('test 3')
    slurp(@store.lookup(req1, @entity_store).body).must_equal('test 1')
    slurp(@store.lookup(req2, @entity_store).body).must_equal('test 2')

    @store.read(key).length.must_equal(3)
  end

  it 'overwrites non-varying responses with #store' do
    req1 = mock_request('/test', {'HTTP_FOO' => 'Foo',   'HTTP_BAR' => 'Bar'})
    res1 = mock_response(200, {'Vary' => 'Foo Bar'}, ['test 1'])
    key = @store.store(req1, res1, @entity_store)
    slurp(@store.lookup(req1, @entity_store).body).must_equal('test 1')

    req2 = mock_request('/test', {'HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam'})
    res2 = mock_response(200, {'Vary' => 'Foo Bar'}, ['test 2'])
    @store.store(req2, res2, @entity_store)
    slurp(@store.lookup(req2, @entity_store).body).must_equal('test 2')

    req3 = mock_request('/test', {'HTTP_FOO' => 'Foo',   'HTTP_BAR' => 'Bar'})
    res3 = mock_response(200, {'Vary' => 'Foo Bar'}, ['test 3'])
    @store.store(req3, res3, @entity_store)
    slurp(@store.lookup(req1, @entity_store).body).must_equal('test 3')

    @store.read(key).length.must_equal(2)
  end

  private
    define_method :mock_request do |uri, opts|
      env = Rack::MockRequest.env_for(uri, opts || {})
      Rack::Cache::Request.new(env)
    end

    define_method :mock_response do |status, headers, body|
      headers ||= {}
      body = Array(body).compact
      Rack::Cache::Response.new(status, headers, body)
    end

    define_method :slurp do |body|
      buf = ''
      body.each { |part| buf << part }
      buf
    end

    # Stores an entry for the given request args, returns a url encoded cache key
    # for the request.
    define_method :store_simple_entry do |*request_args|
      path, headers = request_args
      @request = mock_request(path || '/test', headers || {})
      @response = mock_response(200, {'Cache-Control' => 'max-age=420'}, ['test'])
      body = @response.body
      cache_key = @store.store(@request, @response, @entity_store)
      @response.body.must_equal(body)
      cache_key
    end

    define_method :uri do |uri|
      URI.parse uri
    end
end


text:
/*------------------------------------------------------
 Company:           Valentys Ltda.
 Author:            David Gaete <dmunozgaete@gmail.com> (https://github.com/dmunozgaete)

 Description:       Web Is Mobile, the authentication work better in manual
                    flow authentication for Facebook
 Github:            https://github.com/dmunozgaete/angular-gale

 Versión:           1.0.0-rc.1
 Build Date:        2016-01-22 3:20:29
------------------------------------------------------*/

angular.module('app.components')
    .controller("FacebookRedirectController", function($scope, $Identity, $Api, Facebook, $window, $location)
    {

        var redirect = function(local_url)
        {
            var redirect_uri = "{0}://{1}{2}/#{3}".format([
                $location.protocol(),
                $location.host(),
                ($location.port() ? ":" + $location.port() : ""),
                local_url
            ]);

            $window.location.href = redirect_uri;

        };

        var parameters = $location.search();

        if (parameters.access_token)
        {
            var accessToken = parameters.access_token;

            Facebook.api("me/?fields=id,email,name,picture.type(large),location",
                {
                    access_token: accessToken
                },
                function(data)
                {
                    //GO TO API, CHECK THE TOKEN ,
                    // AND IF IS CORRECT , CREATE OR GET THE USER
                    data.accessToken = accessToken;
                    data.image = data.picture.data.url;
                    delete data.picture; //Remove this =)

                    $Api.create("/Security/Oauth/Facebook", data)
                        .success(function(oauthToken)
                        {
                            //Authenticated
                            $Identity.logIn(oauthToken);

                            redirect(parameters.url);

                        });
                });
        }
        else
        {

            //http://widulapp.azurewebsites.net/?oauth-flow=facebook&error=access_denied&error_code=200&error_description=Permissions+error&error_reason=user_denied&state=%2Fpublic%2Fevents%2Fview%2Fresume%2Findex%2F81645f35-8dbd-49fd-9383-6d7a5ab66a3b#_=_
            //TODO: DENIED ACCESS
            //SHOW ERROR
            redirect(parameters.state);
        }
    })

.run(function($location)
{
    //CHECK IF THE FACEBOOK FLOW , HAS RETURNING URL =)!
    var path = $location.absUrl();
    if (path.indexOf("oauth-flow=facebook") >= 0)
    {
        //Prepare the path for parse
        var match_uri = "=facebook#/state=";
        var returningUrl = path.substring(path.indexOf(match_uri) + match_uri.length);
        $location.url("/public/fbauth?url=" + returningUrl);
    }

})

.config(function($stateProvider, $locationProvider)
{

    $stateProvider
        .state("public.fbauth",
        {
            url: '/fbauth',
            views:
            {
                "content":
                {
                    templateUrl: 'bundles/app/components/security/external-authenticators/oauth-flows/facebook-redirect.html',
                    controller: 'FacebookRedirectController'
                }
            }
        });

})

redpajama_set_name: RedPajamaGithub


text:
package io.vertx.spi.cluster.hazelcast.impl;

import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.DataSerializable;
import io.vertx.core.spi.cluster.RegistrationInfo;

import java.io.IOException;
import java.util.Objects;

/**
 * @author Thomas Segismont
 */
public class HazelcastRegistrationInfo implements DataSerializable {

  private RegistrationInfo registrationInfo;

  public HazelcastRegistrationInfo() {
  }

  public HazelcastRegistrationInfo(RegistrationInfo registrationInfo) {
    this.registrationInfo = Objects.requireNonNull(registrationInfo);
  }

  public RegistrationInfo unwrap() {
    return registrationInfo;
  }

  @Override
  public void writeData(ObjectDataOutput dataOutput) throws IOException {
    dataOutput.writeUTF(registrationInfo.nodeId());
    dataOutput.writeLong(registrationInfo.seq());
    dataOutput.writeBoolean(registrationInfo.localOnly());
  }

  @Override
  public void readData(ObjectDataInput dataInput) throws IOException {
    registrationInfo = new RegistrationInfo(dataInput.readUTF(), dataInput.readLong(), dataInput.readBoolean());
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    HazelcastRegistrationInfo that = (HazelcastRegistrationInfo) o;

    return registrationInfo.equals(that.registrationInfo);
  }

  @Override
  public int hashCode() {
    return registrationInfo.hashCode();
  }

  @Override
  public String toString() {
    return registrationInfo.toString();
  }
}


text:
/* globals $, _ */
var Plumage = require('PlumageRoot');
var TypeAhead = require('view/form/fields/TypeAhead');
var FilterFieldMixin = require('view/form/fields/FilterFieldMixin');

module.exports = Plumage.view.form.fields.FilterTypeAhead = TypeAhead.extend(_.extend(FilterFieldMixin,
/** @lends Plumage.view.form.fields.FilterTypeAhead.prototype */
{
  updateModelOnChange: true,

  comparison: 'equals'
}));


text:
<!DOCTYPE html>

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

    <title>Paulo Negrao - Personal Website</title>

    <link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon">

    <link rel="stylesheet" href="css/tabafont.css">

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

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

    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"
        integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet"
        type="text/css">
    <link rel="stylesheet" href="https://cdn.rawgit.com/konpa/devicon/master/devicon.min.css">

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

                        Skills

                        Credentials

                        About

                        Contact

                        Business Systems Analyst  &

                        Full Stack Developer

Skills

Credentials

About

I am an IT-oriented professional capable to deal with different technologies and roles. From
                        mainframes, client-server & web-based systems, to act in programming, analysis and management
                        activities. I have a consistent curriculum of academic and technical training/certifications
                        from the industry's main players.

In Canada, I've got a Master of Science in Computer Science from Northeastern University. I also tooked the BCIT's Applied Web and Applied Software Development
                        programs. and the CodeCore College's Developer Bootcamp. During these
                        programs, I
                        was able to consolidate my skills inside the Full-Stack Application Development field,
                        enhancing
                        my abilities in subjects like Java, Node, Javascript, React.js, React Native, Angular, Cordova, Android, PHP,
                        Ruby on Rails, JQuery, AJAX, JSON, HTML5 & CSS, OOP, RESTful APIs, AR, VR, IoT, Relational and Non-Relational databases, and etc.

I consider myself (maybe, I should say: I had better be) a continuous learner, always
                        committed
                        to improve and extend my experience and skills in different fields of knowledge, passionate
                        about applying the improvements in technology to day-to-day life, and to automate and optimize
                        business processes.

paulo.negrao@ymail.com

Contact Me

+1-778-681-7081

                        © pN's Website 2020


text:
import * as R from '../ramda/dist/index';

declare const number_object_record: { [number: number]: object };

// @dts-jest:pass:snap -> R.Dictionary<string>
R.invertObj(number_object_record);


text:
sprite sheet based animation library for SFML 2

## Building From Source

First make sure that you have [CMake](http://www.cmake.org/) and an C++ compiler environment installed.

Then open a terminal, go to the source directory and type the following commands:

    $ mkdir build
    $ cd build
    $ cmake ..
    $ make

## Running unit tests - NO YET IMPLEMENTED

After building this project you may run its unit tests by using these commands:

    $ make test  # To run all tests via CTest
    $ make catch # Run all tests directly, showing more details to you

## License

3 Clause BSD, see LICENSE file for details


text:
package com.nortal.petit.converter.provider;

import java.util.Map;

public interface Container<K, V> extends Provider<K, V> {
	void put(K key, V value);

	void putAll(Map<K, V> values);
}


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

namespace Kazyx.Uwpmm.UPnP.ContentDirectory
{
    public class SearchCapabilities : ContentDirectoryResponse
    {
        public bool AnyPropertiesSupported { get; private set; }

        public IList<string> SupportedProperties { get; private set; }

        public static SearchCapabilities Parse(XDocument xml)
        {
            var body = GetBodyOrThrowError(xml);
            var res = body.Element(NS_U + "GetSearchCapabilitiesResponse");
            var caps = (string)res.Element("SearchCaps");

            var supported = new List<string>();
            var any = false;
            if (caps != null)
            {
                if (caps == "*")
                {
                    any = true;
                }
                else
                {
                    var sepa = caps.Split(',');
                    foreach (var capa in sepa)
                    {
                        var val = capa.Trim();
                        if (val.Length != 0)
                        {
                            supported.Add(val);
                        }
                    }
                }
            }

            return new SearchCapabilities
            {
                AnyPropertiesSupported = any,
                SupportedProperties = supported,
            };
        }

    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Storage;
using Windows.Phone.UI.Input;

namespace ESAIP_Quiz
{
    public sealed partial class Quiz_Play : Page
    {
        public Quiz_Play()
        {
          // Initialisation des fonctionnalités de la page
            this.InitializeComponent();
            this.NavigationCacheMode = NavigationCacheMode.Required;
            HardwareButtons.BackPressed += HardwareButtons_BackPressed;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
          // Lorsque l'on clique sur le bouton...
            SubmitData();
        }

        private async void SubmitData()
        {
            // Récupération du dossier local
            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
            if (local != null)
            {
                // Récupération du dossier DataFolder
                var dataFolder = await local.GetFolderAsync("DataFolder");

                try
                {
                    // Récupération du fichier json
                    var src = await local.OpenStreamForReadAsync("Participation.json");
                    // Lecture des données
                    using (StreamReader json = new StreamReader(src))
                    {
                        String putData = json.ReadToEnd();

                        // HTTP web request
                        WebRequest request = WebRequest.Create("http://coreosjpg.cloudapp.net/quiz/1234/participation/1234567");
                        request.Method = "PUT";
                        request.ContentType = "text/json";

                        // Traitement de la requête
                        using (var stream = await request.GetRequestStreamAsync())
                        {
                            // Conversion du fichier json
                            var datas = Encoding.UTF8.GetBytes(putData);
                            // Ecriture
                            await stream.WriteAsync(datas, 0, datas.Length);
                        }
                    }
                }
                catch (Exception e)
                {
                    return;
                }
            }
        }

        private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
        {
          // Lorsque l'on appuye sur le bouton système "retour"
            e.Handled = true;
            if (Frame.CanGoBack)
                Frame.GoBack();
        }
    }
}


text:
On this page you will learn from code samples for programming in ASP Classic.Writing of the code to read barcode from image with barcode reader sdk in ASP Classic can be executed by programmers of any level using ByteScout Premium Suite. Want to read barcode from image with barcode reader sdk in your ASP Classic app? ByteScout Premium Suite is designed for it. ByteScout Premium Suite is the bundle that includes twelve SDK products from ByteScout including tools and components for PDF, barcodes, spreadsheets, screen video recording.

The following code snippet for ByteScout Premium Suite works best when you need to quickly read barcode from image with barcode reader sdk in your ASP Classic application. Follow the instructions from scratch to work and copy the ASP Classic code. Want to see how it works with your data then code testing will allow the function to be tested and work properly.

Trial version of ByteScout Premium Suite is available for free. Source code samples are included to help you with your ASP Classic app.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Premium%20Suite%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Premium%20Suite%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### ****TestBarcodeReading.asp:**

```
<%

' In case of "Server.CreateObject Failed", "Server object error "ASP 0177 : 8000ffff" or similar errors:
' Please try the following:
' - Open IIS
' - Find application pools (DefaultAppPool is used by default)
' - Open its properties and check .NET CLR version selected:
' - if you have  .NET 1.1 then change to .NET CLR 2.00
' - if you have .NET CLR 2.00 then try to change to .NET CLR 4.0

Set bc = Server.CreateObject("Bytescout.BarCodeReader.Reader")

' Limit search to 1D barcodes only (exclude 2D barcodes to speed up the search).
' Change to bc.BarcodeTypesToFind.SetAll() to scan for all supported 1D and 2D barcodes
' or select specific type, e.g. bc.BarcodeTypesToFind.PDF417 = True
bc.BarcodeTypesToFind.SetAll1D()

bc.ReadFromFile Server.MapPath("BarcodePhoto.jpg")

For i = 0 To bc.FoundCount - 1
     Response.Write "Found barcode on page #" & CStr(bc.GetFoundBarcodePage(i)) & " with type " & Cstr(bc.GetFoundBarcodeType(i)) & " and value " & bc.GetFoundBarcodeValue(i)

Next

Set bc = Nothing

%>

```

<!-- code block end -->


text:
<?php

namespace Google\AdsApi\AdWords\v201809\cm;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class AdGroupFeedErrorReason
{
    const FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE = 'FEED_ALREADY_EXISTS_FOR_PLACEHOLDER_TYPE';
    const INVALID_ID = 'INVALID_ID';
    const CANNOT_ADD_FOR_DELETED_FEED = 'CANNOT_ADD_FOR_DELETED_FEED';
    const CANNOT_ADD_ALREADY_EXISTING_ADGROUP_FEED = 'CANNOT_ADD_ALREADY_EXISTING_ADGROUP_FEED';
    const CANNOT_OPERATE_ON_REMOVED_ADGROUP_FEED = 'CANNOT_OPERATE_ON_REMOVED_ADGROUP_FEED';
    const INVALID_PLACEHOLDER_TYPES = 'INVALID_PLACEHOLDER_TYPES';
    const MISSING_FEEDMAPPING_FOR_PLACEHOLDER_TYPE = 'MISSING_FEEDMAPPING_FOR_PLACEHOLDER_TYPE';
    const NO_EXISTING_LOCATION_CUSTOMER_FEED = 'NO_EXISTING_LOCATION_CUSTOMER_FEED';
    const UNKNOWN = 'UNKNOWN';

}


text:
import { ArchitectCommand, ArchitectCommandOptions } from '../models/architect-command';
import { Arguments } from '../models/interface';
import { Schema as RunCommandSchema } from './run';

export class RunCommand extends ArchitectCommand<RunCommandSchema> {
  public async run(options: ArchitectCommandOptions & Arguments) {
    if (options.target) {
      return this.runArchitectTarget(options);
    } else {
      throw new Error('Invalid architect target.');
    }
  }
}


text:
// This file is automatically generated.

package adila.db;

/*
 * Oppo N1 mimi
 *
 * DEVICE: N1mini
 * MODEL: N5116
 */
final class n1mini_n5116 {
    public static final String DATA = "Oppo|N1 mimi|";
}


text:
Closure example,

```js
'use strict';

function getBind(context, name) {
    return function () {
        return context[name].apply(context, arguments);
    };
}

var button = {
    clicked: false,
    click: function () {
        this.clicked = true;
        console.log('console.log button.clicked : ', button.clicked);
        console.log('print this : ', this);
    }
};

function test(item, fn) {
    return function () {
        return fn(item);
    };
}

console.log(test('nalinda', getBind(button, 'click'))());
```
- Closures have access to the outer function's variable even after the outer function returns

```js
'use strict';

function greet() {
    var greeting = 'My Name is : ';

    function getGreet(params) {
        return greeting + params.firstName + ' ' + params.lastName;
    }

    return getGreet;
}

var nalinda = greet()({
        firstName: 'Nalinda',
        lastName: 'Karunaratna'
});

console.log(nalinda); // My Name is : Nalinda Karunaratna
```

- Closures store references to the outer function's variables

```js
function myID() {
    var myNewID = 899;

    return {
        getID: function () {
            return myNewID;
        },

        setID: function (newID) {
            myNewID = newID;
        }
    };
}

var thisID = myID();
console.log(thisID.getID()); // 899
console.log(thisID.setID(10000));
console.log(thisID.getID()); // 10000
```


text:
.. _examples_accept:

examples/accept.cpp
#####################

Accept connections from Bitcoin nodes on port 8333.

::

    #include <bitcoin/bitcoin.hpp>
    using namespace bc;

    using std::placeholders::_1;
    using std::placeholders::_2;

    // Listening has started.
    // Wait to accept a connection.
    void listening_started(const std::error_code& ec, acceptor_ptr accept);
    // Connection to another Bitcoin node has been established.
    // Wait for version message.
    void accepted_connection(const std::error_code& ec, channel_ptr node,
        acceptor_ptr accept);
    // Version message received.
    // Display the user agent.
    void version_received(const std::error_code& ec, const version_type& version,
        channel_ptr node);
    void node_stopped(const std::error_code& ec);

    void listening_started(const std::error_code& ec, acceptor_ptr accept)
    {
        if (ec)
        {
            log_error() << "Listen: " << ec.message();
            return;
        }
        // Accept first connection.
        accept->accept(
            std::bind(accepted_connection, _1, _2, accept));
    }

    void accepted_connection(const std::error_code& ec, channel_ptr node,
        acceptor_ptr accept)
    {
        if (ec)
        {
            log_error() << "Accept: " << ec.message();
            return;
        }
        log_info() << "Accepted connection!";
        node->subscribe_stop(node_stopped);
        // Now we need to keep it alive otherwise the connection is closed.
        node->subscribe_version(
            std::bind(version_received, _1, _2, node));
        // Keep accepting more connections.
        accept->accept(
            std::bind(accepted_connection, _1, _2, accept));
    }

    void version_received(const std::error_code& ec, const version_type& version,
        channel_ptr node)
    {
        // error::service_stopped means the connection was closed.
        if (ec == error::service_stopped)
            return;
        else if (ec)
        {
            log_error() << "Version message: " << ec.message();
            return;
        }
        log_info() << "User agent: " << version.user_agent;
    }

    void node_stopped(const std::error_code& ec)
    {
        if (ec == error::service_stopped)
            log_info() << "Connection closed.";
        else if (ec)
            log_error() << "Connection closed: " << ec.message();
    }

    int main()
    {
        threadpool pool(4);
        network net(pool);
        net.listen(8333, listening_started);
        std::cin.get();
        pool.stop();
        pool.join();
        return 0;
    }


text:
using Microsoft.AspNetCore.Routing.Patterns;

namespace Microsoft.AspNetCore.Routing.Template;

/// <summary>
/// A factory used to create <see cref="TemplateBinder"/> instances.
/// </summary>
public abstract class TemplateBinderFactory
{
    /// <summary>
    /// Creates a new <see cref="TemplateBinder"/> from the provided <paramref name="template"/> and
    /// <paramref name="defaults"/>.
    /// </summary>
    /// <param name="template">The route template.</param>
    /// <param name="defaults">A collection of extra default values that do not appear in the route template.</param>
    /// <returns>A <see cref="TemplateBinder"/>.</returns>
    public abstract TemplateBinder Create(RouteTemplate template, RouteValueDictionary defaults);

    /// <summary>
    /// Creates a new <see cref="TemplateBinder"/> from the provided <paramref name="pattern"/>.
    /// </summary>
    /// <param name="pattern">The <see cref="RoutePattern"/>.</param>
    /// <returns>A <see cref="TemplateBinder"/>.</returns>
    public abstract TemplateBinder Create(RoutePattern pattern);
}


text:
var App = require('app');

var modelSetup = require('test/init_model_test');
require('models/service/hdfs');

var hdfsService,
  hdfsServiceData = {
    id: 'hdfs'
  },
  hostComponentsData = [
    {
      id: 'journalnode',
      componentName: 'JOURNALNODE'
    }
  ],
  cases = [
    {
      propertyName: 'journalNodes',
      componentId: 'journalnode'
    }
  ];

describe('App.HDFSService', function () {

  beforeEach(function () {
    hdfsService = App.HDFSService.createRecord(hdfsServiceData);
  });

  afterEach(function () {
    modelSetup.deleteRecord(hdfsService);
  });

  cases.forEach(function (item) {
    var propertyName = item.propertyName;
    describe('#' + propertyName, function () {
      it('should take one component from hostComponents', function () {
        hdfsService.reopen({
          hostComponents: hostComponentsData
        });
        expect(hdfsService.get(propertyName)).to.have.length(1);
        expect(hdfsService.get(propertyName)[0].id).to.equal(item.componentId);
      });
    });
  });

});


text:
package com.palmithor.musicapi.rest.artist;

import com.palmithor.musicapi.dto.ArtistDto;
import com.palmithor.musicapi.rest.ResponseHandler;
import org.springframework.stereotype.Component;

/**
 * Response handler for ArtistDTO responses
 *
 * @author palmithor
 * @since 25.1.2017.
 */
@Component
public class ArtistResponseHandler extends ResponseHandler<ArtistDto> {

    public ArtistResponseHandler() {
        super(ArtistDto.class);
    }
}


text:
import { buildClientApp } from "reaction/Artsy/Router/client"
import { data as sd } from "sharify"
import { routes as viewingRoomRoutes } from "reaction/Apps/ViewingRoom/routes"
import React from "react"
import ReactDOM from "react-dom"
import { loadableReady } from "@loadable/component"

const mediator = require("desktop/lib/mediator.coffee")

buildClientApp({
  routes: viewingRoomRoutes,
  context: {
    user: sd.CURRENT_USER,
    mediator,
  },
})
  .then(({ ClientApp }) => {
    loadableReady(() => {
      ReactDOM.hydrate(<ClientApp />, document.getElementById("react-root"))
    })
  })
  .catch(error => {
    console.error(error)
  })

if (module.hot) {
  module.hot.accept()
}


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

namespace Quantler.Tests.Bootstrap.MessagingEvents
{
    class NetMQRunnerTests
    {
    }
}


text:
from config import Config
from inspect import currentframe, getframeinfo
from netaddr import IPNetwork

class HostGroup(object):

    @property
    def name(self):
        return self._name

    @property
    def has_inline_groups(self):
        return len(self._inline_hostgroups)

    @property
    def inline_groups(self):
        return self._inline_hostgroups

    @name.setter
    def name(self, value):
        self._name = value

    @property
    def hosts(self):
        return self._prefixes

    def __init__(self, groupname):
        self.config = Config()
        self._prefixes = list()
        self._inline_hostgroups = list()
        self._name = groupname

    def __eq__(self, other):
        if self.name == other.name:
            return True

    def __repr__(self):
        return self.name

    def print_stats(self):
        print('\tHostgroup {} contains {} prefixes'.format(self.name, len(self._prefixes)))

    def parse_file(self, rec_name=None):
        try:
            if rec_name:
                f = open('{}/{}.hosts'.format(self.config.objects, rec_name))
            else:
                f = open('{}/{}.hosts'.format(self.config.objects, self.name))
            lines = f.readlines()

            for line in lines:
                if line.startswith('#'):
                    continue
                if line.startswith('@'):
                    rec_group = line.split(' ')[0][1:].strip()
                    inline_hg = HostGroup(rec_group)
                    inline_hg.parse_file()
                    self._inline_hostgroups.append(inline_hg)
                    prefix = line.split('#')[0].strip()
                    self._prefixes.append(prefix)
                    continue
                if line.strip():
                    prefix = line.split('#')[0].strip()
                    self._prefixes.append(prefix)
        except Exception, e:
            frameinfo = getframeinfo(currentframe())
            print frameinfo.filename, frameinfo.lineno, e
            raise e

    def render_junos(self):
        if not len(self._prefixes):
            raise Exception("Object can not be empty: {}".format(self.name))

        config = 'delete policy-options prefix-list {}'.format(self.name)
        for prefix in self._prefixes:
            if prefix.startswith('@'):
                for ihg in self._inline_hostgroups:
                    if ihg.name == prefix[1:]:
                        config = '{}\ndelete groups {}'.format(config, ihg.name)
                        for iprefix in ihg.hosts:
                            config = '{}\nset groups {} policy-options prefix-list {} {}'.format(config,
                                                                                ihg.name,
                                                                                ihg.name,
                                                                                iprefix)
                config = '{}\nset policy-options prefix-list {} apply-groups {}'.format(config, self.name, prefix[1:])
            else:
                config = '{}\nset policy-options prefix-list {} {}'.format(config, self.name, prefix)
        return config

    def render_ios(self, subgroup=False):
        config = ''
        if not subgroup:
            config = 'no object-group ip address {}\n'.format(self.name)
            config += 'object-group ip address {}'.format(self.name)
        for prefix in self._prefixes:
            if prefix.startswith('@'):
                ihg = [g for g in self._inline_hostgroups if g.name == prefix[1:]][0]
                config += ihg.render_ios(True)
            else:
                ipn = IPNetwork(prefix)
                if ipn.prefixlen == 32:
                    config = '{}\nhost {}'.format(config, ipn.ip)
                else:
                    config = '{}\n{} {}'.format(config, ipn.ip, ipn.netmask)
        if not subgroup:
            config += '\nexit'
        return config

class PortGroup(object):

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

    @property
    def ports(self):
        return self._ports

    def __init__(self, groupname):
        self.config = Config()
        self._ports = list()
        self._name = groupname

    def __eq__(self, other):
        return self.name == other.name

    def __repr__(self):
        return self.name

    def parse_file(self, rec_name=None):
        try:
            if rec_name:
                f = open('{}/{}.ports'.format(self.config.objects, rec_name))
            else:
                f = open('{}/{}.ports'.format(self.config.objects, self.name))

            lines = f.readlines()

            for line in lines:
                if line.startswith('#'):
                    continue
                if line.startswith('@'):
                    rec_group = line.split(' ')[0][1:].strip()
                    self.parse_file(rec_group)
                    continue
                if line.strip():
                    port = line.split('#')[0].strip()
                    if port.startswith('-'):
                        port = '0-{}'.format(port)
                    if port.endswith('-'):
                        port = '{}65535'.format(port)
                    self._ports.append(port)
        except Exception, e:
            frameinfo = getframeinfo(currentframe())
            print frameinfo.filename, frameinfo.lineno, e
            raise e

    def render_ios(self):
        config = 'no object-group ip port {}\n'.format(self.name)
        config += 'object-group ip port {}\n'.format(self.name)
        for port in self.ports:
            if '-' in port:
                split = port.split('-')
                config += 'range {} {}\n'.format(split[0], split[1])
            else:
                config += 'eq {}\n'.format(port)
        config += 'exit'
        return config

if __name__ == '__main__':
    hg = HostGroup('qa')
    hg.parse_file()
    print hg.hosts
    print hg.render_junos()
    pg = PortGroup('web_services')
    pg.parse_file()
    print pg.ports


text:
package http

import (
	"crypto/tls"
	"crypto/x509"
	"encoding/pem"
	"github.com/crvv/todns/config"
	"io/ioutil"
	"log"
	"net"
)

func newTlsListener() net.Listener {
	certificate, err := tls.LoadX509KeyPair(config.GetCrt(), config.GetKey())
	if err != nil {
		log.Fatalln(err)
	}
	clientCrt, err := ioutil.ReadFile(config.GetClientCrt())
	if err != nil {
		log.Fatalln(err)
	}
	block, _ := pem.Decode(clientCrt)
	cert, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		log.Fatalln(err)
	}
	clientCAs := x509.NewCertPool()
	clientCAs.AddCert(cert)

	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{certificate},
		NextProtos:   []string{"http"},
		ClientAuth:   tls.RequireAndVerifyClientCert,
		ClientCAs:    clientCAs,
	}
	listener, err := tls.Listen("tcp", config.GetHttpsListen(), tlsConfig)
	if err != nil {
		log.Fatalln(err)
	}
	return listener
}


text:
package com.networknt.db;

/**
 * Microsoft SQL Server database data source.
 *
 * @author Steve Hu
 */
public class SqlServerDataSource extends GenericDataSource {
    private static final String SQLSERVER_DS = "SqlServerDataSource";

    @Override
    public String getDsName() {
        if(dsName != null) {
            return dsName;
        } else {
            return SQLSERVER_DS;
        }
    }

    public SqlServerDataSource(String dsName) {
        super(dsName);
    }

    public SqlServerDataSource() {
        super();
    }

}


text:
package im.actor.core.modules.internal.messages;

import im.actor.core.api.ApiOutPeer;
import im.actor.core.api.rpc.RequestMessageReceived;
import im.actor.core.api.rpc.ResponseVoid;
import im.actor.core.entity.Peer;
import im.actor.core.modules.ModuleContext;
import im.actor.core.network.RpcCallback;
import im.actor.core.network.RpcException;

public class CursorReceiverActor extends CursorActor {

    public CursorReceiverActor(ModuleContext context) {
        super(CURSOR_RECEIVED, context);
    }

    @Override
    protected void perform(final Peer peer, final long date) {
        ApiOutPeer outPeer = buidOutPeer(peer);

        if (outPeer == null) {
            return;
        }

        request(new RequestMessageReceived(outPeer, date), new RpcCallback<ResponseVoid>() {
            @Override
            public void onResult(ResponseVoid response) {
                onCompleted(peer, date);
            }

            @Override
            public void onError(RpcException e) {
                CursorReceiverActor.this.onError(peer, date);
            }
        });
    }

    @Override
    public void onReceive(Object message) {
        if (message instanceof MarkReceived) {
            MarkReceived received = (MarkReceived) message;
            moveCursor(received.getPeer(), received.getDate());
        } else {
            super.onReceive(message);
        }
    }

    public static class MarkReceived {
        private Peer peer;
        private long date;

        public MarkReceived(Peer peer, long date) {
            this.peer = peer;
            this.date = date;
        }

        public Peer getPeer() {
            return peer;
        }

        public long getDate() {
            return date;
        }
    }
}


text:
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    def handle(self, *args, **options):
        from dumbwaiter.app import Dumbwaiter
        d = Dumbwaiter()
        d.run()


text:
Document type (sub-documents): Subdocument length too short: leaks terminator
--DESCRIPTION--
Generated by scripts/convert-bson-corpus-tests.php

DO NOT EDIT THIS FILE
--FILE--
<?php

require_once __DIR__ . '/../utils/basic.inc';

$bson = hex2bin('1500000003666F6F000A0000000862617200010000');

throws(function() use ($bson) {
    var_dump(toPHP($bson));
}, 'MongoDB\Driver\Exception\UnexpectedValueException');

?>
===DONE===
<?php exit(0); ?>
--EXPECT--
OK: Got MongoDB\Driver\Exception\UnexpectedValueException
===DONE===


text:
const app = require('express')();
const server = require('http').Server(app);
const url = require('url');
const fixieUrl = url.parse(process.env.QUOTAGUARDSTATIC_URL);

const requestUrl = url.parse('https://linebot-nodejs.herokuapp.com/');

app.set('port', process.env.PORT || 8080);
app.get('/', function (req, res) {
    res.send('hello');
});
var LINEBot = require('line-messaging');
var bot = LINEBot.create({
    channelID: process.env.channelID,
    channelSecret: process.env.channelSecret,
    channelToken: process.env.channelToken
}, server);
app.use(bot.webhook('/webhook'));
bot.on(LINEBot.Events.MESSAGE, function (replyToken, message) {
    console.log('replyToken', replyToken);
    if (message.isMessageType('text')) {
        if (message.getText() === 'day') {
            var text = new LINEBot.TextMessageBuilder('I\'m a super man!');
            var sticker = new LINEBot.StickerMessageBuilder(1, 109);
            bot.replyMultiMessage(replyToken, [text, sticker]).then(function (data) {
                console.log('res1', data);
            }).catch(function (error) {
                console.log('error1', error);
            });
            console.log('res1', message.getText());
        } else {
            var text1 = new LINEBot.TextMessageBuilder('Hi');
            var sticker1 = new LINEBot.StickerMessageBuilder(1, 109);
            bot.replyMultiMessage(replyToken, [text1, sticker1]).then(function (data) {
                console.log('res2', data);
            }).catch(function (error) {
                console.log('error2', error);
            });
            console.log('res2', message.getText());
        }
    } else {
        console.log('message.getText()', message.getText());
    }
});

server.listen(app.set('port'));

// var http, options, proxy, url;

// http = require("http");

// url = require("url");

// proxy = url.parse(process.env.QUOTAGUARDSTATIC_URL);
// target  = url.parse("http://ip.jsontest.com/");

// options = {
//   hostname: proxy.hostname,
//   port: proxy.port || 80,
//   path: target.href,
//   headers: {
//     "Proxy-Authorization": "Basic " + (new Buffer(proxy.auth).toString("base64")),
//     "Host" : target.hostname
//   }
// };

// http.get(options, function(res) {
//   res.pipe(process.stdout);
//   return console.log("status code", res.statusCode);
// });


text:
require_relative '../../qa'

# This script deletes all selected test ssh keys for a specific user
# Keys can be selected by a string matching part of the key's title and by created date
#   - Specify `title_portion` to delete only keys that include the string provided
#   - Specify `delete_before` to delete only keys that were created before the given date
#
# If `dry_run` is true the script will list the keys by title and indicate whether each will be deleted
#
# Required environment variables: GITLAB_QA_ACCESS_TOKEN and GITLAB_ADDRESS
#   - GITLAB_QA_ACCESS_TOKEN should have API access and belong to the user whose keys will be deleted

module QA
  module Tools
    class DeleteTestSSHKeys
      include Support::Api

      ITEMS_PER_PAGE = '100'

      def initialize(title_portion: 'E2E test key:', delete_before: Date.today.to_s, dry_run: false)
        raise ArgumentError, "Please provide GITLAB_ADDRESS" unless ENV['GITLAB_ADDRESS']
        raise ArgumentError, "Please provide GITLAB_QA_ACCESS_TOKEN" unless ENV['GITLAB_QA_ACCESS_TOKEN']

        @api_client = Runtime::API::Client.new(ENV['GITLAB_ADDRESS'], personal_access_token: ENV['GITLAB_QA_ACCESS_TOKEN'])
        @title_portion = title_portion
        @delete_before = Date.parse(delete_before)
        @dry_run = dry_run
      end

      def run
        STDOUT.puts 'Running...'

        keys_head_response = head Runtime::API::Request.new(@api_client, "/user/keys", per_page: ITEMS_PER_PAGE).url
        total_pages = keys_head_response.headers[:x_total_pages]

        test_ssh_key_ids = fetch_test_ssh_key_ids(total_pages)
        STDOUT.puts "Number of test ssh keys to be deleted: #{test_ssh_key_ids.length}"

        return if dry_run?

        delete_ssh_keys(test_ssh_key_ids) unless test_ssh_key_ids.empty?
        STDOUT.puts "\nDone"
      end

      private

      attr_reader :dry_run
      alias_method :dry_run?, :dry_run

      def delete_ssh_keys(ssh_key_ids)
        STDOUT.puts "Deleting #{ssh_key_ids.length} ssh keys..."
        ssh_key_ids.each do |key_id|
          delete_response = delete Runtime::API::Request.new(@api_client, "/user/keys/#{key_id}").url
          dot_or_f = delete_response.code == 204 ? "\e[32m.\e[0m" : "\e[31mF\e[0m"
          print dot_or_f
        end
      end

      def fetch_test_ssh_key_ids(pages)
        key_ids = []

        pages.to_i.times do |page_no|
          get_keys_response = get Runtime::API::Request.new(@api_client, "/user/keys", page: (page_no + 1).to_s, per_page: ITEMS_PER_PAGE).url
          keys = JSON.parse(get_keys_response.body).select do |key|
            to_delete = key['title'].include?(@title_portion) && Date.parse(key['created_at']) < @delete_before

            puts "Key title: #{key['title']}\tcreated_at: #{key['created_at']}\tdelete? #{to_delete}" if dry_run?

            to_delete
          end
          key_ids.concat(keys.map { |key| key['id'] })
        end

        key_ids.uniq
      end
    end
  end
end


text:
node-bufferjs
====

Pure JavaScript utils which extend the global `Buffer` object in Node.JS.

    npm install bufferjs

API
====

    require('bufferjs');

  * buffer.addChunk(chunk)
  * Buffer.indexOf(haystack, needle, startIndex)
  * buffer.indexOf(needle, startIndex)

buffer.addChunk(chunk)
----

Adds a buffer `chunk` to `buffer`.

Returns `true` when full

Returns `new Buffer` if buffer overflows

    require('bufferjs/add-chunk');

    var buffer = new Buffer(9),
      overflow;

    buffer.addChunk(new Buffer("abc"));
    buffer.addChunk(new Buffer("def"));
    buffer.toString(); // "abcdef???"
    // Note: "???" is whatever random garbage was internally `malloc`d.

    console.log(true === buffer.addChunk(new Buffer("ghi"))); // true, buffer is full
    // true when buffer is full

    // adding past the index will throw an error
    overflow = buffer.addChunk(new Buffer("jkl"));
    buffer.toString(); // abcdefghi
    overflow.toString(); // jkl

Buffer.indexOf(haystack, needle, startIndex)
----

Searches the given _haystack_ Buffer for the given _needle_ Buffer. Returns the index
of the first occurence of `needle`, or `-1` if the pattern was not found. `needle` may also
be a regular String, for convenience. `startIndex` tells at which index to begin the search.

    require('bufferjs/indexOf');

    var haystack = new Buffer(10);
    var needle = '\r\n';
    haystack.write(needle, 5);

    Buffer.indexOf(haystack, needle); // 5
    Buffer.indexOf(haystack, 'NOT_IN_HAYSTACK'); // -1

buffer.indexOf(needle, startIndex)
----

OO-style variant of `Buffer.indexOf`. `this` is the _haystack_, and only _needle_ needs
to be supplied when called.

    require('bufferjs/indexOf');

    var haystack = new Buffer(10);
    var needle = '\r\n';
    haystack.write(needle, 5);

    haystack.indexOf(needle); // 5
    haystack.indexOf('NOT_IN_HAYSTACK'); // -1

Buffer.concat(list, [totalLength])
----

**Deprecated**: Node.JS 0.8.x has Buffer.concat built-in (compatible).
See http://nodejs.org/api/buffer.html#buffer_class_method_buffer_concat_list_totallength

**WARNING**: v1.2.1 uses NON-NATIVE concat. v2.0.0 uses NATIVE concat ONLY.

Returns a new `Buffer` with the contents of all buffers in the `Array`.

    require('bufferjs/concat');

    var buffers = [
            new Buffer("abc")
          , new Buffer("def")
          , new Buffer("ghi")
        ]
      , buffer
      ;

    buffer = Buffer.concat(buffers);
    console.log(buffer.toString('utf8'));
    // abcdefghi


text: blogs template


text:
package com.joypupil.study.test.文件加解密;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
/**
 * 文件加密、解密
 * @author admin_Hzw
 *
 */
public class FileEncryptAndDecrypt {
	/**
	 * 文件file进行加密
	 * @param fileUrl 文件路径
	 * @param destPath 加密文件存储的路径
	 * @param key 密码
	 * @throws Exception
	 */
	public static void encrypt(String fileUrl, String destPath, String key) throws Exception {
		File file = new File(fileUrl);
//		String path = file.getPath();
//		if(!file.exists()){
//			return;
//		}
//		int index = path.lastIndexOf("\\");
//		String destFile = path.substring(0, index)+"\\"+"abc";
		File dest = new File(destPath);
		long start;
		long end;
		start = System.currentTimeMillis();

		InputStream in = new FileInputStream(fileUrl);
		OutputStream out = new FileOutputStream(destPath);
		byte[] buffer = new byte[1024];
		int r;
		byte[] buffer2=new byte[1024];
		while (( r= in.read(buffer)) > 0) {
			for(int i=0;i<r;i++)
			{
				byte b=buffer[i];
				buffer2[i]=b==255?0:++b;
			}
			out.write(buffer2, 0, r);
			out.flush();
		}
		in.close();
		out.close();
		file.delete();
		dest.renameTo(file);
		appendMethodA(fileUrl, key);

		out.flush();
		end = System.currentTimeMillis();
		System.out.println("加密文件" + fileUrl + "用时:" + (end - start));

	}

	/**
	 *
	 * @param fileName
	 * @param content 密钥
	 */
	public static void appendMethodA(String fileName, String content) {
		try {
			// 打开一个随机访问文件流,按读写方式
			RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
			// 文件长度,字节数
			long fileLength = randomFile.length();
			//将写文件指针移到文件尾。
			randomFile.seek(fileLength);
			randomFile.writeBytes(content);
			randomFile.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 解密
	 * @param fileUrl 源文件
	 * @param tempUrl 临时文件
	 * @param ketLength 密码长度
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String fileUrl, String tempUrl, int keyLength) throws Exception{
		File file = new File(fileUrl);
		if (!file.exists()) {
			return null;
		}
		File dest = new File(tempUrl);
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}

		long start;
		long end;
		start = System.currentTimeMillis();

		InputStream is = new FileInputStream(fileUrl);
		OutputStream out = new FileOutputStream(tempUrl);

		byte[] buffer = new byte[1024];
		byte[] buffer2=new byte[1024];
		byte bMax=(byte)255;
		long size = file.length() - keyLength;
		int mod = (int) (size%1024);
		int div = (int) (size>>10);
		int count = mod==0?div:(div+1);
		int k = 1, r;
		while ((k <= count && ( r = is.read(buffer)) > 0)) {
			if(mod != 0 && k==count) {
				r =  mod;
			}

			for(int i = 0;i < r;i++)
			{
				byte b=buffer[i];
				buffer2[i]=b==0?bMax:--b;
			}
			out.write(buffer2, 0, r);
			k++;
		}
		out.close();
		is.close();

		out.flush();
		end = System.currentTimeMillis();
		System.out.println("解密文件" + fileUrl + "用时:" + (end - start));

		return tempUrl;
	}

	/**
	 * 判断文件是否加密
	 * @param fileName
	 * @return
	 */
	public static String readFileLastByte(String fileName, int keyLength) {
		File file = new File(fileName);
		if(!file.exists())return null;
		StringBuffer str = new StringBuffer();
		try {
			// 打开一个随机访问文件流,按读写方式
			RandomAccessFile randomFile = new RandomAccessFile(fileName, "r");
			// 文件长度,字节数
			long fileLength = randomFile.length();
			//将写文件指针移到文件尾。
			for(int i = keyLength ; i>=1 ; i--){
				randomFile.seek(fileLength-i);
				str.append((char)randomFile.read());
			}
			randomFile.close();
			return str.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	public static void main(String[] args) throws Exception {
		String path = "F:\\test\\test";
//		long start = System.currentTimeMillis();
		encrypt(path+"\\test1.txt", path + "\\temp","mimimamamima99188");  //加密
//
//		decrypt(path+"\\Need.for.Speed.Rivals.CN.HD.V4.part01.rar","F:\\test\\decrypt.rar","mimimamamima99188".length());//解密
//		long end = System.currentTimeMillis();
//		System.out.println(end - start);
//		System.out.println((byte) 255 == (byte) -1);
//		byte a = (byte) 255;
//		Byte b = a;
//		System.out.println(Byte.toUnsignedInt(a));
		System.out.println(System.currentTimeMillis() - 1478658249886l);
	}
}


text:
layout: post
title: Compliance-as-code to bring high velocity to enterprise IT
date: '2015-05-06T15:27:30+01:00'
tags:
- Interview
---
[Interview][1] with Diginomica

[1]:	http://diginomica.com/2015/04/30/compliance-as-code-brings-high-velocity-to-enterprise-it/


text:
Regulamento

        Os bolões só serão registrados quando todas as cotas forem vendidas.

            • Os valores das cotas são acrescidos de porcentagem de administração.

            • A garantia de acertar um dos prêmios é de aproximadamente 80% com base em estudos e probabilidades da loteria.

            • Dos valores de premiações em caso de acerto 10% ficam para o site e administrador


text:
package com.sun.xacml;

import com.sun.xacml.attr.AttributeValue;
import com.sun.xacml.attr.DateAttribute;
import com.sun.xacml.attr.DateTimeAttribute;
import com.sun.xacml.attr.TimeAttribute;

import com.sun.xacml.cond.EvaluationResult;

import com.sun.xacml.ctx.RequestElement;
import com.sun.xacml.ctx.Result;

import com.sun.xacml.reduction.ReductionGraph;

import java.net.URI;

import java.util.Map;
import java.util.Set;

import org.w3c.dom.Node;

/**
 * Manages the context of a single policy evaluation. Typically, an instance
 * is instantiated whenever the PDP gets a request and needs to perform an
 * evaluation as a result. The BasicEvaluationCtx class
 * provides a basic implementation that is used by default.
 *
 * @since 1.0
 * @author Seth Proctor
 * @author Ludwig Seitz
 */
public interface EvaluationCtx
{

    /**
     * Create a context for an administrative request from an
     * existing context.
     *
     * @param decision  The decision code corresponding to those in the
     *                   Result class.
     * @param delegate  The delegate in this request (a set containing a
     *                    single RequestElement).
     *
     * @return  An administrative context for this context.
     */
    public EvaluationCtx createAdminCtx(int decision, Set<RequestElement> delegate);

    /**
     * Creates a copy of this context with disabled attribute finder.
     *
     * @return  A copy of this context with disabled attribute finder.
     */
    public EvaluationCtx copyWithoutAttributeFinder();

    /**
     * Returns the DOM root of the original RequestType XML document, if
     * this context is backed by an XACML Request. If this context is not
     * backed by an XML representation, then an exception is thrown.
     *
     * @return the DOM root node
     *
     * @throws UnsupportedOperationException if the context is not backed
     *                                       by an XML representation
     */
    public Node getRequestRoot();

    /**
     * Returns the resource scope, which will be one of the five fields
     * denoting Immediate, Children, Descendants, XPath-expression or
     * EntireHierarchy.
     *
     * @return the scope of the resource
     */
    public int getScope();

    /**
     * Returns the identifier for the resource being requested.
     *
     * @return the resource
     */
    public AttributeValue getResourceId();

    /**
     * Changes the value of the resource-id attribute in this context. This
     * is useful when you have multiple resources (ie, a scope other than
     * IMMEDIATE), and you need to keep changing only the resource-id to
     * evaluate the different effective requests.
     *
     * @param resourceId the new resource-id value
     */
    public void setResourceId(AttributeValue resourceId);

    /**
     * Returns the value for the current time as known by the PDP (if this
     * value was also supplied in the Request, this will generally be a
     * different value). Details of caching or location-based resolution
     * are left to the underlying implementation.
     *
     * @return the current time
     */
    public TimeAttribute getCurrentTime();

    /**
     * Returns the value for the current date as known by the PDP (if this
     * value was also supplied in the Request, this will generally be a
     * different value). Details of caching or location-based resolution
     * are left to the underlying implementation.
     *
     * @return the current date
     */
    public DateAttribute getCurrentDate();

    /**
     * Returns the value for the current dateTime as known by the PDP (if this
     * value was also supplied in the Request, this will generally be a
     * different value). Details of caching or location-based resolution
     * are left to the underlying implementation.
     *
     * @return the current date
     */
    public DateTimeAttribute getCurrentDateTime();

    /**
     * Return available attribute values of the selected category.
     *
     * @param category the category the attribute value(s) must be in
     * @param type the type of the attribute value(s) to find
     * @param id the id of the attribute value(s) to find
     * @param issuer the issuer of the attribute value(s) to find or null
     *
     * @return a result containing a bag either empty because no values were
     * found or containing at least one value, or status associated with an
     * Indeterminate result
     */
    public EvaluationResult getAttribute(URI category, URI type, URI id,
            URI issuer);

    /**
     * Returns the attribute value(s) retrieved using the given XPath
     * expression.
     *
     * @param contextPath the XPath expression to search
     * @param namespaceNode the DOM node defining namespace mappings to use,
     *                      or null if mappings come from the context root
     * @param type the type of the attribute value(s) to find
     * @param xpathVersion the version of XPath to use
     *
     * @return a result containing a bag either empty because no values were
     * found or containing at least one value, or status associated with an
     * Indeterminate result
     */
    public EvaluationResult getAttribute(String contextPath,
            Node namespaceNode, URI type,
            String xpathVersion);

    /**
     * Get the decision.
     *
     * @return The int value of the decision according to
     *         the Result class.
     */
    public int getDecision();

    /**
     * Get the delegation depth.
     *
     *  @return  The int value specifying the number of nodes
     *           in the reduction graph until now (not including this one).
     */
    public int getDelegationDepth();

    /**
     * Get a whole category.
     *
     * @param category  The name of the category.
     *
     * @return The Set of <RequestElements with
     *         the matching category.
     */
    public Set<RequestElement> getCategory(URI category);

    /**
     * @return The Set of RequestElements
     *         describing the attributes to be included in the result.
     */
    public Set<RequestElement> getIncludedAttributes();

    /**
     * @return  the Map of RequestElements
     *          defining this request.
     */
    public Map<URI, Set<RequestElement>> getRequestElements();

    /**
     * Save the parent PolicySet in this evaluation context
     * for doing reduction of delegated policies if that becomes necessary.
     *
     * @param pps  the parent policy set
     */
    public void saveParentPolicySet(AbstractPolicy pps);

    /**
     * Create a reduction graph for the current parent PolicySet.
     *
     */
    public void createReductionGraph();

    /**
     * @return  The current reduction graph.
     */
    public ReductionGraph getReductionGraph();

    /**
     * Remove the current ReductionGraph from the stack.
     */
    public void popReductionGraph();

    /**
     * Get the parent PolicySet for this evaluation context.
     *
     * @return  the parent policy set
     */
    public AbstractPolicy getParentPolicySet();

    /**
     * Remove the current parent PolicySet from the stack
     * of parent policy sets.
     */
    public void popParentPolicySet();

    /**
     * Add new inactive PolicyId to the Map
     * @param policyId  the id of the new inactive policy
     */
    public void addInactivePolicyId(URI policyId);

    /**
     * Return an unmodifiable Set of URIs of
     * inactive policies
     * @return  the inactive policies
     */
    public Set<URI> getInactivePolicyIds();

    /**
     * Checks whether a Policy or PolicySet
     * supports a revocation of a specific Policy of PolicySet
     * in this context.
     *
     * @param supporting  The policy or policy set that could support
     *                    a revocation.
     * @param candidate  The id of the policy or policy set that is candidate
     *                   for revocation.
     *
     * @return  true if the policy/policy set supports a revocation,
     *          false otherwise.
     */
    public boolean supportsRevocation(AbstractPolicy supporting,
            URI candidate);

    /**
     * Signal a new event to this EvaluationCtx.
     *
     * @param element  The new event.
     */
    public void newEvent(Object element);

    /**
     * Signal that an event has finished and pass the result
     * which is a Result
     *
     * @param result  The result of the finished event.
     */
    public void closeCurrentEvent(Result result);

    /**
     * Signal that an event has finished and pass the result
     * which is a MatchResult
     *
     * @param result  The result of the finished event.
     */
    public void closeCurrentEvent(MatchResult result);

    /**
     * Signal that an event has finished and pass the result
     * which is a EvaluationResult
     *
     * @param result  The result of the finished event.
     */
    public void closeCurrentEvent(EvaluationResult result);

    /**
     * Signal that an event has finished with a String message.
     *
     * @param message  The message.
     */
    public void closeCurrentEvent(String message);

    /**
     * Signal that an event has finished with no result.
     */
    public void closeCurrentEvent();

}


text:
package lou.arane.app.usecases;

import java.nio.file.Path;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lou.arane.app.Context;
import lou.arane.core.Cmd;
import lou.arane.scripts.CopyFiles;
import lou.arane.util.FileResource;
import lou.arane.util.URLResource;
import lou.arane.util.Util;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

/**
 * Download manga from site mangasee.
 *
 * @author LOU
 */
public class MangaSee implements Cmd {

    private static final Pattern numberPattern = Pattern.compile("\\d+(\\.\\d+)?");

    private static final Pattern chapterPattern = numberPattern;

    private static final String baseUri = "http://mangasee.co/manga/";

	private final Context ctx;

    public MangaSee(Context context) {
    	this.ctx = context;
    }

	@Override
	public boolean canRun() {
		//domain must match
		String url = ctx.source.externalForm();
		return url.startsWith(baseUri);
	}

	@Override
	public void doRun() {
		ctx.downloadChapterList();
		downloadChapters();
		downloadPages();
		downloadImages();
		collectImagesIntoChapters();
	}

    private void downloadChapters() {
        FileResource indexPath = ctx.chapterList;
        Document indexDoc = indexPath.parseHtml(baseUri);
        for (Element chapterAddr : indexDoc.getElementsByClass("chapter_link")) {
            String chapterName = chapterAddr.text().trim();
            String href = chapterAddr.absUrl("href");
            URLResource.of(href).ifPresent(chapterUrl -> {
            	Path chapterPath = ctx.chaptersDir.resolve(chapterName + ".html");
            	ctx.add(chapterUrl, new FileResource(chapterPath));
            });
        }
        ctx.download();
    }

    private void downloadPages() {
        for (Path chapterHtml : Util.findHtmlFiles(ctx.chaptersDir)) {
            Matcher chapterIndMatcher = numberPattern.matcher(chapterHtml.getFileName().toString());
            String chapterIdx = "";
            if (chapterIndMatcher.find()) {
                chapterIdx = chapterIndMatcher.group();
            }
            else {
                throw new IllegalArgumentException("Cannot detect chapter index for " + chapterHtml);
            }
            Document chapter = Util.parseHtml(chapterHtml);
            Element pageForm = chapter.getElementById("pages");
            int pageNo = pageForm.getElementsByTag("option").size();
            for (String pageIdx : Util.rangeClosed(1, pageNo)) {
                Optional<URLResource> pageUrl = URLResource.of(
                    baseUri + String.format(
                    	"?series=%s&chapter=%s&index=1&page=%s"
                    	, ctx.sourceName
                    	, chapterIdx
                    	, pageIdx));
                if (pageUrl.isPresent()) {
	                Path pagePath = ctx.pagesDir.resolve(
	                    String.format("c%s_p%s.html",
	                    Util.padStart(chapterIdx, 3, '0'),
	                    Util.padStart(pageIdx, 3, '0')));
	                ctx.add(pageUrl.get(), new FileResource(pagePath));
                }
            }
        }
        ctx.download();
    }

    /**
     * For each page, look for image under:

     */
    private void downloadImages() {
    	Util
    	.findHtmlFiles(ctx.pagesDir)
    	.stream()
    	.map(pages -> Util.parseHtml(pages, baseUri))
    	.forEach(this::downloadImages);
        ctx.download();
    }

	private void downloadImages(Document pages) {
		pages
		.select("a[href] img[src]")
		.stream()
        .map(img -> img.absUrl("src"))
        .map(URLResource::of)
        .filter(Optional::isPresent)
        .map(Optional::get)
        .forEach(imageUrl -> {
        	String pageName = imageUrl.fileName();
        	Path imagePath = ctx.imagesDir.resolve(pageName);
        	ctx.add(imageUrl, new FileResource(imagePath));
        });
	}

    /** Organize the downloaded images into chapters */
    private void collectImagesIntoChapters() {
        new CopyFiles(ctx.imagesDir, ctx.outputDir).setDirPattern(chapterPattern).run();
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <title>Thermostat</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
  <link href="https://fonts.googleapis.com/css?family=Gravitas+One" rel="stylesheet">
  <link href="css/thermostat.css" rel="stylesheet">

      <form id="get-weather-data" autocomplete="off">

Weather in <input type="text" name="city" value="London" id="weather-city">

      </form>

      <button id="up" class="chevron"></button>
      <button id="down" class="chevron"></button>

    <button id="reset" class="trigger">Reset</button>

    <button id="power-save" class="trigger">Power Save</button>


text:
package remote

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"

	"github.com/Azure/azure-sdk-for-go/arm/storage"
	mainStorage "github.com/Azure/azure-sdk-for-go/storage"
	"github.com/Azure/go-autorest/autorest/azure"
	riviera "github.com/jen20/riviera/azure"
)

func azureFactory(conf map[string]string) (Client, error) {
	storageAccountName, ok := conf["storage_account_name"]
	if !ok {
		return nil, fmt.Errorf("missing 'storage_account_name' configuration")
	}
	containerName, ok := conf["container_name"]
	if !ok {
		return nil, fmt.Errorf("missing 'container_name' configuration")
	}
	keyName, ok := conf["key"]
	if !ok {
		return nil, fmt.Errorf("missing 'key' configuration")
	}

	env, err := getAzureEnvironmentFromConf(conf)
	if err != nil {
		return nil, err
	}

	accessKey, ok := confOrEnv(conf, "access_key", "ARM_ACCESS_KEY")
	if !ok {
		resourceGroupName, ok := conf["resource_group_name"]
		if !ok {
			return nil, fmt.Errorf("missing 'resource_group_name' configuration")
		}

		var err error
		accessKey, err = getStorageAccountAccessKey(conf, resourceGroupName, storageAccountName, env)
		if err != nil {
			return nil, fmt.Errorf("Couldn't read access key from storage account: %s.", err)
		}
	}

	storageClient, err := mainStorage.NewClient(storageAccountName, accessKey, env.StorageEndpointSuffix,
		mainStorage.DefaultAPIVersion, true)
	if err != nil {
		return nil, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err)
	}

	blobClient := storageClient.GetBlobService()
	leaseID, _ := confOrEnv(conf, "lease_id", "ARM_LEASE_ID")

	return &AzureClient{
		blobClient:    &blobClient,
		containerName: containerName,
		keyName:       keyName,
		leaseID:       leaseID,
	}, nil
}

func getStorageAccountAccessKey(conf map[string]string, resourceGroupName, storageAccountName string, env azure.Environment) (string, error) {
	creds, err := getCredentialsFromConf(conf, env)
	if err != nil {
		return "", err
	}

	oauthConfig, err := env.OAuthConfigForTenant(creds.TenantID)
	if err != nil {
		return "", err
	}
	if oauthConfig == nil {
		return "", fmt.Errorf("Unable to configure OAuthConfig for tenant %s", creds.TenantID)
	}

	spt, err := azure.NewServicePrincipalToken(*oauthConfig, creds.ClientID, creds.ClientSecret, env.ResourceManagerEndpoint)
	if err != nil {
		return "", err
	}

	accountsClient := storage.NewAccountsClientWithBaseURI(env.ResourceManagerEndpoint, creds.SubscriptionID)
	accountsClient.Authorizer = spt

	keys, err := accountsClient.ListKeys(resourceGroupName, storageAccountName)
	if err != nil {
		return "", fmt.Errorf("Error retrieving keys for storage account %q: %s", storageAccountName, err)
	}

	if keys.Keys == nil {
		return "", fmt.Errorf("Nil key returned for storage account %q", storageAccountName)
	}

	accessKeys := *keys.Keys
	return *accessKeys[0].Value, nil
}

func getCredentialsFromConf(conf map[string]string, env azure.Environment) (*riviera.AzureResourceManagerCredentials, error) {
	subscriptionID, ok := confOrEnv(conf, "arm_subscription_id", "ARM_SUBSCRIPTION_ID")
	if !ok {
		return nil, fmt.Errorf("missing 'arm_subscription_id' configuration")
	}
	clientID, ok := confOrEnv(conf, "arm_client_id", "ARM_CLIENT_ID")
	if !ok {
		return nil, fmt.Errorf("missing 'arm_client_id' configuration")
	}
	clientSecret, ok := confOrEnv(conf, "arm_client_secret", "ARM_CLIENT_SECRET")
	if !ok {
		return nil, fmt.Errorf("missing 'arm_client_secret' configuration")
	}
	tenantID, ok := confOrEnv(conf, "arm_tenant_id", "ARM_TENANT_ID")
	if !ok {
		return nil, fmt.Errorf("missing 'arm_tenant_id' configuration")
	}

	return &riviera.AzureResourceManagerCredentials{
		SubscriptionID:          subscriptionID,
		ClientID:                clientID,
		ClientSecret:            clientSecret,
		TenantID:                tenantID,
		ActiveDirectoryEndpoint: env.ActiveDirectoryEndpoint,
		ResourceManagerEndpoint: env.ResourceManagerEndpoint,
	}, nil
}

func getAzureEnvironmentFromConf(conf map[string]string) (azure.Environment, error) {
	envName, ok := confOrEnv(conf, "environment", "ARM_ENVIRONMENT")
	if !ok {
		return azure.PublicCloud, nil
	}

	env, err := azure.EnvironmentFromName(envName)
	if err != nil {
		// try again with wrapped value to support readable values like german instead of AZUREGERMANCLOUD
		var innerErr error
		env, innerErr = azure.EnvironmentFromName(fmt.Sprintf("AZURE%sCLOUD", envName))
		if innerErr != nil {
			return env, fmt.Errorf("invalid 'environment' configuration: %s", err)
		}
	}

	return env, nil
}

func confOrEnv(conf map[string]string, confKey, envVar string) (string, bool) {
	value, ok := conf[confKey]
	if ok {
		return value, true
	}

	value = os.Getenv(envVar)

	return value, value != ""
}

type AzureClient struct {
	blobClient    *mainStorage.BlobStorageClient
	containerName string
	keyName       string
	leaseID       string
}

func (c *AzureClient) Get() (*Payload, error) {
	blob, err := c.blobClient.GetBlob(c.containerName, c.keyName)
	if err != nil {
		if storErr, ok := err.(mainStorage.AzureStorageServiceError); ok {
			if storErr.Code == "BlobNotFound" {
				return nil, nil
			}
		}
		return nil, err
	}

	defer blob.Close()

	data, err := ioutil.ReadAll(blob)
	if err != nil {
		return nil, err
	}

	payload := &Payload{
		Data: data,
	}

	// If there was no data, then return nil
	if len(payload.Data) == 0 {
		return nil, nil
	}

	return payload, nil
}

func (c *AzureClient) Put(data []byte) error {
	headers := map[string]string{
		"Content-Type": "application/json",
	}

	if c.leaseID != "" {
		headers["x-ms-lease-id"] = c.leaseID
	}

	return c.blobClient.CreateBlockBlobFromReader(
		c.containerName,
		c.keyName,
		uint64(len(data)),
		bytes.NewReader(data),
		headers,
	)
}

func (c *AzureClient) Delete() error {
	headers := map[string]string{}
	if c.leaseID != "" {
		headers["x-ms-lease-id"] = c.leaseID
	}

	return c.blobClient.DeleteBlob(c.containerName, c.keyName, headers)
}


text:
// Copyright (C) 2012 - 2013 Brno University of Technology (http://nes.fit.vutbr.cz/ansa)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see http://www.gnu.org/licenses/.
//

/**
 * @file IGMPv3.h
 * @author Adam Malik(towdie13@gmail.com), Vladimir Vesely (ivesely@fit.vutbr.cz), Tamas Borbely (tomi@omnetpp.org)
 * @date 12.5.2013
 */

#ifndef __INET_IGMPV3_H
#define __INET_IGMPV3_H

#include "inet/common/INETDefs.h"
#include "inet/networklayer/contract/ipv4/IPv4Address.h"
#include "inet/networklayer/ipv4/IGMPMessage.h"
#include "inet/networklayer/common/InterfaceEntry.h"
#include "inet/networklayer/ipv4/IPv4InterfaceData.h"

#include <set>

namespace inet {

class IInterfaceTable;
class IRoutingTable;

class INET_API IGMPv3 : public cSimpleModule, protected cListener
{
  protected:
    typedef std::vector<IPv4Address> IPv4AddressVector;

    enum RouterState {
        IGMPV3_RS_INITIAL,
        IGMPV3_RS_QUERIER,
        IGMPV3_RS_NON_QUERIER,
    };

    enum RouterGroupState {
        IGMPV3_RGS_NO_MEMBERS_PRESENT,
        IGMPV3_RGS_MEMBERS_PRESENT,
        IGMPV3_RGS_CHECKING_MEMBERSHIP,
    };

    enum HostGroupState {
        IGMPV3_HGS_NON_MEMBER,
        IGMPV3_HGS_DELAYING_MEMBER,
        IGMPV3_HGS_IDLE_MEMBER,
    };

    enum FilterMode {
        IGMPV3_FM_INCLUDE,
        IGMPV3_FM_EXCLUDE,
    };

    enum ReportType {
        IGMPV3_RT_IS_IN = 1,
        IGMPV3_RT_IS_EX = 2,
        IGMPV3_RT_TO_IN = 3,
        IGMPV3_RT_TO_EX = 4,
        IGMPV3_RT_ALLOW = 5,
        IGMPV3_RT_BLOCK = 6,
    };

    struct HostInterfaceData;

    struct HostGroupData
    {
        HostInterfaceData *parent;
        IPv4Address groupAddr;
        FilterMode filter;
        IPv4AddressVector sourceAddressList;    // sorted
        HostGroupState state;
        cMessage *timer;    // for scheduling responses to Group-Specific and Group-and-Source-Specific Queries
        IPv4AddressVector queriedSources;    // saved from last Group-Specific or Group-and-Source-Specific Query; sorted

        HostGroupData(HostInterfaceData *parent, IPv4Address group);
        virtual ~HostGroupData();
        std::string getStateInfo() const;
    };

    typedef std::map<IPv4Address, HostGroupData *> GroupToHostDataMap;

    struct HostInterfaceData
    {
        IGMPv3 *owner;
        InterfaceEntry *ie;
//        int multicastRouterVersion;
        GroupToHostDataMap groups;
        cMessage *generalQueryTimer;    // for scheduling responses to General Queries

        HostInterfaceData(IGMPv3 *owner, InterfaceEntry *ie);
        virtual ~HostInterfaceData();
        HostGroupData *getOrCreateGroupData(IPv4Address group);
        void deleteGroupData(IPv4Address group);
    };

    struct RouterInterfaceData;
    struct RouterGroupData;

    struct SourceRecord
    {
        RouterGroupData *parent;
        IPv4Address sourceAddr;
        cMessage *sourceTimer;

        SourceRecord(RouterGroupData *parent, IPv4Address source);
        virtual ~SourceRecord();
    };

    typedef std::map<IPv4Address, SourceRecord *> SourceToSourceRecordMap;

    struct RouterGroupData
    {
        RouterInterfaceData *parent;
        IPv4Address groupAddr;
        FilterMode filter;
        RouterGroupState state;
        cMessage *timer;
        SourceToSourceRecordMap sources;    // XXX should map source addresses to source timers
                                            // i.e. map<IPv4Address,cMessage*>

        RouterGroupData(RouterInterfaceData *parent, IPv4Address group);
        virtual ~RouterGroupData();
        bool hasSourceRecord(IPv4Address source) { return sources.find(source) != sources.end(); }
        SourceRecord *createSourceRecord(IPv4Address source);
        SourceRecord *getOrCreateSourceRecord(IPv4Address source);
        void deleteSourceRecord(IPv4Address source);

        std::string getStateInfo() const;
        void collectForwardedSources(IPv4MulticastSourceList& result) const;

      private:
        void printSourceList(std::ostream& out, bool withRunningTimer) const;
    };

    typedef std::map<IPv4Address, RouterGroupData *> GroupToRouterDataMap;

    struct RouterInterfaceData
    {
        IGMPv3 *owner;
        InterfaceEntry *ie;
        GroupToRouterDataMap groups;
        RouterState state;
        cMessage *generalQueryTimer;

        RouterInterfaceData(IGMPv3 *owner, InterfaceEntry *ie);
        virtual ~RouterInterfaceData();
        RouterGroupData *getOrCreateGroupData(IPv4Address group);
        void deleteGroupData(IPv4Address group);
    };

    enum IGMPTimerKind {
        IGMPV3_R_GENERAL_QUERY_TIMER,
        IGMPV3_R_GROUP_TIMER,
        IGMPV3_R_SOURCE_TIMER,
        IGMPV3_H_GENERAL_QUERY_TIMER,
        IGMPV3_H_GROUP_TIMER,
    };

  protected:
    IRoutingTable *rt;
    IInterfaceTable *ift;

    bool enabled;
    int robustness;
    double queryInterval;
    double queryResponseInterval;
    double groupMembershipInterval;
    double otherQuerierPresentInterval;
    double startupQueryInterval;
    double startupQueryCount;
    double lastMemberQueryInterval;
    double lastMemberQueryCount;
    double lastMemberQueryTime;
    double unsolicitedReportInterval;

    typedef std::map<int, HostInterfaceData *> InterfaceToHostDataMap;
    typedef std::map<int, RouterInterfaceData *> InterfaceToRouterDataMap;
    InterfaceToHostDataMap hostData;
    InterfaceToRouterDataMap routerData;

    int numGroups;
    int numHostGroups;
    int numRouterGroups;

    int numQueriesSent;
    int numQueriesRecv;
    int numGeneralQueriesSent;
    int numGeneralQueriesRecv;
    int numGroupSpecificQueriesSent;
    int numGroupSpecificQueriesRecv;
    int numGroupAndSourceSpecificQueriesSent;
    int numGroupAndSourceSpecificQueriesRecv;
    int numReportsSent;
    int numReportsRecv;

  protected:
    virtual int numInitStages() const override { return NUM_INIT_STAGES; }
    virtual void initialize(int stage) override;
    virtual void handleMessage(cMessage *msg) override;
    virtual void receiveSignal(cComponent *source, simsignal_t signalID, cObject *obj, cObject *details) override;
    virtual ~IGMPv3();

  protected:
    virtual HostInterfaceData *createHostInterfaceData(InterfaceEntry *ie);
    virtual RouterInterfaceData *createRouterInterfaceData(InterfaceEntry *ie);
    virtual HostInterfaceData *getHostInterfaceData(InterfaceEntry *ie);
    virtual RouterInterfaceData *getRouterInterfaceData(InterfaceEntry *ie);
    virtual void deleteHostInterfaceData(int interfaceId);
    virtual void deleteRouterInterfaceData(int interfaceId);

    virtual void configureInterface(InterfaceEntry *ie);

    virtual void startTimer(cMessage *timer, double interval);

    virtual void sendGeneralQuery(RouterInterfaceData *interface, double maxRespTime);
    virtual void sendGroupSpecificQuery(RouterGroupData *group);
    virtual void sendGroupAndSourceSpecificQuery(RouterGroupData *group, const IPv4AddressVector& sources);
    virtual void sendGroupReport(InterfaceEntry *ie, const std::vector<GroupRecord>& records);
    virtual void sendQueryToIP(IGMPv3Query *msg, InterfaceEntry *ie, IPv4Address dest);
    virtual void sendReportToIP(IGMPv3Report *msg, InterfaceEntry *ie, IPv4Address dest);

    virtual void processHostGeneralQueryTimer(cMessage *msg);
    virtual void processHostGroupQueryTimer(cMessage *msg);
    virtual void processRouterGeneralQueryTimer(cMessage *msg);
    virtual void processRouterGroupTimer(cMessage *msg);
    virtual void processRouterSourceTimer(cMessage *msg);

    virtual void processIgmpMessage(IGMPMessage *msg);
    virtual void processQuery(IGMPv3Query *msg);
    virtual void processReport(IGMPv3Report *msg);

    virtual void multicastSourceListChanged(InterfaceEntry *ie, IPv4Address group, const IPv4MulticastSourceList& sourceList);

    /**
     * Function for computing the time value in seconds from an encoded value.
     * Codes in the [1,127] interval are the number of 1/10 seconds,
     * codes above 127 are contain a 3-bit exponent and a four bit mantissa
     * and represents the (mantissa + 16) * 2^(3+exp) number of 1/10 seconds.
     */
    virtual double decodeTime(unsigned char code);
};

}    // namespace inet

#endif /* INET_IGMPV3_H */


text:
package expect4j;

import expect4j.matches.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import junit.framework.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TODO
 *
 * @author Chris Verges
 * @author Justin Ryan
 */
public class ExpectUtilsSSHTest extends TestCase {
    /**
     * Interface to the Java 2 platform's core logging facilities.
     */
    private static final Logger logger = LoggerFactory.getLogger(ExpectUtilsSSHTest.class);

    public ExpectUtilsSSHTest(String testName) {
        super(testName);
    }

    protected void setUp() throws Exception {
    }

    protected void tearDown() throws Exception {
    }

    /**
     * Test of SSH method, of class expect4j.ExpectUtils.
     * First response should be something like:
     * Last login: Wed Mar 14 12:13:29 2007 from pool-71-126-249-188.bstnma.fios.verizon.net
     */
    public void testSSH() throws Exception {
        System.out.println("SSH");

        String hostname = "hostname";
        String username = "username";
        String password = "password";

        if( hostname.equals("hostname") ) return;

        Expect4j expect = ExpectUtils.SSH(hostname, username, password, 2222);
        //expect.setDefaultTimeout(Expect4j.TIMEOUT_FOREVER);

        // Mar 15 17:42:02 2007
        final DateFormat format = new SimpleDateFormat("MMM dd HH:mm:ss yyy z");
        expect.expect( new Match[] {
            new RegExpMatch("Last login: \\w{3} (.*) from", new Closure() {
                public void run(ExpectState state) throws Exception {
                    String time = state.getMatch(1);
                    Date date = format.parse( time + " UTC");
                    state.addVar("timestamp", date );
                }
            })
        });

        expect.close();

        Date result = (Date) expect.getLastState().getVar("timestamp");
        assertNotNull( result );
        logger.info("Timestamp: " + result);

        Date expResult = new Date();
        logger.info("Timestamp: " + expResult);
        assertTrue( result.before(expResult) );

        expect.close();
    }
}


text:
/*
 *
 * 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.
 *
 */
package com.rometools.modules.cc.types;

import static org.junit.Assert.assertFalse;

import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

import org.junit.Before;
import org.junit.Test;

import com.rometools.modules.cc.types.License;

/**
 * @author Matthew Buckett
 */
public class LicenseTest {

    @Before
    public void setUp() {
        // As the looked up licenses are held statically we need to clear this between tests.
        License.clear();
    }

    @Test(timeout = 1000)
    public void testConcurrent() throws InterruptedException {
        final AtomicBoolean run = new AtomicBoolean(true);
        final AtomicLong type = new AtomicLong(0);
        // Tracking any problems.
        final AtomicBoolean hadProblem = new AtomicBoolean(false);
        final AtomicBoolean hadException = new AtomicBoolean(false);

        // This thread keeps on adding new licenses (not very realistic but shows the bug)
        final Thread addNew = new Thread() {
            @Override
            public void run() {
                try {
                    while (run.get()) {
                        final License license = License.findByValue("http://creativecommons.org/licenses/" + type.incrementAndGet() + "/1");
                        if (license == null) {
                            hadProblem.set(true);
                        }
                    }
                } catch (final Exception e) {
                    hadException.set(true);
                }
            }
        };

        // This thread attempts to get ones we know have already been put in.
        final Thread getExisting = new Thread() {
            @Override
            public void run() {
                final Random rnd = new Random();
                try {
                    while (run.get()) {
                        final License license = License.findByValue("http://creativecommons.org/licenses/" + rnd.nextInt(type.intValue()) + "/1");
                        if (license == null) {
                            hadProblem.set(true);
                        }
                    }
                } catch (final Exception e) {
                    hadException.set(true);
                }
            }
        };

        addNew.start();
        getExisting.start();
        // Let them do some stuff.
        Thread.sleep(400);
        // Get them to both stop.
        run.set(false);
        // Allow them a little time to stop.
        addNew.join(50);
        getExisting.join(50);
        // Check we didn't have any problems and they have both stopped.
        assertFalse(hadProblem.get());
        assertFalse(hadException.get());
        assertFalse(addNew.isAlive());
        assertFalse(getExisting.isAlive());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <plurals name="phone_in_ecm_notification_time">
        <item quantity="other">Підключення для передачі даних відсутня %s хв.</item>
        <item quantity="one">Підключення для передачі даних відсутня %s хв.</item>
    </plurals>
    <plurals name="alert_dialog_exit_ecm">
        <item quantity="other">Телефон залишатиметься в режимі екстрених зворотних викликів ще %s хв. При цьому будуть недоступні додатки з підтримкою передачі даних. Вийти?</item>
        <item quantity="one">Телефон залишатиметься в режимі екстрених зворотних викликів ще %s хв. При цьому будуть недоступні додатки з підтримкою передачі даних. Вийти?</item>
    </plurals>
    <plurals name="alert_dialog_not_avaialble_in_ecm">
        <item quantity="other">Вибрана дія неможливо при екстрених зворотних викликах. Телефон буде залишатися в цьому режимі ще %s хв. Вийти?</item>
        <item quantity="one">Вибрана дія неможливо при екстрених зворотних викликах. Телефон буде залишатися в цьому режимі ще %s хв. Вийти?</item>
    </plurals>
</resources>