text:
package com.fkeglevich.rawdumper.camera.parameter;

import com.fkeglevich.rawdumper.util.event.AsyncEventDispatcher;
import com.fkeglevich.rawdumper.util.event.EventDispatcher;
import com.fkeglevich.rawdumper.util.event.SimpleDispatcher;

/**
 * TODO: Add class header
 * <p>
 * Created by Flávio Keglevich on 20/09/17.
 */

class StaticParameter<T> extends Parameter<T>
{
    static <T> Parameter<T> create(String key, ValueDecoder<T> decoder, ValueEncoder<T> encoder)
    {
        return new StaticParameter<>(key, decoder, encoder, false);
    }

    static <T> Parameter<T> createAsyncEvent(String key, ValueDecoder<T> decoder, ValueEncoder<T> encoder)
    {
        return new StaticParameter<>(key, decoder, encoder, true);
    }

    static <T> Parameter<T> createReadOnly(String key, ValueDecoder<T> decoder)
    {
        return new StaticParameter<>(key, decoder, null, false);
    }

    private final String key;
    private final ValueDecoder<T> decoder;
    private final ValueEncoder<T> encoder;
    private final EventDispatcher<ParameterChangeEvent<T>> onChanging;
    private final EventDispatcher<ParameterChangeEvent<T>> onChanged;

    private StaticParameter(String key, ValueDecoder<T> decoder, ValueEncoder<T> encoder, boolean async)
    {
        this.key = key;
        this.decoder = decoder;
        this.encoder = encoder;
        this.onChanging = async ? new AsyncEventDispatcher<>() : new SimpleDispatcher<>();
        this.onChanged = async ? new AsyncEventDispatcher<>() : new SimpleDispatcher<>();
    }

    @Override
    public String getKey()
    {
        return key;
    }

    @Override
    ValueDecoder<T> getDecoder()
    {
        if (decoder == null) throw new RuntimeException("This parameter doesn't have a decoder!");
        return decoder;
    }

    @Override
    ValueEncoder<T> getEncoder()
    {
        if (encoder == null) throw new RuntimeException("This parameter is read-only!");
        return encoder;
    }

    @Override
    public EventDispatcher<ParameterChangeEvent<T>> getOnChanging()
    {
        return onChanging;
    }

    @Override
    public EventDispatcher<ParameterChangeEvent<T>> getOnChanged()
    {
        return onChanged;
    }
}


text:
<?php

declare(strict_types=1);

namespace Linio\Component\Cache\Adapter;

use Linio\Component\Cache\Exception\KeyNotFoundException;
use PHPUnit\Framework\TestCase;

class ArrayAdapterTest extends TestCase
{
    public const TEST_NAMESPACE = 'mx';

    public function testIsSettingAndGetting(): void
    {
        $adapter = new ArrayAdapter();
        $adapter->setNamespace(static::TEST_NAMESPACE);

        $setResult = $adapter->set('foo', 'bar');
        $actual = $adapter->get('foo');

        $this->assertTrue($setResult);
        $this->assertEquals('bar', $actual);
    }

    public function testIsGettingNonexistentKey(): void
    {
        $this->expectException(\Linio\Component\Cache\Exception\KeyNotFoundException::class);

        $adapter = new ArrayAdapter();
        $adapter->setNamespace(static::TEST_NAMESPACE);

        $actual = $adapter->get('foo');
    }

    public function testIsFindingKey(): void
    {
        $adapter = new ArrayAdapter();
        $adapter->setNamespace(static::TEST_NAMESPACE);
        $adapter->set('foo', 'bar');

        $actual = $adapter->contains('foo');

        $this->assertTrue($actual);
    }

    public function testIsNotFindingKey(): void
    {
        $adapter = new ArrayAdapter();
        $adapter->setNamespace(static::TEST_NAMESPACE);
        $adapter->set('foo', 'bar');

        $actual = $adapter->contains('baz');

        $this->assertFalse($actual);
    }

    public function testIsGettingMultipleKeys(): void
    {
        $adapter = new ArrayAdapter();
        $adapter->setNamespace(static::TEST_NAMESPACE);
        $adapter->set('foo', 'bar');
        $adapter->set('fooz', 'baz');

        $actual = $adapter->getMulti(['foo', 'fooz']);

        $this->assertEquals(['foo' => 'bar', 'fooz' => 'baz'], $actual);
    }

    public function testIsGettingMultipleKeysWithInvalidKeys(): void
    {
        $adapter = new ArrayAdapter();
        $adapter->setNamespace(static::TEST_NAMESPACE);
        $adapter->set('foo', 'bar');
        $adapter->set('fooz', 'baz');

        $actual = $adapter->getMulti(['foo', 'nop']);

        $this->assertEquals(['foo' => 'bar'], $actual);
    }

    public function testIsSettingMultipleKeys(): void
    {
        $adapter = new ArrayAdapter();
        $adapter->setNamespace(static::TEST_NAMESPACE);

        $actual = $adapter->setMulti(['foo' => 'bar', 'fooz' => 'baz']);

        $this->assertTrue($actual);
        $this->assertEquals('bar', $adapter->get('foo'));
        $this->assertEquals('baz', $adapter->get('fooz'));
    }

    public function testIsDeletingKey(): void
    {
        $adapter = new ArrayAdapter();
        $adapter->setNamespace(static::TEST_NAMESPACE);
        $adapter->set('foo', 'bar');

        $deleteResult = $adapter->delete('foo');

        $actual = 'bar';
        try {
            $actual = $adapter->get('foo');
        } catch (KeyNotFoundException $e) {
            $actual = null;
        }

        $this->assertTrue($deleteResult);
        $this->assertNull($actual);
    }

    public function testIsDeletingMultipleKeys(): void
    {
        $adapter = new ArrayAdapter();
        $adapter->setNamespace(static::TEST_NAMESPACE);
        $adapter->set('foo', 'bar');
        $adapter->set('fooz', 'baz');

        $deleteResult = $adapter->deleteMulti(['foo', 'fooz']);

        $actual1 = 'bar';
        try {
            $actual1 = $adapter->get('foo');
        } catch (KeyNotFoundException $e) {
            $actual1 = null;
        }

        $actual2 = 'baz';
        try {
            $actual2 = $adapter->get('fooz');
        } catch (KeyNotFoundException $e) {
            $actual2 = null;
        }

        $this->assertTrue($deleteResult);
        $this->assertNull($actual1);
        $this->assertNull($actual2);
    }

    public function testIsDeletingNonexistentKey(): void
    {
        $adapter = new ArrayAdapter();
        $adapter->setNamespace(static::TEST_NAMESPACE);

        $actual = $adapter->delete('foo');

        $this->assertTrue($actual);
    }

    public function testIsDeletingNonexistentMultipleKeys(): void
    {
        $adapter = new ArrayAdapter();
        $adapter->setNamespace(static::TEST_NAMESPACE);
        $adapter->set('foo', 'bar');
        $adapter->set('fooz', 'baz');

        $deleteResult = $adapter->deleteMulti(['foo', 'nop']);

        $actual1 = 'bar';
        try {
            $actual1 = $adapter->get('foo');
        } catch (KeyNotFoundException $e) {
            $actual1 = null;
        }

        $actual2 = 'baz';
        try {
            $actual2 = $adapter->get('fooz');
        } catch (KeyNotFoundException $e) {
            $actual2 = null;
        }

        $this->assertTrue($deleteResult);
        $this->assertNull($actual1);
        $this->assertEquals('baz', $actual2);
    }

