text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;

namespace FileHelpers.Tests.Errors
{
    [TestFixture]
    public class BadUsage
    {
        #region  "  DuplicateAttributes  "

        [FixedLengthRecord]
        public class TestDupli
        {
            [FieldFixedLength(10)]
            [FieldDelimiter("|")]
            public string Field1;
        }

        [Test]
        public void DuplicatedDefinition()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<TestDupli>());
        }

        #endregion

        #region  "  SwitchedAttributes "

        [FixedLengthRecord]
        public class SwitchedAttributes1
        {
            [FieldDelimiter("|")]
            public string Field1;
        }

        [DelimitedRecord("|")]
        public class SwitchedAttributes2
        {
            [FieldFixedLength(12)]
            public string Field1;
        }

        [Test]
        public void SwitchedAttb1()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<SwitchedAttributes1>());
        }

        [Test]
        public void SwitchedAttb2()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<SwitchedAttributes2>());
        }

        #endregion

        #region  "  NullValue "

        [DelimitedRecord("|")]
        public class NullValue1Type
        {
            [FieldNullValue(22)]
            public string Field1;
        }

        [Test]
        public void NullValue1()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<NullValue1Type>());
        }

        #endregion

        #region  "  NoMarkedClass "

        public class NoMarkedClass
        {
            [FieldNullValue(22)]
            public string Field1;
        }

        [Test]
        public void NoMarked()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<NoMarkedClass>());
        }

        #endregion

        #region  "  FixedWithOutLength "

        [FixedLengthRecord]
        public class FixedWithOutLengthClass
        {
            public string Field1;
        }

        [Test]
        public void FixedWithOutLength()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<FixedWithOutLengthClass>());
        }

        #endregion

        #region  "  NoFields "

        [FixedLengthRecord]
        public class NoFieldsClass {}

        [Test]
        public void NoFields()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<NoFieldsClass>());
        }

        #endregion

        #region  "  NoFields2"

        [DelimitedRecord(",")]
        public class NoFieldsClass2
        {
            [FieldHidden]
            public string MyField;
        }

        [Test]
        public void NoFields2()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<NoFieldsClass2>());
        }

        [DelimitedRecord(",")]
        public class NoFieldsClass2Obsoletes1
        {
#pragma warning disable 618
            [FieldNotInFile]
#pragma warning restore 618
            public string MyField;
        }

        [Test]
        public void NoFields2Obsoletes1()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<NoFieldsClass2Obsoletes1>());
        }

        [DelimitedRecord(",")]
        public class NoFieldsClass2Obsoletes2
        {
#pragma warning disable 618
            [FieldIgnored]
#pragma warning restore 618
            public string MyField;
        }

        [Test]
        public void NoFields2Obsoletes2()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<NoFieldsClass2Obsoletes2>());
        }

        #endregion

        #region  "  NoFields3  "

        [DelimitedRecord(",")]
        public class NoFieldsClass3
        {
            [FieldHidden]
            public string MyField;

            [FieldHidden]
            public string MyField2;
        }

        [Test]
        public void NoFields3()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<NoFieldsClass3>());
        }

        #endregion

        #region  "  NoConstructor  "

        [FixedLengthRecord]
        public class NoConstructorClass
        {
            [FieldFixedLength(22)]
            public string Field1;

            public NoConstructorClass(bool foo)
            {
                foo = true;
            }
        }

        [Test]
        public void NoConstructor()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<NoConstructorClass>());
        }

        #endregion

        #region  "  NoConstructorConverter  "

        private class ConvClass : ConverterBase
        {
            public ConvClass(bool foo) {}

            public override object StringToField(string from)
            {
                throw new NotImplementedException();
            }
        }

        [DelimitedRecord(",")]
        public class NoConstructorConvClass
        {
            [FieldConverter(typeof (ConvClass))]
            public string Field1;
        }

        [Test]
        public void NoConstructorConverter()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<NoConstructorConvClass>());
        }

        [DelimitedRecord(",")]
        public class NoConstructorConvClass2
        {
            [FieldConverter(typeof (ConvClass), "hola")]
            public string Field1;
        }

        [Test]
        public void NoConstructorConverter2()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<NoConstructorConvClass2>());
        }

        [DelimitedRecord(",")]
        public class NoConstructorConvClass3
        {
            [FieldConverter(typeof (ConvClass), 123)]
            public string Field1;
        }

        [Test]
        public void NoConstructorConverter3()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<NoConstructorConvClass3>());
        }

        [DelimitedRecord(",")]
        public class NoConstructorConvClass4
        {
            [FieldConverter(typeof (FakeConverter), 123)]
            public string Field1;

            private class FakeConverter {}
        }

        [Test]
        public void NoConstructorConverter4()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<NoConstructorConvClass4>());
        }

        #endregion

        #region  "  DateFormat  "

        [DelimitedRecord("|")]
        public class DateFormat1Class
        {
            [FieldConverter(ConverterKind.Date, null)]
            public DateTime DateField;
        }

        [DelimitedRecord("|")]
        public class DateFormat2Class
        {
            [FieldConverter(ConverterKind.Date, "")]
            public DateTime DateField;
        }

        [DelimitedRecord("|")]
        public class DateFormat3Class
        {
            [FieldConverter(ConverterKind.Date, "d€€#|||??¡¡3&&...dddMMyyyy")]
            public DateTime DateField;
        }

        [Test]
        public void BadDateFormat1()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<DateFormat1Class>());
        }

        [Test]
        public void BadDateFormat2()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<DateFormat2Class>());
        }

//		[Test]
//		public void BadDateFormat3()
//		{
        //Assert.Throws<BadUsageException>(()
        //        => new FileHelperEngine(typeof (DateFormat3Class));
//		}

        #endregion

//		#region  "  TrimBad  "
//
//		[DelimitedRecord("|")]
//		public class TrimClass
//		{
//			[Trim(TrimMode.Both)]
//			public int Field1;
//		}
//
//		[Test]
//		public void TrimOtherThanString()
//		{
//			new FileHelperEngine(typeof (TrimClass));
//		}
//
//		#endregion

        #region  "  AlignBad  "

        [DelimitedRecord("|")]
        public class AlignClass
        {
            [FieldAlign(AlignMode.Left)]
            public int Field1;
        }

        [Test]
        public void AlignError()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<AlignClass>());
        }

        #endregion

        #region  "  NonSystemType  "

        [DelimitedRecord("|")]
        public class NonSystemTypeClass
        {
            // One non system type ex FileInfo
            public FileInfo Field1;
        }

        [Test]
        public void NonSystemType()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine<NonSystemTypeClass>());
        }

        #endregion

        #region  "  ValueType  "

        public struct ValueTypeClass
        {
            // One non system type ex FileInfo
            public FileInfo Field1;
        }

        [Test]
        public void ValueType()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine(typeof (ValueTypeClass)));
        }

        #endregion

        #region  "  BadRecordTypes  "

        [DelimitedRecord("|")]
        public class BadRecordTypeClass
        {
            public string Field1;
        }

        [Test]
        public void BadRecordType()
        {
            var engine = new FileHelperEngine(typeof (BadRecordTypeClass));
            Assert.Throws<BadUsageException>(()
                => engine.WriteString(new[] {"hola"}));
        }

        [Test]
        public void NullRecordType()
        {
            Assert.Throws<BadUsageException>(()
                => new FileHelperEngine((Type) null));
        }

        #endregion

        [Test]
        public void WriteBadUsage()
        {
            var engine = new FileHelperEngine<SampleType>();

            var res = new SampleType[2];

            res[0] = new SampleType();

            res[0].Field1 = DateTime.Now.AddDays(1);
            res[0].Field2 = "je";
            res[0].Field3 = 0;

            Assert.Throws<BadUsageException>(()
                => engine.WriteString(res));
        }

        [Test]
        public void WriteBadUsage2()
        {
            var engine = new FileHelperEngine<SampleType>();
            Assert.Throws<ArgumentNullException>(()
                => engine.WriteString(null));
        }
    }
}


text: Classes and utilities to integrate OpenL Rules Project with Activiti

redpajama_set_name: RedPajamaGithub


text:
title: Nitro on IOS 4.3
author: hbraun
layout: post
permalink: /2011/03/nitro-on-ios-4-3/
blogger_blog:
  - relative-order.blogspot.com
blogger_author:
  -
blogger_permalink:
  - /2011/03/nitro-on-ios-43.html
categories:
  - Uncategorized
---
Why is Nitro disabled in UIWebView and full screen web apps on IOS 4.3?
Read more about it [here][1]

  - More on this topic: http://www.theregister.co.uk/2011/03/15/apple_ios_throttles_web_apps_on_home_screen/

 [1]: http://www.mobilexweb.com/blog/apple-phonegap-html5-nitro


text:
Chef cookbook that provides a LWRP for Laravel Nginx sites with PHP-FPM. Provides a base Nginx config for common Laravel settings at `/etc/nginx/laravel.conf`.

