text:
package strings

import (
	"encoding/base64"
	"strings"
	"unicode"
	"unicode/utf8"

	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/plugins/processors"
)

type Strings struct {
	Lowercase    []converter `toml:"lowercase"`
	Uppercase    []converter `toml:"uppercase"`
	Titlecase    []converter `toml:"titlecase"`
	Trim         []converter `toml:"trim"`
	TrimLeft     []converter `toml:"trim_left"`
	TrimRight    []converter `toml:"trim_right"`
	TrimPrefix   []converter `toml:"trim_prefix"`
	TrimSuffix   []converter `toml:"trim_suffix"`
	Replace      []converter `toml:"replace"`
	Left         []converter `toml:"left"`
	Base64Decode []converter `toml:"base64decode"`
	ValidUTF8    []converter `toml:"valid_utf8"`

	converters []converter
	init       bool
}

type ConvertFunc func(s string) string

type converter struct {
	Field       string
	FieldKey    string
	Tag         string
	TagKey      string
	Measurement string
	Dest        string
	Cutset      string
	Suffix      string
	Prefix      string
	Old         string
	New         string
	Width       int
	Replacement string

	fn ConvertFunc
}

func (c *converter) convertTag(metric telegraf.Metric) {
	var tags map[string]string
	if c.Tag == "*" {
		tags = metric.Tags()
	} else {
		tags = make(map[string]string)
		tv, ok := metric.GetTag(c.Tag)
		if !ok {
			return
		}
		tags[c.Tag] = tv
	}

	for key, value := range tags {
		dest := key
		if c.Tag != "*" && c.Dest != "" {
			dest = c.Dest
		}
		metric.AddTag(dest, c.fn(value))
	}
}

func (c *converter) convertTagKey(metric telegraf.Metric) {
	var tags map[string]string
	if c.TagKey == "*" {
		tags = metric.Tags()
	} else {
		tags = make(map[string]string)
		tv, ok := metric.GetTag(c.TagKey)
		if !ok {
			return
		}
		tags[c.TagKey] = tv
	}

	for key, value := range tags {
		if k := c.fn(key); k != "" {
			metric.RemoveTag(key)
			metric.AddTag(k, value)
		}
	}
}

func (c *converter) convertField(metric telegraf.Metric) {
	var fields map[string]interface{}
	if c.Field == "*" {
		fields = metric.Fields()
	} else {
		fields = make(map[string]interface{})
		fv, ok := metric.GetField(c.Field)
		if !ok {
			return
		}
		fields[c.Field] = fv
	}

	for key, value := range fields {
		dest := key
		if c.Field != "*" && c.Dest != "" {
			dest = c.Dest
		}
		if fv, ok := value.(string); ok {
			metric.AddField(dest, c.fn(fv))
		}
	}
}

func (c *converter) convertFieldKey(metric telegraf.Metric) {
	var fields map[string]interface{}
	if c.FieldKey == "*" {
		fields = metric.Fields()
	} else {
		fields = make(map[string]interface{})
		fv, ok := metric.GetField(c.FieldKey)
		if !ok {
			return
		}
		fields[c.FieldKey] = fv
	}

	for key, value := range fields {
		if k := c.fn(key); k != "" {
			metric.RemoveField(key)
			metric.AddField(k, value)
		}
	}
}

func (c *converter) convertMeasurement(metric telegraf.Metric) {
	if metric.Name() != c.Measurement && c.Measurement != "*" {
		return
	}

	metric.SetName(c.fn(metric.Name()))
}

func (c *converter) convert(metric telegraf.Metric) {
	if c.Field != "" {
		c.convertField(metric)
	}

	if c.FieldKey != "" {
		c.convertFieldKey(metric)
	}

	if c.Tag != "" {
		c.convertTag(metric)
	}

	if c.TagKey != "" {
		c.convertTagKey(metric)
	}

	if c.Measurement != "" {
		c.convertMeasurement(metric)
	}
}

func (s *Strings) initOnce() {
	if s.init {
		return
	}

	s.converters = make([]converter, 0)
	for _, c := range s.Lowercase {
		c.fn = strings.ToLower
		s.converters = append(s.converters, c)
	}
	for _, c := range s.Uppercase {
		c.fn = strings.ToUpper
		s.converters = append(s.converters, c)
	}
	for _, c := range s.Titlecase {
		c.fn = strings.Title
		s.converters = append(s.converters, c)
	}
	for _, c := range s.Trim {
		c := c
		if c.Cutset != "" {
			c.fn = func(s string) string { return strings.Trim(s, c.Cutset) }
		} else {
			c.fn = func(s string) string { return strings.TrimFunc(s, unicode.IsSpace) }
		}
		s.converters = append(s.converters, c)
	}
	for _, c := range s.TrimLeft {
		c := c
		if c.Cutset != "" {
			c.fn = func(s string) string { return strings.TrimLeft(s, c.Cutset) }
		} else {
			c.fn = func(s string) string { return strings.TrimLeftFunc(s, unicode.IsSpace) }
		}
		s.converters = append(s.converters, c)
	}
	for _, c := range s.TrimRight {
		c := c
		if c.Cutset != "" {
			c.fn = func(s string) string { return strings.TrimRight(s, c.Cutset) }
		} else {
			c.fn = func(s string) string { return strings.TrimRightFunc(s, unicode.IsSpace) }
		}
		s.converters = append(s.converters, c)
	}
	for _, c := range s.TrimPrefix {
		c := c
		c.fn = func(s string) string { return strings.TrimPrefix(s, c.Prefix) }
		s.converters = append(s.converters, c)
	}
	for _, c := range s.TrimSuffix {
		c := c
		c.fn = func(s string) string { return strings.TrimSuffix(s, c.Suffix) }
		s.converters = append(s.converters, c)
	}
	for _, c := range s.Replace {
		c := c
		c.fn = func(s string) string {
			newString := strings.Replace(s, c.Old, c.New, -1)
			if newString == "" {
				return s
			}

			return newString
		}
		s.converters = append(s.converters, c)
	}
	for _, c := range s.Left {
		c := c
		c.fn = func(s string) string {
			if len(s) < c.Width {
				return s
			}

			return s[:c.Width]
		}
		s.converters = append(s.converters, c)
	}
	for _, c := range s.Base64Decode {
		c := c
		c.fn = func(s string) string {
			data, err := base64.StdEncoding.DecodeString(s)
			if err != nil {
				return s
			}
			if utf8.Valid(data) {
				return string(data)
			}
			return s
		}
		s.converters = append(s.converters, c)
	}
	for _, c := range s.ValidUTF8 {
		c := c
		c.fn = func(s string) string { return strings.ToValidUTF8(s, c.Replacement) }
		s.converters = append(s.converters, c)
	}

	s.init = true
}

func (s *Strings) Apply(in ...telegraf.Metric) []telegraf.Metric {
	s.initOnce()

	for _, metric := range in {
		for _, converter := range s.converters {
			converter.convert(metric)
		}
	}

	return in
}

func init() {
	processors.Add("strings", func() telegraf.Processor {
		return &Strings{}
	})
}


text:
using System;
using System.Reflection.Emit;
using Xunit;

namespace UnitTests.Snippets
{
    public sealed class DynamicMethodSnippet
    {
        [Fact]
        public void Snippet()
        {
            CallDynamicMethod();
        }

        private static void CallDynamicMethod()
        {
            var multiplyMethod = new DynamicMethod("MultiplyMethod", typeof(int), new[] { typeof(int) },
                typeof(ForTests).Module);

            ILGenerator multiplyMethodIL = multiplyMethod.GetILGenerator();

            multiplyMethodIL.Emit(OpCodes.Ldarg_0);
            multiplyMethodIL.Emit(OpCodes.Ldc_I4, 2);
            multiplyMethodIL.Emit(OpCodes.Mul);
            multiplyMethodIL.Emit(OpCodes.Ret);

            var calculateMethod = new DynamicMethod("CalculateMethod", typeof(int), new[] { typeof(int), typeof(int) },
                typeof(ForTests).Module);

            ILGenerator calculateMethodIL = calculateMethod.GetILGenerator();

            calculateMethodIL.Emit(OpCodes.Ldarg_0);
            calculateMethodIL.Emit(OpCodes.Ldarg_1);
            calculateMethodIL.Emit(OpCodes.Mul);
            calculateMethodIL.Emit(OpCodes.Call, multiplyMethod);
            calculateMethodIL.Emit(OpCodes.Ret);

            var calcMethodDelegate = (Func<int, int, int>)calculateMethod.CreateDelegate(typeof(Func<int, int, int>));
            int result = calcMethodDelegate(10, 10);

            Console.WriteLine(result);
        }

        public sealed class A
        {
        }

        public sealed class B
        {
            public void Method()
            {
                var x = Cast<A>(this);
                //                var x = this as A;
            }