    public function testIsFlushingData(): void
    {
        $adapter = new ArrayAdapter();
        $adapter->setNamespace(static::TEST_NAMESPACE);
        $adapter->set('foo', 'bar');
        $adapter->set('fooz', 'baz');

        $flushResult = $adapter->flush();

        $actual1 = 'bar';
        try {
            $actual1 = $adapter->get('foo');
        } catch (KeyNotFoundException $e) {
            $actual1 = null;
        }

        $actual2 = 'baz';
        try {
            $actual2 = $adapter->get('fooz');
        } catch (KeyNotFoundException $e) {
            $actual2 = null;
        }

        $this->assertTrue($flushResult);
        $this->assertNull($actual1);
        $this->assertNull($actual2);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="65dip"
    android:background="#f8f8f8"
    android:gravity="center"
    android:padding="10dip" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="8dip"
        android:layout_marginTop="8dip"
        android:gravity="center" >

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:drawablePadding="10dip"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/value"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:drawablePadding="10dip"
            android:drawableRight="@drawable/arrow_right_normal"
            android:textSize="18sp" />
    </RelativeLayout>

</RelativeLayout>


text:
#ifndef _CS_Console_
#define _CS_Console_

#include "CS_Object.h"
#include "CS_String.h"

namespace System {

/*static*/ class Console {
public:
/*x*/	//static ConsoleColor BackgroundColor { get; set; }
/*x*/	//static u32 BufferHeight { get; set; }
/*x*/	//static u32 BufferWidth { get; set; }
/*x*/	//static bool CapsLock { get; }
/*x*/	//static u32 CursorLeft { get; set; }
/*x*/	//static u32 CursorSize { get; set; }
/*x*/	//static u32 CursorTop { get; set; }
/*x*/	//static bool CursorVisible { get; set; }
/*x*/	//static TextWriter Error { get; }
/*x*/	//static ConsoleColor ForegroundColor { get; set; }
/*x*/	//static TextReader In { get; }
/*x*/	//static Encoding InputEncoding { get; set; }
/*x*/	//static bool KeyAvailable { get; }
/*x*/	//static u32 LargestWindowHeight { get; }
/*x*/	//static u32 LargestWindowWidth { get; }
/*x*/	//static bool NumberLock { get; }
/*x*/	//static TextWriter Out { get; }
/*x*/	//static Encoding OutputEncoding { get; set; }
/*x*/	//static System::String* Title { get; set; }
/*x*/	//static bool TreatControlCAsInput { get; set; }
/*x*/	//static u32 WindowHeight { get; set; }
/*x*/	//static u32 WindowLeft { get; set; }
/*x*/	//static u32 WindowTop { get; set; }
/*x*/	//static u32 WindowWidth { get; set; }
/*x*/	//static event ConsoleCancelEventHandler CancelKeyPress;

/*x*/	//static void Beep();
/*x*/	//static void Beep(u32 frequency, u32 duration);
/*x*/	//static void Clear();
/*x*/	//static void MoveBufferArea(u32 sourceLeft, u32 sourceTop, u32 sourceWidth, u32 sourceHeight, u32 targetLeft, u32 targetTop);
/*x*/	//static void MoveBufferArea(u32 sourceLeft, u32 sourceTop, u32 sourceWidth, u32 sourceHeight, u32 targetLeft, u32 targetTop, uniChar sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor);
/*x*/	//static Stream OpenStandardError();
/*x*/	//static Stream OpenStandardError(u32 bufferSize);
/*x*/	//static Stream OpenStandardInput();
/*x*/	//static Stream OpenStandardInput(u32 bufferSize);
/*x*/	//static Stream OpenStandardOutput();
/*x*/	//static Stream OpenStandardOutput(u32 bufferSize);
/*x*/	//static u32 Read();
/*x*/	//static ConsoleKeyInfo ReadKey();
/*x*/	//static ConsoleKeyInfo ReadKey(bool intercept);
/*x*/	//static System::String* ReadLine();
/*x*/	//static void ResetColor();
/*x*/	//static void SetBufferSize(u32 width, u32 height);
/*x*/	//static void SetCursorPosition(u32 left, u32 top);
/*x*/	//static void SetError(TextWriter newError);
/*x*/	//static void SetIn(TextReader newIn);
/*x*/	//static void SetOut(TextWriter newOut);
/*x*/	//static void SetWindowPosition(u32 left, u32 top);
/*x*/	//static void SetWindowSize(u32 width, u32 height);
/*x*/	static void Write(bool value);
/*x*/	static void Write(uniChar value);
/*x*/	static void Write(System::Array<uniChar>* buffer);
/*x*/	//static void Write(decimal value);
/*x*/	static void Write(double value);
/*x*/	static void Write(float value);
/*x*/	static void Write(s32 value);
/*x*/	static void Write(s64 value);
/*x*/	static void Write(System::Object* value);
/*x*/	static void Write(System::String* value);
/*x*/	static void Write(u32 value);
/*x*/	static void Write(u64 value);
/*x*/	//static void Write(System::String* format, System::Object* arg0);
/*x*/	//static void Write(System::String* format, params object[] arg);
/*x*/	static void Write(System::Array<uniChar>* buffer, u32 index, u32 count);
/*x*/	//static void Write(System::String* format, System::Object* arg0, System::Object* arg1);
/*x*/	//static void Write(System::String* format, System::Object* arg0, System::Object* arg1, System::Object* arg2);
/*x*/	//static void Write(System::String* format, System::Object* arg0, System::Object* arg1, System::Object* arg2, System::Object* arg3);
/*x*/	static void WriteLine()											{ printf("\n");					}
/*x*/	inline static void WriteLine(bool value)						{ Write(value); printf("\n");	}
/*x*/	inline static void WriteLine(uniChar value)						{ Write(value); printf("\n");	}
/*x*/	inline static void WriteLine(System::Array<uniChar>* buffer)	{ Write(buffer); printf("\n");	}
/*x*/	//inline static void WriteLine(decimal value)					{ Write(value); printf("\n");	}
/*x*/	inline static void WriteLine(double value)						{ Write(value); printf("\n");	}
/*x*/	inline static void WriteLine(float value)						{ Write(value); printf("\n");	}
/*x*/	inline static void WriteLine(s32 value)							{ Write(value); printf("\n");	}
/*x*/	inline static void WriteLine(s64 value)							{ Write(value); printf("\n");	}
/*x*/	inline static void WriteLine(System::Object* value)				{ Write(value); printf("\n");	}
/*x*/	inline static void WriteLine(System::String* value)				{ Write(value); printf("\n");	}
/*x*/	inline static void WriteLine(u32 value)							{ Write(value); printf("\n");	}
/*x*/	inline static void WriteLine(u64 value)							{ Write(value); printf("\n");	}
/*x*/	//static void WriteLine(System::String* format, System::Object* arg0)					{ Write(value); printf("\n");	}
/*x*/	//static void WriteLine(System::String* format, params object[] arg)					{ Write(value); printf("\n");	}
/*x*/	inline static void WriteLine(System::Array<uniChar>* buffer, u32 index, u32 count)		{ Write(buffer, index, count); printf("\n");	}
/*x*/	//static void WriteLine(System::String* format, System::Object* arg0, System::Object* arg1);
/*x*/	//static void WriteLine(System::String* format, System::Object* arg0, System::Object* arg1, System::Object* arg2);
/*x*/	//static void WriteLine(System::String* format, System::Object* arg0, System::Object* arg1, System::Object* arg2, System::Object* arg3);

};

}

#endif // _CS_Console_


text:
public class BritishCoins {
	public static int[] coins(int pence) {
		final int PENNIES_IN_SHILLING = 12;
		final int SHILLINGS_IN_POUND = 20;
		final int PENNIES_IN_POUND = PENNIES_IN_SHILLING * SHILLINGS_IN_POUND;

		int pennyCount = 0;
		int shillingCount = 0;
		int poundCount = 0;

		// Get pound count
		while (pence >= PENNIES_IN_POUND) {
			pence -= PENNIES_IN_POUND;
			poundCount++;
		}

		// Get shilling count
		while (pence >= PENNIES_IN_SHILLING) {
			pence -= PENNIES_IN_SHILLING;
			shillingCount++;
		}

		// Get penny count (equal to whatever is left in 'pence')
		pennyCount = pence;

		return new int[] { poundCount, shillingCount, pennyCount };
	}
}


text:
/* eslint-env node */
'use strict';

module.exports = function(environment) {
  const useDb = false;

  let ENV = {
    useDb,
    modulePrefix: 'ember-invoice-manager',
    environment,
    rootURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      },
      EXTEND_PROTOTYPES: {
        // Prevent Ember Data from overriding Date.parse.
        Date: false
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    },

    googleFonts: [
      'Open+Sans:300,400,700',
      'Montserrat:300,700'
    ],

    // highlight.js settings
    emberHighlightJs: {
      style: 'monokai-sublime'
    },

    // Set or update content security policies
    contentSecurityPolicy: {
      'font-src': "'self' fonts.gstatic.com",
      'style-src': "'self' fonts.googleapis.com"
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.useDb = false;
  }

  if (environment === 'production') {
    ENV.useDb = false;
  }

  ENV['ember-cli-mirage'] = {
    directory: 'app/mirage',
    enabled: !ENV.useDb
  };

  return ENV;
};


text:
using System.Threading.Tasks;
using System.Web.Http;
using Common;
using Core.Clients;
using Wallet_Api.Models;
using Wallet_Api.Strings;

namespace Wallet_Api.Controllers
{
    public class AccountExistController : ApiController
    {
        private readonly IClientAccountsRepository _clientAccountsRepository;

        public AccountExistController(IClientAccountsRepository clientAccountsRepository)
        {
            _clientAccountsRepository = clientAccountsRepository;
        }

        public async Task<ResponseModel<AccountExistResultModel>> Get(string email)
        {
            if (string.IsNullOrEmpty(email))
                return ResponseModel<AccountExistResultModel>.CreateInvalidFieldError("email", Phrases.FieldShouldNotBeEmpty);

            if (!email.IsValidEmail())
                return ResponseModel<AccountExistResultModel>.CreateInvalidFieldError("email", Phrases.InvalidEmailFormat);

            return ResponseModel<AccountExistResultModel>.CreateOk(
                new AccountExistResultModel { IsEmailRegistered = await _clientAccountsRepository.IsTraderWithEmailExistsAsync(email)});
        }
    }
}


text:
require_relative 'spec_helper'

include Crashlytics

describe Runner do
  let(:html) { File.read(Dir.pwd + "/spec/fixtures/issues.html") }

  subject(:runner) do
    Runner.new 'email', 'pass'
  end

  describe "#run" do
    it 'gets from the crawler' do
      allow_any_instance_of(Crawler).to receive(:statistics_page).and_return(html)
      runner.run
    end
  end

end


text:
SET(CMAKE_SYSTEM_NAME Windows)

# which compilers to use for C and C++
SET(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc)
SET(CMAKE_CXX_COMPILER x86_64-w64-mingw32-g++)
SET(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres)

# here is the target environment located
SET(CMAKE_FIND_ROOT_PATH  /usr/share/mingw-w64)

# adjust the default behaviour of the FIND_XXX() commands:
# search headers and libraries in the target environment, search
# programs in the host environment
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY BOTH)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE BOTH)


text:
/*
** Author: Eric Veach, July 1994.
**
*/

#ifndef __tess_h_
#define __tess_h_

#include "../glues_library.h"

#include "mesh.h"
#include "dict.h"
#include "priorityq.h"

/* The begin/end calls must be properly nested.  We keep track of
 * the current state to enforce the ordering.
 */
enum TessState {T_DORMANT, T_IN_POLYGON, T_IN_CONTOUR};

/* We cache vertex data for single-contour polygons so that we can
 * try a quick-and-dirty decomposition first.
 */
#define TESS_MAX_CACHE 100

typedef struct CachedVertex
{
   GLfloat coords[3];
   void*   data;
} CachedVertex;

struct GLUtesselator
{
   /*** state needed for collecting the input data ***/
   enum TessState state;        /* what begin/end calls have we seen? */

   GLUhalfEdge* lastEdge;       /* lastEdge->Org is the most recent vertex */
   GLUmesh* mesh;               /* stores the input contours, and eventually
                                   the tessellation itself */

   void (GLU_APIENTRY* callError)(GLenum errnum);

   /*** state needed for projecting onto the sweep plane ***/
   GLfloat normal[3]; /* user-specified normal (if provided) */
   GLfloat sUnit[3];  /* unit vector in s-direction (debugging) */
   GLfloat tUnit[3];  /* unit vector in t-direction (debugging) */

   /*** state needed for the line sweep ***/
   GLfloat   relTolerance;      /* tolerance for merging features */
   GLenum    windingRule;       /* rule for determining polygon interior */
   GLboolean fatalError;        /* fatal error: needed combine callback */

   Dict*      dict;             /* edge dictionary for sweep line */
   PriorityQ* pq;               /* priority queue of vertex events */
   GLUvertex* event;            /* current sweep event being processed */

   void (GLU_APIENTRY* callCombine)(GLfloat coords[3], void*  data[4],
                                GLfloat weight[4], void** outData);

  /*** state needed for rendering callbacks (see render.c) ***/
  GLboolean     flagBoundary;   /* mark boundary edges (use EdgeFlag) */
  GLboolean     boundaryOnly;   /* Extract contours, not triangles    */
  /* list of triangles which could not be rendered as strips or fans */
  GLUface*      lonelyTriList;

  void (GLU_APIENTRY* callBegin)(GLenum type);
  void (GLU_APIENTRY* callEdgeFlag)(GLboolean boundaryEdge);
  void (GLU_APIENTRY* callVertex)(void* data);
  void (GLU_APIENTRY* callEnd)(void);
  void (GLU_APIENTRY* callMesh)(GLUmesh* mesh);

  /*** state needed to cache single-contour polygons for renderCache() */

  GLboolean     emptyCache;             /* empty cache on next vertex() call */
  int           cacheCount;             /* number of cached vertices */
  CachedVertex  cache[TESS_MAX_CACHE];  /* the vertex data */

  /*** rendering callbacks that also pass polygon data  ***/
  void (GLU_APIENTRY* callBeginData)(GLenum type, void* polygonData);
  void (GLU_APIENTRY* callEdgeFlagData)(GLboolean boundaryEdge, void* polygonData);
  void (GLU_APIENTRY* callVertexData)(void* data, void* polygonData);
  void (GLU_APIENTRY* callEndData)(void* polygonData);
  void (GLU_APIENTRY* callErrorData)(GLenum errnum, void *polygonData);
  void (GLU_APIENTRY* callCombineData)(GLfloat coords[3], void* data[4],
                                   GLfloat weight[4], void** outData,
                                   void* polygonData);

  jmp_buf env;          /* place to jump to when memAllocs fail */

  void* polygonData;    /* client data for current polygon */
};

GLU_API void GLU_APIENTRY __gl_noBeginData(GLenum type, void* polygonData);
GLU_API void GLU_APIENTRY __gl_noEdgeFlagData(GLboolean boundaryEdge, void* polygonData);
GLU_API void GLU_APIENTRY __gl_noVertexData(void* data, void* polygonData);
GLU_API void GLU_APIENTRY __gl_noEndData(void* polygonData);
GLU_API void GLU_APIENTRY __gl_noErrorData(GLenum errnum, void* polygonData);
GLU_API void GLU_APIENTRY __gl_noCombineData(GLfloat coords[3], void* data[4],
                                       GLfloat weight[4], void** outData,
                                       void* polygonData);

#define CALL_BEGIN_OR_BEGIN_DATA(a)                     \
   if (tess->callBeginData != &__gl_noBeginData)        \
      (*tess->callBeginData)((a),tess->polygonData);    \
   else (*tess->callBegin)((a));

#define CALL_VERTEX_OR_VERTEX_DATA(a)                   \
   if (tess->callVertexData != &__gl_noVertexData)      \
      (*tess->callVertexData)((a),tess->polygonData);   \
   else (*tess->callVertex)((a));