Based on [wordpress-nginx](https://github.com/roots/wordpress-nginx) by Scott Walkinshaw

## Requirements

* [nginx](http://community.opscode.com/cookbooks/nginx)
* [php-fpm](http://community.opscode.com/cookbooks/php-fpm)

## Attributes

* `node['laravel_nginx']['fastcgi_read_timeout']` - Timeout for reading a response from the FastCGI server (default=`3600s`)
* `node['laravel_nginx']['static_file_expiry']` - Expiry time for static assets `js|css|png|jpg|jpeg|gif|ico` (default=`24h`)
* `node['laravel_nginx']['php_fpm']['listen']` - Listen socket for PHP-FPM (default=`/var/run/php-fpm-www.sock`)

## Usage

Basic usage with only host and document root:

```ruby
laravel_nginx_site 'example.com' do
  host 'example.com'
  root '/srv/www/example.com'
end
```

This resource would create an Nginx site at `/etc/nginx/sites-available/example.com` and enable it.

If you need to add additional custom config options, you can use the `code` attribute:

```ruby
laravel_nginx_site 'example.com' do
  host 'example.com'
  root '/srv/www/example.com'
  code "include #{node['nginx']['dir']}/custom.conf;"
  notifies :reload, 'service[nginx]'
end
```

## License and Authors

See [LICENSE](LICENSE.md)


text:
                This inspection reports any instances of double negation in Groovy code, like if (!!functionCall()).

        Powered by InspectorGroovy


text:
package com.github.snd297.hibernateequals.persistence;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.proxy.HibernateProxy;
import org.junit.BeforeClass;
import org.junit.Test;

import com.github.snd297.yp.hibernateequals.persistence.BrokenEqualsCar;
import com.github.snd297.yp.hibernateequals.persistence.Car;
import com.github.snd297.yp.hibernateequals.persistence.GetClassCar;
import com.github.snd297.yp.utils.hibernate.HibernateUtil;

public class EqualsTest {

	private static String getClassCarVin;
	private static String brokenEqualsCarVin;
	private static String carVin;

	@BeforeClass
	public static void classSetup() throws Exception {
		Session sess = null;
		Transaction trx = null;
		try {

			sess = HibernateUtil.getSessionFactory().openSession();
			trx = sess.beginTransaction();

			GetClassCar getClassCar =
					new GetClassCar("H94H878YUIOHFGOH");
			sess.save(getClassCar);

			BrokenEqualsCar brokenEqualsCar =
					new BrokenEqualsCar("J398D8305HKDHG");

			sess.save(brokenEqualsCar);

			Car car = new Car("KH08934U508YTUSZ0IDYGOAIH");
			sess.save(car);

			trx.commit();

			getClassCarVin = getClassCar.getVin();
			brokenEqualsCarVin = brokenEqualsCar.getVin();
			carVin = car.getVin();

		} catch (Exception e) {
			HibernateUtil.rollbackQuietly(trx);
			throw e;
		} finally {
			HibernateUtil.closeQuietly(sess);
		}
	}

	@Test
	public void getClassEquals() throws Exception {
		Session sess = null;
		Transaction trx = null;
		try {
			sess = HibernateUtil.getSessionFactory().openSession();
			trx = sess.beginTransaction();

			GetClassCar getClassCar0 =
					(GetClassCar)
					sess
							.bySimpleNaturalId(GetClassCar.class)
							.getReference(getClassCarVin);
			GetClassCar getClassCar1 =
					new GetClassCar(getClassCarVin);

			assertTrue(getClassCar0 instanceof HibernateProxy);
			assertFalse(getClassCar1.equals(getClassCar0));
			assertTrue(getClassCar0.equals(getClassCar1));

			trx.commit();
		} catch (Exception e) {
			HibernateUtil.rollbackQuietly(trx);
			throw e;
		} finally {
			HibernateUtil.closeQuietly(sess);
		}
	}

	@Test
	public void brokenEquals() throws Exception {
		Session sess = null;
		Transaction trx = null;
		try {
			sess = HibernateUtil.getSessionFactory().openSession();
			trx = sess.beginTransaction();

			BrokenEqualsCar brokenEqualsCar0 =
					(BrokenEqualsCar)
					sess
							.bySimpleNaturalId(BrokenEqualsCar.class)
							.getReference(brokenEqualsCarVin);

			BrokenEqualsCar brokenEqualsCar1 =
					new BrokenEqualsCar(brokenEqualsCarVin);

			assertTrue(brokenEqualsCar0 instanceof HibernateProxy);
			assertFalse(brokenEqualsCar1.equals(brokenEqualsCar0));
			assertTrue(brokenEqualsCar0.equals(brokenEqualsCar1));

			trx.commit();
		} catch (Exception e) {
			HibernateUtil.rollbackQuietly(trx);
			throw e;
		} finally {
			HibernateUtil.closeQuietly(sess);
		}
	}

	@Test
	public void brokenEqualsInitializedProxy() throws Exception {
		Session sess = null;
		Transaction trx = null;
		try {
			sess = HibernateUtil.getSessionFactory().openSession();
			trx = sess.beginTransaction();

			BrokenEqualsCar brokenEqualsCar0 =
					(BrokenEqualsCar)
					sess
							.bySimpleNaturalId(BrokenEqualsCar.class)
							.getReference(brokenEqualsCarVin);
			Hibernate.initialize(brokenEqualsCar0);

			BrokenEqualsCar brokenEqualsCar1 =
					new BrokenEqualsCar(brokenEqualsCarVin);

			assertTrue(brokenEqualsCar0 instanceof HibernateProxy);
			assertFalse(brokenEqualsCar1.equals(brokenEqualsCar0));
			assertTrue(brokenEqualsCar0.equals(brokenEqualsCar1));

			trx.commit();
		} catch (Exception e) {
			HibernateUtil.rollbackQuietly(trx);
			throw e;
		} finally {
			HibernateUtil.closeQuietly(sess);
		}
	}

	@Test
	public void fixedEquals() throws Exception {
		Session sess = null;
		Transaction trx = null;
		try {
			sess = HibernateUtil.getSessionFactory().openSession();
			trx = sess.beginTransaction();

			Car car0 =
					(Car)
					sess
							.bySimpleNaturalId(Car.class)
							.getReference(carVin);

			Car car1 = new Car(carVin);

			assertTrue(car0 instanceof HibernateProxy);
			assertTrue(car1.equals(car0));
			assertTrue(car0.equals(car1));

			trx.commit();
		} catch (Exception e) {
			HibernateUtil.rollbackQuietly(trx);
			throw e;
		} finally {
			HibernateUtil.closeQuietly(sess);
		}
	}
}


text:
var os = require('os')
var spawn = require('child_process').spawn
var Queue = require('firebase-queue'),
    Firebase = require('firebase')

if (process.argv.length < 4) {
  console.log("usage: node worker.js firebaseUrl command [arg1, arg2, ...]")
  console.log("  For authentication, set FIREBASE_TOKEN environment variable.")
  process.exit()
}
var queueUrl = process.argv[2]
var cmdArgs = process.argv.slice(3)

var queueRef = new Firebase(queueUrl)
var start = function () {
  // presence of worker
  queueRef.root().child('.info/connected').on('value', function(snapshot) {
    if (snapshot.val()) {
      var workerRef = queueRef.child("workers").push({hostname: require('os').hostname()})
      workerRef.onDisconnect().remove();
    }
  })
  console.log("WORKER: waiting a runner pushes a task...")
  var queue = new Queue(queueRef, {specId: 'default'}, function (data, progress, resolve, reject) {
    // Read and process task data
    var bufferRef = new Firebase(data.bufferUrl)
    var log = function (msg) {
      bufferRef.child('log').push(msg.toString())
      process.stdout.write(msg.toString())
    }
    log("WORKER: start command: " + cmdArgs + "\n\n")
    var env = Object.create(process.env)
    for (var name in data.env) {
      env[name] = data.env[name]
    }
    var options = { env: env, stdio: ['ignore', 'pipe', 'pipe'] }
    var cmd
    if (os.platform() === 'win32') {
      cmd = spawn(process.env.comspec, ['/c'].concat(cmdArgs), options)
    } else {
      cmd = spawn(cmdArgs[0], cmdArgs.slice(1), options)
    }
    cmd.stdout.on('data', log)
    cmd.stderr.on('data', log)
    cmd.on('error', function (err) { reject(err) })
    cmd.on('close', function (code) {
      if (code === 0) {
        log("\nWORKER: command completed.\n\n")
        resolve()
      } else {
        log("\nWORKER: command failed.\n\n")
        reject("exit code: " + code)
      }
      console.log("WORKER: waiting a runner pushed another task...")
    })
  })
  // graceful shutdown
  process.on('SIGINT', function () {
    console.log('WORKER: Starting queue shutdown...');
    queue.shutdown().then(function () {
      console.log('WORKER: Finished queue shutdown.');
      process.exit(1)
    });
  })
}

if (process.env.FIREBASE_TOKEN) {
  queueRef.authWithCustomToken(process.env.FIREBASE_TOKEN, function (error, result) {
    if (error) {
      console.log("WORKER: Authentication Failed:", error)
    } else {
      console.log("WORKER: Authentication succeeded!")
      start()
    }
  })
  delete process.env.FIREBASE_TOKEN
} else {
  start()
}


text:
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "quiche/quic/qbone/qbone_client_session.h"

#include <utility>

#include "absl/strings/string_view.h"
#include "quiche/quic/core/quic_types.h"
#include "quiche/quic/qbone/qbone_constants.h"
#include "quiche/common/platform/api/quiche_command_line_flags.h"

DEFINE_QUICHE_COMMAND_LINE_FLAG(
    bool, qbone_client_defer_control_stream_creation, true,
    "If true, control stream in QBONE client session is created after "
    "encryption established.");

namespace quic {

QboneClientSession::QboneClientSession(
    QuicConnection* connection,
    QuicCryptoClientConfig* quic_crypto_client_config,
    QuicSession::Visitor* owner, const QuicConfig& config,
    const ParsedQuicVersionVector& supported_versions,
    const QuicServerId& server_id, QbonePacketWriter* writer,
    QboneClientControlStream::Handler* handler)
    : QboneSessionBase(connection, owner, config, supported_versions, writer),
      server_id_(server_id),
      quic_crypto_client_config_(quic_crypto_client_config),
      handler_(handler) {}

QboneClientSession::~QboneClientSession() {}

std::unique_ptr<QuicCryptoStream> QboneClientSession::CreateCryptoStream() {
  return std::make_unique<QuicCryptoClientStream>(
      server_id_, this, nullptr, quic_crypto_client_config_, this,
      /*has_application_state = */ true);
}

void QboneClientSession::CreateControlStream() {
  if (control_stream_ != nullptr) {
    return;
  }
  // Register the reserved control stream.
  QuicStreamId next_id = GetNextOutgoingBidirectionalStreamId();
  QUICHE_DCHECK_EQ(next_id,
                   QboneConstants::GetControlStreamId(transport_version()));
  auto control_stream =
      std::make_unique<QboneClientControlStream>(this, handler_);
  control_stream_ = control_stream.get();
  ActivateStream(std::move(control_stream));
}

void QboneClientSession::Initialize() {
  // Initialize must be called first, as that's what generates the crypto
  // stream.
  QboneSessionBase::Initialize();
  static_cast<QuicCryptoClientStreamBase*>(GetMutableCryptoStream())
      ->CryptoConnect();
  if (!quiche::GetQuicheCommandLineFlag(
          FLAGS_qbone_client_defer_control_stream_creation)) {
    CreateControlStream();
  }
}

void QboneClientSession::SetDefaultEncryptionLevel(
    quic::EncryptionLevel level) {
  QboneSessionBase::SetDefaultEncryptionLevel(level);
  if (quiche::GetQuicheCommandLineFlag(
          FLAGS_qbone_client_defer_control_stream_creation) &&
      level == quic::ENCRYPTION_FORWARD_SECURE) {
    CreateControlStream();
  }
}

int QboneClientSession::GetNumSentClientHellos() const {
  return static_cast<const QuicCryptoClientStreamBase*>(GetCryptoStream())
      ->num_sent_client_hellos();
}

bool QboneClientSession::EarlyDataAccepted() const {
  return static_cast<const QuicCryptoClientStreamBase*>(GetCryptoStream())
      ->EarlyDataAccepted();
}

bool QboneClientSession::ReceivedInchoateReject() const {
  return static_cast<const QuicCryptoClientStreamBase*>(GetCryptoStream())
      ->ReceivedInchoateReject();
}

int QboneClientSession::GetNumReceivedServerConfigUpdates() const {
  return static_cast<const QuicCryptoClientStreamBase*>(GetCryptoStream())
      ->num_scup_messages_received();
}

bool QboneClientSession::SendServerRequest(const QboneServerRequest& request) {
  if (!control_stream_) {
    QUIC_BUG(quic_bug_11056_1)
        << "Cannot send server request before control stream is created.";
    return false;
  }
  return control_stream_->SendRequest(request);
}

void QboneClientSession::ProcessPacketFromNetwork(absl::string_view packet) {
  SendPacketToPeer(packet);
}

void QboneClientSession::ProcessPacketFromPeer(absl::string_view packet) {
  writer_->WritePacketToNetwork(packet.data(), packet.size());
}

void QboneClientSession::OnProofValid(
    const QuicCryptoClientConfig::CachedState& cached) {}

void QboneClientSession::OnProofVerifyDetailsAvailable(
    const ProofVerifyDetails& verify_details) {}

bool QboneClientSession::HasActiveRequests() const {
  return GetNumActiveStreams() + num_draining_streams() > 0;
}

}  // namespace quic


text:
package in.shila.countryselector.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.IOException;
import java.util.Locale;

import in.shila.countryselector.R;
import in.shila.countryselector.utils.DeviceUtils;

public class CountriesListAdapter extends ArrayAdapter<String> {
    private final Context context;
    private final String[] values;
    private LayoutInflater inflater;

    private static final String SELECTED_DISPLAY_FORMAT = "+%s";
    private static final String DROPDOWN_DISPLAY_FORMAT = "%s (+%s)";

    public CountriesListAdapter(Context context, String[] values) {
        super(context, R.layout.country_list_item, values);
        this.context = context;
        this.values = values;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        DropdownViewHolder viewHolder;

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.country_list_item, parent, false);

            viewHolder = new DropdownViewHolder();
            viewHolder.imageView = (ImageView) convertView.findViewById(R.id.imgViewFlag);
            viewHolder.textView = (TextView) convertView.findViewById(R.id.txtViewCountryName);
            convertView.setTag(viewHolder);

        } else {
            viewHolder = (DropdownViewHolder) convertView.getTag();
        }

        final String[] g = values[position].split(",");  //dialing code, country code
        final String countryDisplayName = getCountryDisplayName(g[1].trim());
        final String countryDialCode = g[0].trim();
        viewHolder.textView.setText(String.format(DROPDOWN_DISPLAY_FORMAT, countryDisplayName, countryDialCode));

        final String pngName = g[1].trim().toLowerCase(); //image name

        setImageDrawableFromCountryCode(viewHolder.imageView, pngName);
        return convertView;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        DropdownViewHolder viewHolder;

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.country_selected_item, parent, false);

            viewHolder = new DropdownViewHolder();
            viewHolder.imageView = (ImageView) convertView.findViewById(R.id.imgViewFlag);
            viewHolder.textView = (TextView) convertView.findViewById(R.id.txtViewCountryName);
            convertView.setTag(viewHolder);

        } else {
            viewHolder = (DropdownViewHolder) convertView.getTag();
        }

        String[] g = values[position].split(",");
        viewHolder.textView.setText(String.format(SELECTED_DISPLAY_FORMAT, g[0].trim()));

        String pngName = g[1].trim().toLowerCase();

        setImageDrawableFromCountryCode(viewHolder.imageView, pngName);

        return convertView;
    }

    private String getCountryDisplayName(String ssid) {
        Locale loc = new Locale("", ssid);
        return loc.getDisplayCountry().trim();
    }

    private String getCountryCode(String ssid) {
        Locale loc = new Locale("", ssid);
        return loc.getCountry().trim();
    }

    public int getPositionForDeviceCountry() {
        String dvcCountry = DeviceUtils.getDeviceCountryCode(getContext());
        for (int i = 0; i < values.length; i++) {
            String[] g = values[i].split(",");
            String countryCode = getCountryCode(g[1].trim());
            if (countryCode.equals(dvcCountry)) {
                return i;
            }
        }
        return -1;
    }

    private static class DropdownViewHolder {
        ImageView imageView;
        TextView textView;
    }

    private void setImageDrawableFromCountryCode(ImageView imageView, String pngName) {
        try {
            imageView.setImageDrawable(Drawable.createFromStream(context.getAssets().open("flags/" + pngName + ".png"), null));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


text:
package org.kuali.kfs.module.ld.dataaccess;

import org.kuali.kfs.module.ld.businessobject.LaborGeneralLedgerEntry;

/**
 * This is the data access object for labor general ledger entry
 *
 * @see org.kuali.kfs.module.ld.businessobject.LaborGeneralLedgerEntry
 */
public interface LaborGeneralLedgerEntryDao {

    /**
     * get the max squence number with the given Labor General edger Entry object
     *
     * @param laborGeneralLedgerEntry the given labor General Ledger Entry
     * @return the max squence number with the infomation in the given Labor General edger Entry object
     */
    Integer getMaxSequenceNumber(LaborGeneralLedgerEntry laborGeneralLedgerEntry);
}


text:
StudioBot interacts with students and professors primarily through conversation and simple graphical interfaces such as buttons. The bot has two modes of interaction with users: responses and performances.

When the bot responds to a user, it is usually being asked for information (which it will supply if it is available) or mentioned in conversation. This mode of interaction gives a wide degree of freedom to the path of the conversation, which is usually an informal chat. This is essentially the functionality of a chat-bot, except it will also have access to many studio resources that it can relay to the students on Slack. This allows information to be distributed as it is needed, and searchable within Slack (as well as re-queryable).

However, answering questions and responding to a flurry of informal chats is not StudioBot's primary function. This bot is designed to perform actions and complete tasks that facilitate studio engagement as well as to provide tools for students and professors that both simplifies their workflow and amplifies their productivity.

## Modes of Interaction

#### Basic Response Interactions
##### Common
* **hello**: *A simple hello script that displays a random greeting each time someone says hello to it*
* **goodbye**: *A simple goodbye script that displays a random farewell each time someone says goodbye to it*
* **identify**: *Responds with its identity, what it does (in simple terms) and asks if you would like to see the help command*
* **channel_join**: *Response to being added/invited to a channel. Gives a few unobtrusive hints to it's most useful features*
##### Studio
* **syllabus**: *Responds with a link with the syllabus attached. Might shoot a sassy comment*

#### Basic Performance Interactions
##### Common
* **create_profile**: *Walks the user through the creation of a profile that will be persisted to a database for reference in the future*
* **onboarding**: *Welcomes a new user to the studio*
* **check_in**: *Bot checks in once a week (probably a Friday) to monitor students' stress and outlook. Will persist student responses to database for analysis, and reply with uplifting of motivating responses*

#### Complex Response Interactions
##### Common
* **help**: *Will respond with a short message containing a few of the most useful commands, and will ask if the user would like to see help for all commands. Also accepts an argument containing the name of the specific command the user would like to see help for*
* **thanks**: *Responds with a random "you're welcome" message, and asks if the user would like assistance with anything else. If yes, and user added what they wanted done, do task. If yes, and user hasn't included what they want done, ask. If no, end thread*
* **status**: *If a crit session has been launched (and not closed), StudioBot responds with a percentage bar showing how far along the professor is and how much time remains until users crit. If a crit session has not been launched, or has been closed, StudioBot responds with a message saying a crit session has not been launched or has been closed. If the day is not a studio day, .*
* **deliverables**: *Will reply with the deliverables that were set during the set-deliverables command*

#### Complex Performance Interactions
##### Studio
* **launch-crit**: *Launches an interactive prompt to everyone in the studio asking which position they would like to sign up to for desk crits that day. As students begin selecting their positions, the prompt dynamically changes to reflect the students position. If a students response times out, and they don't respond to the follow-up message, they will be appended to the end of the order. StudioBot then equally allocates time to each student for their desk-crit within studio hours. StudioBot also sends private messages to each student 2 minutes before their crit, and notifies the professor when it is time to move on. launch-crit is automatically launched every Mon, Wed, and Thurs at 1:30pm, but it can be launched manually on any day with a different number of students or amount of time*
`@StudioBot launch-crit start end n_students`
`@StudioBot launch-crit 10:00 14:00 13`
* **set-deliverables**: *Will ask user to send a multi-line message containing the deliverables for the week, studio, or pinup*

lunchtrain?


text:
#import "NSObject.h"

@class CADisplayLink, NSMutableSet;

@interface TKDisplayLinkManager : NSObject
{
    _Bool _hasUpdatedTargetActions;
    _Bool _handlingDisplayRefresh;
    CADisplayLink *_storedDisplayLink;
    NSMutableSet *_activeTargetActions;
    NSMutableSet *_updatedTargetActions;
    unsigned long long _warmUpModeRequirementsCount;
}

+ (void)_releaseCurrentDisplayLinkManager;
+ (id)currentDisplayLinkManager;
@property(nonatomic, setter=_setWarmUpModeRequirementsCount:) unsigned long long _warmUpModeRequirementsCount; // @synthesize _warmUpModeRequirementsCount;
@property(nonatomic, getter=_isHandlingDisplayRefresh, setter=_setHandlingDisplayRefresh:) _Bool _handlingDisplayRefresh; // @synthesize _handlingDisplayRefresh;
@property(nonatomic, setter=_setHasUpdatedTargetActions:) _Bool _hasUpdatedTargetActions; // @synthesize _hasUpdatedTargetActions;
@property(retain, nonatomic, setter=_setUpdatedTargetActions:) NSMutableSet *_updatedTargetActions; // @synthesize _updatedTargetActions;
@property(retain, nonatomic, setter=_setActiveTargetActions:) NSMutableSet *_activeTargetActions; // @synthesize _activeTargetActions;
@property(retain, nonatomic, setter=_setStoredDisplayLink:) CADisplayLink *_storedDisplayLink; // @synthesize _storedDisplayLink;
- (void)_displayDidRefresh:(id)arg1;
- (void)endRequiringWarmUpMode;
- (void)beginRequiringWarmUpMode;
@property(readonly, nonatomic, getter=_isWarmUpModeEnabled) _Bool _warmUpModeEnabled;
- (void)_didRemoveLastTargetAction;
- (void)_didAddFirstTargetAction;
- (id)_prepareUpdatedTargetActionsForModification;
- (void)removeTarget:(id)arg1 selector:(SEL)arg2;
- (void)addTarget:(id)arg1 selector:(SEL)arg2 frameInterval:(unsigned long long)arg3;
- (void)addTarget:(id)arg1 selector:(SEL)arg2;
@property(retain, nonatomic, setter=_setDisplayLink:) CADisplayLink *_displayLink;
@property(readonly, nonatomic) unsigned long long frameInterval;
@property(readonly, nonatomic) double timestamp;
@property(readonly, nonatomic) double duration;
@property(readonly, nonatomic, getter=isPaused) _Bool paused;
- (void)dealloc;
- (id)init;

@end


text:
package com.box.l10n.mojito.localtm.merger;

import com.box.l10n.mojito.collect.ImmutableMapCollectors;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.util.Comparator;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;
import org.springframework.stereotype.Component;

@Component
public class MultiBranchStateMerger {

  /**
   * This merges the "toMergeState" state into the receiving state "intoState".
   *
   * <p>"id"s are NOT updated during the merge. it is is expected they are kept unchanged, the md5
   * is the natural key used for the merged. ids from toMergeState will be ignored, ids in intoState
   * will be kept as it.
   *
   * @param toMergeState the state to merge into intoState
   * @param intoState the state in which toMergeState will be merge into
   * @param priorityBranchNames list of priority branch names, they should be come first and in
   *     providing order when ordering branches
   * @return a new state result of merging toMergeState into intoState
   */
  public MultiBranchState merge(
      MultiBranchState toMergeState,
      MultiBranchState intoState,
      ImmutableSet<String> priorityBranchNames) {
    ImmutableSet<Branch> newBranches =
        mergeBranchesByPriorityThenCreatedDateThenName(
            intoState.getBranches(), toMergeState.getBranches(), priorityBranchNames);

    ImmutableMap<String, BranchStateTextUnit> intoStateUpdated =
        intoState.getBranchStateTextUnits().stream()
            .map(mergerMultiBranchStateIntoBranchStateTextUnit(toMergeState, newBranches))
            .collect(ImmutableMap.toImmutableMap(BranchStateTextUnit::getMd5, Function.identity()));

    ImmutableList<BranchStateTextUnit> fromToMergeStateNotInIntoState =
        toMergeState.getBranchStateTextUnits().stream()
            .filter(bstu -> !intoStateUpdated.containsKey(bstu.getMd5()))
            .collect(ImmutableList.toImmutableList());

    ImmutableList<BranchStateTextUnit> all =
        Stream.concat(intoStateUpdated.values().stream(), fromToMergeStateNotInIntoState.stream())
            .collect(ImmutableList.toImmutableList());

    return MultiBranchState.of().withBranches(newBranches).withBranchStateTextUnits(all);
  }

  public MultiBranchState removeBranch(MultiBranchState state, String branchName) {

    ImmutableSet<Branch> newBranches =
        state.getBranches().stream()
            .filter(b -> !branchName.equals(b.getName()))
            .collect(ImmutableSet.toImmutableSet());

    ImmutableList<BranchStateTextUnit> intoStateUpdated =
        state.getBranchStateTextUnits().stream()
            .map(
                intoStateTextUnit ->
                    intoStateTextUnit.withBranchNameToBranchDatas(
                        removeBranchByName(intoStateTextUnit, branchName)))
            .collect(ImmutableList.toImmutableList());

    return MultiBranchState.of()
        .withBranches(newBranches)
        .withBranchStateTextUnits(intoStateUpdated);
  }

  /**
   * Search inside the toMergeState for a text unit that match by md5 - If it exists, add the
   * branches (and their data) of that text unit to merge (could be in multiple branch but maybe not
   * in all branch of the merge state) into the "intoBranchStateTextUnit". --> to keep reccord of
   * all the branch in which that text unit is used - If it doesn't exist, remove all the branches
   * of the merge state from the "intoBranchStateTextUnit" --> this covers updates in a branch that
   * removes a text unit and potentially could lead it to be unused (no branch remaining)
   */
  Function<BranchStateTextUnit, BranchStateTextUnit> mergerMultiBranchStateIntoBranchStateTextUnit(
      MultiBranchState toMergeState, ImmutableSet<Branch> sortedBranches) {

    ImmutableMap<String, BranchStateTextUnit> toMergeStateBranchTextUnitsByMd5 =
        toMergeState.getBranchStateTextUnits().stream()
            .collect(ImmutableMap.toImmutableMap(BranchStateTextUnit::getMd5, Function.identity()));

    ImmutableMap<String, Branch> toMergeStateBranchNames =
        toMergeState.getBranches().stream()
            .collect(ImmutableMap.toImmutableMap(Branch::getName, Function.identity()));

    return intoBranchStateTextUnit -> {
      ImmutableMap<String, BranchData> branchNamesToBranchDatas;
      BranchStateTextUnit toMergeBranchStateTextUnit =
          toMergeStateBranchTextUnitsByMd5.get(intoBranchStateTextUnit.getMd5());

      if (toMergeBranchStateTextUnit == null) {
        branchNamesToBranchDatas =
            intoBranchStateTextUnit.getBranchNameToBranchDatas().entrySet().stream()
                .filter(
                    branchNameToBranchData ->
                        !toMergeStateBranchNames.containsKey(branchNameToBranchData.getKey()))
                .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
      } else {
        branchNamesToBranchDatas =
            Stream.concat(
                    intoBranchStateTextUnit.getBranchNameToBranchDatas().entrySet().stream(),
                    toMergeBranchStateTextUnit.getBranchNameToBranchDatas().entrySet().stream())
                .collect(
                    ImmutableMap.toImmutableMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (branchData1, branchData2) ->
                            // update the branchData by taking the newer entry from
                            // toMergeBranchStateTextUnit (stream order is key)
                            branchData2));
      }

      ImmutableMap<String, BranchData> branchNameToBranchDataUpdated =
          sortBranchDataByBranch(branchNamesToBranchDatas, sortedBranches);
      return intoBranchStateTextUnit.withBranchNameToBranchDatas(branchNameToBranchDataUpdated);
    };
  }

  ImmutableMap<String, BranchData> sortBranchDataByBranch(
      ImmutableMap<String, BranchData> branchNamesToBranchDatas,
      ImmutableSet<Branch> sortedBranches) {
    ImmutableList<String> sortedBranchNames =
        sortedBranches.stream().map(Branch::getName).collect(ImmutableList.toImmutableList());
    return branchNamesToBranchDatas.entrySet().stream()
        .sorted(
            Comparator.comparing(
                stringBranchDataEntry -> {
                  int idx = sortedBranchNames.indexOf(stringBranchDataEntry.getKey());
                  return idx == -1 ? Integer.MAX_VALUE : idx;
                }))
        .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
  }

  ImmutableMap<String, BranchData> removeBranchByName(
      BranchStateTextUnit intoStateTextUnit, String branchName) {
    return intoStateTextUnit.getBranchNameToBranchDatas().entrySet().stream()
        .filter(stringBranchDataEntry -> !branchName.equals(stringBranchDataEntry.getKey()))
        .collect(ImmutableMapCollectors.mapEntriesToImmutableMap());
  }

  /**
   * Merge 2 set of branches and order them accroding to {@lin
   * sortBranchesByPriorityThenCreatedDateThenName}.
   *
   * <p>Also dedup branch with same name and different timestamps by keeping the first encountered
   * entry
   *
   * @param branches1
   * @param branches2
   * @param priorityBranchNames
   * @return
   */
  ImmutableSet<Branch> mergeBranchesByPriorityThenCreatedDateThenName(
      ImmutableSet<Branch> branches1,
      ImmutableSet<Branch> branches2,
      ImmutableSet<String> priorityBranchNames) {

    Preconditions.checkNotNull(branches1);
    Preconditions.checkNotNull(branches2);
    Preconditions.checkNotNull(priorityBranchNames);

    ImmutableSet<Branch> collect =
        ImmutableSet.copyOf(
            Stream.concat(branches1.stream(), branches2.stream())
                .collect(
                    ImmutableMap.toImmutableMap(
                        Branch::getName, Function.identity(), (branch1, branch2) -> branch1))
                .values());

    return sortBranchesByPriorityThenCreatedDateThenName(collect, priorityBranchNames);
  }

  /**
   * Sort branches putting first priority branches (following the names order provided), then bey
   * createdAt and finally by name
   *
   * @param branches1
   * @param branches2
   * @param priorityBranchNames those branch will come first, in provided order
   * @return
   */
  ImmutableSet<Branch> sortBranchesByPriorityThenCreatedDateThenName(
      ImmutableSet<Branch> branches, ImmutableSet<String> priorityBranchNames) {

    Preconditions.checkNotNull(branches);
    Preconditions.checkNotNull(priorityBranchNames);

    ImmutableList<String> priorityBranchNamesAsList = priorityBranchNames.asList();
    ImmutableSet<Branch> sorted =
        branches.stream()
            .sorted(
                Comparator.comparing(
                        (Branch branch) -> {
                          int idx = priorityBranchNamesAsList.indexOf(branch.getName());
                          return idx == -1 ? Integer.MAX_VALUE : idx;
                        })
                    .thenComparing(
                        Branch::getCreatedAt, Comparator.nullsLast(Comparator.naturalOrder()))
                    .thenComparing(
                        Branch::getName, Comparator.nullsLast(Comparator.naturalOrder())))
            .collect(ImmutableSet.toImmutableSet());

    return sorted;
  }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Network.Models
{
    internal partial class LoadBalancerOutboundRuleListResult
    {
        internal static LoadBalancerOutboundRuleListResult DeserializeLoadBalancerOutboundRuleListResult(JsonElement element)
        {
            Optional<IReadOnlyList<OutboundRule>> value = default;
            Optional<string> nextLink = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("value"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<OutboundRule> array = new List<OutboundRule>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(OutboundRule.DeserializeOutboundRule(item));
                    }
                    value = array;
                    continue;
                }
                if (property.NameEquals("nextLink"))
                {
                    nextLink = property.Value.GetString();
                    continue;
                }
            }
            return new LoadBalancerOutboundRuleListResult(Optional.ToList(value), nextLink.Value);
        }
    }
}