            private static T Cast<T>(object value)
                where T : class
            {
                var method = new DynamicMethod("CastMethod", typeof(T), new[] { typeof(object) });
                ILGenerator il = method.GetILGenerator();

                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Isinst, typeof(T));
                il.Emit(OpCodes.Ret);

                var methodDelegate = (Func<object, T>)method.CreateDelegate(typeof(Func<object, T>));
                return methodDelegate(value);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text: make install_prefix=$PREFIX install


text:
{-# LANGUAGE OverloadedStrings #-}
-- This example shows how to run a CPU-intensive thread in the
-- background while keeping the UI responsive.  All FLTK calls are
-- done on the main thread.
--
-- Press the "start background thread" button to start the
-- CPU-intensive thread.  Then observe that clicking the "increment"
-- button remains responsive.

module Main where

import qualified Graphics.UI.FLTK.LowLevel.FL as FL
import Graphics.UI.FLTK.LowLevel.Fl_Types
import Graphics.UI.FLTK.LowLevel.FLTKHS

import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception (evaluate)
import Control.Monad
import Data.IORef
import qualified Data.Text as T
main :: IO ()
main = do
  -- Set up the window and widgets.
  w <- windowNew (Size (Width 260) (Height 110)) Nothing Nothing
  startButton <- buttonNew (Rectangle (Position (X 15) (Y 10)) (Size (Width 230) (Height 25))) (Just "start background thread")
  b <- outputNew (Rectangle (Position (X 135) (Y 40)) (Size (Width 110) (Height 25))) (Just "primes ") (Just FlNormalOutput)
  button <- buttonNew (Rectangle (Position (X 15) (Y 75)) (Size (Width 110) (Height 25))) (Just "increment")
  counter <- outputNew (Rectangle (Position (X 135) (Y 75)) (Size (Width 110) (Height 25)))  Nothing (Just FlNormalOutput)
  clearVisibleFocus b
  clearVisibleFocus counter

  -- The communication channel between the CPU-heavy thread and the
  -- main thread.
  c <- newTChanIO

  -- When the start button is pressed, start the CPU-heavy thread.
  setCallback startButton $ \_ -> do
    void $ forkIO $ computationThread c

  -- Start the click counter at zero.
  counterRef <- newIORef (0 :: Integer)
  _ <- setValue counter (T.pack (show (0 :: Integer)))

  -- When the button is pressed, increment the counter and update the
  -- label.
  setCallback button $ \_ -> do
    modifyIORef counterRef (+1)
    x <- readIORef counterRef
    void $ setValue counter (T.pack (show x))

  -- Every so often, check for messages from our worker thread.
  FL.addTimeout 0.025 (tick b c)

  -- Start the UI.
  showWidget w
  _ <- FL.run
  return ()

-- Check for a message from our worker thread.  If there is a message,
-- gobble all the messages up and set the label to the contents on the
-- most recent message.
tick :: Ref Output -> TChan Integer -> IO ()
tick b c = do
  mx <- atomically $ tryReadTChan c
  case mx of
    Nothing -> return ()
    Just x -> inner x
  _ <- FL.repeatTimeout 0.025 (tick b c)
  return ()
  where inner x = do
          mx <- atomically $ tryReadTChan c
          case mx of
            Nothing -> void $ setValue b (T.pack (show x))
            Just x' -> inner x'

-- Very slow prime-testing predicate.
isPrime :: Integer -> Bool
isPrime 1 = False
isPrime x = not $ any (\y -> x `mod` y == 0) [2..x-1]

-- Write prime numbers to a channel forever.
computationThread :: TChan Integer -> IO ()
computationThread channel = do
  let primes = filter isPrime [1000000..]
  forM_ primes $ \p -> do
    _ <- evaluate p
    atomically $ writeTChan channel p


text:
// Copyright (c) 2012 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.

#ifndef CONTENT_COMMON_CHILD_THREAD_H_
#define CONTENT_COMMON_CHILD_THREAD_H_

#include "base/basictypes.h"
#include "base/platform_file.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/shared_memory.h"
#include "base/tracked_objects.h"
#include "content/common/content_export.h"
#include "content/common/message_router.h"
#include "ipc/ipc_message.h"  // For IPC_MESSAGE_LOG_ENABLED.
#include "ipc/ipc_platform_file.h"
//FIXME #include "webkit/glue/resource_loader_bridge.h"

class MessageLoop;

namespace IPC {
class SyncChannel;
class SyncMessageFilter;
}

namespace WebKit {
class WebFrame;
}

namespace content {
class ChildHistogramMessageFilter;
class FileSystemDispatcher;
class QuotaDispatcher;
class ResourceDispatcher;
class SocketStreamDispatcher;

// The main thread of a child process derives from this class.
class CONTENT_EXPORT ChildThread : public IPC::Listener, public IPC::Sender {
 public:
  // Creates the thread.
  ChildThread();
  // Used for single-process mode.
  explicit ChildThread(const std::string& channel_name);
  virtual ~ChildThread();

  // IPC::Sender implementation:
  virtual bool Send(IPC::Message* msg) OVERRIDE;

  // See documentation on MessageRouter for AddRoute and RemoveRoute
  void AddRoute(int32 routing_id, IPC::Listener* listener);
  void RemoveRoute(int32 routing_id);

  IPC::Listener* ResolveRoute(int32 routing_id);

  IPC::SyncChannel* channel() { return channel_.get(); }

/* FIXME
  // Creates a ResourceLoaderBridge.
  // Tests can override this method if they want a custom loading behavior.
  virtual webkit_glue::ResourceLoaderBridge* CreateBridge(
      const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info);

  // Allocates a block of shared memory of the given size and
  // maps in into the address space. Returns NULL of failure.
  // Note: On posix, this requires a sync IPC to the browser process,
  // but on windows the child process directly allocates the block.
  base::SharedMemory* AllocateSharedMemory(size_t buf_size);

  ResourceDispatcher* resource_dispatcher();

  SocketStreamDispatcher* socket_stream_dispatcher() {
    return socket_stream_dispatcher_.get();
  }
*/
  FileSystemDispatcher* file_system_dispatcher() const {
    return file_system_dispatcher_.get();
  }

  QuotaDispatcher* quota_dispatcher() const {
    return quota_dispatcher_.get();
  }

  // Safe to call on any thread, as long as it's guaranteed that the thread's
  // lifetime is less than the main thread.
  IPC::SyncMessageFilter* sync_message_filter();
/*FIXME

  ChildHistogramMessageFilter* child_histogram_message_filter() const {
    return histogram_message_filter_.get();
  }
*/
  MessageLoop* message_loop();

  // Returns the one child thread.
  static ChildThread* current();
/* FIXME

  virtual bool IsWebFrameValid(WebKit::WebFrame* frame);
*/
 protected:
  friend class ChildProcess;

  // Called when the process refcount is 0.
  void OnProcessFinalRelease();

  virtual bool OnControlMessageReceived(const IPC::Message& msg);

  void set_on_channel_error_called(bool on_channel_error_called) {
    on_channel_error_called_ = on_channel_error_called;
  }

  // IPC::Listener implementation:
  virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
  virtual void OnChannelConnected(int32 peer_pid) OVERRIDE;
  virtual void OnChannelError() OVERRIDE;
  void OnAsyncFileOpened(base::PlatformFileError error_code,
                         IPC::PlatformFileForTransit file_for_transit,
                         int message_id);

 private:
  void Init();
/* FIXME
  // IPC message handlers.
  void OnShutdown();
  void OnSetProfilerStatus(tracked_objects::ThreadData::Status status);
  void OnGetChildProfilerData(int sequence_number);
  void OnDumpHandles();
#ifdef IPC_MESSAGE_LOG_ENABLED
  void OnSetIPCLoggingEnabled(bool enable);
#endif
#if defined(USE_TCMALLOC)
  void OnGetTcmallocStats();
#endif
*/
  void EnsureConnected();

  std::string channel_name_;
  scoped_ptr<IPC::SyncChannel> channel_;

  // Allows threads other than the main thread to send sync messages.
  scoped_refptr<IPC::SyncMessageFilter> sync_message_filter_;

  // Implements message routing functionality to the consumers of ChildThread.
  MessageRouter router_;
  /* FIXME
  // Handles resource loads for this process.
  scoped_ptr<ResourceDispatcher> resource_dispatcher_;

  // Handles SocketStream for this process.
  scoped_ptr<SocketStreamDispatcher> socket_stream_dispatcher_;
*/
  // The OnChannelError() callback was invoked - the channel is dead, don't
  // attempt to communicate.
  bool on_channel_error_called_;

  MessageLoop* message_loop_;

  scoped_ptr<FileSystemDispatcher> file_system_dispatcher_;

  scoped_ptr<QuotaDispatcher> quota_dispatcher_;
  /* FIXME

  scoped_refptr<ChildHistogramMessageFilter> histogram_message_filter_;
*/
  base::WeakPtrFactory<ChildThread> channel_connected_factory_;

  DISALLOW_COPY_AND_ASSIGN(ChildThread);
};

}  // namespace content

#endif  // CONTENT_COMMON_CHILD_THREAD_H_


text:
<?php

namespace Falcraft\Tests\Data\Types;

// Connects/stores vertices implementing interface
require_once('../../../Data/Types/Enumeration.php');

use Falcraft\Data\Types;

echo "Falcraft\\Data\\Types\\Enumeration.php Test\n";
echo "----------------------------------------\n\n";

echo "Build Enumerator via Object Methods -> ";

$success = true;

$testEnum = null;

try {
    $testEnum = new Types\Enumeration('testEnumerationClass', array(
        'TEST1' => 1,
        'TEST2' => 2,)
    );
} catch (\Exception $e) {
    $success = false;
}

if ($success) {
    echo "Success!\n";
} else {
    echo "Failure...\n";
}

echo "\nConstants of Enumerator Instantiated -> \n";
var_dump($testEnum->getConstants());

echo "\nAdding Additional Constants ('ADD1', 'ADD2', 'REM') -> ";

$additionalConstants = false;

try {
    $additionalConstants = array('ADD1' => 3, 'ADD2' => 4, 'REM' => 5);
    $testEnum->addConstants($additionalConstants);
} catch (\Exception $e) {
    $success = false;
}

if ($success) {
    echo "Success!\n";
} else {
    echo "Failure...\n";
}

echo "\nConstants of Enumerator Instantiated -> \n";
var_dump($testEnum->getConstants());

echo "\nRemove Constant ('REM') -> ";

$success = true;

try {
    $testEnum->removeConstant('REM');
} catch (\Exception $e) {
    $success = false;
}

if ($success) {
    echo "Success!\n";
} else {
    echo "Failure...\n";
}

echo "\nConstants of Enumerator Instantiated -> \n";
var_dump($testEnum->getConstants());

echo "\nSet Erroneous Default ('REM') -> ";

$fail = true;

try {
    $t = $testEnum->setDefault('REM');
} catch (\Exception $e) {
    $fail = false;
}

if ($fail) {
    echo "Failure!\n";
} else {
    echo "Success...\n";
}

echo "Set Correct Defaul ('ADD2') -> ";

$success = true;

try {
    $t = $testEnum->setDefault('ADD2');
    if (!$t) {
        $success = false;
    }
} catch (\Exception $e) {
    $success = false;
}

if ($success) {
    echo "Success!\n";
} else {
    echo "Failure...\n";
}

echo "Access Default Value -> ";

$success = true;

$default = $defaultValue = null;

try {
    $default = $testEnum->getDefault();
    $defaultValue = $testEnum->getDefaultValue();
} catch (\Exception $e) {
    $success = false;
}

if ($success) {
    echo "Success! $default ($defaultValue)\n";
} else {
    echo "Failure...\n";
}

echo "Establish Namespace -> ";

$success = true;

$namespace = null;

try {
    $testEnum->setNamespace('Falcraft\\Tests\\Data\\Types');
    $namespace = $testEnum->getNamespace();
} catch (\Exception $e) {
    $success = false;
}

if ($success) {
    echo "Success! $namespace\n";
} else {
    echo "Failure...\n";
}

echo "Bake Enumeration -> ";

$success = true;

try {
    $testEnum->bake();
} catch (\Exception $e) {
    $success - false;
}

if ($success) {
    echo "Success!\n";
} else {
    echo "Failure...\n";
}

echo "Change Enumeration After Baking -> ";

$fail = true;

try {
    $testEnum->removeConstant('ADD1');
    $fail = false;
} catch (\Exception $e) {

}

if ($fail) {
    echo "Failure!\n";
} else {
    echo "Success...\n";
}

echo "Enumeration Internals -> \n\n";

var_dump($testEnum);

echo "\nUsing An Enumerator (ADD1) ->";

$success = true;

$test = null;

try {
    $test = testEnumerationClass::ADD1;
} catch (\Exception $e) {
    $success = false;
}

if ($success) {
    echo "Success! ($test)\n";
} else {
    echo "Failure...\n";
}

echo "Independent Enumerator Generation -> ";

$fail = true;

$testRebakeEnum = null;

try {
    echo "    Same Qualifier: ";
    $testRebakeEnum = new Types\Enumeration('testEnumerationClass', array(
        'REBAKE1' => 1,
        'REBAKE2' => 2,)
    );

    $testRebakeEnum->setNamespace('Falcraft\\Tests\\Data\\Types');
    $fail = false;
} catch (\Exception $e) {
    $fail = true;
}

if ($fail) {
    echo "Failure!\n";
} else {
    echo "Success...\n";
}

echo "Generate Instance From Enumeration Instance -> ";

$success = true;

$enumeratedValue = null;

try {
    $enumeratedValue = $testEnum->getInstance(testEnumerationClass::ADD2);
} catch (\Exception $e) {
    $success = false;
}

if ($success) {
    echo "Success!\n\n";
    var_dump($enumeratedValue);
    echo "\n";
} else {
    echo "Failure...\n";
}

echo "Generate Instance From Enumeration Class -> ";

$success = true;

$enumeratedValue = null;

try {
    $enumeratedValue = Types\Enumeration::createEnumeration(
        'Falcraft\\Tests\\Data\\Types\\testEnumerationClass'
    );
} catch (\Exception $e) {
    $success = false;
}

if ($success) {
    echo "Success!\n\n";
    var_dump($enumeratedValue);
    echo "\n";
} else {
    echo "Failure...\n";
}

echo "Generate Instance From Generated Class -> ";

$success = true;

$enumeratedValue = null;

try {
    $enumeratedValue = new testEnumerationClass();
} catch (\Exception $e) {
    $success = false;
}

if ($success) {
    echo "Success!\n\n";
    var_dump($enumeratedValue);
    echo "\n";
} else {
    echo "Failure...\n\n";
}


text:
<?php

/**
 * The "beaconinfo" collection of methods.
 * Typical usage is:
 *  <code>
 *   $proximitybeaconService = new Google_Service_Proximitybeacon(...);
 *   $beaconinfo = $proximitybeaconService->beaconinfo;
 *  </code>
 */
class Google_Service_Proximitybeacon_Resource_Beaconinfo extends Google_Service_Resource
{
  /**
   * Given one or more beacon observations, returns any beacon information and
   * attachments accessible to your application. Authorize by using the [API
   * key](https://developers.google.com/beacons/proximity/how-
   * tos/authorizing#APIKey) for the application. (beaconinfo.getforobserved)
   *
   * @param Google_Service_Proximitybeacon_GetInfoForObservedBeaconsRequest $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_Proximitybeacon_GetInfoForObservedBeaconsResponse
   */
  public function getforobserved(Google_Service_Proximitybeacon_GetInfoForObservedBeaconsRequest $postBody, $optParams = array())
  {
    $params = array('postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('getforobserved', array($params), "Google_Service_Proximitybeacon_GetInfoForObservedBeaconsResponse");
  }
}


text:
namespace CSBackend
{
	namespace Android
	{
		//declare private statics
		std::map<std::string, MethodReference> _IJavaInterface::mStaticMethodRefMap;
		JavaVM* _IJavaInterface::mspJavaVM = nullptr;

		//--------------------------------------------------------------------------------------
		/// Get JNI Environment Ptr
		//--------------------------------------------------------------------------------------
		JNIEnv * _IJavaInterface::GetJNIEnvironmentPtr()
		{
			JNIEnv* env;
			mspJavaVM->AttachCurrentThread(&env, nullptr);
			return env;
		}
		//--------------------------------------------------------------------------------------
		/// Get Java VM
		///
		/// @return VM
		//--------------------------------------------------------------------------------------
		JavaVM* _IJavaInterface::GetJavaVM()
		{
			return mspJavaVM;
		}
		//--------------------------------------------------------------------------------------
		/// Init Callable Static Method
		//--------------------------------------------------------------------------------------
		void _IJavaInterface::InitCallableStaticMethod(std::string instrClassName, std::string instrMethodName, std::string instrSignature)
		{
			JNIEnv* pEnv = GetJNIEnvironmentPtr();

			MethodReference ref;
			jclass javaInterfaceClass = pEnv->FindClass(instrClassName.c_str());
			ref.mClassID = static_cast<jclass>(pEnv->NewGlobalRef(javaInterfaceClass));
			ref.mMethodID = pEnv->GetStaticMethodID(ref.mClassID, instrMethodName.c_str(), instrSignature.c_str());
			pEnv->DeleteLocalRef(javaInterfaceClass);

			if (ref.mMethodID == 0 || ref.mClassID == 0)
				CS_LOG_ERROR("Could not get method and class ID\nClassname \""+instrClassName+"\"\nMethodname \""+instrMethodName+"\"\nSigniture \""+instrSignature+"\"");

			if (mStaticMethodRefMap.find(instrMethodName) == mStaticMethodRefMap.end())
				mStaticMethodRefMap[instrMethodName] = ref;
			else
				CS_LOG_ERROR("Could not add method reference - method name already exists.");
		}

		//--------------------------------------------------------------------------------------
		/// Get Static Method Reference
		//--------------------------------------------------------------------------------------
		MethodReference _IJavaInterface::GetStaticMethodReference(std::string instrMethodName)
		{
			MethodReference ref;
			ref.mClassID = 0;
			ref.mMethodID = 0;

			if (mStaticMethodRefMap.find(instrMethodName) != mStaticMethodRefMap.end())
				ref = mStaticMethodRefMap[instrMethodName];
			else
				CS_LOG_ERROR("Could not find method reference. Have you initialised it in the Java Interface?");

			return ref;
		}
		//--------------------------------------------------------------------------------------
		/// Create JString From STDString
		//--------------------------------------------------------------------------------------
		jstring _IJavaInterface::CreateJStringFromSTDString(std::string instrString)
		{
			JNIEnv* pEnv = GetJNIEnvironmentPtr();
			if (pEnv != nullptr)
			{
				jstring jstrNewString = pEnv->NewStringUTF(instrString.c_str());
				return jstrNewString;
			}
			return nullptr;
		}
		//--------------------------------------------------------------------------------------
		/// Create STDString From JString
		//--------------------------------------------------------------------------------------
		std::string _IJavaInterface::CreateSTDStringFromJString(jstring injstrString)
		{
			JNIEnv* pEnv = GetJNIEnvironmentPtr();
			if (pEnv != nullptr && injstrString != nullptr)
			{
				const char * cString = pEnv->GetStringUTFChars(injstrString, JNI_FALSE);
				if (cString != nullptr)
				{
					std::string stdString = std::string(cString);
					pEnv->ReleaseStringUTFChars(injstrString, cString);
					return stdString;
				}
			}
			return "";
		}
		//--------------------------------------------------------------------------------------
		/// Create STDString From JByteArray
		//--------------------------------------------------------------------------------------
		std::string _IJavaInterface::CreateSTDStringFromJByteArray(jbyteArray injabyArray, int indwLength)
		{
			if (injabyArray != nullptr && indwLength > 0)
			{
				JNIEnv* pEnv = GetJNIEnvironmentPtr();
				if (pEnv != nullptr)
				{
					jbyte* pBytes = pEnv->GetByteArrayElements(injabyArray, JNI_FALSE);
					if (pBytes != nullptr)
					{
						std::string strOutput((const char*)pBytes, indwLength);
						pEnv->ReleaseByteArrayElements(injabyArray, pBytes, 0);
						return strOutput;
					}
				}
			}

			return "";
		}
		//--------------------------------------------------------------------------------------
		/// Get Int Element From JArray
		//--------------------------------------------------------------------------------------
		s32 _IJavaInterface::GetIntElementFromJArray(jintArray injadwArray, u32 inudwIndex)
		{
			JNIEnv* pEnv = GetJNIEnvironmentPtr();
			if (pEnv != nullptr && injadwArray != nullptr)
			{
				jint* pIntegers = pEnv->GetIntArrayElements(injadwArray, JNI_FALSE);
				if (pIntegers != nullptr)
				{
					s32 dwOutput = pIntegers[inudwIndex];
					pEnv->ReleaseIntArrayElements(injadwArray, pIntegers, 0);
					return dwOutput;
				}
			}
			return -1;
		}
	}
}

#endif


text:
package org.elasticsearch.discovery.gce;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.http.*;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.client.util.Sleeper;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.ESLoggerFactory;

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

public class RetryHttpInitializerWrapper implements HttpRequestInitializer {

    private int maxWait;

    private static final ESLogger logger =
            ESLoggerFactory.getLogger(RetryHttpInitializerWrapper.class.getName());

    // Intercepts the request for filling in the "Authorization"
    // header field, as well as recovering from certain unsuccessful
    // error codes wherein the Credential must refresh its token for a
    // retry.
    private final Credential wrappedCredential;

    // A sleeper; you can replace it with a mock in your test.
    private final Sleeper sleeper;

    public RetryHttpInitializerWrapper(Credential wrappedCredential) {
        this(wrappedCredential, Sleeper.DEFAULT, ExponentialBackOff.DEFAULT_MAX_ELAPSED_TIME_MILLIS);
    }

    public RetryHttpInitializerWrapper(Credential wrappedCredential, int maxWait) {
        this(wrappedCredential, Sleeper.DEFAULT, maxWait);
    }

    // Use only for testing.
    RetryHttpInitializerWrapper(
            Credential wrappedCredential, Sleeper sleeper, int maxWait) {
        this.wrappedCredential = Objects.requireNonNull(wrappedCredential);
        this.sleeper = sleeper;
        this.maxWait = maxWait;
    }

    @Override
    public void initialize(HttpRequest httpRequest) {
        final HttpUnsuccessfulResponseHandler backoffHandler =
                new HttpBackOffUnsuccessfulResponseHandler(
                        new ExponentialBackOff.Builder()
                                .setMaxElapsedTimeMillis(maxWait)
                                .build())
                        .setSleeper(sleeper);

        httpRequest.setInterceptor(wrappedCredential);
        httpRequest.setUnsuccessfulResponseHandler(
                new HttpUnsuccessfulResponseHandler() {
                    int retry = 0;

                    @Override
                    public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) throws IOException {
                        if (wrappedCredential.handleResponse(
                                request, response, supportsRetry)) {
                            // If credential decides it can handle it,
                            // the return code or message indicated
                            // something specific to authentication,
                            // and no backoff is desired.
                            return true;
                        } else if (backoffHandler.handleResponse(
                                request, response, supportsRetry)) {
                            // Otherwise, we defer to the judgement of
                            // our internal backoff handler.
                            logger.debug("Retrying [{}] times : [{}]", retry, request.getUrl());
                            return true;
                        } else {
                            return false;
                        }
                    }
                });
        httpRequest.setIOExceptionHandler(
                new HttpBackOffIOExceptionHandler(
                        new ExponentialBackOff.Builder()
                                .setMaxElapsedTimeMillis(maxWait)
                                .build())
                        .setSleeper(sleeper)
        );
    }
}


text:
namespace AsmResolver.PE.DotNet.Cil
{
    ///
    /// Provides members defining all possible stack behaviours that a single CIL operation can have.
    ///
    public enum CilStackBehaviour : byte
    {
        ///
        /// Indicates the operation pops no values from the stack.
        ///
        Pop0,

        ///
        /// Indicates the operation pops one value from the stack.
        ///
        Pop1,

        ///
        /// Indicates the operation pops one value off the stack for the first operand, and one value of the stack
        /// for the second operand.
        ///
        Pop1_Pop1,

        ///
        /// Indicates the operation pops a 32-bit integer off the stack.
        ///
        PopI,

        ///
        /// Indicates the operation pops a 32-bit integer off the stack for the first operand, and a value off the stack
        /// for the second operand.
        ///
        PopI_Pop1,

        ///
        /// Indicates the operation pops a 32-bit integer off the stack for the first operand, and a 32-bit integer off
        /// the stack for the second operand.
        ///
        PopI_PopI,

        ///
        /// Indicates the operation pops a 32-bit integer off the stack for the first operand, and a 64-bit integer off
        /// the stack for the second operand.
        ///
        PopI_PopI8,

        ///
        /// Indicates the operation pops a 32-bit integer off the stack for the first operand, a 32-bit integer off the
        /// stack for the second operand, and a 32-bit integer off the stack for the third operand.
        ///
        PopI_PopI_PopI,

        ///
        /// Indicates the operation pops a 32-bit integer off the stack for the first operand, and a 32-bit floating
        /// point number off the stack for the second operand.
        ///
        PopI_PopR4,

        ///
        /// Indicates the operation pops a 32-bit integer off the stack for the first operand, and a 64-bit floating
        /// point number off the stack for the second operand.
        ///
        PopI_PopR8,

        ///
        /// Indicates the operation pops a reference off the stack.
        ///
        PopRef,

        ///
        /// Indicates the operation pops a reference off the stack for the first operand, and a value off the stack for
        /// the second operand.
        ///
        PopRef_Pop1,

        ///
        /// Indicates the operation pops a reference off the stack for the first operand, and a 32-bit integer off the
        /// stack for the second operand.
        ///
        PopRef_PopI,

        ///
        /// Indicates the operation pops a reference off the stack for the first operand, a value off the stack for the
        /// second operand, and a value off the stack for the third operand.
        ///
        PopRef_PopI_PopI,

        ///
        /// Indicates the operation pops a reference off the stack for the first operand, a value off the stack for the
        /// second operand, and a 64-bit integer off the stack for the third operand.
        ///
        PopRef_PopI_PopI8,

        ///
        /// Indicates the operation pops a reference off the stack for the first operand, a value off the stack for the
        /// second operand, and a 32-bit integer off the stack for the third operand.
        ///
        PopRef_PopI_PopR4,

        ///
        /// Indicates the operation pops a reference off the stack for the first operand, a value off the stack for the
        /// second operand, and a 64-bit floating point number off the stack for the third operand.
        ///
        PopRef_PopI_PopR8,

        ///
        /// Indicates the operation pops a reference off the stack for the first operand, a value off the stack for the
        /// second operand, and a reference off the stack for the third operand.
        ///
        PopRef_PopI_PopRef,

        ///
        /// Indicates the operation pops a reference off the stack for the first operand, a value off the stack for the
        /// second operand, and a 32-bit integer off the stack for the third operand.
        ///
        PopRef_PopI_Pop1,

        ///
        /// Indicates the operation clears the evaluation stack.
        ///
        PopAll,

        ///
        /// Indicates the operation pushes no values onto the stack.
        ///
        Push0,

        ///
        /// Indicates the operation pushes one value onto the stack.
        ///
        Push1,

        ///
        /// Indicates the operation pushes 1 value onto the stack for the first operand, and 1 value onto the stack for
        /// the second operand.
        ///
        Push1_Push1,

        ///
        /// Indicates the operation pushes a 32-bit integer onto the stack.
        ///
        PushI,

        ///
        /// Indicates the operation pushes a 64-bit integer onto the stack.
        ///
        PushI8,

        ///
        /// Indicates the operation pushes a 32-bit floating point number onto the stack.
        ///
        PushR4,

        ///
        /// Indicates the operation pushes a 64-bit floating point number onto the stack.
        ///
        PushR8,

        ///
        /// Indicates the operation pushes a reference onto the stack.
        ///
        PushRef,

        ///
        /// Indicates the operation pops a variable amount of values off the stack.
        ///
        VarPop,

        ///
        /// Indicates the operation pushes a variable amount of values onto the stack.
        ///
        VarPush,
    }
}


text:
package org.apache.metron.maas.config;

import java.util.HashMap;
import java.util.Map;

/**
 * An endpoint for a service being deployed.  An endpoint is constituted by a URL and
 * a set of functions which it exposes.
 */
public class Endpoint {
  String url;
  Map<String, String> functions = new HashMap<String, String>(){{
    put("apply", "apply");
  }};

  /**
   * Retrieve the URL associated with the endpoint
   * @return a URL
   */
  public String getUrl() {
    return url;
  }

  public void setUrl(String url) {
    this.url = url;
  }

  /**
   * Retrieve the functions (or functions) exposed.  The key of the map is the logical alias
   * for an endpoint function that you can use across multiple services (i.e. 'apply')
   * and the value is the realized endpoint function name.
   *
   * For instance, if I have a service bound to localhost:8080 and exposes /foo and /bar and
   * for your organization or use you've decided to call functions which are used for enrichment 'enrich'
   * and functions which are used for data science as 'ds', you can alias /foo to 'enrich'
   * and /bar to 'ds' by creating a map which maps the 'enrich' to 'foo' and 'ds' to 'bar'.
   *
   * @return
   */
  public Map<String, String> getFunctions() {
    return functions;
  }

  public void setFunctions(Map<String, String> functions) {
    this.functions = functions;
  }

  @Override
  public String toString() {
    return "Endpoint{" +
            "url='" + url + '\'' +
            ", functions=" + functions +
            '}';
  }

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

    Endpoint endpoint = (Endpoint) o;

    if (getUrl() != null ? !getUrl().equals(endpoint.getUrl()) : endpoint.getUrl() != null) return false;
    return getFunctions() != null ? getFunctions().equals(endpoint.getFunctions()) : endpoint.getFunctions() == null;

  }

  @Override
  public int hashCode() {
    int result = getUrl() != null ? getUrl().hashCode() : 0;
    result = 31 * result + (getFunctions() != null ? getFunctions().hashCode() : 0);
    return result;
  }
}


text:
+++
title = "Simple, Durable, Yours"
date = "2019-10-16"
description = "We built Urbit from scratch to be a system that's simple, durable, and yours. Everything that computing today is not — but should be."
extra = { }
+++

We live in a world dense with digital services. We see the world through them, we depend on them completely, and they're not going away. They're only becoming more ubiquitous.

But computers are a mess.

![](https://media.urbit.org/site/understanding-urbit/simple-durable-yours/simple-durable-yours-notifications.svg)

We spend all our time switching between services, juggling logins and different interfaces. And once we're logged in, the services we use harvest our data, spy on us, and often shut down with little warning.

If computers are going to be a part of our lives for generations to come, we need a sound foundation for them. We need a _system_, not a grab bag of apps and services. Urbit is that system.

![](https://media.urbit.org/site/understanding-urbit/simple-durable-yours/simple-durable-yours-rock%402x.png)

We built Urbit from scratch to be a system that's simple, durable, and yours. Everything that computing today is not — but should be.

What do we mean by simple, durable, and yours? Let's walk through it one by one.

## Simple

Urbit is designed to be incredibly simple for ordinary users. Your data, applications, and connections all live in a single, unified operating system that belongs to you. Your Urbit requires no system administration and gets all its updates over the air. For developers, Urbit is incredibly compact and efficient. It's about 50K lines of code — smaller than your average webapp. The entire OS can be understood by a single person and is designed to make building decentralized apps straightforward.

## Durable

Your Urbit is designed to be durable: both to store your data across generations and to be resilient against crashes. You can't really trust a computer that could disappear or become obsolete. We've become accustomed to this distrust, but it's not the way things should be. Your Urbit is meant to be a permanent digital home. At its foundation, Urbit is designed a bit like a blockchain — making reliability and permanence a priority for the individual.

## Yours

Finally, your Urbit belongs to you in every possible way. You own it with a private key, control it completely, and can inspect its source code. We want your Urbit to be your digital home. A home you don't own is just a hotel room.

![](https://media.urbit.org/site/understanding-urbit/simple-durable-yours/simple-durable-yours-evolution.svg)

Urbit began as a sketch, driven from a basic intuition that a better platform could be built. Today, Urbit is two components: Urbit ID, an identity system that's already live on Ethereum; and Urbit OS, a decentralized network and OS stack that's young but working well.

Over time we've quietly evolved Urbit into a carefully engineered, compact system. Urbit isn't done — but it's well on its way. The network has been live since 2013 and the interface is coming along nicely. You can own a piece of Urbit today if you can find an invite from a friend, or by buying an Urbit ID. We're ready for people to begin homesteading this new territory we created with new communities and new software.

We think it's possible to leave today's technology behind and build something better. Something more humane, calm, and collectively owned. Our vision of the future isn't one where technology intrudes in every corner of our lives. It's one where technology is mostly invisible.


text:
package org.apache.poi.ss.usermodel;

/**
 * @author Yegor Kozlov
 */
public interface Drawing {
    Picture createPicture(ClientAnchor anchor, int pictureIndex);

    Comment createCellComment(ClientAnchor anchor);
}


text:
#include "TerrainSubdivisionGenerator.h"

namespace world {

using namespace arma;

TerrainSubdivisionGenerator::TerrainSubdivisionGenerator()
        : _buffer(std::map<std::pair<int, int>, arma::Mat<double>>()) {}

TerrainSubdivisionTree *TerrainSubdivisionGenerator::generateSubdivisions(
    Terrain &terrain, int subdivideFactor, int subdivisionsCount) {
    auto *result = new TerrainSubdivisionTree(terrain);
    generateSubdivisionLevels(*result, subdivideFactor, subdivisionsCount);
    return result;
}

void TerrainSubdivisionGenerator::generateSubdivisionLevels(
    TerrainSubdivisionTree &tree, int subdivideFactor, int subdivisionsCount) {
    generateSubdivisionLevel(tree, subdivideFactor);

    // Subdivisions d'un niveau supplémentaire (récursivité)
    if (subdivisionsCount > 1) {
        for (int x = 0; x < subdivideFactor; x++) {
            for (int y = 0; y < subdivideFactor; y++) {
                TerrainSubdivisionTree &subtree = tree.getSubtree(x, y);
                generateSubdivisionLevels(subtree, subdivideFactor,
                                          subdivisionsCount - 1);
            }
        }
    }
}

void TerrainSubdivisionGenerator::generateSubdivisionLevel(
    TerrainSubdivisionTree &terrain, int subdivideFactor) {
    terrain.subdivide(subdivideFactor);

    // Pas de prébuffering

    // Géneration des buffers pour le niveau de détail actuel
    for (int x = 0; x < subdivideFactor; x++) {
        for (int y = 0; y < subdivideFactor; y++) {
            generateSubdivision(terrain, x, y);
        }
    }

    // Conversion des buffers en terrain
    for (int x = 0; x < subdivideFactor; x++) {
        for (int y = 0; y < subdivideFactor; y++) {
            adaptFromBuffer(terrain, x, y);
        }
    }

    _buffer.clear();
}

void TerrainSubdivisionGenerator::generateSubdivision(
    TerrainSubdivisionTree &terrain, int xsub, int ysub) {
    // TODO Faire plusieurs tests pour voir si on obtient un meilleur résultat
    // en changeant les paramètres de l'algo de perlin.
    /*mat &mat = createInBuf(xsub, ysub, terrain.getSubtree(xsub,
    ysub)._terrain->_array); _perlin.generatePerlinNoise2D(mat, _offset,
    _octaveCount, _frequency, _persistence);

    double oneTerrainLength = 1.0 / terrain._subdivideFactor;

    // Harmonisation horizontale
    // -> Le joint en y doit toujours se faire avant le joint en x pour
    n'importe quel terrain if (ysub != 0) { _perlin.join(getBuf(xsub, ysub - 1),
                     mat,
                     Direction::AXIS_Y,
                     _octaveCount, _frequency, _persistence);

        if (xsub != 0) {
            _perlin.join(getBuf(xsub - 1, ysub - 1),
                         getBuf(xsub, ysub - 1),
                         Direction::AXIS_X,
                         _octaveCount, _frequency, _persistence, true);
        }
    }
    if (xsub == terrain._subdivideFactor - 1) {
        _perlin.join(getBuf(xsub - 1, ysub),
                     mat,
                     Direction::AXIS_X,
                     _octaveCount, _frequency, _persistence, true);
    }*/
}

void TerrainSubdivisionGenerator::adaptFromBuffer(TerrainSubdivisionTree &tree,
                                                  int xsub, int ysub) const {
    /*TerrainSubdivisionTree &subtree = tree.getSubtree(xsub, ysub);
    Terrain &subterrain = *subtree._terrain;
    Mat<double> &mat = getBuf(xsub, ysub);

    int rows = subterrain._array.n_rows;
    int cols = subterrain._array.n_cols;
    int sf = tree._subdivideFactor;

    for (int x = 0; x < rows; x++) {
        for (int y = 0; y < cols; y++) {
            subterrain._array(x, y) = mat(x, y) * _subdivNoiseRatio
                                      + (1 - _subdivNoiseRatio) *
    tree.getZInterpolated(
                    ((double) xsub + (double) x / rows) / sf,
                    ((double) ysub + (double) y / cols) / sf);
        }
    }

    subtree._noisePart = _subdivNoiseRatio;*/
}

arma::Mat<double> &TerrainSubdivisionGenerator::getBuf(int x, int y) const {
    return _buffer.at(std::make_pair(x, y));
}
} // namespace world


text:
require 'spec_helper'

describe ImageDownloader do
  let(:settings) { Settings.new }
  let(:images) { Images.new(settings) }
  let(:imagedownloader) { ImageDownloader.new(settings, images) }
  describe "#initialize" do
    it "doesn't throw an error when initialized with settings and images" do
      expect(imagedownloader.settings).to eq(settings)
      expect(imagedownloader.images).to eq(images)
    end

    it "will throw an error when initialized with no settings or images" do
      expect { ImageDownloader.new() }.to raise_error
    end
  end

  describe "#download" do
    it "downloads the images when the settings are set" do
      allow(settings).to receive(:prepare).and_return(true)
      allow(images).to receive(:search).and_return(true)
      expect(imagedownloader.download).to eq(true)
    end

    it "raises an error if the settings and images are not set" do
      expect { imagedownloader.download }.to raise_error
    end
  end
end

describe Images do
  let(:settings) { Settings.new }
  let(:images) { Images.new(settings) }
  describe "#initialize" do
    it "doesn't raise an error when initialized with the settings" do
      expect(images.settings).to eq(settings)
    end

    it "raises an error when initialized without the settings" do
      expect { Images.new() }.to raise_error
    end
  end

  describe "#search" do
    it "returns true when the settings are speciifed" do
      allow(images).to receive(:get_images).and_return(true)
      allow(images).to receive(:save_images).and_return(true)
      expect(images.search).to eq(true)
    end

    it "raises an error when the settings are not specified" do
      expect { Images.new.search }.to raise_error
    end
  end
end


text:
var through = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var path = require('path');
var fs = require('fs');
var pofile = require('pofile');
var _ = require('lodash');

const PLUGIN_NAME = 'gulp-split-translations.js';

module.exports = function(sections) {
	// Creating a stream through which each file will pass
	var stream = through.obj(function(file, enc, callback) {
		if (file.isBuffer()) {
			// If we aren't splitting out sections, just pass through.
			if (!Object.keys(sections).length) {
				this.push(file);
				return callback();
			}

			var content = file.contents.toString();
			var parsed = JSON.parse(content);
			var lang = Object.keys(parsed)[0];

			var poContent = fs.readFileSync(
				path.resolve(
					__dirname,
					'../../../site-translations/' + lang + '/main.po'
				),
				'utf8'
			);
			var poParsed = pofile.parse(poContent);
			var poItems = _.indexBy(poParsed.items, 'msgid');

			_.forEach(
				sections,
				function(sectionPaths, sectionName) {
					var sectionReferenceRegex = new RegExp(
						'^(' + sectionPaths.join('|') + ')'
					);
					var sectionJson = {};
					sectionJson[lang] = {};

					// For each translation term in this language.
					for (var i in parsed[lang]) {
						var poItem = poItems[i];
						if (poItem) {
							var matchingReferences = 0;
							for (var j in poItem.references) {
								if (poItem.references[j].match(sectionReferenceRegex)) {
									++matchingReferences;
								}
							}

							// We only pull it into the section if ALL the references belong to the section.
							// Otherwise we want to put it as part of the "common" translation file.
							if (matchingReferences == poItem.references.length) {
								sectionJson[lang][i] = parsed[lang][i];
								delete parsed[lang][i];
							}
						}
					}

					this.push(
						new gutil.File({
							cwd: file.cwd,
							base: file.base,
							path: path.join(path.dirname(file.path), sectionName + '.json'),
							contents: new Buffer(JSON.stringify(sectionJson), 'utf-8'),
						})
					);
				},
				this
			);

			file.contents = new Buffer(JSON.stringify(parsed), 'utf-8');
		} else if (file.isStream()) {
			// Streams not supported.
			this.emit(
				'error',
				new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported.')
			);
			return callback();
		}

		// Anything else just falls through.
		this.push(file);
		return callback();
	});

	// returning the file stream
	return stream;
};


text:
package gomf

import (
	"bytes"
	"context"
	"fmt"
	"mime/multipart"
	"net/http"
	"net/textproto"
)

type FormBuilder struct {
	w *multipart.Writer
	b *bytes.Buffer
}

func New() *FormBuilder {
	buf := new(bytes.Buffer)
	writer := multipart.NewWriter(buf)
	return &FormBuilder{
		w: writer,
		b: buf,
	}
}

func (ufw *FormBuilder) WriteField(name, value string) error {
	w, err := ufw.w.CreateFormField(name)
	if err != nil {
		return err
	}

	_, err = w.Write([]byte(value))
	if err != nil {
		return err
	}

	return nil
}

// WriteFile if contentType is empty-string, will auto convert to application/octet-stream
func (ufw *FormBuilder) WriteFile(fieldName, fileName, contentType string, content []byte) error {
	if contentType == "" {
		contentType = "application/octet-stream"
	}

	wx, err := ufw.w.CreatePart(textproto.MIMEHeader{
		"Content-Type": []string{
			contentType,
		},
		"Content-Disposition": []string{
			fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fieldName, fileName),
		},
	})
	if err != nil {
		return err
	}

	_, err = wx.Write(content)
	if err != nil {
		return err
	}

	return nil
}

func (fb *FormBuilder) Close() error {
	return fb.w.Close()
}

func (fb *FormBuilder) GetBuffer() *bytes.Buffer {
	return fb.b
}

func (fb *FormBuilder) GetHTTPRequest(ctx context.Context, reqURL string) (*http.Request, error) {
	err := fb.Close()
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("POST", reqURL, fb.b)
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", fb.w.FormDataContentType())
	req = req.WithContext(ctx)

	return req, nil
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?attr/colorBackground">

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="vertical"
            tools:listitem="@layout/list_table"
            android:id="@+id/recView" />

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

    <TextView
        android:id="@+id/message"
        android:layout_centerVertical="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:textColor="?android:textColor"
        android:visibility="gone"
        android:text="@string/message"/>

    <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:indeterminate="true"
        android:visibility="gone"/>
</RelativeLayout>


text:
var demand = require('must');
var RelationshipType = require('../RelationshipType');

exports.initList = function (List) {
	// We can use relationships that refer to the same List to test
	List.add({
		single: { type: RelationshipType, ref: List.key },
		many: { type: RelationshipType, ref: List.key, many: true },
	});
};

exports.testFieldType = function (List) {

	var relatedItem = new List.model();
	before(function (done) {
		relatedItem.save(done);
	});

	describe('single', function () {
		it('should validate id input', function (done) {
			List.fields.single.validateInput({ single: relatedItem.id }, function (result) {
				demand(result).be.true();
				done();
			});
		});

		it('should validate undefined input', function (done) {
			List.fields.single.validateInput({}, function (result) {
				demand(result).be.true();
				done();
			});
		});

		it('should validate empty input', function (done) {
			List.fields.single.validateInput({ single: '' }, function (result) {
				demand(result).be.true();
				done();
			});
		});

		it('should validate null input', function (done) {
			List.fields.single.validateInput({ single: null }, function (result) {
				demand(result).be.true();
				done();
			});
		});

		it('should invalidate boolean input', function (done) {
			List.fields.single.validateInput({ single: true }, function (result) {
				demand(result).be.false();
				done();
			});
		});

		it('should validate item objects (object with id property)', function (done) {
			List.fields.single.validateInput({ single: relatedItem }, function (result) {
				demand(result).be.true();
				done();
			});
		});

		it('should invalidate object input without id', function (done) {
			List.fields.single.validateInput({ single: {} }, function (result) {
				demand(result).be.false();
				done();
			});
		});

		it('should invalidate array input', function (done) {
			List.fields.single.validateInput({ single: [] }, function (result) {
				demand(result).be.false();
				done();
			});
		});

		it('should validate required present input', function (done) {
			var testItem = new List.model();
			List.fields.single.validateRequiredInput(testItem, { single: relatedItem.id }, function (result) {
				demand(result).be.true();
				done();
			});
		});

		it('should validate required present input with item', function (done) {
			var testItem = new List.model();
			List.fields.single.validateRequiredInput(testItem, { single: relatedItem }, function (result) {
				demand(result).be.true();
				done();
			});
		});

		it('should validate required present input with existing value', function (done) {
			var testItem = new List.model({
				single: relatedItem.id,
			});
			List.fields.single.validateRequiredInput(testItem, { single: relatedItem.id }, function (result) {
				demand(result).be.true();
				done();
			});
		});

		it('should invalidate required not present input', function (done) {
			var testItem = new List.model();
			List.fields.single.validateRequiredInput(testItem, {}, function (result) {
				demand(result).be.false();
				done();
			});
		});

		it('should validate required input with existing value', function (done) {
			var testItem = new List.model({
				single: relatedItem.id,
			});
			List.fields.single.validateRequiredInput(testItem, {}, function (result) {
				demand(result).be.true();
				done();
			});
		});

		it('should invalidate required blank input with existing value', function (done) {
			var testItem = new List.model({
				single: relatedItem.id,
			});
			List.fields.single.validateRequiredInput(testItem, { single: '' }, function (result) {
				demand(result).be.false();
				done();
			});
		});

		it('should save the provided value', function (done) {
			var testItem = new List.model();
			List.fields.single.updateItem(testItem, { single: relatedItem.id }, function () {
				// TODO: We should be testing for errors here
				testItem.save(function (err, updatedItem) {
					List.model.findById(updatedItem.id, function (err, persistedData) {
						demand(String(persistedData.single)).equal(String(relatedItem.id));
						done();
					});
				});
			});
		});

		it('should save the provided value with an item object', function (done) {
			var testItem = new List.model();
			List.fields.single.updateItem(testItem, { single: relatedItem }, function () {
				// TODO: We should be testing for errors here
				testItem.save(function (err, updatedItem) {
					List.model.findById(updatedItem.id, function (err, persistedData) {
						demand(String(persistedData.single)).equal(String(relatedItem.id));
						done();
					});
				});
			});
		});

		it('should clear the current value when provided null', function (done) {
			var testItem = new List.model({
				single: relatedItem.id,
			});
			testItem.save(function (err) {
				List.fields.single.updateItem(testItem, { single: null }, function () {
					// TODO: We should be testing for errors here
					testItem.save(function (err, updatedItem) {
						List.model.findById(updatedItem.id, function (err, persistedData) {
							demand(persistedData.single).be.null();
							done();
						});
					});
				});
			});
		});

		it('should clear the current value when provided ""', function (done) {
			var testItem = new List.model({
				single: relatedItem.id,
			});
			testItem.save(function (err) {
				List.fields.single.updateItem(testItem, { single: '' }, function () {
					// TODO: We should be testing for errors here
					testItem.save(function (err, updatedItem) {
						List.model.findById(updatedItem.id, function (err, persistedData) {
							demand(persistedData.single).be.null();
							done();
						});
					});
				});
			});
		});

		it('should clear the current value when data object does not contain the field', function (done) {
			var testItem = new List.model({
				single: relatedItem.id,
			});
			testItem.save(function (err) {
				List.fields.single.updateItem(testItem, {}, function () {
					testItem.save(function (err, updatedItem) {
						List.model.findById(updatedItem.id, function (err, persistedData) {
							demand(persistedData.single).be.null();
							done();
						});
					});
				});
			});
		});
	});

	describe('many', function () {
		it('should validate id input', function (done) {
			List.fields.many.validateInput({ many: relatedItem.id }, function (result) {
				demand(result).be.true();
				done();
			});
		});

		it('should validate empty array input', function (done) {
			List.fields.many.validateInput({ many: [] }, function (result) {
				demand(result).be.true();
				done();
			});
		});

		it('should validate null input', function (done) {
			List.fields.many.validateInput({ many: null }, function (result) {
				demand(result).be.true();
				done();
			});
		});

		it('should validate array input with ids', function (done) {
			List.fields.many.validateInput({ many: [relatedItem.id] }, function (result) {
				demand(result).be.true();
				done();
			});
		});

		it('should validate arrays of item objects (object with id property)', function (done) {
			List.fields.many.validateInput({ many: [relatedItem] }, function (result) {
				demand(result).be.true();
				done();
			});
		});

		it('should validate undefined input', function (done) {
			List.fields.many.validateInput({}, function (result) {
				demand(result).be.true();
				done();
			});
		});

		it('should clear the current values when data object does not contain the field', function (done) {
			var testItem = new List.model({
				many: [relatedItem.id, relatedItem.id],
			});
			testItem.save(function (err) {
				List.fields.many.updateItem(testItem, {}, function () {
					testItem.save(function (err, updatedItem) {
						List.model.findById(updatedItem.id, function (err, persistedData) {
							demand(persistedData.many).to.eql([]);
							done();
						});
					});
				});
			});
		});

		it('should update the current values with the new values from the data object', function (done) {
			var testItem = new List.model({
				many: [relatedItem.id, relatedItem.id, relatedItem.id],
			});
			testItem.save(function (err) {
				List.fields.many.updateItem(testItem, { many: [relatedItem.id, relatedItem.id] }, function () {
					testItem.save(function (err, updatedItem) {
						List.model.findById(updatedItem.id, function (err, persistedData) {
							demand(String(persistedData.many)).to.eql(String([relatedItem.id, relatedItem.id]));
							done();
						});
					});
				});
			});
		});
	});

	describe('addFilterToQuery', function () {
		it('should filter arrays', function () {
			var result = List.fields.single.addFilterToQuery({
				value: ['Some', 'strings'],
			});
			demand(result.single).eql({
				$in: ['Some', 'strings'],
			});
		});

		it('should convert a single string to an array and filter that', function () {
			var result = List.fields.single.addFilterToQuery({
				value: 'a string',
			});
			demand(result.single).eql({
				$in: ['a string'],
			});
		});

		it('should support inverted filtering with an array', function () {
			var result = List.fields.single.addFilterToQuery({
				value: ['Some', 'strings'],
				inverted: true,
			});
			demand(result.single).eql({
				$nin: ['Some', 'strings'],
			});
		});

		it('should filter by existance if no value is specified', function () {
			var result = List.fields.single.addFilterToQuery({});
			demand(result.single).be.null();
		});

		it('should filter by non-existance if no value is specified', function () {
			var result = List.fields.single.addFilterToQuery({
				inverted: true,
			});
			demand(result.single).eql({
				$ne: null,
			});
		});

		it('should filter by emptiness if many is true and no value is specified', function () {
			var result = List.fields.many.addFilterToQuery({});
			demand(result.many).eql({
				$size: 0,
			});
		});

		it('should filter by non-emptiness if many is true and no value is specified', function () {
			var result = List.fields.many.addFilterToQuery({
				inverted: true,
			});
			demand(result.many).eql({
				$not: {
					$size: 0,
				},
			});
		});
	});
};


text:
AWVersionAgent
----

There is so many update checker using `UIAlertView` to notify user to upgrade your app, but the alert will stop user's action. `AWVersionAgent` will check new version in background and notify user that new version is available from Local Notification.

Usage:
----

1. Add `[[AWVersionAgent sharedAgent] checkNewVersionForApp:@"your-app-id"];` in `application:didFinishLaunchingWithOptions:` to check new version in background.
1. Add `[[AWVersionAgent sharedAgent] upgradeAppWithNotification:notification];` in `application:didReceiveLocalNotification:` to response local notification.
1. You can enable debug mode by `[[AWVersionAgent sharedAgent] setDebug:YES];`.

```objc
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self.window makeKeyAndVisible];

    [[AWVersionAgent sharedAgent] checkNewVersion];

    return YES;
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    [[AWVersionAgent sharedAgent] upgradeAppWithNotification:notification];
}
```

License
----
AWVersionAgent is available under the MIT license.


text:
using DNK.Belarus.ExchangeRates.DATA;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DNK.Belarus.ExchangeRates
{
    public partial class FormExchangeRates : Form
    {
        private readonly EventHandler AddEvent;
        private readonly EventHandler EditEvent;

        private DateTimePicker dtp_begin = new DateTimePicker();
        private DateTimePicker dtp_end = new DateTimePicker();

        private readonly dankoDataContext _db;

        public FormExchangeRates()
        {
            InitializeComponent();
            int month = DateTime.Today.Month;
            int year = DateTime.Today.Year;

            dtp_begin.Value = DateTime.Today;
            dtp_begin.Format = DateTimePickerFormat.Short;
            dtp_begin.Size = new Size(88, 25);
            toolStrip.Items.Insert(3, new ToolStripControlHost(dtp_begin));

            dtp_end.Value = dtp_begin.Value;
            dtp_end.Format = DateTimePickerFormat.Short;
            dtp_end.Size = new Size(88, 25);

            toolStrip.Items.Insert(5, new ToolStripControlHost(dtp_end));

            dgvExhangeRates.AutoGenerateColumns = false;
        }
        public FormExchangeRates(string connectionString) : this()
        {
            _db = new dankoDataContext(new SqlConnection(connectionString + " MultipleActiveResultSets=true;"));
            _db.CommandTimeout = 300;
            AddEvent = Add;
            EditEvent = Edit;
            btnAdd.Click += AddEvent;
        }
        //==============================================================================================================
        private void dtp_begin_ValueChanged(object sender, EventArgs e)
        {
            if (dtp_begin.Value > dtp_end.Value)
            {
                dtp_end.Value = dtp_begin.Value;
            }
            GetData();
        }
        //==============================================================================================================
        private void dtp_end_ValueChanged(object sender, EventArgs e)
        {
            if (dtp_end.Value < dtp_begin.Value)
            {
                dtp_begin.Value = dtp_end.Value;
            }
            GetData();
        }
        //==============================================================================================================
        private void FormExchangeRates_Load(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                _db.GetDataDictionary();
                tscbRates.ComboBox.DataSource = _db.RateList.ToList<Rate>();
                tscbRates.ComboBox.DisplayMember = "RA_CODE";
                tscbRates.ComboBox.ValueMember = "ra_key";
                tscbRates.ComboBox.SelectedItem = ((List<Rate>)tscbRates.ComboBox.DataSource).FirstOrDefault(p => p.RA_CODE == "E");
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        //==============================================================================================================
        private void tsbRefresh_Click(object sender, EventArgs e)
        {
            GetData();
        }
        //==============================================================================================================
        private void GetData()
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                bsExhangeRates.DataSource = _db.GetRealCourse((Rate)tscbRates.SelectedItem, dtp_begin.Value, dtp_end.Value).ToList<RealCourse>();
                dgvExhangeRates.DataSource = bsExhangeRates;
                if (checkBoxEdit.Checked)
                    UpdateFields();
                else
                    InitializFields();
            }
            finally
            {
                this.Cursor = null;
            }
        }
        //==============================================================================================================
        private void tscbRates_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetData();
        }

        private void FormExchangeRates_Shown(object sender, EventArgs e)
        {
            this.tscbRates.SelectedIndexChanged += new System.EventHandler(this.tscbRates_SelectedIndexChanged);
            dtp_begin.ValueChanged += new System.EventHandler(dtp_begin_ValueChanged);
            dtp_end.ValueChanged += new System.EventHandler(dtp_end_ValueChanged);
            GetData();
        }
        //==============================================================================================================
        private void Add(object sender, EventArgs e)
        {
            errorProvider.SetError(btnAdd, "");
            if (nudCourse.Value <= 0 && nudCourseCB.Value <= 0)
            {
                errorProvider.SetError(btnAdd, "Введите корректные курсы валют");
                return;
            }
            if (tscbRates.SelectedItem == null)
            {
                errorProvider.SetError(btnAdd, "Выберите валюту");
                return;
            }

            object newRecord = _db.AddRealCource(dtpDate.Value, nudCourse.Value, nudCourseCB.Value, (Rate)tscbRates.SelectedItem);
            if (_db.IsError)
            {
                errorProvider.SetError(btnAdd, string.Format("Ошибка добавления курса валют : {0}", _db.Error));
                return;
            }
            _db.Save();
            if (_db.IsError)
            {
                errorProvider.SetError(btnAdd, string.Format("Ошибка сохранение в БД : {0}", _db.Error));
                return;
            }

            if (newRecord != null)
            {
                bsExhangeRates.Add(newRecord);
            }
            dtpDate.Focus();
        }
        //==============================================================================================================
        private void Edit(object sender, EventArgs e)
        {
            errorProvider.SetError(btnAdd, "");
            if (bsExhangeRates.Current == null)
            {
                errorProvider.SetError(btnAdd, "Выберите строчку с курсом валют, которую хотите изменить");
                return;
            }

            _db.UpdateRealCource(dtpDate.Value, nudCourse.Value, nudCourseCB.Value, bsExhangeRates.Current);
            if (_db.IsError)
            {
                errorProvider.SetError(btnAdd, string.Format("Ошибка изменения текущей строчки с курсом валют : {0}", _db.Error));
                return;
            }
            _db.Save();
            if (_db.IsError)
            {
                errorProvider.SetError(btnAdd, string.Format("Ошибка сохранения в БД : {0}", _db.Error));
            }
        }
        //==============================================================================================================
        private void InitializFields()
        {
            errorProvider.SetError(btnAdd, "");
            dtpDate.Value = DateTime.Today;
            nudCourse.Value = 0;
            nudCourseCB.Value = 0;
        }
        //==============================================================================================================
        private void UpdateFields()
        {
            errorProvider.SetError(btnAdd,"");
            btnAdd.Enabled = false;
            if (bsExhangeRates.Current != null)
            {
                var exhangeRate = bsExhangeRates.Current as RealCourse;
                if (exhangeRate != null && exhangeRate.RC_DATEBEG != null && exhangeRate.RC_COURSE != null && exhangeRate.RC_COURSE_CB != null)
                {
                    dtpDate.Value = exhangeRate.RC_DATEBEG ?? DateTime.Today;
                    nudCourse.Value = exhangeRate.RC_COURSE ?? 0;
                    nudCourseCB.Value = exhangeRate.RC_COURSE_CB ?? 0;
                    btnAdd.Enabled = _db.IsAllowEdit(exhangeRate);
                    if (!btnAdd.Enabled)
                        errorProvider.SetError(btnAdd, string.Format("Изменять курс можно только на {0:d} (если нет счетов на эту дату)", DateTime.Today));
                }
                else
                {
                    errorProvider.SetError(btnAdd, "Некорректная текущая дата");
                }
            }
        }
        //==============================================================================================================
        private void bsExhangeRates_PositionChanged(object sender, EventArgs e)
        {
            if (checkBoxEdit.Checked)
            {
                InitializFields();
                UpdateFields();
            }
        }
        //==============================================================================================================
        private void checkBoxEdit_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxEdit.Checked)
            {
                btnAdd.Click -= AddEvent;
                btnAdd.Click += EditEvent;
                groupBoxNew.Text = "Изменить курс валюты";
                btnAdd.Text = "Изменить";
                UpdateFields();
            }
            else
            {
                btnAdd.Click -= EditEvent;
                btnAdd.Click += AddEvent;
                groupBoxNew.Text = "Новый курс валюты";
                btnAdd.Text = "Добавить";
                btnAdd.Enabled = true;
                InitializFields();
            }
        }
        //==============================================================================================================
    }
}


text:
using GamePlayer.Game;

namespace GamePlayer.Engine.Commands
{
    [CommandAttribute("opponent_moves", "Listing of opponent's moves")]
    public class OpponentMovesCommand : ICommand
    {
        public CommandResponse Execute(GameState game, string[] args)
        {
            return new CommandResponse(CommandAction.None); // Noop for now
        }
    }
}