#define CALL_EDGE_FLAG_OR_EDGE_FLAG_DATA(a)             \
   if (tess->callEdgeFlagData != &__gl_noEdgeFlagData)  \
      (*tess->callEdgeFlagData)((a),tess->polygonData); \
   else (*tess->callEdgeFlag)((a));

#define CALL_END_OR_END_DATA()                          \
   if (tess->callEndData != &__gl_noEndData)            \
      (*tess->callEndData)(tess->polygonData);          \
   else (*tess->callEnd)();

#define CALL_COMBINE_OR_COMBINE_DATA(a,b,c,d)           \
   if (tess->callCombineData != &__gl_noCombineData)    \
      (*tess->callCombineData)((a),(b),(c),(d),tess->polygonData); \
   else (*tess->callCombine)((a),(b),(c),(d));

#define CALL_ERROR_OR_ERROR_DATA(a)                     \
   if (tess->callErrorData != &__gl_noErrorData)        \
      (*tess->callErrorData)((a),tess->polygonData);    \
   else (*tess->callError)((a));

#endif /* __tess_h_ */


text:
from __future__ import unicode_literals

from django.db import migrations
import multiselectfield

class Migration(migrations.Migration):

    dependencies = [
        ('projects', '0013_merge'),
    ]

    operations = [
        migrations.AlterField(
            model_name='project',
            name='currencies',
            field=multiselectfield.MultiSelectField(choices=[(b'EUR', 'Euro')], default=[], max_length=100, null=True),
        ),
    ]


text:
/**
 * Resizable tc.
 * @author yiminghe@gmail.com
 */
KISSY.use('resizable', function (S, Resizable) {
    // ie9 mousemove does not fire
    if (document.documentMode == 9) {
        return;
    }

    var Gesture = S.Event.Gesture;

    var $ = S.all;

    describe('preserveRatio works', function () {

        beforeEach(function () {
            this.addMatchers({
                toBeAlmostEqual: function (expected) {
                    return Math.abs(parseInt(this.actual) - parseInt(expected)) < 20;
                },

                toBeEqualRect: function (expect) {
                    var actual = this.actual;
                    for (var i in actual) {
                        if (actual[i] - expect[i] < 5) {
                            continue;
                        } else {
                            return false;
                        }
                    }
                    return true;
                },

                toBeEqual: function (expected) {
                    return Math.abs(parseInt(this.actual) - parseInt(expected)) < 5;
                }
            });
        });

        var cssText = 'position: absolute;' +
            'width: 100px;height: 100px;' +
            'left: 100px;top:100px;';

        var dom = $('

').appendTo('body');
        dom.attr('style', cssText);

        beforeEach(function () {
            dom.attr('style', cssText);
        });

        var resizable = new Resizable({
            node: dom,
            preserveRatio: true,
            handlers: ["b", "t", "r", "l", "tr", "tl", "br", "bl"]
        });

        var lNode = dom.one('.ks-resizable-handler-l');

        it('l resize works', function () {
            jasmine.simulateForDrag(lNode[0], Gesture.start, {
                clientX: 102,
                clientY: 110
            });
            waits(200);
            runs(function () {
                jasmine.simulateForDrag(document, Gesture.move, {
                    clientX: 92,
                    clientY: 110
                });
            });
            waits(200);
            runs(function () {
                jasmine.simulateForDrag(document, Gesture.move, {
                    clientX: 82,
                    clientY: 110
                });
            });
            waits(200);
            runs(function () {
                jasmine.simulateForDrag(document, Gesture.end, {
                    clientX: 82,
                    clientY: 110
                });
            });
            waits(200);
            runs(function () {
                expect(dom.width()).toBeEqual(120);
                expect(dom.height()).toBeEqual(120);
                expect(dom.offset().left).toBeEqual(80);
                expect(dom.offset().top).toBeEqual(100);
            });
        });

        it('destroy works', function () {
            resizable.destroy();
            S.each(['t', 'l', 'b', 'r', 'tl', 'tr', 'bl', 'br'], function (s) {
                expect(dom.one('.ks-resizable-handler-' + s)).toBe(null);
            });
        });
    });

});


text:
package korolev.blazeServer

import java.net.InetAddress
import java.security.KeyStore
import java.util.concurrent.Executors
import javax.net.ssl.{KeyManagerFactory, SSLContext}

import org.http4s.blaze.util.BogusKeystore

import scala.concurrent.{ExecutionContext, ExecutionContextExecutorService}

/**
  * @author Aleksey Fomkin <aleksey.fomkin@gmail.com>
  */
case class BlazeServerConfig(
  port: Int = 8181,
  host: String = InetAddress.getLoopbackAddress.getHostAddress,
  /**
    * Standard Java SSL context.
    * Use [[BlazeServerConfig.bogusSslContext]] for tests
    */
  sslContext: Option[SSLContext] = None,
  bufferSize: Int = 8 * 1024,
  doNotBlockCurrentThread: Boolean = false
)(
  // Trampoline
  implicit val executionContext: ExecutionContextExecutorService
)

object BlazeServerConfig {

  val default = {
    implicit val ec: ExecutionContextExecutorService = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(10))
    //import scala.concurrent.ExecutionContext.Implicits.global
    BlazeServerConfig()
  }

  def bogusSslContext: SSLContext = {
    val ksStream = BogusKeystore.asInputStream()
    assert(ksStream != null)
    val ks = KeyStore.getInstance("JKS")
    ks.load(ksStream, BogusKeystore.getKeyStorePassword)
    val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
    kmf.init(ks, BogusKeystore.getCertificatePassword)
    val context = SSLContext.getInstance("SSL")
    context.init(kmf.getKeyManagers, null, null)
    context
  }
}


text:
There are simple servers for most Unix and Windows operating systems, sure, but do you want the hassle of installing Java and its constant need for updates? Do you want to manage starting the actual server itself? Probably not. I know I don't want to.

This is also helpful to give to your buddies so they can run their own local server, or it's very handy for a LAN party.

This stack uses the vanilla Minecraft server, Minecraft Overviewer set to the leaflet development branch, and caddy to serve static HTML files.

## How?