text:
'use strict';

angular
  .module('SDLMSys')
  .controller('UserSearchCtrl', ['$scope', '$http', '$location', '$localStorage', 'SEARCH_HOST', UserSearchCtrl]);

function UserSearchCtrl($scope, $http, $location, $localStorage, SEARCH_HOST ) {

	console.log("Constructing UserSearchCtrl...");
	$scope.resultUsers = [];

	$scope.limits = 10;

	function clearPreviousResult()
	{
		$scope.errorLog = "";
		$scope.resultLog = "";
		$scope.resultUsers.splice(0,$scope.resultUsers.length);
	}

	$scope.getUsers = function(query)
	{
		clearPreviousResult();
		//var response = SearchSvc.searchUserSync(query, 0, $scope.limits);

		var searchURL = SEARCH_HOST.URL + '/doclib_main/User/' +  SEARCH_HOST.SINGLE_API + '?q=' + query + '&from=' + 0 + '&size=' +  $scope.limits;

		return $http.get(searchURL)
		.then(function(response) {
			//console.log(response);
			console.log(response);
			if ( response.status == 200 ) // successful
			{
				if (response.data)
				{
					var length = response.data.hits.hits.length;
					for (var i = 0; i < length; i++){
						$scope.resultUsers.push(response.data.hits.hits[i]._source);
					}
					//console.log($scope.resultUsers);
				}
			}
			else
			{
				//console.log(response.statusText);
				$scope.errorLog = response.statusText;
			}
			return $scope.resultUsers;
		});
    }

	$scope.selectUser = function($item, $model, $label, $event){
		$localStorage.lastSelectedItem = $item;
		$location.path('/controlpanel/' + $item.id);
	}

}