* Install [Vagrant](http://vagrantup.com)
* Install [VirtualBox](https://www.virtualbox.org/) if you don't already have one.
* Clone this repo
* `vagrant up`

## Alternative How?

If you want to run this stack directly, without the use of a VM, the process is painless. You do need a few things installed, but the list of required items is quite short. You need an 'ecosystem' directory (just a place to put the server and the overviewer). For instance, this might be `/home/notch/mcserver`. It is not likely to be the Vagrant default, so be sure and set this variable!

* Install [Docker](http://docker.com)
* Ensure GNU Make is installed (specific to your operating system)
* `export MC_HOME=/path/to/minecraft/ecosystem` somewhere, probably in your `~/.bashrc`
* `cd vagrant-minecraft && ./provision.sh`

Once the ecosystem is up and running (check with `docker ps`), you can remove and restart individual components by `cd`ing into the directory and then running `make clean && make` for the minecraft server, overviewer, and caddy.

## What this provides

This repository gives you access to a fresh-built VM hosting the newest version of vanilla Minecraft. It also generates a map of your world and keeps it up to date daily. There is nothing for you to do or configure. It Just Works(TM).

### From your machine

* Map: http://localhost:8088
* Server: localhost:25565

### From other machines

* Map: http://your-ip-or-dns:8088
* Server: your-ip-or-dns:25565

You will need to manage your local firewall settings accordingly. This process works much better if you have local DNS resolution from a fine product like [pfSense](http://pfsense.org) or [DD-WRT](http://www.dd-wrt.com/).


text:
function Add-ReposAsSubtrees {
  [CmdletBinding()]
  param(
    [Parameter(Mandatory = $true)]
    [hashtable[]]
    $SourceRepoList,

    [Parameter(Mandatory = $true)]
    [string]
    $BaseFolder,

    [Parameter(Mandatory = $true)]
    [string]
    $TargetRepoUrl,

    [Parameter(Mandatory = $true)]
    [scriptblock]
    $PrepParamsFunc
  )

  if ($SourceRepoList.Length -eq 0 -or [string]::IsNullOrEmpty($BaseFolder) -or [string]::IsNullOrEmpty($TargetRepoUrl)) {
    throw "Source repos, base folder and target repo must be supplied"
  }

  if (!(Test-Path -Path $BaseFolder)) {
    throw "Base folder does not exist"
  }

  $targetRepoName = (Split-Path -Path $TargetRepoUrl -Leaf) -replace '.git', ''
  $TargetRepoPath = Join-Path -Path $BaseFolder -ChildPath $targetRepoName

  Push-Location

  Set-Location $BaseFolder

  if (!(Test-Path -Path $TargetRepoPath)) {
    Write-Output "`r`n$TargetRepoUrl"
    git clone $TargetRepoUrl
  }

  Set-Location $TargetRepoPath

  foreach ($sourceRepo in $SourceRepoList) {
    $params = (& $PrepParamsFunc $sourceRepo)

    Add-RepoAsSubtree `
      -TargetRepoPath $TargetRepoPath `
      -SourceRemoteName $params.SourceRemoteName `
      -SourceRepoUrl $params.SourceRepoUrl `
      -DestinationPrefix $params.DestinationPrefix
  }

  Pop-Location
}

function Add-RepoAsSubtree {
  [CmdletBinding()]
  param(
    [Parameter(Mandatory = $true)]
    [string]
    $TargetRepoPath,

    [Parameter(Mandatory = $true)]
    [string]
    $SourceRemoteName,

    [Parameter(Mandatory = $true)]
    [string]
    $SourceRepoUrl,

    [Parameter(Mandatory = $true)]
    [string]
    $DestinationPrefix
  )

  $destination = Join-Path -Path $TargetRepoPath -ChildPath $DestinationPrefix

  Write-Output "`r`n**************************************** BEGIN - $SourceRepoUrl"

  Write-Output "`r`n-------------------- Create folder $destination"
  New-Item -Type Directory -Path $destination | Out-Null

  Write-Output "`r`n-------------------- git remote add -f $SourceRemoteName $sourceRepoUrl`r`n"
  git remote add -f $SourceRemoteName $SourceRepoUrl

  Write-Output "`r`n-------------------- git merge -s ours --no-commit $SourceRemoteName/master`r`n"
  git merge --allow-unrelated-histories -s ours --no-commit $SourceRemoteName/master

  Write-Output "`r`n-------------------- git read-tree --prefix=$DestinationPrefix\ -u $SourceRemoteName/master`r`n"
  git read-tree --prefix=$DestinationPrefix/ -u $SourceRemoteName/master

  Write-Output "`r`n-------------------- git add . --all AND git commit -m `'Merge $sourceRepoUrl as our subdirectory`'`r`n"
  git add . --all
  git commit -m ("Merge $sourceRepoUrl as our subdirectory")

  Write-Output "`r`n-------------------- git pull --no-rebase -s subtree $SourceRemoteName master`r`n"
  git pull --no-rebase -s subtree $SourceRemoteName master

  Write-Output "`r`n-------------------- git push origin master`r`n"
  git push origin master

  Write-Output "`r`n-------------------- git remote rm $SourceRemoteName`r`n"
  git remote rm $SourceRemoteName

  Write-Output "`r`n**************************************** END - $SourceRepoUrl`r`n"
}

# An example of param builder function
function Get-ParamsHash {
  [CmdletBinding()]
  param(
    [Parameter(Mandatory = $true)]
    [hashtable]
    $SourceRepo
  )

  $sourceRemoteName = (Split-Path -Path $SourceRepo.Folder -Leaf)
  $sourceRepoUrl = $SourceRepo.Url
  $sourceRepoFolder = $SourceRepo.Folder

  return @{
    'SourceRemoteName' = $sourceRemoteName;
    'SourceRepoUrl' = $sourceRepoUrl;
    'DestinationPrefix' = $sourceRepoFolder
  }
}


text:
require 'spec_helper'

describe Hitnmiss do
  it 'has a version number' do
    expect(Hitnmiss::VERSION).not_to be nil
  end

  describe "setting the cache driver" do
    it "specifies the cache driver to use" do
      Hitnmiss.register_driver(:my_driver, Hitnmiss::InMemoryDriver.new)
      repo_klass = Class.new do
        include Hitnmiss::Repository

        driver :my_driver
      end
    end
  end

  describe "setting default expiration" do
    it "specifies the default expiration to use if the cacheable entity doesn't have an expiration" do
      repo_klass = Class.new do
        include Hitnmiss::Repository

        default_expiration 134
      end
    end
  end

  describe "priming the cache" do
    it "obtains the value, caches it, and return the cached value" do
      repo_klass = Class.new do
        include Hitnmiss::Repository

        private

        def fetch(*args)
          Hitnmiss::Entity.new('foo', expiration: 235)
        end
      end

      allow(repo_klass).to receive(:name).and_return('test_prime')

      expect(repo_klass.new.prime('some_token')).to eq('foo')
    end
  end

  describe "setting cacheable entity expiration" do
    it "sets the expiration of the cache to cacheable entities expiration" do
      repo_klass = Class.new do
        include Hitnmiss::Repository

        private

        def fetch(*args)
          Hitnmiss::Entity.new('foo', expiration: 235)
        end
      end

      allow(repo_klass).to receive(:name).and_return('test_entity_expir')

      cur_time = Time.now.utc

      Timecop.freeze(cur_time) do
        repo_klass.new.prime('some_token')

        driver = Hitnmiss.driver(:in_memory)
        cache = driver.instance_variable_get(:@cache)
        expect(cache['test_entity_expir.String:some_token']['expiration']).to eq(cur_time.to_i + 235)
      end
    end
  end

  describe "getting a not already cached value" do
    it "primes the cache, and returns the cached value" do
      repo_klass = Class.new do
        include Hitnmiss::Repository

        private

        def fetch(*args)
          Hitnmiss::Entity.new('foo', expiration: 235)
        end
      end

      allow(repo_klass).to receive(:name).and_return('test_get_noncached')

      expect(repo_klass.new.get('some_token')).to eq('foo')
    end
  end

  describe "getting an already cached value" do
    it "returns the cached value" do
      repo_klass = Class.new do
        include Hitnmiss::Repository

        private

        def fetch(*args)
          Hitnmiss::Entity.new('foo', expiration: 235)
        end
      end

      allow(repo_klass).to receive(:name).and_return('test_get_cached')

      repository = repo_klass.new
      repository.prime

      expect(repository.get('some_token')).to eq('foo')
    end
  end

  describe 'prime entire repository with cached values' do
    it 'returns the cached values' do
      repo_klass = Class.new do
        include Hitnmiss::Repository

        private

        def fetch_all(keyspace)
          [
            { args: ['key1'], entity: Hitnmiss::Entity.new('myval', expiration: 22223) },
            { args: ['key2'], entity: Hitnmiss::Entity.new('myval2', expiration: 43564) }
          ]
        end
      end

      allow(repo_klass).to receive(:name).and_return('test_prime_all')

      repository = repo_klass.new

      expect(repository.prime_all).to eq(['myval', 'myval2'])
    end
  end

  describe 'get all cached values' do
    it 'returns all the currently cached values' do
      repo_klass = Class.new do
        include Hitnmiss::Repository

        private

        def fetch(*args)
          if args.first && args.first == 'hi'
            Hitnmiss::Entity.new('hello', expiration: 235)
          else
            Hitnmiss::Entity.new('goodbye', expiration: 235)
          end
        end
      end

      allow(repo_klass).to receive(:name).and_return('test_all')

      repository = repo_klass.new
      repository.prime('hi')
      repository.prime('something_else')

      expect(repository.all).to eq(['hello', 'goodbye'])
    end
  end

  describe 'delete a cached value' do
    it 'deletes the cached value' do
      repo_klass = Class.new do
        include Hitnmiss::Repository

        private

        def fetch(*args)
          Hitnmiss::Entity.new('foo', expiration: 235)
        end
      end

      allow(repo_klass).to receive(:name).and_return('test_delete')

      repository = repo_klass.new

      repository.prime('aoeuaoeuao')
      repository.delete('aoeuaoeuao')
      expect(repository.all).to be_empty
    end
  end

  describe 'clear all cached values' do
    it 'deletes all the cached values' do
      repo_klass = Class.new do
        include Hitnmiss::Repository

        private

        def fetch(*args)
          if args.first && args.first == 'hi'
            Hitnmiss::Entity.new('hello', expiration: 235)
          else
            Hitnmiss::Entity.new('goodbye', expiration: 235)
          end
        end
      end

      allow(repo_klass).to receive(:name).and_return('test_delete')

      repository = repo_klass.new
      repository.prime('hi')
      repository.prime('something_else')
      repository.clear

      expect(repository.all).to be_empty
    end
  end

  describe 'setting and getting a fingerprint' do
    it 'sets and gets the fingerprint' do
      repo_klass = Class.new do
        include Hitnmiss::Repository

        private

        def fetch(*args)
          Hitnmiss::Entity.new('hello', expiration: 235, fingerprint: 'some-fingerprint')
        end
      end

      repository = repo_klass.new
      repository.prime
      hit = repository.send(:get_from_cache)
      expect(hit).to be_a(Hitnmiss::Driver::Hit)
      expect(hit.fingerprint).to eq('some-fingerprint')
    end
  end
end


text:
//
//  DemoCalendarMonth.m
//  Created by Devin Ross on 10/31/09.
//

#import "CalendarMonthViewController.h"

@implementation CalendarMonthViewController

#pragma mark - View Lifecycle
- (void) viewDidLoad{
	[super viewDidLoad];
	[self.monthView selectDate:[NSDate month]];

}

#pragma mark - MonthView Delegate & DataSource
- (NSArray*) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate{
	[self generateRandomDataForStartDate:startDate endDate:lastDate];
	return self.dataArray;
}
- (void) calendarMonthView:(TKCalendarMonthView*)monthView didSelectDate:(NSDate*)date{

	// CHANGE THE DATE TO YOUR TIMEZONE
	TKDateInformation info = [date dateInformationWithTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
	NSDate *myTimeZoneDay = [NSDate dateFromDateInformation:info timeZone:[NSTimeZone systemTimeZone]];

	NSLog(@"Date Selected: %@",myTimeZoneDay);

	[self.tableView reloadData];
}
- (void) calendarMonthView:(TKCalendarMonthView*)mv monthDidChange:(NSDate*)d animated:(BOOL)animated{
	[super calendarMonthView:mv monthDidChange:d animated:animated];
	[self.tableView reloadData];
}

#pragma mark - UITableView Delegate & DataSource
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;

}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSArray *ar = [self.dataDictionary objectForKey:[self.monthView dateSelected]];
	if(ar == nil) return 0;
	return [ar count];
}
- (UITableViewCell *) tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

	NSArray *ar = [self.dataDictionary objectForKey:[self.monthView dateSelected]];
	cell.textLabel.text = [ar objectAtIndex:indexPath.row];

    return cell;

}

- (void) generateRandomDataForStartDate:(NSDate*)start endDate:(NSDate*)end{
	// this function sets up dataArray & dataDictionary
	// dataArray: has boolean markers for each day to pass to the calendar view (via the delegate function)
	// dataDictionary: has items that are associated with date keys (for tableview)

	NSLog(@"Delegate Range: %@ %@ %d",start,end,[start daysBetweenDate:end]);

	self.dataArray = [NSMutableArray array];
	self.dataDictionary = [NSMutableDictionary dictionary];

	NSDate *d = start;
	while(YES){

		int r = arc4random();
		if(r % 3==1){
			[self.dataDictionary setObject:[NSArray arrayWithObjects:@"Item one",@"Item two",nil] forKey:d];
			[self.dataArray addObject:[NSNumber numberWithBool:YES]];

		}else if(r%4==1){
			[self.dataDictionary setObject:[NSArray arrayWithObjects:@"Item one",nil] forKey:d];
			[self.dataArray addObject:[NSNumber numberWithBool:YES]];

		}else
			[self.dataArray addObject:[NSNumber numberWithBool:NO]];

		TKDateInformation info = [d dateInformationWithTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
		info.day++;
		d = [NSDate dateFromDateInformation:info timeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
		if([d compare:end]==NSOrderedDescending) break;
	}

}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Aecidium inulae-grandis Nevod.

### Remarks
null


text:
<?php

namespace Collections\Tests\Dictionary;

use Collections\Dictionary;
use PHPUnit\Framework\TestCase;

class ClearTest extends TestCase
{
    public function test_clear_creates_empty_dictionary_of_same_type()
    {
        $d = new Dictionary('string','int');
        $d = $d->add('a', 1);

        $empty = $d->clear();

        //original is unchanged
        $this->assertEquals(1, $d->count());
        $this->assertEquals(0, $empty->count());

        //key and value types should be the same
        $this->assertEquals($d->getKeyType(), $empty->getKeyType());
        $this->assertEquals($d->getValueType(), $empty->getValueType());
    }
}


text:
package com.spotify.styx.monitoring;

import com.spotify.styx.storage.Storage;
import com.spotify.styx.util.Time;
import java.lang.reflect.Proxy;
import javaslang.control.Try;

/**
 * A proxy for instrumenting an instance of {@link Storage} {@link Proxy#newProxyInstance}.
 */
public class MeteredStorageProxy extends MeteredProxy<Storage> {

  private MeteredStorageProxy(Storage delegate, Stats stats, Time time) {
    super(delegate, stats, time);
  }

  public static Storage instrument(Storage storage, Stats stats, Time time) {
    return MeteredProxy.instrument(Storage.class, new MeteredStorageProxy(storage, stats, time));
  }

  @Override
  protected void checkResult(final String operation, final long durationMillis,
                               final Try<?> result,
                               final Stats stats) {
    final String status = (result.isSuccess()) ? "success" : "failure";
    stats.recordStorageOperation(operation, durationMillis, status);
  }
}


text:
<!DOCTYPE html>

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

    <link rel="icon" type="image/png" href="https://just2us.com/img/favicon-180.png" />
    <link rel="apple-touch-icon" href="https://just2us.com/img/favicon-192.png"/>

    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/clean-blog.min.css">
    <link rel="stylesheet" href="/css/syntax.css">

    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic&display=swap' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&display=swap' rel='stylesheet' type='text/css'>

    <link type="application/atom+xml" rel="alternate" href="https://just2me.com/feed.xml" title="Just2me" />

<title>My Biggest On Stage Preparation - DEMO Asia | Just2me</title>
<meta name="generator" content="Jekyll v4.0.0" />
<meta property="og:title" content="My Biggest On Stage Preparation - DEMO Asia" />
<meta name="author" content="Junda Ong" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="For the last 3 weeks, I have been preparing for DEMO Asia, a launchpad event for companies to showcase high-tech products." />
<meta property="og:description" content="For the last 3 weeks, I have been preparing for DEMO Asia, a launchpad event for companies to showcase high-tech products." />
<link rel="canonical" href="https://just2me.com/2012/02/29/my-biggest-on-stage-preparation-demo/" />
<meta property="og:url" content="https://just2me.com/2012/02/29/my-biggest-on-stage-preparation-demo/" />
<meta property="og:site_name" content="Just2me" />
<meta property="og:image" content="https://just2me.com/img/jewel-fountain.jpeg" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2012-02-29T17:56:00+08:00" />
<meta name="twitter:card" content="summary" />
<meta property="twitter:image" content="https://just2me.com/img/jewel-fountain.jpeg" />
<meta property="twitter:title" content="My Biggest On Stage Preparation - DEMO Asia" />
<meta name="twitter:site" content="@samwize" />
<meta name="twitter:creator" content="@Junda Ong" />
<meta property="fb:admins" content="704185456" />

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

            </button>
            Just2me

                  Stories

                  Apps

                  Quotes

                  About

My Biggest On Stage Preparation - DEMO Asia

                    Published on February 29, 2012

For the last 3 weeks, I have been preparing for DEMO Asia, a launchpad event for companies to showcase high-tech products.

For that mere 6 minutes on stage, I had a lot of preparation work.

I have to script every word, every gesture, get reviews from a few demo coaches, improve the scripts, come up with backup plans in case things go wrong, go for audition, go for dry rehearsal, private rehearsal, full dress rehearsal..

At last, I get to go on stage tomorrow, to present you a product that finally helps developer create telephony apps easily.

    TAGGED WITH

    conference,

    hoiio

                        We Won Top Award at DEMO Asia 2012 →

                        ← My Body Building Regime - Only 12 minutes a week!

                Please enable JavaScript to view the comments powered by Disqus.

Copyright © Junda Ong 1983-2021


text:
package org.apache.ibatis.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.OffsetTime;

/**
 * @since 3.4.5
 * @author Tomas Rohovsky
 */
public class OffsetTimeTypeHandler extends BaseTypeHandler<OffsetTime> {

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, OffsetTime parameter, JdbcType jdbcType)
          throws SQLException {
    ps.setObject(i, parameter);
  }

  @Override
  public OffsetTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
    return rs.getObject(columnName, OffsetTime.class);
  }

  @Override
  public OffsetTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    return rs.getObject(columnIndex, OffsetTime.class);
  }

  @Override
  public OffsetTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    return cs.getObject(columnIndex, OffsetTime.class);
  }

}


text:
<?php

/**
 * Disable error reporting
 *
 * Set this to error_reporting( E_ALL ) or error_reporting( E_ALL | E_STRICT ) for debugging
 */
error_reporting(0);

/** Set ABSPATH for execution */
define( 'ABSPATH', dirname(dirname(__FILE__)) . '/' );
define( 'WPINC', 'wp-includes' );

/**
 * @ignore
 */
function __() {}

/**
 * @ignore
 */
function _x() {}

/**
 * @ignore
 */
function add_filter() {}

/**
 * @ignore
 */
function esc_attr() {}

/**
 * @ignore
 */
function apply_filters() {}

/**
 * @ignore
 */
function get_option() {}

/**
 * @ignore
 */
function is_lighttpd_before_150() {}

/**
 * @ignore
 */
function add_action() {}

/**
 * @ignore
 */
function did_action() {}

/**
 * @ignore
 */
function do_action_ref_array() {}

/**
 * @ignore
 */
function get_bloginfo() {}

/**
 * @ignore
 */
function is_admin() {return true;}

/**
 * @ignore
 */
function site_url() {}

/**
 * @ignore
 */
function admin_url() {}

/**
 * @ignore
 */
function home_url() {}

/**
 * @ignore
 */
function includes_url() {}

/**
 * @ignore
 */
function wp_guess_url() {}

if ( ! function_exists( 'json_encode' ) ) :
/**
 * @ignore
 */
function json_encode() {}
endif;

function get_file($path) {

	if ( function_exists('realpath') )
		$path = realpath($path);

	if ( ! $path || ! @is_file($path) )
		return '';

	return @file_get_contents($path);
}

$load = $_GET['load'];
if ( is_array( $load ) )
	$load = implode( '', $load );

$load = preg_replace( '/[^a-z0-9,_-]+/i', '', $load );
$load = explode(',', $load);

if ( empty($load) )
	exit;

require(ABSPATH . WPINC . '/script-loader.php');
require(ABSPATH . WPINC . '/version.php');

$compress = ( isset($_GET['c']) && $_GET['c'] );
$force_gzip = ( $compress && 'gzip' == $_GET['c'] );
$expires_offset = 31536000; // 1 year
$out = '';

$wp_scripts = new WP_Scripts();
wp_default_scripts($wp_scripts);

foreach( $load as $handle ) {
	if ( !array_key_exists($handle, $wp_scripts->registered) )
		continue;

	$path = ABSPATH . $wp_scripts->registered[$handle]->src;
	$out .= get_file($path) . "\n";
}

header('Content-Type: application/x-javascript; charset=UTF-8');
header('Expires: ' . gmdate( "D, d M Y H:i:s", time() + $expires_offset ) . ' GMT');
header("Cache-Control: public, max-age=$expires_offset");

if ( $compress && ! ini_get('zlib.output_compression') && 'ob_gzhandler' != ini_get('output_handler') && isset($_SERVER['HTTP_ACCEPT_ENCODING']) ) {
	header('Vary: Accept-Encoding'); // Handle proxies
	if ( false !== stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate') && function_exists('gzdeflate') && ! $force_gzip ) {
		header('Content-Encoding: deflate');
		$out = gzdeflate( $out, 3 );
	} elseif ( false !== stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') && function_exists('gzencode') ) {
		header('Content-Encoding: gzip');
		$out = gzencode( $out, 3 );
	}
}

echo $out;
exit;


text:
<?php

namespace Shopware\PluginCreator\Services\TemplateFileProvider;

use Shopware\PluginCreator\Services\NameGenerator;
use Shopware\PluginCreator\Struct\Configuration;

/**
 * Class BackendControllerFileProvider returns files for the backend controller
 * @package Shopware\PluginCreator\Services\TemplateFileProvider
 */
class BackendControllerFileProvider implements FileProviderInterface
{
    /**
     * @inheritdoc
     */
    public function getFiles(Configuration $configuration, NameGenerator $nameGenerator)
    {
        if ($configuration->hasBackend || $configuration->hasWidget) {
            return array(
                "Controllers/Backend.tpl" => "Controllers/Backend/{$configuration->name}.php"
            );
        }

        return [];
    }
}


text:
package org.wso2.carbon.dashboards.core.internal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.analytics.idp.client.core.api.IdPClient;
import org.wso2.carbon.analytics.idp.client.core.exception.IdPClientException;
import org.wso2.carbon.analytics.permissions.PermissionProvider;
import org.wso2.carbon.analytics.permissions.bean.Permission;
import org.wso2.carbon.analytics.permissions.bean.Role;
import org.wso2.carbon.analytics.permissions.exceptions.PermissionException;
import org.wso2.carbon.dashboards.core.DashboardMetadataProvider;
import org.wso2.carbon.dashboards.core.DashboardThemeConfigProvider;
import org.wso2.carbon.dashboards.core.WidgetMetadataProvider;
import org.wso2.carbon.dashboards.core.bean.DashboardConfigurations;
import org.wso2.carbon.dashboards.core.bean.DashboardMetadata;
import org.wso2.carbon.dashboards.core.bean.importer.DashboardArtifact;
import org.wso2.carbon.dashboards.core.bean.importer.WidgetCollection;
import org.wso2.carbon.dashboards.core.bean.importer.WidgetType;
import org.wso2.carbon.dashboards.core.bean.widget.GeneratedWidgetConfigs;
import org.wso2.carbon.dashboards.core.exception.DashboardException;
import org.wso2.carbon.dashboards.core.exception.DashboardRuntimeException;
import org.wso2.carbon.dashboards.core.exception.UnauthorizedException;
import org.wso2.carbon.dashboards.core.internal.database.DashboardMetadataDao;
import org.wso2.carbon.dashboards.core.internal.database.DashboardMetadataDaoFactory;
import org.wso2.carbon.dashboards.core.internal.roles.provider.RolesProvider;
import org.wso2.carbon.datasource.core.api.DataSourceService;
import org.wso2.carbon.uiserver.api.App;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import static org.wso2.carbon.dashboards.core.utils.DashboardUtil.findWidgets;

/**
 * Default dashboard metadata provider.
 *
 * @since 4.0.0
 */
public class DashboardMetadataProviderImpl implements DashboardMetadataProvider {

    private static final Logger LOGGER = LoggerFactory.getLogger(DashboardMetadataProviderImpl.class);
    private static final String PERMISSION_APP_NAME = "DASH";
    private static final String PERMISSION_SUFFIX_VIEWER = ".viewer";
    private static final String PERMISSION_SUFFIX_EDITOR = ".editor";
    private static final String PERMISSION_SUFFIX_OWNER = ".owner";

    private final DashboardMetadataDao dao;
    private DataSourceService dataSourceService;
    private final DashboardConfigurations dashboardConfigurations;
    private final PermissionProvider permissionProvider;
    private final IdPClient identityClient;
    private final DashboardThemeConfigProvider dashboardThemeConfigProvider;

    private WidgetMetadataProvider widgetMetadataProvider;

    public DashboardMetadataProviderImpl(DataSourceService dataSourceService,
                                         DashboardConfigurations dashboardConfigurations,
                                         PermissionProvider permissionProvider, IdPClient identityClient,
                                         Map<String, DashboardThemeConfigProvider>
                                                 dashboardThemeConfigProviderClassMap) {
        try {
            this.dao = DashboardMetadataDaoFactory.createDao(dataSourceService, dashboardConfigurations);
            this.dao.initDashboardTable();
        } catch (DashboardException e) {
            throw new DashboardRuntimeException("Cannot create dashboard DAO for DB access.", e);
        }
        this.dataSourceService = dataSourceService;
        this.dashboardConfigurations = dashboardConfigurations;
        this.permissionProvider = permissionProvider;
        this.identityClient = identityClient;
        try {
            this.dashboardThemeConfigProvider = getDashboardThemeConfigProvider(dashboardThemeConfigProviderClassMap);
        } catch (DashboardException e) {
            throw new DashboardRuntimeException("Error occurred while getting the dashboard theme config provider.", e);
        }
    }

    DashboardMetadataProviderImpl(DashboardMetadataDao dao, DashboardConfigurations dashboardConfigurations,
                                  PermissionProvider permissionProvider, IdPClient identityClient,
                                  DashboardThemeConfigProvider dashboardThemeConfigProvider) {
        this.dao = dao;
        this.dashboardConfigurations = dashboardConfigurations;
        this.permissionProvider = permissionProvider;
        this.identityClient = identityClient;
        this.dashboardThemeConfigProvider = dashboardThemeConfigProvider;
    }

    private DashboardThemeConfigProvider getDashboardThemeConfigProvider(
            Map<String, DashboardThemeConfigProvider> dashboardThemeConfigProviderClassMap) throws DashboardException {
        String themeConfigClassName = this.dashboardConfigurations.getThemeConfigProviderClass();
        DashboardThemeConfigProvider dashboardThemeConfigProvider
                = dashboardThemeConfigProviderClassMap.get(themeConfigClassName);

        if (dashboardThemeConfigProvider == null) {
            throw new DashboardException("Cannot find the class " +
                    themeConfigClassName + " of type DashboardThemeConfigProvider.");
        }
        return dashboardThemeConfigProvider;
    }

    @Override
    public void init(App dashboardApp) {
        this.widgetMetadataProvider = new WidgetMetadataProviderImpl(dashboardApp, dataSourceService,
                                                                     dashboardConfigurations);
        DashboardImporter dashboardImporter = new DashboardImporter(this, widgetMetadataProvider);
        dashboardImporter.importDashboards();
    }

    void setWidgetMetadataProvider(WidgetMetadataProvider widgetMetadataProvider) {
        this.widgetMetadataProvider = widgetMetadataProvider;
    }

    @Override
    public WidgetMetadataProvider getWidgetMetadataProvider() {
        return widgetMetadataProvider;
    }

    @Override
    public Optional<DashboardMetadata> get(String dashboardUrl) throws DashboardException {
        // TODO: 11/10/17 validate parameters
        return dao.get(dashboardUrl);
    }