text:
package android.support.v4.os;

import android.os.Build;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.IOException;

/**
 * Helper for accessing features in {@link Environment} introduced after API
 * level 4 in a backwards compatible fashion.
 */
public class EnvironmentCompat {
    /**
     * Unknown storage state, such as when a path isn't backed by known storage
     * media.
     *
     * @see #getStorageState(File)
     */
    public static final String MEDIA_UNKNOWN = "unknown";
    private static final String TAG = "EnvironmentCompat";

    /**
     * Returns the current state of the storage device that provides the given
     * path.
     *
     * @return one of {@link #MEDIA_UNKNOWN}, {@link Environment#MEDIA_REMOVED},
     * {@link Environment#MEDIA_UNMOUNTED},
     * {@link Environment#MEDIA_CHECKING},
     * {@link Environment#MEDIA_NOFS},
     * {@link Environment#MEDIA_MOUNTED},
     * {@link Environment#MEDIA_MOUNTED_READ_ONLY},
     * {@link Environment#MEDIA_SHARED},
     * {@link Environment#MEDIA_BAD_REMOVAL}, or
     * {@link Environment#MEDIA_UNMOUNTABLE}.
     */
    public static String getStorageState(File path) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 19) {
            return EnvironmentCompatKitKat.getStorageState(path);
        }

        try {
            final String canonicalPath = path.getCanonicalPath();
            final String canonicalExternal = Environment.getExternalStorageDirectory()
                    .getCanonicalPath();

            if (canonicalPath.startsWith(canonicalExternal)) {
                return Environment.getExternalStorageState();
            }
        } catch (IOException e) {
            Log.w(TAG, "Failed to resolve canonical path: " + e);
        }

        return MEDIA_UNKNOWN;
    }
}