    @Override
    public Optional<DashboardMetadata> getDashboardByUser(String user, String dashboardUrl, String originComponent)
            throws DashboardException {
        // TODO: 11/10/17 validate parameters
        boolean isAuthorized = originComponent != null ? checkPermissions(user, dashboardUrl, originComponent) :
                checkPermissions(user, dashboardUrl);
        if (isAuthorized) {
            return get(dashboardUrl);
        } else {
            throw new UnauthorizedException("Insufficient permissions to retrieve the dashboard with ID" +
                    dashboardUrl);
        }
    }

    @Override
    public List<DashboardMetadata> getAllByUser(String user) throws DashboardException {
        List<DashboardMetadata> dashboardList = dao.getAll();
        return dashboardList.stream().
                filter(dashboardMetadata -> {
                    DashboardMetadata dashboardMetadataDetails;
                    try {
                        Optional<DashboardMetadata> dashboardMetadataOptional = get(dashboardMetadata.getUrl());
                        if (dashboardMetadataOptional.isPresent()) {
                            dashboardMetadataDetails = dashboardMetadataOptional.get();
                        } else {
                            return false;
                        }
                    } catch (DashboardException e) {
                        //no need to handle exception since this is a data filter method.
                        LOGGER.error("Error occurred while getting dashboard.", e);
                        return false;
                    }

                    if (permissionProvider.hasPermission(user, new Permission(PERMISSION_APP_NAME,
                            dashboardMetadata.getUrl() + PERMISSION_SUFFIX_OWNER))) {
                        dashboardMetadata.setHasOwnerPermission(true);
                        dashboardMetadata.setHasDesignerPermission(!dashboardMetadataDetails.getContent().isReadOnly());
                        dashboardMetadata.setHasViewerPermission(true);
                        return true;
                    } else if (permissionProvider.hasPermission(user, new Permission(PERMISSION_APP_NAME,
                            dashboardMetadata.getUrl() + PERMISSION_SUFFIX_EDITOR))) {
                        dashboardMetadata.setHasDesignerPermission(!dashboardMetadataDetails.getContent().isReadOnly());
                        dashboardMetadata.setHasViewerPermission(true);
                        return true;
                    } else if (permissionProvider.hasPermission(user, new Permission(PERMISSION_APP_NAME,
                            dashboardMetadata.getUrl() + PERMISSION_SUFFIX_VIEWER))) {
                        dashboardMetadata.setHasViewerPermission(true);
                        return true;
                    }
                    return false;
                }).collect(Collectors.toList());
    }

    @Override
    public void add(DashboardMetadata dashboardMetadata) throws DashboardException {
        RolesProvider rolesProvider = new RolesProvider(dashboardConfigurations);

        dao.add(dashboardMetadata);
        for (Permission permission : buildDashboardPermissions(dashboardMetadata.getUrl())) {
            permissionProvider.addPermission(permission);
            for (String roleId: rolesProvider.getCreatorRoleIds()) {
                permissionProvider.grantPermission(permission, new Role(roleId, ""));
            }
        }
    }

    @Override
    public void add(String user, DashboardMetadata dashboardMetadata) throws DashboardException {
        // TODO: 11/10/17 validate parameters
        RolesProvider rolesProvider = new RolesProvider(dashboardConfigurations);
        List<String> creatorRoleIds = rolesProvider.getCreatorRoleIds();
        Set<String> filteredRoleIds = creatorRoleIds.stream()
                .filter(role -> hasRoles(user, role))
                .collect(Collectors.toSet());
        if (!filteredRoleIds.isEmpty()) {
            dashboardMetadata.setOwner(user);
            dao.add(dashboardMetadata);
            for (Permission permission : buildDashboardPermissions(dashboardMetadata.getUrl())) {
                permissionProvider.addPermission(permission);
                for (String roleId : rolesProvider.getCreatorRoleIds()) {
                    permissionProvider.grantPermission(permission, new Role(roleId, ""));
                }
            }
        } else {
            throw new UnauthorizedException("Insufficient permissions to add dashboards");
        }
    }

    @Override
    public void update(DashboardMetadata dashboardMetadata) throws DashboardException {
        dao.update(dashboardMetadata);
    }

    @Override
    public void update(String user, DashboardMetadata dashboardMetadata) throws DashboardException {
        // TODO: 11/10/17 validate parameters
        if ((permissionProvider.hasPermission(user,
                new Permission(PERMISSION_APP_NAME, dashboardMetadata.getUrl() + PERMISSION_SUFFIX_OWNER))
                || permissionProvider.hasPermission(user,
                new Permission(PERMISSION_APP_NAME, dashboardMetadata.getUrl() + PERMISSION_SUFFIX_EDITOR)))
                && !isReadOnly(dashboardMetadata.getUrl())) {
            dao.update(dashboardMetadata);
        } else {
            throw new UnauthorizedException("Insufficient permissions to update the dashboard with ID "
                    + dashboardMetadata.getUrl());
        }
    }

    @Override
    public void delete(String user, String dashboardUrl) throws DashboardException {
        // TODO: 11/10/17 validate parameters
        if (permissionProvider.hasPermission(user, new Permission(PERMISSION_APP_NAME,
                dashboardUrl + PERMISSION_SUFFIX_OWNER))) {
            dao.delete(dashboardUrl);
            for (Permission permission : buildDashboardPermissions(dashboardUrl)) {
                permissionProvider.deletePermission(permission);
            }
        } else {
            throw new UnauthorizedException("Insufficient permissions to delete the dashboard with the ID " +
                    dashboardUrl);
        }
    }

    @Override
    public Map<String, List<Role>> getDashboardRoles(String dashboardUrl, String username) throws DashboardException {
        Map<String, List<Role>> roles = new HashMap<>();
        try {
            roles.put("owners", permissionProvider.getGrantedRolesOfTenant(
                    new Permission(PERMISSION_APP_NAME, dashboardUrl + PERMISSION_SUFFIX_OWNER),
                    username));
            roles.put("editors", permissionProvider.getGrantedRolesOfTenant(
                    new Permission(PERMISSION_APP_NAME, dashboardUrl + PERMISSION_SUFFIX_EDITOR),
                    username));
            roles.put("viewers", permissionProvider.getGrantedRolesOfTenant(
                    new Permission(PERMISSION_APP_NAME, dashboardUrl + PERMISSION_SUFFIX_VIEWER),
                    username));
        } catch (PermissionException e) {
            throw new DashboardException("Unable to get roles for the dashboard '" + dashboardUrl + "'", e);
        }
        return roles;
    }

    @Override
    public List<org.wso2.carbon.analytics.idp.client.core.models.Role> getAllRoles(String username)
            throws DashboardException {
        try {
            return identityClient.getAllRolesOfTenant(username);
        } catch (IdPClientException e) {
            throw new DashboardException("Unable to get all user roles.", e);
        }
    }

    @Override
    public List<org.wso2.carbon.analytics.idp.client.core.models.Role> getRolesByUsername(String username)
            throws DashboardException {
        try {
            return identityClient.getUserRoles(username);
        } catch (IdPClientException e) {
            throw new DashboardException("Unable to get user roles.", e);
        }
    }

    @Override
    public void updateDashboardRoles(String user, String dashboardUrl, Map<String, List<String>> roleIdMap)
            throws DashboardException {
        if (permissionProvider.hasPermission(user, new Permission(PERMISSION_APP_NAME,
                dashboardUrl + PERMISSION_SUFFIX_OWNER))) {
            updateDashboardRoles(dashboardUrl, roleIdMap, user);
        } else {
            throw new UnauthorizedException("Insufficient permissions to update roles of the dashboard with ID" +
                    dashboardUrl);
        }
    }