text:
#include <aws/lambda/model/EnvironmentError.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace Lambda
{
namespace Model
{

EnvironmentError::EnvironmentError() :
    m_errorCodeHasBeenSet(false),
    m_messageHasBeenSet(false)
{
}

EnvironmentError::EnvironmentError(JsonView jsonValue) :
    m_errorCodeHasBeenSet(false),
    m_messageHasBeenSet(false)
{
  *this = jsonValue;
}

EnvironmentError& EnvironmentError::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("ErrorCode"))
  {
    m_errorCode = jsonValue.GetString("ErrorCode");

    m_errorCodeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Message"))
  {
    m_message = jsonValue.GetString("Message");

    m_messageHasBeenSet = true;
  }

  return *this;
}

JsonValue EnvironmentError::Jsonize() const
{
  JsonValue payload;

  if(m_errorCodeHasBeenSet)
  {
   payload.WithString("ErrorCode", m_errorCode);

  }

  if(m_messageHasBeenSet)
  {
   payload.WithString("Message", m_message);

  }

  return payload;
}

} // namespace Model
} // namespace Lambda
} // namespace Aws


text:
from __future__ import division
import time
import sys

# Import the PCA9685 module.
import Adafruit_PCA9685

#inport paho mqtt
import paho.mqtt.client as mqtt

# Uncomment to enable debug output.
#import logging
#logging.basicConfig(level=logging.DEBUG)

# Initialise the PCA9685 using the default address (0x40).
pwm = Adafruit_PCA9685.PCA9685()

# Alternatively specify a different address and/or bus:
#pwm = Adafruit_PCA9685.PCA9685(address=0x41, busnum=2)

# Configure min and max servo pulse lengths
servo_min = 150  # Min pulse length out of 4096
servo_max = 550  # Max pulse length out of 4096

# Helper function to make setting a servo pulse width simpler.
def set_servo_pulse(channel, pulse):
    pulse_length = 1000000    # 1,000,000 us per second
    pulse_length //= 60       # 60 Hz
    print('{0}us per period'.format(pulse_length))
    pulse_length //= 4096     # 12 bits of resolution
    print('{0}us per bit'.format(pulse_length))
    pulse *= 1000
    pulse //= pulse_length
    pwm.set_pwm(channel, 0, pulse)

#print('Moving servo on channel 0, press Ctrl-C to quit...')
#while True:
    # Move servo on channel O between extremes.
#    pwm.set_pwm(0, 0, servo_min)
#    time.sleep(1)
#    pwm.set_pwm(0, 0, servo_max)
#    time.sleep(1)
#    pwm.set_pwm(1,0,300)

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("SERVO/OUT")
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))
    try:
        commando = msg.payload.split(":")
        channel = int(commando[0])
        valueToSet = int(commando[1])
        if (channel<0 or channel>16 or valueToSet<servo_min or valueToSet>servo_max):
            return
        pwm.set_pwm(channel,0,valueToSet)
    except (ValueError,IndexError):
        pass

#main
def main_entry_point():
    # Set frequency to 60hz, good for servos.
    pwm.set_pwm_freq(60)
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect("localhost", 1883, 60)
    client.loop_forever()

if __name__ == '__main__':
    main_entry_point()


text:
Version 2.0.27 by Volodymyr Volynets

	<time class="change_log_date_commit" datetime="2019-01-14">2019-01-14</time>

Framework

	Enhancement #1172 (Added tags.)

Repository / Git:
	Name: Numbers\Framework
	Title: Numbers Framework
	Version: 2.0.26
	Last Tag: 2.0.26
	User Name: Volodymyr Volynets
	User Email: volodymyr.volynets@gmail.com
Statistics:
	Addition: 3
	Deletion: 2
Modules:
	Numbers Framework (Numbers\Framework, 2.0.26)                                             |     3    2
		    1    1	 | Object/Table/Trait2.php
		    2    1	 | Object/Table/Widgets.php


text:
import plugins = require('./tools.plugins');
import paths = require('./tools.paths');
import { logger } from './tools.logging';

const installExec = async (packageNames: string[]) => {
  const smartshellInstance = new plugins.smartshell.Smartshell({
    executor: 'bash',
  });

  let installString = '';
  for (const packageName of packageNames) {
    logger.log('info', `Found ${packageName}!`);
    installString = installString + `${packageName} `;
  }
  // lets remove old packages
  const uninstallCommand = `npm uninstall -g ${installString}`;
  const installCommand = `npm install -g ${installString}`;
  logger.log('info', `uninstalling old packages with "${uninstallCommand}"`);
  await smartshellInstance.exec(uninstallCommand);
  logger.log('info', `installing tools with ${installCommand}`);
  await smartshellInstance.exec(installCommand);
  logger.log('ok', `installed tools successfully!`);
};

const packageLibrary = plugins.smartfile.fs.toObjectSync(
  plugins.path.join(paths.assetsDir, 'package_library.json')
);

export const install = async (packageSetArg: string) => {
  switch (packageSetArg) {
    case 'default':
      await installExec(packageLibrary.default);
      break;
    default:
      logger.log('warn', 'no set has been specified');
      break;
  }
};


text:
namespace base {
class FilePath;
}

namespace shell {

class AndroidHandler : public mojo::ApplicationDelegate,
                       public mojo::ContentHandlerFactory::Delegate {
 public:
  AndroidHandler();
  ~AndroidHandler();

 private:
  // mojo::ApplicationDelegate:
  void Initialize(mojo::ApplicationImpl* app) override;
  bool ConfigureIncomingConnection(
      mojo::ApplicationConnection* connection) override;

  // mojo::ContentHandlerFactory::Delegate:
  void RunApplication(
      mojo::InterfaceRequest<mojo::Application> application_request,
      mojo::URLResponsePtr response) override;

  void ExtractApplication(base::FilePath* extracted_dir,
                          base::FilePath* cache_dir,
                          mojo::URLResponsePtr response,
                          const base::Closure& callback);

  mojo::ContentHandlerFactory content_handler_factory_;
  mojo::URLResponseDiskCachePtr url_response_disk_cache_;
  scoped_refptr<base::SingleThreadTaskRunner> handler_task_runner_;

  MOJO_DISALLOW_COPY_AND_ASSIGN(AndroidHandler);
};

bool RegisterAndroidHandlerJni(JNIEnv* env);

}  // namespace shell

#endif  // MOJO_SHELL_ANDROID_CONTENT_HANDLER_H_


text:
package gwtquery.plugins.enhance.client.richtext.bundles;

import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;

public interface ToolbarImages extends ClientBundle {

  ImageResource bold();

  ImageResource createLink();

  ImageResource hr();

  ImageResource indent();

  ImageResource insertImage();

  ImageResource italic();

  ImageResource justifyCenter();

  ImageResource justifyLeft();

  ImageResource justifyRight();

  ImageResource ol();

  ImageResource outdent();

  ImageResource removeFormat();

  ImageResource removeLink();

  ImageResource strikeThrough();

  ImageResource subscript();

  ImageResource superscript();

  ImageResource ul();

  ImageResource underline();

  ImageResource backColors();

  ImageResource foreColors();

  ImageResource fonts();

  ImageResource fontSizes();
}


text:
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  template: '
johnny utah
',
  selector: 'tab-page'
})
export class TabPage {}

@Component({
  templateUrl: 'page.html',
  selector: 'api-demo-page',
  encapsulation: ViewEncapsulation.None,
  styles: [
    `
      ion-tabs {
        margin-bottom: 20px;
      }
    `,
    `
      ion-tabs,
      ion-tabs .tabbar {
        position: relative;
        top: auto;
        height: auto;
        visibility: visible;
        opacity: 1;
      }
    `
  ]
})
export class ApiDemoPage {
  root = TabPage;
}

@Component({
  template: '<ion-nav [root]="root"></ion-nav>',
  selector: 'api-demo-app'
})
export class ApiDemoApp {
  root = ApiDemoPage;
}


text:
#include <stdlib.h>
#include "mmpriv.h"

int mm_verbose = 1;
int mm_dbg_flag = 0;
double mm_realtime0;

#if defined(WIN32) || defined(_WIN32)
#include <windows.h>

struct timezone
{
  __int32  tz_minuteswest; /* minutes W of Greenwich */
  int  tz_dsttime;     /* type of dst correction */
};

/*
 * gettimeofday.c
 *    Win32 gettimeofday() replacement
 *    taken from PostgreSQL, according to
 *    https://stackoverflow.com/questions/1676036/what-should-i-use-to-replace-gettimeofday-on-windows
 *
 * src/port/gettimeofday.c
 *
 * Copyright (c) 2003 SRA, Inc.
 * Copyright (c) 2003 SKC, Inc.
 *
 * Permission to use, copy, modify, and distribute this software and
 * its documentation for any purpose, without fee, and without a
 * written agreement is hereby granted, provided that the above
 * copyright notice and this paragraph and the following two
 * paragraphs appear in all copies.
 *
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT,
 * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
 * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
 * DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS
 * IS" BASIS, AND THE AUTHOR HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE,
 * SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 */

/* FILETIME of Jan 1 1970 00:00:00. */
static const unsigned __int64 epoch = ((unsigned __int64) 116444736000000000ULL);

/*
 * timezone information is stored outside the kernel so tzp isn't used anymore.
 *
 * Note: this function is not for Win32 high precision timing purpose. See
 * elapsed_time().
 */
int gettimeofday(struct timeval * tp, struct timezone *tzp)
{
    FILETIME    file_time;
    SYSTEMTIME  system_time;
    ULARGE_INTEGER ularge;

    GetSystemTime(&system_time);
    SystemTimeToFileTime(&system_time, &file_time);
    ularge.LowPart = file_time.dwLowDateTime;
    ularge.HighPart = file_time.dwHighDateTime;

    tp->tv_sec = (long) ((ularge.QuadPart - epoch) / 10000000L);
    tp->tv_usec = (long) (system_time.wMilliseconds * 1000);

    return 0;
}

// taken from https://stackoverflow.com/questions/5272470/c-get-cpu-usage-on-linux-and-windows
double cputime()
{
	HANDLE hProcess = GetCurrentProcess();
	FILETIME ftCreation, ftExit, ftKernel, ftUser;
	SYSTEMTIME stKernel;
	SYSTEMTIME stUser;

	GetProcessTimes(hProcess, &ftCreation, &ftExit, &ftKernel, &ftUser);
	FileTimeToSystemTime(&ftKernel, &stKernel);
	FileTimeToSystemTime(&ftUser, &stUser);

	double kernelModeTime = ((stKernel.wHour * 60.) + stKernel.wMinute * 60.) + stKernel.wSecond * 1. + stKernel.wMilliseconds / 1000.;
	double userModeTime = ((stUser.wHour * 60.) + stUser.wMinute * 60.) + stUser.wSecond * 1. + stUser.wMilliseconds / 1000.;

	return kernelModeTime + userModeTime;
}

long peakrss(void) { return 0; }
#else
#include <sys/resource.h>
#include <sys/time.h>

double cputime(void)
{
	struct rusage r;
	getrusage(RUSAGE_SELF, &r);
	return r.ru_utime.tv_sec + r.ru_stime.tv_sec + 1e-6 * (r.ru_utime.tv_usec + r.ru_stime.tv_usec);
}

long peakrss(void)
{
	struct rusage r;
	getrusage(RUSAGE_SELF, &r);
#ifdef __linux__
	return r.ru_maxrss * 1024;
#else
	return r.ru_maxrss;
#endif
}

#endif /* WIN32 || _WIN32 */

double realtime(void)
{
	struct timeval tp;
	gettimeofday(&tp, NULL);
	return tp.tv_sec + tp.tv_usec * 1e-6;
}

void mm_err_puts(const char *str)
{
	int ret;
	ret = puts(str);
	if (ret == EOF) {
		perror("[ERROR] failed to write the results");
		exit(EXIT_FAILURE);
	}
}

void mm_err_fwrite(const void *p, size_t size, size_t nitems, FILE *fp)
{
	int ret;
	ret = fwrite(p, size, nitems, fp);
	if (ret == EOF) {
		perror("[ERROR] failed to write data");
		exit(EXIT_FAILURE);
	}
}

void mm_err_fread(void *p, size_t size, size_t nitems, FILE *fp)
{
	int ret;
	ret = fread(p, size, nitems, fp);
	if (ret == EOF) {
		perror("[ERROR] failed to read data");
		exit(EXIT_FAILURE);
	}
}

#include "ksort.h"

#define sort_key_128x(a) ((a).x)
KRADIX_SORT_INIT(128x, mm128_t, sort_key_128x, 8)

#define sort_key_64(x) (x)
KRADIX_SORT_INIT(64, uint64_t, sort_key_64, 8)

KSORT_INIT_GENERIC(uint32_t)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DynThings.Core
{
    public class SetupModels
    {
        public class DatabaseSetup
        {
            public String Server { get; set; }
            public string DatabaseName { get; set; }
            public string User { get; set; }
            public string Password { get; set; }

            public DatabaseSetup()
            {

            }
            public DatabaseSetup(string server,string database, string username,string password)
            {
                Server = server;
                DatabaseName = database;
                User = username;
                Password = password;
            }
        }

        public class PlatformConfig
        {
            public string Title { get; set; }
            public bool DevelopmentMode { get; set; }
            public bool PublicAccess { get; set; }
            public bool PublicSignUp { get; set; }
            public int TimeZone { get; set; }

        }

    }
}


text:
OpenVPN scripts
------------

Script for OpenVPN service which can add new users and authenticate they by the name/cert and password.

##### 1.0 Set the next parameters at your server config file:
    auth-user-pass-verify "/etc/openvpn/openvp_auth.py -v 1 -a" via-file
    script-security 2

##### 2.0   Then change the next parameter USERS_FILE in openvp_auth.py:
    USERS_FILE = "/etc/openvpn/users"  # user name and password hash will be store here (format - username:hash)

##### 3.0 After that execute the script(openvp_auth.py) with the next parameters: -v1 -g user:login
    ./openvp_auth.py -v1 -g user_test:qwerty

##### 4. Use credentials from step 3, for OpenVPN clients authentication via user name and password.
4.1 Add to OpenVPN clients configure file the next string:

    auth-user-pass /path/to/file/with/username_and_password

4.2 File format:

    cat /path/to/file/with/username_and_password
    ---------------------------------------------------------
    user_test
    qwerty
    ---------------------------------------------------------

##### 5.0 Default log file location:
    ---------------------------------------------------------
    /var/log/openvputils.log
    ---------------------------------------------------------

##### 6.0 Params:

    -h, --help          show this help message and exit
    -a --auth           recived from OpenVPN deamon path to file with user and password
    -g --generate       generate user and password; usage -g user:password
    -d, --disconnect    client disconnect
    -c, --create        create new table

##### Screenshot

###### Other:

[Firewall script](https://github.com/storytime/configs/blob/master/.other_configs/openvpn/scripts/fr.sh)


text:
---
published: true
title: Unit tests beyond Test Driven Development
layout: post
---

I'm not really a fan of Test Driven Development (TDD). All that write a failing test before the feature, then implement it until the test passes, gives me a feeling of the amount of hours spent on writing code without need.

That said, it doesn't mean I don't like Unit tests. Quite the opposite. I like them very much, and I think they're a very useful tool on your belt.

This is an example of how I sometimes use Unit tests on my day to day.

In one of those pesky summer days that almost resemble winter, for being so cold and rainy, I received a bug report saying that the user wasn't unable to subscribe his child named "João" that only has 2 months old, in order to start receiving the newsletter with baby stuff promotions. He tried with different browsers, but ended up always on the error page.

Well, say no more... Let's put it to the test (pun intended).

    [TestClass]
    public class BugReport_102
    {
        /*
         * User complains that he cannot subscribe his child with name "João" and age 0
         */

        [TestMethod]
        public void CanInvokeSubscribeWithBugReportData()
        {
            var userController = new UserController();
            var result = userController.Subscribe("joao@email.org", "João", 0) as ViewResult;
            Assert.AreEqual("Subscribe", result.ViewName);
        }
    }

Pretty simple test. We just invoke our controller with the request data. For demo only, we don't need to mock any dependency. That would fall out the scope of this article.

![unit test failing](http://www.kspace.pt/images/blog/bugreport_test_fail_zps6qvorojf.PNG)

There you go. Bug report replicated successfully. Now that we replicated the problem, it's easier to pin point the problem. Apparently, someone (the virtual me) forgot to double check the age when performing some rate per age.

![unit test pass](http://www.kspace.pt/images/blog/bugreport_test_pass_zpsaudqhnsw.PNG)

Done. Bug fixed. the best thing is that if you keep the test, you're ensuring that you don't have regressions on this particular bug.

Some may argue that this is very similar to TDD. I honestly disagree, mainly in the point that I don't like to write code without knowing if ever will going to be used.

## Is TDD a bad thing?

Of course not. It's a very good way to minimize bug within your application, and so, keeping the quality very high.

It's only my personal opinion that sometimes feels like we're writing lots of code, for simple stuff.

One might argue that writing the test before is cheaper than writing it afterwards, and maybe they're right...


text:
/* tslint:disable:max-line-length */
/**
 * Test Swagger
 * v1
 * example.com/api-base-path
 */

export interface UserDetails {
  readonly pk?: number;
  /** Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only. */
  username: string;
  /** format: email */
  readonly email?: string;
  first_name?: string;
  last_name?: string;
}


text:
from traits.api import HasPrivateTraits, List, Int,\
                                 Property, cached_property

class TestScores ( HasPrivateTraits ):

    scores  = List( Int )
    average = Property( depends_on = 'scores' )

    @cached_property
    def _get_average ( self ):
        s = self.scores
        print "Computing..."
        return (float( reduce( lambda n1, n2: n1 + n2, s, 0 ) )
                 / len( s ))

math_test = TestScores(scores=[80,77,99,85])
print math_test.scores
print math_test.average
print math_test.average
math_test.scores.append(55)
print math_test.average


text:
require 'spec_helper'

describe NewCommentPostman do
  describe 'delivers mail' do
    let!(:owner) { FactoryGirl.create(:user) }
    let!(:commenter) { FactoryGirl.create(:user) }
    let!(:proposta) { FactoryGirl.create(:proposta, user: owner) }
    let!(:follower1) { FactoryGirl.create(:user) }
    let!(:follower2) { FactoryGirl.create(:user) }
    let!(:seguido) { FactoryGirl.create(:seguido, user: follower1, topico: proposta) }
    let!(:seguido2) { FactoryGirl.create(:seguido, user: follower2, topico: proposta) }
    let!(:comment) { FactoryGirl.create(:comment, commentable: proposta, user: commenter) }
    let!(:postman) { NewCommentPostman.new(proposta, comment) }
    let!(:mail) { double('mail') }

    before do
      mail.should_receive(:deliver).exactly(3).times
    end

    it 'to topic owner' do
      TopicoMailer.should_receive(:new_comment).with(owner.id, proposta.id, comment.id).and_return(mail)
      TopicoMailer.should_receive(:new_comment).any_number_of_times.and_return(mail)

      postman.deliver
    end

    it 'to each follower' do
      TopicoMailer.should_receive(:new_comment).with(follower1.id, proposta.id, comment.id).and_return(mail)
      TopicoMailer.should_receive(:new_comment).with(follower2.id, proposta.id, comment.id).and_return(mail)
      TopicoMailer.should_receive(:new_comment).any_number_of_times.and_return(mail)

      postman.deliver
    end
  end
end


text:
/*
	elf-importer.hh - Imports ELF files
*/
#pragma once
#include "formats/common.hh"
#if defined(HAS_ELF)
#include <fstream>
namespace Nozoku {
	namespace Formats {
		class ELF_Importer {
		private:
		public:
			static ValidationResult Validate(std::ifstream& stream);

		};
	};
};
#endif


text:
<?php
namespace Concrete\DocumentationGenerator\Generator\Asset;

use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class VendorCssAssetListGenerator extends AbstractVendorAssetListGenerator
{

    /** @var string */
    protected $fileTypeSuffix = ".css";

    /** @var string */
    protected $vendorFileTypeSuffix = ".less";

    public function getHandle()
    {
        return "vendor_css_list";
    }

    /**
     * @return string
     */
    public function getBaseDirectory()
    {
        return DIR_BASE_CORE . "/css/build/vendor/";
    }

    /**
     * Output the asset
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @param string $handle
     * @param string $path
     * @param string $source
     * @return void
     */
    public function outputAsset(InputInterface $input, OutputInterface $output, $handle, $path, $source)
    {
        $output->writeln("`{$handle}` | `{$path}` | `/js/build/vendor/$source`");
    }

    /**
     * Output the title for this generator
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return void
     */
    public function outputTitle(InputInterface $input, OutputInterface $output)
    {
        $output->writeln("# Vendor CSS Assets", "");
    }

    /**
     * Output the header
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return void
     */
    public function outputHeader(InputInterface $input, OutputInterface $output)
    {
        $output->writeln(array(
            " Handle | Location | Source ",
            " ------ | -------- | ------ "));
    }

}


text:
package org.likelist.dao;
import java.util.List;

import org.likelist.po.EsjU2sComment;;

public interface ICommentDAO {
	public EsjU2sComment addComment(int shopId, String text, int uid);
	public long findCommentsCount(int shopId);
	public List<EsjU2sComment> findCommentsByPage(int shopId, int offset,
			int pageSize);
}


text:
package com.feragusper.buenosairesantesydespues.mapper;

import com.feragusper.buenosairesantesydespues.di.PerActivity;
import com.feragusper.buenosairesantesydespues.domain.model.HistoricalRecord;
import com.feragusper.buenosairesantesydespues.model.HistoricalRecordModel;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

import javax.inject.Inject;

/**
 * @author Fernando.Perez
 * @since 0.1
 * <p>
 * Mapper class used to transform {@link HistoricalRecord} (in the domain layer) to {@link HistoricalRecordModel} in the
 * presentation layer.
 */
@PerActivity
public class HistoricalRecordModelDataMapper {

    @Inject
    HistoricalRecordModelDataMapper() {
    }

    /**
     * Transform a Collection of {@link HistoricalRecord} into a Collection of {@link HistoricalRecordModel}.
     *
     * @param historicalRecordsCollection Objects to be transformed.
     * @return List of {@link HistoricalRecordModel}.
     */
    public Collection<HistoricalRecordModel> transform(Collection<HistoricalRecord> historicalRecordsCollection) {
        Collection<HistoricalRecordModel> historicalRecordModelsCollection;

        if (historicalRecordsCollection != null && !historicalRecordsCollection.isEmpty()) {
            historicalRecordModelsCollection = new ArrayList<>();
            for (HistoricalRecord historicalRecord : historicalRecordsCollection) {
                historicalRecordModelsCollection.add(transform(historicalRecord));
            }
        } else {
            historicalRecordModelsCollection = Collections.emptyList();
        }

        return historicalRecordModelsCollection;
    }

    /**
     * Transform a {@link HistoricalRecord} into an {@link HistoricalRecordModel}.
     *
     * @param historicalRecord Object to be transformed.
     * @return {@link HistoricalRecordModel}.
     */
    public HistoricalRecordModel transform(HistoricalRecord historicalRecord) {
        if (historicalRecord == null) {
            throw new IllegalArgumentException("Cannot transform a null value");
        }
        HistoricalRecordModel historicalRecordModel = new HistoricalRecordModel(historicalRecord.getHistoricalRecordId());
        historicalRecordModel.setTitle(historicalRecord.getTitle());
        historicalRecordModel.setDescription(historicalRecord.getDescription());
        historicalRecordModel.setCredits(historicalRecord.getCredits());
        historicalRecordModel.setLat(historicalRecord.getLat());
        historicalRecordModel.setLng(historicalRecord.getLng());
        historicalRecordModel.setYear(historicalRecord.getYear());
        historicalRecordModel.setNeighborhood(historicalRecord.getNeighborhood());
        historicalRecordModel.setAddress(historicalRecord.getAddress());
        historicalRecordModel.setImageURLBefore(historicalRecord.getImageURLBefore());
        historicalRecordModel.setImageURLAfter(historicalRecord.getImageURLAfter());
        historicalRecordModel.setThumbnail(historicalRecord.getThumbnail());
        historicalRecordModel.setShareURL(historicalRecord.getShareURL());

        return historicalRecordModel;
    }
}


text:
<form id="filterForm" class="form-horizontal">

              <button id="applyFilter" type="button" class="btn btn-secondary" ng-click="toggleFilters();">
                {{ 'OK' | translate }}
              </button>

                {{ 'ALL' | translate }}

                  <input type="radio" name="referral-radio" ng-model="referral.selection" ng-click="toggleReferral(this)" id="referral-all" value="all">

                {{ 'REFERRAL_REQUIRED' | translate }}

                  <input type="radio" name="referral-radio" ng-model="referral.selection" ng-click="toggleReferral(this)" id="referral-required" value="referral-required">

                {{ 'REFERRAL_NOT_REQUIRED' | translate }}

                  <input type="radio" name="referral-radio" ng-model="referral.toggleSelectionselection" ng-click="toggleReferral(this)" id="referral-not-required" value="referral-not-required">

{{ 'NATIONALITY' | translate }}

              {{ nation }}

                <input type="checkbox" ng-click="toggleNationality(nation)" value="">

      </form>


text:
from __future__ import unicode_literals, print_function

__author__ = 'ufian'

import config
import telepot
import time
import mongoengine as me
import datetime

from telepot.loop import MessageLoop
from telepot.delegate import per_chat_id, per_callback_query_chat_id, create_open, pave_event_space
from telepot.namedtuple import InlineQueryResultArticle, InputTextMessageContent, \
    InlineKeyboardMarkup, InlineKeyboardButton, \
    ReplyKeyboardMarkup, KeyboardButton

import utils as u
import model
import stages as st
import calculator as calc

class CCalException(Exception):
    pass

def get_connect():
    return me.connect(
        config.DB['db'],
        host=config.DB['host'],
        port=config.DB['port'],
        serverSelectionTimeoutMS=2500
    )

class EatSession(telepot.helper.ChatHandler):
    STAGES = {
        st.DEFAULT: st.DefaultStage,
        st.PRODUCT: st.ProductStage,
        st.EAT: st.EatStage,
        st.STAT: st.StatStage,
        st.TODAY: st.TodayStage,
    }

    @property
    def context(self):
        return self.user_config.context

    @property
    def user_data(self):
        return self.user_config.data

    @property
    def db(self):
        return getattr(get_connect(), config.DB['db'])

    def stage(self, new_stage=None):
        stage = new_stage or self.context.get('stage', st.DEFAULT)
        if stage not in self.STAGES:
            stage = st.DEFAULT

        self.context['stage'] = stage
        return self.STAGES[stage](self)

    def save_message(self, msg, skip_reply=False):
        user_id = u.get_user_id(msg)
        msg_copy = msg.copy()
        msg_copy['date'] = datetime.datetime.utcnow()
        self.db.messages.insert_one(msg_copy)
        if not skip_reply:
            self.sendMessage(user_id, 'Дамп из телегарма сохранен')

    def open(self, initial_msg, seed):
        self.user_id = seed
        self.user_config = model.UserConfig.objects.filter(user_id=self.user_id).first()
        print("Load ", self.user_config, 'by', seed)
        if self.user_config is None:
            self.user_config = model.UserConfig(user_id=self.user_id)
            self.user_config.save()

        if self.user_config.context is None:
            self.user_config.context = dict()

        if self.user_config.data is None:
            self.user_config.data = dict()

        return False

    def on_chat_message(self, msg):
        self.save_message(msg, skip_reply=True)

        self.stage().on_chat_message(msg, u.get_text(msg))

    def on_callback_query(self, msg):
        self.save_message(msg, skip_reply=True)
        cb_data = u.get_callback_data(msg)
        stage, sep, cb_data = cb_data.partition('|')
        if sep != '|':
            cb_data = stage
            stage = None

        self.context['cb_message'] = u.get_edit_id(msg['message'])
        self.stage(stage).on_callback_query(msg, cb_data)

    def on_close(self, ex):
        # st.DEFAULT -> fix message
        stage = self.stage(st.DEFAULT)
        if 'last_message' in self.context:
            stage.base_message('Finish', update_msg=self.context['last_message'])

        if 'cb_message' in self.context and self.context['cb_message'] != self.context.get('last_message'):
            stage.base_message(
                'Finish',
                update_msg=self.context['cb_message'],
                with_keyboard= 'last_message' not in self.context
            )

        if 'last_message' in self.context:
            self.user_config.data['last_message'] = self.context['last_message']

        self.user_config.context = dict()
        self.user_config.save()

if __name__ == '__main__':
    conn = get_connect()
    params = list(model.GlobalConfig.objects.timeout(True))

    bot = telepot.DelegatorBot(config.BOT_TOKEN, [
        pave_event_space()(
            [per_chat_id(('private',)), per_callback_query_chat_id(('private',))],
            create_open,
            EatSession,
            include_callback_query=True, timeout=300),
    ])

    MessageLoop(bot).run_as_thread()
    print('Listening ...')

    while 1:
        time.sleep(10)


text:
package app.model.Dummy.Plantain;

import app.fw.commons.PropertiesInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.soap.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by asmodei on 20.08.2017.
 */
public class PlantainCommons {
    private final Logger LOG = LoggerFactory.getLogger(this.getClass());

    public String key1;
    public String key2;

    public PlantainCommons() {
        this.key1 =  PropertiesInitializer.properties.get("plantain.key1");
        this.key2 =  PropertiesInitializer.properties.get("plantain.key2");
    }

    Map<String, String> headers;
    public String uri = "http://example.org/";
    public String nameSpace = "exam";

    public Map<String, String> getHeaders(String operation) {
        headers = new HashMap<>();
        headers.put("SOAPAction", String.format("\"http://example.org/%s\"",operation));
        headers.put("Content-Type","text/xml;charset=UTF-8");
        return headers;
    }
    public MessageFactory initMessageFactory(){
        MessageFactory messageFactory = null;
        try {
            messageFactory = MessageFactory.newInstance();
        } catch (SOAPException e) {
            LOG.info("Невозможно инициализировать Фабрику");
            e.printStackTrace();
        }
        return messageFactory;
    }
    public SOAPMessage initSOAPMessage(){
        SOAPMessage soapMessage = null;
        try {
            soapMessage = initMessageFactory().createMessage();
        } catch (SOAPException e) {
            LOG.info("Невозможно создать тело для сообщения");
            e.printStackTrace();
        }
        return soapMessage;
    }
    public SOAPEnvelope initSOAPEnvelope(SOAPPart soapPart) {
        SOAPEnvelope envelope = null;
        try {
            envelope = soapPart.getEnvelope();
        } catch (SOAPException e) {
            LOG.info("Невозможно инициализировать Envelope");
            e.printStackTrace();
        }
        try {
            envelope.addNamespaceDeclaration(nameSpace, uri);
        } catch (SOAPException e) {
            LOG.info(String.format("Невозможно добавить пространство имени %s с параметром %s", nameSpace, uri));
            e.printStackTrace();
        }
        return envelope;
    }

    public SOAPEnvelope initSOAPEnvelopeCreate(SOAPPart soapPart) {
        SOAPEnvelope envelope = null;
        try {
            envelope = soapPart.getEnvelope();
        } catch (SOAPException e) {
            LOG.info("Невозможно инициализировать Envelope");
            e.printStackTrace();
        }
        try {
            envelope.addNamespaceDeclaration(nameSpace, uri);
        } catch (SOAPException e) {
            LOG.info(String.format("Невозможно добавить пространство имени %s с параметром %s", nameSpace, uri));
            e.printStackTrace();
        }
        return envelope;
    }

    public String convertToString(SOAPMessage soapMessage){
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        String result = null;
        try {
            soapMessage.writeTo(stream);
        } catch (SOAPException e) {
            e.printStackTrace();
        } catch (IOException e) {
            LOG.info("Невозможно осуществить запись в поток");
            e.printStackTrace();
        }
        try {
            result = new String(stream.toByteArray(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            LOG.info("Ошибка при попытке записи в переменную. Кодировка utf-8");
        }
        return result;
    }
    public static Boolean notNull(String value){return value != null;}
    public static Boolean isEmpty(String value){return value.equals("");}

    public static String getMD5HexHash(String stringForHashing) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(stringForHashing.getBytes());
        byte[] digest = md.digest();
        StringBuffer sb = new StringBuffer();
        for (byte b : digest) {
            sb.append(String.format("%02x",b));
        }
        String resultHash = sb.toString();
        return resultHash;
    }

}


text:
package services

import play.api.libs.json.{JsBoolean, JsObject, JsString, JsValue}

/**
  * Object to house some common used constants and methods.
  */
object Constants {

  val ServerConfig: (String, String) = ("/_server.config.json", "/_server.config.example.json")

  val AppConfig: (String, String) = ("/app.config.json", "/app.config.example.json")
  val ProfileConfig: (String, String) = ("/profile.config.json", "/profile.config.example.json")
  val WorkHistoryConfig: (String, String) = ("/work-history.config.json", "/work-history.config.example.json")
  val FeaturedProjectsConfig: (String, String) = ("/featured-projects.config.json", "/featured-projects.config.example.json")
  val LangsFramesConfig: (String, String) = ("/langs-frames.config.json", "/langs-frames.config.example.json")
  val ArticlesConfig: (String, String) = ("/articles.config.json", "/articles.config.example.json")

  val CreditsConfig: (String, String) = ("/credits.config.json", "/credits.config.example.json")
  val GithubConfig: (String, String) = ("/github.config.json", "/github.config.example.json")

  /**
    * Creates the standard format for json returned to the user when a failure occured.
    *
    * @param message - The message to display.
    * @return - Returns a [[JsObject]] with the given message and the value success as false.
    */
  def failMessage(message: String): JsObject = JsObject(Seq(
    "success" -> JsBoolean(false),
    "message" -> JsString(message)
  ))

  /**
    * @see [[failMessage()]]
    * @param data - The data to render.
    */
  def succMessage(data: JsValue): JsObject = JsObject(Seq(
    "success" -> JsBoolean(true),
    "data" -> data
  ))

}


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Caliburn.Micro;
using Features.CrossPlatform.Messages;

namespace Features.CrossPlatform.ViewModels.Events
{
    public class EventDestinationViewModel : Screen, IHandle<SimpleMessage>
    {
        private readonly IEventAggregator eventAggregator;

        public EventDestinationViewModel(IEventAggregator eventAggregator)
        {
            this.eventAggregator = eventAggregator;

            Messages = new BindableCollection<SimpleMessage>();
        }

        public void Subscribe()
        {
            eventAggregator.SubscribeOnPublishedThread(this);
        }

        public void Unsubscribe()
        {
            eventAggregator.Unsubscribe(this);
        }

        public Task HandleAsync(SimpleMessage message, CancellationToken cancellationToken)
        {
            Messages.Add(message);

            return Task.FromResult(true);
        }

        public BindableCollection<SimpleMessage> Messages { get; }
    }
}


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

namespace RM.QuickLogOn.OAuth.RU.ViewModels
{
    public class OdnoklassnikiUserInfoJsonModel
    {
        public string uid { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
    }
}


text:
<template name="mugenRoleGroups_form">
    <form id="mugenRoleGroups_form">

Name *
<input type="text" id="name" value="{{name}}" placeholder="Name" class="form-control">
{{error "name"}}

        <button id="btnSave" type="submit" class="btn btn-success">Ingresar</button>
        Atras
    </form>
</template>


text:
require 'json'
require 'pathname'
require 'rest-client'
require 'ruby-progressbar'
require 'vcr'

require './movie_page_scraper.rb'
require './movie.rb'
require './vcr_config'

# Calculates statistics on Edgar Wright's 1000 favorite movies on mubi.com
# rubocop:disable ClassLength
class Mubi
  def initialize
    movie_list_json
    movie_list

    generate_histogram_methods
    generate_histogram_write_methods
  end

  def formatted_runtime
    seconds = total_runtime * 60
    # Extract days of the year to strip 0 padding
    days = Time.at(seconds).utc.strftime('%j').to_i

    Time.at(seconds).utc.strftime("#{days} days, %H hours, and %M minutes.")
  end

  # Attribute methods

  # rubocop:disable MethodLength
  def movie_list_json
    @movie_list_json ||= VCR.use_cassette 'mubi_list_films' do
      # Each page has 48 movies, 1000 movies total
      pages = (1000 / 48.0).ceil

      progressbar = ProgressBar.create \
        title: 'Fetching Movie List ',
        total: pages

      json = (1..pages).map do |page|
        progressbar.increment

        JSON.parse RestClient.get \
          'https://mubi.com/services/api/lists/108835/list_films',
          params: { page: page }
      end

      progressbar.finish

      # There shouldn't be any duplicates, but just in case
      json.flatten.uniq
    end
  end

  # Constructs a Movie object for each one in Edgar's top 1000
  # rubocop:disable AbcSize
  def movie_list
    @movie_list ||= VCR.use_cassette 'mubi_list_film_pages' do
      progressbar = ProgressBar.create \
        title: 'Scraping Movie Pages',
        total: movie_list_json.length

      movie_list = movie_list_json.each.map do |m|
        progressbar.increment

        s = MoviePageScraper.new m['film_id']

        Movie.new \
          id: m['film_id'],
          title: m['film']['title'],
          directors: m['film']['directors'].map { |d| d['name'] },
          release_country: s.release_country,
          release_year: m['film']['year'],
          genres: s.genres,
          runtime: s.runtime,
          synopsis: s.synopsis,
          rating: s.rating
      end

      progressbar.finish

      movie_list
    end
  end

  # In minutes
  def total_runtime
    @total_runtime ||= movie_list.map(&:runtime).reduce(0, :+)
  end

  def write_all_histograms
    HIST_ATTRIBUTES.each do |a|
      send "#{unpluralize a}_histogram_write"
    end

    nil
  end

  private

  HIST_ATTRIBUTES = %w(
    directors
    release_year
    release_country
    genres
    runtime
    synopsis_words
    rating
  ).freeze

  # Make methods for making histograms of the appropriate Movie attributes
  def generate_histogram_methods
    HIST_ATTRIBUTES.each do |a|
      method_name = "#{unpluralize a}_histogram"
      instance_variable_name = "@#{method_name}"

      define_singleton_method method_name do
        memoized_result = memoize instance_variable_name do
          hist = Hash.new 0
          # Array of attributes corresponding to the method name
          array = movie_list.map { |m| m.send a }

          array.flatten.each { |e| hist[e] += 1 }
          Hash[hist.sort_by { |_, v| v }.reverse]
        end

        instance_variable_set instance_variable_name, memoized_result
      end
    end
  end

  def generate_histogram_write_methods
    project_root = Pathname.pwd.parent
    data_dir = project_root.join('stats').join('data')
    Dir.mkdir data_dir unless Dir.exist? data_dir

    HIST_ATTRIBUTES.each do |a|
      unpluralized_attribute = unpluralize a
      method_base = "#{unpluralized_attribute}_histogram"

      define_singleton_method "#{method_base}_write" do
        File.open data_dir.join(unpluralized_attribute), 'w' do |file|
          hist = send method_base

          file.write unpluralized_attribute
          file.write ' count'
          file.write "\n"

          hist.each_pair do |k, v|
            write_stat_line file, k, v
          end
        end

        nil
      end
    end
  end

  # Avoids recalculation if the instance variable is already defined
  def memoize(instance_variable_name)
    if instance_variable_defined? instance_variable_name
      instance_variable_get instance_variable_name
    else
      yield
    end
  end

  def unpluralize(word)
    return word.chop if word.end_with? 's'
    word
  end

  def write_stat_line(file, stat, value)
    file.write "\"#{stat}\""
    file.write ' '
    file.write value
    file.write "\n"
  end
end


text:
<title>
Waging war over resources
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

Waging war over resources

BOOKS: Michael T. Klare, Resource Wars: The New Landscape of Global Conflict, Metropolitan Books, 289 pages, 2001, $26.

Review by Ashley Smith | December 7, 2001 | Page 9

U.S. LEADERS say that the war is about wiping out terrorism. But their bombs terrorize innocent Afghan people. They say it's about liberating people from the Taliban. Yet they support Northern Alliance warlords who wrecked the country in the early 1990s.

Anyone who sees the contradictions is asking, what's this war really about? Michael Klare's new book, Resource Wars, helps to answer this question.

He argues that conflicts in the world today stem from competition between countries over diminishing and essential resources, such as oil and water.

He discounts the fashionable view that war is the result of a clash of civilizations, between the Christian West and the Islamic world for instance.

Klare argues that, in place of the political and ideological conflict that characterized international relations during the Cold War, nations today have returned to a pattern of economic, political and military competition over vital resources typical in the first half of the 20th century.

Klare's discussion of the conflicts over oil in the Persian Gulf and the Caspian Sea reveals the central driving motives of U.S. policy in the current war. Therefore, the U.S. has established bases, pre-positioned war materiel and made plans for U.S. intervention to protect oil reserves in the Persian Gulf. As Gen. Anthony Zinni told Congress in 1999, "With over 65 percent of the world's oil reserves located within the Gulf states [the U.S.] must have free access to the region's resources."

Klare shows how the U.S., in the wake of the Gulf War, has prepared for war to secure the region along three fronts: enforcing genocidal sanctions and conducting relentless bombing against Iraq, establishing a military plan to prevent Iran from threatening U.S. control of the oil shipping lanes in the Strait of Hormuz, and funneling weapons and establishing military bases to protect the Saudi regime. The U.S. has thus established itself as the main overlord in the region.

At the same time, the U.S. has attempted to seize control of oil reserves in the Caspian Sea region of Central Asia as an alternative to the Persian Gulf. One of the underlying motives for the U.S. intervention in Afghanistan is stabilizing the country for a potential pipeline for Caspian Sea oil and establishing military bases throughout Central Asia to enforce U.S. policy.

Meanwhile, other powers--Russia, China and Iran--pursue similar aims. While the current war has papered over these underlying conflicts, they could easily reemerge.

In a stunning prediction written before the war, Klare writes that the various powers "may find themselves in a situation where their vital interests appear at risk and direct military involvement seems to offer the only solution. In this manner, the Caspian could prove the setting for a major regional conflagration."

Klare's model of the resource war is flawed when applied to those wars that can't be reduced to conflicts over resources, such as U.S. interventions in Kosovo, Somalia and Haiti. These had more to do with the U.S. asserting regional control and checking other powers. Without an understanding of this, Klare offers solutions--such as cooperation between nations and using the United Nations--that won't work.

Still, Resource Wars provides a wealth of information to cut through the lies that justify U.S. war aims.

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>