    public void updateDashboardRoles(String dashboardUrl, Map<String, List<String>> roleIdMap, String username)
            throws DashboardException {
        List<org.wso2.carbon.analytics.idp.client.core.models.Role> allRoles;
        try {
            if (username != null) {
                allRoles = identityClient.getAllRolesOfTenant(username);
            } else {
                allRoles = identityClient.getAllRoles();
            }
        } catch (IdPClientException e) {
            throw new DashboardException("Unable to get all user roles.", e);
        }
        Map<String, Role> allRoleMap = new HashMap<>();
        for (org.wso2.carbon.analytics.idp.client.core.models.Role role : allRoles) {
            allRoleMap.put(role.getDisplayName(), new Role(role.getId(), role.getDisplayName()));
        }

        Iterator iterator = roleIdMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Permission permission = new Permission(PERMISSION_APP_NAME, dashboardUrl + "." + entry.getKey()
                    .toString());
            permissionProvider.revokePermission(permission);
            for (String roleId : (List<String>) entry.getValue()) {
                permissionProvider.grantPermission(permission, allRoleMap.get(roleId));
            }
            iterator.remove();
        }
    }

    /**
     * Return exportable dashboard definition.
     *
     * @param dashboardUrl URL of the dashboard
     * @return Exportable dashboard definition
     * @throws DashboardException If an error occurred while reading or processing dashboards
     */
    @Override
    public DashboardArtifact exportDashboard(String dashboardUrl, boolean permissions, String username)
            throws DashboardException {
        Optional<DashboardMetadata> dashboardMetadataOptional = dao.get(dashboardUrl);
        Map<String, List<Role>> dashboardRoles = getDashboardRoles(dashboardUrl, username);
        if (!dashboardMetadataOptional.isPresent()) {
            throw new DashboardException("Cannot find the dashboard '" + dashboardUrl + "'");
        }

        DashboardArtifact artifact = new DashboardArtifact();

        // Set JSON parsed content to pages.
        DashboardMetadata dashboardMetadata = dashboardMetadataOptional.get();
        artifact.setDashboard(dashboardMetadata);

        Map<WidgetType, Set<String>> widgets = findWidgets(dashboardMetadata.getContent());

        // Set metadata of generated widgets
        Set<GeneratedWidgetConfigs> generatedWidgetConfigs = widgetMetadataProvider
                .getGeneratedWidgetConfigs(widgets.get(WidgetType.GENERATED));
        WidgetCollection widgetCollection = new WidgetCollection();
        widgetCollection.setGenerated(generatedWidgetConfigs);

        // Set list of custom widgets
        widgetCollection.setCustom(widgets.get(WidgetType.CUSTOM));
        artifact.setWidgets(widgetCollection);

        if (permissions) {
            dashboardRoles.forEach((permission, roles) -> {
                List<String> roleNames = roles.stream().map(Role::getName).collect(Collectors.toList());
                artifact.addPermissions(permission, roleNames);
            });
        }
        return artifact;
    }

    /**
     * Build basic dashboard permission string.
     *
     * @param dashboardUrl
     * @return
     */
    private List<Permission> buildDashboardPermissions(String dashboardUrl) {
        List<Permission> permissions = new ArrayList<>();
        permissions.add(new Permission(PERMISSION_APP_NAME, dashboardUrl + PERMISSION_SUFFIX_OWNER));
        permissions.add(new Permission(PERMISSION_APP_NAME, dashboardUrl + PERMISSION_SUFFIX_EDITOR));
        permissions.add(new Permission(PERMISSION_APP_NAME, dashboardUrl + PERMISSION_SUFFIX_VIEWER));
        return permissions;
    }

    private boolean hasRoles(String user, String roleId) {
        try {
            org.wso2.carbon.analytics.idp.client.core.models.Role adminRole = identityClient.getAdminRole();
            return identityClient.getUserRoles(user).stream()
                    .anyMatch(userRole -> Objects.equals(userRole.getId(), roleId) || Objects.equals(userRole
                            .getId(), adminRole.getId()));
        } catch (IdPClientException e) {
            LOGGER.error("Error in retrieving user roles for the user " + user, e);
        }
        return false;
    }

    /**
     * This method is to check permission based on the origin component type of the request
     *
     * @param user            logged in user
     * @param dashboardUrl    dashboard URL
     * @param originComponent origin component - designer/settings
     * @return boolean
     */
    private boolean checkPermissions(String user, String dashboardUrl, String originComponent) {
        switch (originComponent) {
            case "designer":
                return (hasPermission(user, dashboardUrl, PERMISSION_SUFFIX_EDITOR) ||
                        hasPermission(user, dashboardUrl, PERMISSION_SUFFIX_OWNER)) && !isReadOnly(dashboardUrl);
            case "settings":
                return hasPermission(user, dashboardUrl, PERMISSION_SUFFIX_OWNER);
            default:
                return false;
        }
    }

    /**
     * Check dashbaord content is ready only
     *
     * @param dashboardUrl url
     * @return true if it is read only
     */
    private boolean isReadOnly(String dashboardUrl) {
        DashboardMetadata metadata;
        try {
            Optional<DashboardMetadata> optional = get(dashboardUrl);
            if (optional.isPresent()) {
                metadata = optional.get();
                return metadata.getContent().isReadOnly();
            } else {
                return false;
            }
        } catch (DashboardException e) {
            //no need to handle exception since this is a data filter method.
            LOGGER.error("Error occurred while getting dashboard.", e);
            return false;
        }
    }

    /**
     * This method is to check permission based on the origin component type of the request
     *
     * @param user         logged in user
     * @param dashboardUrl dashboard URL
     * @return boolean
     */
    private boolean checkPermissions(String user, String dashboardUrl) {
        return hasPermission(user, dashboardUrl, PERMISSION_SUFFIX_VIEWER) ||
                hasPermission(user, dashboardUrl, PERMISSION_SUFFIX_EDITOR) ||
                hasPermission(user, dashboardUrl, PERMISSION_SUFFIX_OWNER);
    }

    /**
     * This method is to check whether the user has appropriate permissions
     *
     * @param user             Username
     * @param dashboardUrl     dashboardUrl
     * @param permissionSuffix viewer/editor/owner
     * @return boolean
     */
    private boolean hasPermission(String user, String dashboardUrl, String permissionSuffix) {
        return permissionProvider.hasPermission(user, new Permission(PERMISSION_APP_NAME, dashboardUrl +
                permissionSuffix));
    }

    /**
     * Returns dashboardConfigurations for report generation
     * @return DashboardConfigurations
     */
    @Override
    public DashboardConfigurations getReportGenerationConfigurations() {
        return this.dashboardConfigurations;
    }

    @Override
    public boolean isCreator(String username) throws DashboardException {
        List<org.wso2.carbon.analytics.idp.client.core.models.Role> userRoles;
        boolean isCreator = false;
        try {
            userRoles = identityClient.getUserRoles(username);
        } catch (IdPClientException e) {
            throw new DashboardException("Unable to get roles for the username.");
        }
        RolesProvider rolesProvider = new RolesProvider(dashboardConfigurations);
        List<String> creatorRoleIds = rolesProvider.getCreatorRoleIds();
        for (org.wso2.carbon.analytics.idp.client.core.models.Role userRole : userRoles) {
            for (String creatorRoleId : creatorRoleIds) {
                if (userRole.getId().equalsIgnoreCase(creatorRoleId)) {
                    isCreator = true;
                    break;
                }
            }
        }
        return isCreator;
    }

    @Override
    public boolean isWidgetCreator(String username) throws DashboardException {
        List<org.wso2.carbon.analytics.idp.client.core.models.Role> userRoles;
        boolean isWidgetCreator = false;
        try {
            userRoles = identityClient.getUserRoles(username);
        } catch (IdPClientException e) {
            throw new DashboardException("Unable to get roles for the username.", e);
        }
        RolesProvider rolesProvider = new RolesProvider(dashboardConfigurations);
        List<String> widgetCreatorRoleIds = rolesProvider.getWidgetCreatorRoleIds();
        for (org.wso2.carbon.analytics.idp.client.core.models.Role userRole : userRoles) {
            for (String widgetCreatorRoleId : widgetCreatorRoleIds) {
                if (userRole.getId().equalsIgnoreCase(widgetCreatorRoleId)) {
                    isWidgetCreator = true;
                    break;
                }
            }
        }
        return isWidgetCreator;
    }

    @Override
    public String getFaviconPath(String username) throws DashboardException {
        return this.dashboardThemeConfigProvider.getFaviconPath(username);
    }

    @Override
    public String getLogoPath(String username) throws DashboardException {
        return this.dashboardThemeConfigProvider.getLogoPath(username);
    }
}


text:
@import '../variables.css';

.pane {
  background: var(--bg);
  border-right: 1px solid var(--color-border);
  height: 100%;
  max-height: calc(100vh - 44px);
  display: flex;
  flex-direction: column;
  top: 0;
  left: 0;
  width: 100%;

  /* transition: all .25s ease-in-out; */
  overflow: hidden;
  position: absolute;
  will-change: transform;

  @media print {
    overflow: visible;
  }
}

.focusIndicator {
  composes: focusWithinIndicator from "../sharedStyles/focusWithinIndicator.css";
}

[dir="ltr"] .pane:last-child {
  border-right: none;
}

[dir="rtl"] .pane:first-child {
  border-right: none;
}

[dir="rtl"] .pane:last-child {
  border-left: none;
}

/**
 * Pane Content
 */

.paneContent {
  height: 100%;
  width: 100%;
  overflow: auto;
  outline: 0;

  &.hasPadding {
    padding: var(--gutter-static);
  }

  &.noOverflow {
    overflow: hidden;
  }

  @media print {
    overflow: visible;
  }
}

.container {
  max-width: var(--container-max-width);
  margin: auto;
}

@media (--medium-up) {
  .pane {
    position: relative;
  }
}


text:
package zone.dragon.dropwizard;

import org.glassfish.hk2.api.DynamicConfiguration;
import org.glassfish.hk2.utilities.Binder;
import org.glassfish.hk2.utilities.binding.AbstractBinder;

/**
 * @author Bryan Harclerode
 */
public interface SimpleBinder extends Binder {
    @Override
    default void bind(DynamicConfiguration config) {
        new AbstractBinder() {
            @Override
            protected void configure() {
                configureBindings(this);
            }
        }.bind(config);
    }

    void configureBindings(AbstractBinder config);
}


text:
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _

from django_hstore import hstore
from formulator.models import Form
from multilogger.users.models import User, App, Site
from djorm_pguuid.fields import UUIDField
#from djorm_expressions.models import ExpressionManager

class AbstractBaseModel(models.Model):
    uuid = UUIDField(auto_add=True, db_index=True, primary_key=True, unique=True)
    #objects = ExpressionManager()

    class Meta:
        abstract = True

@python_2_unicode_compatible
class Register(AbstractBaseModel):
    LANGS = [('EN', 'English'), ('ES', 'Espanol'), ('DE', 'Deutsch')]

    name = models.CharField(max_length=100)
    lang = models.CharField(max_length=2, choices=LANGS, default='EN')
    active = models.BooleanField(default=True)
    choosable = models.BooleanField(default=True)
    begin = models.DateTimeField(_('Registration starts on'))
    end = models.DateTimeField(_('Registration ends on'))
    site = models.ForeignKey(Site)
    form = models.ForeignKey(Form)

    def __str__(self):
        return self.name + ' in ' + self.site

@python_2_unicode_compatible
class Profile(AbstractBaseModel):
    user = models.ForeignKey(User)
    apps = models.ManyToManyField(App)
    data = hstore.DictionaryField(null=True)

    def __str__(self):
        return 'Profile for ' + self.user.email


text:
import numpy as np

from .base import AnalyticalPropagator
from ..constants import Earth
from ..dates import timedelta

class Kepler(AnalyticalPropagator):
    """Analytical propagator only taking the evolution of the Mean anomaly"""

    @property
    def orbit(self):
        return self._orbit if hasattr(self, "_orbit") else None

    @orbit.setter
    def orbit(self, orbit):
        self._orbit = orbit.copy(form="keplerian_mean")

    def propagate(self, date):

        if type(date) is timedelta:  # pragma: no cover
            date = self.orbit.date + date

        delta_t = (date - self.orbit.date).total_seconds()

        n = self.orbit.infos.n

        delta = n * delta_t

        new = self.orbit.copy()
        new.date = date
        new[5] = self.orbit[5] + delta

        return new.copy(form="cartesian")


text:
// MockClientINode.cs
//
// The MIT License (MIT)
//
// Copyright (c) 2017 DarkCaster <dark.caster@outlook.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
using System;
using System.Threading.Tasks;
using DarkCaster.DataTransfer.Config;
using DarkCaster.DataTransfer.Client;

namespace Tests.Mocks
{
	public class MockClientINode : INode
	{
		private readonly int minDelay;
		private readonly int maxDelay;
		private readonly float failProbability;
		private readonly float partialOpProbability;
		private readonly int noFailOpsCounter;

		public MockClientITunnel LastTunnel { get; set; }

		public MockClientINode(int minDelay, int maxDelay, float failProbability, float partialOpProbability, int noFailOpsCount)
		{
			this.minDelay = minDelay;
			this.maxDelay = maxDelay;
			this.failProbability = failProbability;
			this.partialOpProbability = partialOpProbability;
			this.noFailOpsCounter = noFailOpsCount;
			LastTunnel = null;
		}

		public ITunnel OpenTunnel(ITunnelConfig config)
		{
			if (config == null)
				throw new Exception("config parameter cannot be null!");
			LastTunnel=new MockClientITunnel(minDelay, maxDelay, failProbability, partialOpProbability, noFailOpsCounter);
			return LastTunnel;
		}

		public Task<ITunnel> OpenTunnelAsync(ITunnelConfig config)
		{
			var taskSource = new TaskCompletionSource<ITunnel>();
			try { taskSource.SetResult(OpenTunnel(config)); }
			catch (OperationCanceledException) { taskSource.SetCanceled(); }
			catch (Exception ex) { taskSource.SetException(ex); }
			return taskSource.Task;
		}
	}
}


text: Rails.application.config.session_store :cookie_store, key: '_bmonkey_session'


text:
(function(){
	"use strict";

	angular.module('app.controllers').controller('LandingCtrl', function( $scope, $mdToast, $mdDialog, $interval ){

		$scope.promoImage = '//i.imgur.com/ZbLzOPP.jpg';
		$scope.icon = 'send';

		var icons = [
		'office', 'facebook', 'twitter', 'apple', 'whatsapp', 'linkedin', 'windows', 'accessibility', 'alarm', 'aspect_ratio',
		'autorenew', 'bookmark_outline', 'dashboard', 'dns', 'favorite_outline', 'get_app', 'highlight_remove', 'history', 'list',
		'picture_in_picture', 'print', 'settings_ethernet', 'settings_power', 'shopping_cart', 'spellcheck', 'swap_horiz', 'swap_vert',
		'thumb_up', 'thumbs_up_down', 'translate', 'trending_up', 'visibility', 'warning', 'mic', 'play_circle_outline', 'repeat',
		'skip_next', 'call', 'chat', 'clear_all', 'dialpad', 'dnd_on', 'forum', 'location_on', 'vpn_key', 'filter_list', 'inbox',
		'link', 'remove_circle_outline', 'save', 'text_format', 'access_time', 'airplanemode_on', 'bluetooth', 'data_usage',
		'gps_fixed', 'now_wallpaper', 'now_widgets', 'storage', 'wifi_tethering', 'attach_file', 'format_line_spacing',
		'format_list_numbered', 'format_quote', 'vertical_align_center', 'wrap_text', 'cloud_queue', 'file_download', 'folder_open',
		'cast', 'headset', 'keyboard_backspace', 'mouse', 'speaker', 'watch', 'audiotrack', 'edit', 'brush', 'looks', 'crop_free',
		'camera', 'filter_vintage', 'hdr_strong', 'photo_camera', 'slideshow', 'timer', 'directions_bike', 'hotel', 'local_library',
		'directions_walk', 'local_cafe', 'local_pizza', 'local_florist', 'my_location', 'navigation', 'pin_drop', 'arrow_back', 'menu',
		'close', 'more_horiz', 'more_vert', 'refresh', 'phone_paused', 'vibration', 'cake', 'group', 'mood', 'person',
		'notifications_none', 'plus_one', 'school', 'share', 'star_outline'
		],
		counter = 0;

		$interval(function(){
			$scope.icon = icons[++counter];
			if ( counter > 112 ){
				counter = 0;
			}
		}, 2000);

		$scope.toastNotification = function(){
			$mdToast.show(
				$mdToast.simple()
				.content('This is a toast notification!')
				.position('top right')
				.hideDelay(3000)
				);
		};

		$scope.showDialog = function( event ){
			$mdDialog.show(
				$mdDialog.alert()
				.parent(angular.element(document.body))
				.title('This is an alert title')
				.content('You can specify some description text in here.')
				.ariaLabel('Alert Dialog Demo')
				.ok('Got it!')
				.targetEvent(event)
				);
		};

	});

})();


text:
namespace net {

Error MapSystemError(logging::SystemErrorCode error) {
  if (error != 0) {
    char error_string[256];
    SbSystemGetErrorString(error, error_string, sizeof(error_string));
    DVLOG(2) << "Error (" << error << ") " << error_string;
  }

  // TODO: Define standard Starboard error codes.
  if (error == 0)
    return OK;

  return ERR_FAILED;
}

Error MapSocketError(SbSocketError error) {
  if (error != kSbSocketOk)
    DVLOG(2) << "Error " << error;

  // TODO: Define standard Starboard error codes.
  switch (error) {
    case kSbSocketOk:
      return OK;
    case kSbSocketPending:
      return ERR_IO_PENDING;
    case kSbSocketErrorConnectionReset:
      return ERR_CONNECTION_RESET;
    case kSbSocketErrorFailed:
      return ERR_FAILED;
    default:
      NOTREACHED() << "Unrecognized error: " << error;
      return ERR_FAILED;
  }
}

}  // namespace net


text:
<?php
namespace app\api;

use yii\base\Module;

class ApiModule extends Module
{

}


text:
/// <reference types="node" />
import { ScaleLinear } from 'd3-scale';
import { Axis } from 'd3-axis';
import EventEmitter from 'events';
import { FunctionPlotOptions } from './types';
interface ChartMetaMargin {
    left?: number;
    right?: number;
    top?: number;
    bottom?: number;
}
export interface ChartMeta {
    /**
     * graph's left, right, top, bottom margins
     */
    margin?: ChartMetaMargin;
    /**
     * width of the canvas (minus the margins)
     */
    width?: number;
    /**
     * height of the canvas (minus the margins)
     */
    height?: number;
    zoomBehavior?: any;
    xScale?: ScaleLinear<number, number>;
    yScale?: ScaleLinear<number, number>;
    xAxis?: Axis<any>;
    yAxis?: Axis<any>;
    xDomain?: number[];
    yDomain?: number[];
}
/**
 * An instance can subscribe to any of the following events by doing `instance.on([eventName], callback)`,
 * events can be triggered by doing `instance.emit([eventName][, params])`
 *
 * - `mouseover` fired whenever the mouse is over the canvas
 * - `mousemove` fired whenever the mouse is moved inside the canvas, callback params: a single object `{x: number, y: number}` (in canvas space
 coordinates)
 * - `mouseout` fired whenever the mouse is moved outside the canvas
 * - `before:draw` fired before drawing all the graphs
 * - `after:draw` fired after drawing all the graphs
 * - `zoom:scaleUpdate` fired whenever the scale of another graph is updated, callback params `xScale`, `yScale`
 (x-scale and y-scale of another graph whose scales were updated)
 * - `tip:update` fired whenever the tip position is updated, callback params `{x, y, index}` (in canvas
 space coordinates, `index` is the index of the graph where the tip is on top of)
 * - `eval` fired whenever the sampler evaluates a function, callback params `data` (an array of segment/points),
 `index` (the index of datum in the `data` array), `isHelper` (true if the data is created for a helper e.g.
 for the derivative/secant)
 *
 * The following events are dispatched to all the linked graphs
 *
 * - `all:mouseover` same as `mouseover` but it's dispatched in each linked graph
 * - `all:mousemove` same as `mousemove` but it's dispatched in each linked graph
 * - `all:mouseout` same as `mouseout` but it's dispatched in each linked graph
 * - `all:zoom:scaleUpdate` same as `zoom:scaleUpdate` but it's dispatched in each linked graph
 * - `all:zoom` fired whenever there's scaling/translation on the graph, dispatched on all the linked graphs
 */
export declare class Chart extends EventEmitter.EventEmitter {
    static cache: Record<string, Chart>;
    private readonly id;
    readonly markerId: string;
    options: FunctionPlotOptions;
    meta: ChartMeta;
    /**
     * Array of function-plot instances linked to the events of this instance,
     i.e. when the zoom event is dispatched on this instance it's also dispatched on all the instances of
     this array
     */
    private linkedGraphs;
    private line;
    /**
     * `svg` element that holds the graph (canvas + title + axes)
     */
    root: any;
    /**
     * Element that holds the tip
     */
    tip: any;
    /**
     * `g.canvas` element that holds the area where the graphs are plotted (clipped with a mask)
     */
    canvas: any;
    /**
     * Element that holds the canvas where the functions are drawn
     */
    content: any;
    /**
     * Draggable element that receives zoom and pan events
     */
    draggable: any;
    constructor(options: FunctionPlotOptions);
    /**
     * Rebuilds the entire graph from scratch recomputing
     *
     * - the inner width/height
     * - scales/axes
     *
     * After this is done it does a complete redraw of all the datums,
     * if only the datums need to be redrawn call `instance.draw()` instead
     *
     * @returns {Chart}
     */
    build(): this;
    private getDraggableNode;
    /**
     * The draggable container won't change across different instances of Chart,
     * therefore multiple instances will share the draggable container, to avoid dispatching
     * the event from the old instance grab it in runtime with this function
     */
    private getEmitInstance;
    internalVars(): void;
    initializeAxes(): void;
    drawGraphWrapper(): void;
    buildTitle(): void;
    buildLegend(): void;
    buildCanvas(): void;
    buildClip(): void;
    buildAxis(): void;
    buildAxisLabel(): void;
    /**
     * @private
     *
     * Draws each of the datums stored in data.options, to do a full
     * redraw call `instance.draw()`
     */
    buildContent(): void;
    buildZoomHelper(): void;
    setUpPlugins(): void;
    addLink(): void;
    updateAxes(): void;
    syncOptions(): void;
    getFontSize(): number;
    draw(): void;
    setUpEventListeners(): void;
}
declare function functionPlot(options?: FunctionPlotOptions): Chart;
declare namespace functionPlot {
    var globals: {
        COLORS: import("d3-color").HSLColor[];
        DEFAULT_WIDTH: number;
        DEFAULT_HEIGHT: number;
        TIP_X_EPS: number;
        DEFAULT_ITERATIONS: number;
        MAX_ITERATIONS: number;
    };
    var $eval: typeof import("./helpers/eval");
    var graphTypes: typeof import("./graph-types");
}
export default functionPlot;


text:
import urllib
import hashlib

from django import template
from django.conf import settings
from django.utils.safestring import mark_safe
from django.utils.encoding import force_bytes, force_text

from readthedocs.projects.models import Project
from readthedocs.core.resolver import resolve

register = template.Library()

@register.filter
def gravatar(email, size=48):
    """
    hacked from djangosnippets.org, but basically given an email address

    render an img tag with the hashed up bits needed for leetness
    omgwtfstillreading
    """
    url = "http://www.gravatar.com/avatar.php?%s" % urllib.urlencode({
        'gravatar_id': hashlib.md5(email).hexdigest(),
        'size': str(size)
    })
    return ('<img src="%s" width="%s" height="%s" alt="gravatar" '
            'class="gravatar" border="0" />' % (url, size, size))

@register.simple_tag(name="doc_url")
def make_document_url(project, version=None, page=''):
    if not project:
        return ""
    return resolve(project=project, version_slug=version, filename=page)

@register.filter(is_safe=True)
def restructuredtext(value, short=False):
    try:
        from docutils.core import publish_parts
    except ImportError:
        if settings.DEBUG:
            raise template.TemplateSyntaxError(
                "Error in 'restructuredtext' filter: "
                "The Python docutils library isn't installed."
            )
        return force_text(value)
    else:
        docutils_settings = {
            'raw_enabled': False,
            'file_insertion_enabled': False,
        }
        docutils_settings.update(getattr(settings, 'RESTRUCTUREDTEXT_FILTER_SETTINGS', {}))
        parts = publish_parts(source=force_bytes(value), writer_name="html4css1",
                              settings_overrides=docutils_settings)
        out = force_text(parts["fragment"])
        try:
            if short:
                out = out.split("\n")[0]
        except IndexError:
            pass
        finally:
            return mark_safe(out)

@register.filter
def get_project(slug):
    try:
        return Project.objects.get(slug=slug)
    except:
        return None

@register.filter
def get_version(slug):
    try:
        return Project.objects.get(slug=slug)
    except:
        return None

@register.simple_tag
def url_replace(request, field, value):
    dict_ = request.GET.copy()
    dict_[field] = value
    return dict_.urlencode()

@register.filter
def key(d, key_name):
    return d[key_name]


text:
package br.com.ceducarneiro.exerciciofinal.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.orm.SugarRecord;

import java.util.List;

@JsonIgnoreProperties(value = {"modified"})
public class Author extends SugarRecord {

    @JsonProperty(value = "id")
    private Long guid;
    private String name;
    private boolean modified;

    public static List<Author> findAllModified() {
        return Author.find(Author.class, "modified = ?", Boolean.TRUE.toString());
    }

    public static Author findByGuid(Long guid) {
        List<Author> authors = Author.find(Author.class, "guid= ?", String.valueOf(guid));
        return authors.isEmpty() ? null : authors.get(0);
    }

    public Long getGuid() {
        return guid;
    }

    public void setGuid(Long guid) {
        this.guid = guid;
    }

    public String getName() {
        return name;
    }

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

    public boolean isModified() {
        return modified;
    }

    public void setModified(boolean modified) {
        this.modified = modified;
    }
}


text:
from __future__ import unicode_literals

import base64
try:
    from Crypto import Random
except ImportError:
    from Crypto.Util.randpool import RandomPool as Random
from Crypto.Cipher import AES
from django.conf import settings

def _create_cipher(iv):
    return AES.new(settings.SECRET_KEY[:16], AES.MODE_CFB, iv)

def encrypt(data):
    """Encrypts data using AES encryption.

    The encrypted data will be decryptable using the decrypt() function.
    The first 16 characters of settings.SECRET_KEY are used as the
    encryption key.

    The resulting data will be a binary blob.
    """
    iv = Random.new().read(AES.block_size)
    cipher = _create_cipher(iv)
    return iv + cipher.encrypt(data)

def decrypt(data):
    """Decrypts data encrypted using the encrypt() function."""
    cipher = _create_cipher(data[:AES.block_size])
    return cipher.decrypt(data[AES.block_size:])

def encrypt_password(password):
    """Encrypts a password.

    The password will be encrypted using AES encryption, and serialized
    into base64.
    """
    return base64.b64encode(encrypt(password))

def decrypt_password(encrypted_password):
    """Decrypts a password.

    This will decrypt a base64-encoded encrypted password into a usable
    password string.
    """
    return decrypt(base64.b64decode(encrypted_password))