text:
package core

import (
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common"
)

// BootVolumeBackup A point-in-time copy of a boot volume that can then be used to create
// a new boot volume or recover a boot volume. For more information, see Overview
// of Boot Volume Backups (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/bootvolumebackups.htm)
// To use any of the API operations, you must be authorized in an IAM policy.
// If you're not authorized, talk to an administrator. If you're an administrator
// who needs to write policies to give users access, see Getting Started with
// Policies (https://docs.cloud.oracle.com/iaas/Content/Identity/Concepts/policygetstarted.htm).
// **Warning:** Oracle recommends that you avoid using any confidential information when you
// supply string values using the API.
type BootVolumeBackup struct {

	// The OCID of the compartment that contains the boot volume backup.
	CompartmentId *string `mandatory:"true" json:"compartmentId"`

	// A user-friendly name for the boot volume backup. Does not have to be unique and it's changeable.
	// Avoid entering confidential information.
	DisplayName *string `mandatory:"true" json:"displayName"`

	// The OCID of the boot volume backup.
	Id *string `mandatory:"true" json:"id"`

	// The current state of a boot volume backup.
	LifecycleState BootVolumeBackupLifecycleStateEnum `mandatory:"true" json:"lifecycleState"`

	// The date and time the boot volume backup was created. This is the time the actual point-in-time image
	// of the volume data was taken. Format defined by RFC3339 (https://tools.ietf.org/html/rfc3339).
	TimeCreated *common.SDKTime `mandatory:"true" json:"timeCreated"`

	// The OCID of the boot volume.
	BootVolumeId *string `mandatory:"false" json:"bootVolumeId"`

	// Defined tags for this resource. Each key is predefined and scoped to a
	// namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
	// Example: `{"Operations": {"CostCenter": "42"}}`
	DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`

	// System tags for this resource. Each key is predefined and scoped to a namespace.
	// Example: `{"foo-namespace": {"bar-key": "value"}}`
	SystemTags map[string]map[string]interface{} `mandatory:"false" json:"systemTags"`

	// The date and time the volume backup will expire and be automatically deleted.
	// Format defined by RFC3339 (https://tools.ietf.org/html/rfc3339). This parameter will always be present for backups that
	// were created automatically by a scheduled-backup policy. For manually created backups,
	// it will be absent, signifying that there is no expiration time and the backup will
	// last forever until manually deleted.
	ExpirationTime *common.SDKTime `mandatory:"false" json:"expirationTime"`

	// Free-form tags for this resource. Each tag is a simple key-value pair with no
	// predefined name, type, or namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm).
	// Example: `{"Department": "Finance"}`
	FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`

	// The image OCID used to create the boot volume the backup is taken from.
	ImageId *string `mandatory:"false" json:"imageId"`

	// The OCID of the Key Management master encryption assigned to the boot volume backup.
	// For more information about the Key Management service and encryption keys, see
	// Overview of Key Management (https://docs.cloud.oracle.com/iaas/Content/KeyManagement/Concepts/keyoverview.htm) and
	// Using Keys (https://docs.cloud.oracle.com/iaas/Content/KeyManagement/Tasks/usingkeys.htm).
	KmsKeyId *string `mandatory:"false" json:"kmsKeyId"`

	// The size of the boot volume, in GBs.
	SizeInGBs *int64 `mandatory:"false" json:"sizeInGBs"`

	// The OCID of the source boot volume backup.
	SourceBootVolumeBackupId *string `mandatory:"false" json:"sourceBootVolumeBackupId"`

	// Specifies whether the backup was created manually, or via scheduled backup policy.
	SourceType BootVolumeBackupSourceTypeEnum `mandatory:"false" json:"sourceType,omitempty"`

	// The date and time the request to create the boot volume backup was received. Format defined by RFC3339 (https://tools.ietf.org/html/rfc3339).
	TimeRequestReceived *common.SDKTime `mandatory:"false" json:"timeRequestReceived"`

	// The type of a volume backup.
	Type BootVolumeBackupTypeEnum `mandatory:"false" json:"type,omitempty"`

	// The size used by the backup, in GBs. It is typically smaller than sizeInGBs, depending on the space
	// consumed on the boot volume and whether the backup is full or incremental.
	UniqueSizeInGBs *int64 `mandatory:"false" json:"uniqueSizeInGBs"`
}

func (m BootVolumeBackup) String() string {
	return common.PointerString(m)
}

// BootVolumeBackupLifecycleStateEnum Enum with underlying type: string
type BootVolumeBackupLifecycleStateEnum string

// Set of constants representing the allowable values for BootVolumeBackupLifecycleStateEnum
const (
	BootVolumeBackupLifecycleStateCreating        BootVolumeBackupLifecycleStateEnum = "CREATING"
	BootVolumeBackupLifecycleStateAvailable       BootVolumeBackupLifecycleStateEnum = "AVAILABLE"
	BootVolumeBackupLifecycleStateTerminating     BootVolumeBackupLifecycleStateEnum = "TERMINATING"
	BootVolumeBackupLifecycleStateTerminated      BootVolumeBackupLifecycleStateEnum = "TERMINATED"
	BootVolumeBackupLifecycleStateFaulty          BootVolumeBackupLifecycleStateEnum = "FAULTY"
	BootVolumeBackupLifecycleStateRequestReceived BootVolumeBackupLifecycleStateEnum = "REQUEST_RECEIVED"
)

var mappingBootVolumeBackupLifecycleState = map[string]BootVolumeBackupLifecycleStateEnum{
	"CREATING":         BootVolumeBackupLifecycleStateCreating,
	"AVAILABLE":        BootVolumeBackupLifecycleStateAvailable,
	"TERMINATING":      BootVolumeBackupLifecycleStateTerminating,
	"TERMINATED":       BootVolumeBackupLifecycleStateTerminated,
	"FAULTY":           BootVolumeBackupLifecycleStateFaulty,
	"REQUEST_RECEIVED": BootVolumeBackupLifecycleStateRequestReceived,
}

// GetBootVolumeBackupLifecycleStateEnumValues Enumerates the set of values for BootVolumeBackupLifecycleStateEnum
func GetBootVolumeBackupLifecycleStateEnumValues() []BootVolumeBackupLifecycleStateEnum {
	values := make([]BootVolumeBackupLifecycleStateEnum, 0)
	for _, v := range mappingBootVolumeBackupLifecycleState {
		values = append(values, v)
	}
	return values
}

// BootVolumeBackupSourceTypeEnum Enum with underlying type: string
type BootVolumeBackupSourceTypeEnum string

// Set of constants representing the allowable values for BootVolumeBackupSourceTypeEnum
const (
	BootVolumeBackupSourceTypeManual    BootVolumeBackupSourceTypeEnum = "MANUAL"
	BootVolumeBackupSourceTypeScheduled BootVolumeBackupSourceTypeEnum = "SCHEDULED"
)

var mappingBootVolumeBackupSourceType = map[string]BootVolumeBackupSourceTypeEnum{
	"MANUAL":    BootVolumeBackupSourceTypeManual,
	"SCHEDULED": BootVolumeBackupSourceTypeScheduled,
}

// GetBootVolumeBackupSourceTypeEnumValues Enumerates the set of values for BootVolumeBackupSourceTypeEnum
func GetBootVolumeBackupSourceTypeEnumValues() []BootVolumeBackupSourceTypeEnum {
	values := make([]BootVolumeBackupSourceTypeEnum, 0)
	for _, v := range mappingBootVolumeBackupSourceType {
		values = append(values, v)
	}
	return values
}

// BootVolumeBackupTypeEnum Enum with underlying type: string
type BootVolumeBackupTypeEnum string

// Set of constants representing the allowable values for BootVolumeBackupTypeEnum
const (
	BootVolumeBackupTypeFull        BootVolumeBackupTypeEnum = "FULL"
	BootVolumeBackupTypeIncremental BootVolumeBackupTypeEnum = "INCREMENTAL"
)

var mappingBootVolumeBackupType = map[string]BootVolumeBackupTypeEnum{
	"FULL":        BootVolumeBackupTypeFull,
	"INCREMENTAL": BootVolumeBackupTypeIncremental,
}

// GetBootVolumeBackupTypeEnumValues Enumerates the set of values for BootVolumeBackupTypeEnum
func GetBootVolumeBackupTypeEnumValues() []BootVolumeBackupTypeEnum {
	values := make([]BootVolumeBackupTypeEnum, 0)
	for _, v := range mappingBootVolumeBackupType {
		values = append(values, v)
	}
	return values
}


text:
  Account Type
  <select
    ng-model="currentPayment.scholarship.accountType"
    class="form-control"
  >
    <option value="STAFF" translate>Staff</option>
    <option value="MINISTRY" translate>Ministry</option>
    <option value="NON_US_STAFF" translate>Non-U.S. Staff</option>
  </select>

    Account Number
    <input
      ng-model="currentPayment.scholarship.accountNumber"
      type="text"
      class="form-control"
    />

    Business Unit
    <input
      ng-model="currentPayment.scholarship.businessUnit"
      type="text"
      class="form-control"
    />

    Operating Unit
    <input
      ng-model="currentPayment.scholarship.operatingUnit"
      type="text"
      class="form-control"
    />

    Department
    <input
      ng-model="currentPayment.scholarship.department"
      type="text"
      class="form-control"
    />

    Project Id
    <i
      class="fa fa-question-circle"
      button
      uib-popover="{{'If there is no Project Id (or `NONE`), leave blank' | translate}}"
      popover-trigger="'mouseenter'"
      popover-append-to-body="true"
    >

    <input
      ng-model="currentPayment.scholarship.projectId"
      type="text"
      class="form-control"
    />

redpajama_set_name: RedPajamaGithub


text:
Swipe Menu
===============

[![Travis CI](https://travis-ci.org/harryzjm/SwipeMenu.svg?branch=master)](https://travis-ci.org)
[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)

SwipeMenu is a simple, strong, fast menu and also easy to use in your iOS app.

![show](./Logo/SwipeMenu.gif)

## Requirements

- iOS 9.0+
- Xcode 8.0
- Swift 3.1
ps: Because of `NSLayoutAnchor`, so it up to iOS 9.0

## Installation

### Carthage

[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with [Homebrew](http://brew.sh/) using the following command:

```bash
$ brew update
$ brew install carthage
```

To integrate SwipeMenu into your Xcode project using Carthage, specify it in your `Cartfile`:

```swift
github "harryzjm/SwipeMenu"
```

Run `carthage` to build the framework and drag the built `SwipeMenu.framework` and `SnapKit.framework` into your Xcode project.

#### Source File

Simply add the file in Source directory into your project.

## Usage

### Creating and Add

```swift
import SwipeMenu

let menu = SwipeMenu()
view.addSubview(menu)

```

### Must Perfect SwipeMenuDataSource
SwipeMenuDataSource will be used to provide menu data source.

```swift
@objc public protocol SwipeMenuDataSource {
    func numberOfItemsInMenu(menu: SwipeMenu) -> Int
    func menu(menu: SwipeMenu, titleForRow row: Int) -> String

    optional func menu(menu: SwipeMenu, indicatorIconForRow row: Int) -> UIImage
}
```

### May be you want SwipeMenuDelegate
SwipeMenuDelegate will be used to select action.

```swift
@objc public protocol SwipeMenuDelegate {
    optional func menu(menu: SwipeMenu, didSelectRow row: Int)
}
```

## Communication

- If you **need help**, open an issue or send an email.
- If you **found a bug**, open an issue or send an email.
- If you'd like to **ask a question**,open an issue or send an email.
- If you **want to contribute**, submit a pull request.

## License

SwipeMenu is released under the MIT license. See LICENSE for details.

##  Author😀

🇨🇳[Hares - https://github.com/harryzjm](https://github.com/harryzjm)
Email: **angel-i@outlook.com**


text:
package org.zalando.intellij.swagger.completion;

import com.google.common.collect.Lists;
import org.jetbrains.annotations.NotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.zalando.intellij.swagger.fixture.SwaggerFixture;
import org.zalando.intellij.swagger.fixture.SwaggerFixture.JsonOrYaml;

import java.util.List;
import java.util.stream.Collectors;

public class JsonCaretCompletionTest {

    private SwaggerFixture myFixture;

    @Before
    public void setUpBefore() throws Exception {
        myFixture = SwaggerFixture.forResourceFolder("testing/completion/json");
    }

    @After
    public void tearDownAfter() throws Exception {
        myFixture.tearDown();
    }

    @Test
    public void thatJsonKeyInsideQuotesIsCompleted() {
        getCaretCompletions("key_inside_quotes")
                .assertContains(getExpectedElements())
                .assertNotContains(getExistingElements());
    }

    @Test
    public void thatJsonKeyWithNoQuotesIsCompleted() {
        final List<String> keysInQuotes = getExpectedElements().stream()
                .map(value -> "\"" + value + "\"")
                .collect(Collectors.toList());

        getCaretCompletions("key_with_no_quotes")
                .assertContains(keysInQuotes)
                .assertNotContains(getExistingElements());
    }

    @Test
    public void thatJsonKeyWithStartingQuoteIsCompleted() {
        getCaretCompletions("key_with_starting_quote")
                .assertContains(getExpectedElements())
                .assertNotContains(getExistingElements());
    }

    private List<String> getExistingElements() {
        return Lists.newArrayList("swagger", "host");
    }

    private List<String> getExpectedElements() {
        return Lists.newArrayList("basePath", "produces", "consumes", "schemes",
                "paths", "tags", "parameters", "responses");
    }

    @NotNull
    private SwaggerFixture.AssertableList getCaretCompletions(@NotNull String testFileNoExt) {
        return myFixture.getCompletions(testFileNoExt, JsonOrYaml.JSON);
    }

}


text:
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { withKnobs, boolean, number, select } from '@storybook/addon-knobs';
import BigNumber from 'bignumber.js';
import StoryDecorator from '../_support/StoryDecorator';
import StoryProvider from '../_support/StoryProvider';
import VotingRegistrationStepsChooseWallet from '../../../source/renderer/app/components/voting/voting-registration-wizard-steps/VotingRegistrationStepsChooseWallet';
import VotingRegistrationStepsRegister from '../../../source/renderer/app/components/voting/voting-registration-wizard-steps/VotingRegistrationStepsRegister';
import VotingRegistrationStepsConfirm from '../../../source/renderer/app/components/voting/voting-registration-wizard-steps/VotingRegistrationStepsConfirm';
import VotingRegistrationStepsEnterPinCode from '../../../source/renderer/app/components/voting/voting-registration-wizard-steps/VotingRegistrationStepsEnterPinCode';
import VotingRegistrationStepsQrCode from '../../../source/renderer/app/components/voting/voting-registration-wizard-steps/VotingRegistrationStepsQrCode';
import VotingInfo from '../../../source/renderer/app/components/voting/voting-info/VotingInfo';
import { FundPhase } from '../../../source/renderer/app/stores/VotingStore';
import { CatalystFund } from '../../../source/renderer/app/api/voting/types';
import { VotingFooterLinks } from '../../../source/renderer/app/components/voting/VotingFooterLinks';
import {
  LANGUAGE_OPTIONS,
  DATE_ENGLISH_OPTIONS,
  TIME_OPTIONS,
} from '../../../source/renderer/app/config/profileConfig';
import {
  VOTING_REGISTRATION_MIN_TRANSACTION_CONFIRMATIONS,
  VOTING_REGISTRATION_MIN_WALLET_FUNDS,
} from '../../../source/renderer/app/config/votingConfig';
import {
  generateHash,
  generatePolicyIdHash,
  generateWallet,
} from '../_support/utils';
import { HwDeviceStatuses } from '../../../source/renderer/app/domains/Wallet';
import VerticalFlexContainer from '../../../source/renderer/app/components/layout/VerticalFlexContainer';
import { Locale } from '../../../source/common/types/locales.types';

const mockFundInfo: CatalystFund = {
  current: {
    number: 7,
    startTime: new Date('Jan 20, 2022, 11:00 UTC'),
    endTime: new Date('Feb 3, 2022, 11:00 UTC'),
    resultsTime: new Date('Feb 10, 2022'),
    registrationSnapshotTime: new Date('Jan 6, 2022, 11:00 UTC'),
  },
  next: {
    number: 8,
    startTime: new Date('Jan 6, 2022, 11:00 UTC'),
    registrationSnapshotTime: new Date('Apr 7, 2022, 11:00 UTC'),
  },
};

const assets = {
  available: [
    {
      id: generateHash(),
      policyId: generatePolicyIdHash(),
      uniqueId: generatePolicyIdHash(),
      assetName: '',
      quantity: new BigNumber(200),
    },
    {
      id: generateHash(),
      policyId: generatePolicyIdHash(),
      uniqueId: generatePolicyIdHash(),
      assetName: '',
      quantity: new BigNumber(200),
    },
  ],
  total: [
    {
      id: generateHash(),
      policyId: generatePolicyIdHash(),
      uniqueId: generatePolicyIdHash(),
      assetName: '',
      quantity: new BigNumber(200),
    },
    {
      id: generateHash(),
      policyId: generatePolicyIdHash(),
      uniqueId: generatePolicyIdHash(),
      assetName: '',
      quantity: new BigNumber(200),
    },
  ],
};
const WALLETS = [
  generateWallet('Wallet 1', '100000000000000', assets, 0),
  generateWallet(
    'Wallet 2',
    '500000000',
    assets,
    0,
    undefined,
    true,
    'syncing'
  ),
];
const stepsList = ['Wallet', 'Sign', 'Confirm', 'PIN code', 'QR code'];

const votingInfo = {
  fundInfo: mockFundInfo,
  currentLocale: LANGUAGE_OPTIONS[0].value as Locale,
  currentDateFormat: DATE_ENGLISH_OPTIONS[0].value,
  currentTimeFormat: TIME_OPTIONS[0].value,
  onRegisterToVoteClick: action('onRegisterToVoteClick'),
  onExternalLinkClick: action('onExternalLinkClick'),
};

storiesOf('Voting / Voting Registration Wizard', module)
  .addDecorator((story) => (
    <StoryProvider>
      <StoryDecorator>{story()}</StoryDecorator>
    </StoryProvider>
  ))
  .addDecorator(withKnobs) // ====== Stories ======
  .add('Voting Registration - Step 1', () => (
    <VotingRegistrationStepsChooseWallet
      onClose={action('onClose')}
      stepsList={stepsList}
      activeStep={1}
      numberOfStakePools={number('numberOfStakePools', 100)}
      onSelectWallet={action('onSelectWallet')}
      wallets={WALLETS}
      minVotingRegistrationFunds={VOTING_REGISTRATION_MIN_WALLET_FUNDS}
      selectedWalletId={WALLETS[0].id}
      isWalletAcceptable={action('isWalletAcceptable')}
      getStakePoolById={action('getStakePoolById')}
      nextFundNumber={8}
    />
  ))
  .add('Voting Registration - Step 2', () => (
    <VotingRegistrationStepsRegister
      onClose={action('onClose')}
      onBack={action('onBack')}
      stepsList={stepsList}
      activeStep={2}
      nextFundNumber={8}
      transactionFee={
        new BigNumber(
          number('transactionFee', 0.3, {
            min: 0,
            max: 1000000,
          })
        )
      }
      // @ts-ignore ts-migrate(2554) FIXME: Expected 2-3 arguments, but got 1.
      isSubmitting={boolean('isSubmitting')}
      onConfirm={action('onConfirm')}
      onExternalLinkClick={action('onExternalLinkClick')}
      hwDeviceStatus={HwDeviceStatuses.CONNECTING}
      isHardwareWallet={boolean('isHardwareWallet', false)}
      isTrezor={boolean('isTrezor', false)}
      selectedWallet={WALLETS[0]}
    />
  ))
  .add('Voting Registration - Step 3', () => (
    <VotingRegistrationStepsConfirm
      onClose={action('onClose')}
      stepsList={stepsList}
      activeStep={3}
      isTransactionPending={boolean('isTransactionPending', true)}
      isTransactionConfirmed={boolean('isTransactionConfirmed', false)}
      transactionConfirmations={number('transactionConfirmations', 0, {
        range: true,
        max: VOTING_REGISTRATION_MIN_TRANSACTION_CONFIRMATIONS,
      })}
      onConfirm={action('onConfirm')}
      onRestart={action('onRestart')}
      transactionError={boolean('transactionError', false)}
      nextFundNumber={8}
    />
  ))
  .add('Voting Registration - Step 4', () => (
    <VotingRegistrationStepsEnterPinCode
      onClose={action('onClose')}
      stepsList={stepsList}
      activeStep={4}
      onSetPinCode={action('onSetPinCode')}
      nextFundNumber={8}
    />
  ))
  .add('Voting Registration - Step 5', () => (
    <VotingRegistrationStepsQrCode
      onClose={action('onClose')}
      onDownloadPDF={action('onDownloadPDF')}
      stepsList={stepsList}
      activeStep={2}
      qrCode="djkhfkwdjhfkwdhfkwjdhfkwdhf9wdyf9wdh9u3h03hd0f3hd0h30hf30dhf03dhf03dhf03dhf03dhf0u3dhf0u3dhf0u3dfh30uhfd30uh"
      nextFundNumber={8}
    />
  ));
storiesOf('Voting / Voting Info', module)
  .addDecorator((story) => (
    <StoryDecorator>
      <VerticalFlexContainer>
        {story()}
        <VotingFooterLinks />
      </VerticalFlexContainer>
    </StoryDecorator>
  ))
  .addDecorator(withKnobs) // ====== Stories ======
  .add('Snapshot phase', () => (
    <VotingInfo {...votingInfo} fundPhase={FundPhase.SNAPSHOT} />
  ))
  .add('Voting phase', () => (
    <VotingInfo {...votingInfo} fundPhase={FundPhase.VOTING} />
  ))
  .add('Tallying phase', () => (
    <VotingInfo {...votingInfo} fundPhase={FundPhase.TALLYING} />
  ))
  .add('Results phase', () => (
    <VotingInfo {...votingInfo} fundPhase={FundPhase.RESULTS} />
  ))
  .add('API error', () => <VotingInfo {...votingInfo} fundPhase={null} />);


text:
//
// Copyright 2009 Christian Henning
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#ifndef BOOST_GIL_EXTENSION_IO_BMP_DETAIL_IS_ALLOWED_HPP
#define BOOST_GIL_EXTENSION_IO_BMP_DETAIL_IS_ALLOWED_HPP

#include <boost/gil/channel.hpp>

#include <boost/mpl/bool_fwd.hpp>

namespace boost { namespace gil { namespace detail {

template< typename View >
bool is_allowed( const image_read_info< bmp_tag >& info
               , mpl::true_   // is read_and_no_convert
               )
{
    bmp_bits_per_pixel::type src_bits_per_pixel = 0;

    switch( info._bits_per_pixel )
    {
        case 1:
        case 4:
        case 8:
        {
            if(  info._header_size == bmp_header_size::_win32_info_size
              && info._compression != bmp_compression::_rle8
              && info._compression != bmp_compression::_rle4
              )
            {
                src_bits_per_pixel = 32;
            }
            else
            {
                src_bits_per_pixel = 24;
            }

            break;
        }

        case 15:
        case 16:
        {
            src_bits_per_pixel = 24;

            break;
        }

        case 24:
        case 32:
        {
            src_bits_per_pixel = info._bits_per_pixel;

            break;
        }
        default:
        {
            io_error( "Pixel size not supported." );
        }
    }

    typedef typename channel_traits< typename element_type< typename View::value_type >::type >::value_type channel_t;
    bmp_bits_per_pixel::type dst_bits_per_pixel = detail::unsigned_integral_num_bits< channel_t >::value
                                                * num_channels< View >::value;

    return ( dst_bits_per_pixel == src_bits_per_pixel );
}

template< typename View >
bool is_allowed( const image_read_info< bmp_tag >& /* info */
               , mpl::false_  // is read_and_convert
               )
{
    return true;
}

} // namespace detail
} // namespace gil
} // namespace boost

#endif


text:
/**
 * Artist Array Processing
*/

function register(){
    this.buttonCount++;
    arrayInput();
    //$("#test").text(("#vorname").val());
    //showUp();
}

function arrayInput(){
    array.push(buttonCount);
    array.push($("#vorname").val());
    array.push($("#pob").val());
    array.push($("#dob").val());
    array.push($("#checkbox:checked").val());
    console.log("CHECKBOX: "+ $("#checkbox:checked").val());
    console.log("VALUE: " + array[array.length-1]);
}

function search() {
    var success=false;
    var searchString=$("#search-2").val();
    var resultString=" Perfect match: \n";
    console.log("search function active");
    console.log(searchString);
    for (var i=0;i<array.length;i++){
        console.log("Array value: " + array[i]);
        //search by name - only by name.
        if(i%5==1 && array[i]==searchString) {
            resultString+= "ID: "+ array[i-1] + ", Name: " + array[i] + ", Pob: " + array[i+1]+ ", Dob: "+ array[i+2] +" \n";
            success=true;
        }
    }
    if(success=false){
     console.log("false no findings");
    }
    else{
        //Ausnahme: Keine main.js Methode zur Aktualisierung des Frontends. - nur ein alert.
        alert(resultString);
    }
}


text:
from django.middleware.csrf import get_token

class CsrfCookieUsedMiddleware(object):
    """
    Simple middleware that ensures Django's CSRF middleware will
    always include the CSRF cookie on outgoing responses.

    See: https://groups.google.com/d/msg/django-developers/Zi9_AyfBd_0/t_TlsL8-CHMJ
    """
    def process_request(self, request):
        get_token(request)


text:
from __future__ import (unicode_literals, absolute_import,
                        division, print_function)
import json
import datetime

from optparse import make_option
from django.core.management.base import BaseCommand
from django.db import IntegrityError

from snisi_core.models.Roles import Role
from snisi_core.models.Providers import Provider
from snisi_core.models.Numbers import PhoneNumber, PhoneNumberType
from snisi_tools.datetime import datetime_from_iso, DEBUG_change_system_date
from snisi_tools.pnlp_import import entity_from
from snisi_tools.numbers import normalized_phonenumber

new_slug_matrix = {}

female_firstnames = ["Kardiatou", "Saran", "Salimata", "Djeneba", "Sadio",
                     "Emeline", "Ramata", "Mariam", "Monique",
                     "Aminata", "Baïni", "Alice", "Fatoumata",
                     "Fatouma", "Assitan", "Aminata", "Viviane",
                     "Anacleta", "Katie", "Kalidi", "Zana", "Djénéba Jeanne",
                     "Hidya", "Suzi", "Seriba", "Adélaïde", "Christine",
                     "Diakalia", "Abibatou", "Djéneba", "Aissata", "Adama",
                     "Rachel", "Fanta", "Sukanta", "Djénébou",
                     "Coumba", "Diahara", "Kadidia",
                     "Madina", "Sadia", "Bintou", "Cristina", "Keneko",
                     "Mintou", "Huberte", "Mama", "Clara"]

role_matrix = {
    'partners': 'partner',
    'district': 'charge_sis',
    'region': 'charge_sis',
    'cscom': 'dtc',
    'pnlp': 'central',
    'antim': 'snisi_tech',
    'national': 'central'}

maiden_names = ['Coulibaly', 'Traoré', 'Diarra', 'Diallo', 'Sougoué']

november = datetime.datetime(2011, 11, 30, 12, 0)
july = datetime.datetime(2012, 7, 31, 12, 0)

class Command(BaseCommand):

    option_list = BaseCommand.option_list + (
        make_option('-f',
                    help='JSON export of all PNLP providers',
                    action='store',
                    dest='input_file'),
        make_option('-m',
                    help='JSON matrix of old and new codes',
                    action='store',
                    dest='matrix_input_file'),
        make_option('-u',
                    help='JSON matrix of old and new users',
                    action='store',
                    dest='matrix_input_user_file'),
        )

    def handle(self, *args, **options):
        global new_slug_matrix

        matrix_input_file = open(options.get('matrix_input_file'), 'r')
        matrix = json.load(matrix_input_file)
        users_matrix = json.load(
            open(options.get('matrix_input_user_file'), 'r'))
        get_entry = lambda l, new_username: [
            e for e in l if e['new_username'] == new_username][-1]

        new_slug_matrix = matrix['old_new']
        new_slug_matrix.update({
            'mali': 'mali',
            'segou': '2732',
            'bamako': '9GR8',
            'mopti': 'SSH3'})

        ssangare = {
            "date_joined": "2013-07-24T10:00:00",
            "entity": "maci1",
            "first_name": "Sidiki",
            "is_active": True,
            "is_staff": False,
            "is_superuser": False,
            "last_login": "2013-07-24T10:00:00",
            "last_name": "Sangaré",
            "password": "pbkdf2_sha256$12000$0chjcCnjHwuG$V3O/Kj"
                        "SLQLstLh3/IJHiPCMrSornNXaP5sbYhkGuR/A=",
            "phone_number": "+22370061548",
            "phone_number_extra": None,
            "pwhash": "aa",
            "role": "cscom",
            "username": "ssangare"
        }

        input_file = open(options.get('input_file'), 'r')
        malaria_users = json.load(input_file) + [ssangare]

        # change date to NOVEMBER 11
        DEBUG_change_system_date(november, True)

        print("Removing all providers...")
        Provider.objects.all().delete()

        print("Creating Providers...")

        duplicates = {}
        missed_locations = []

        for provider_data in malaria_users:
            print(provider_data['username'])

            # If user has a changind location. Create with the old one.
            if provider_data['username'] \
                    in [i['new_username'] for i in users_matrix]:
                entry = get_entry(users_matrix, provider_data['username'])
                provider_data['entity'] = entry['old_entity']

            phone_number = normalized_phonenumber(
                provider_data['phone_number'])
            phone_number2 = normalized_phonenumber(
                provider_data['phone_number_extra'])
            try:
                provider_data['location'] = entity_from(
                    new_slug_matrix[provider_data['entity']])
            except KeyError:
                missed_locations.append(provider_data['entity'])
                continue

            provider_data['last_login'] = datetime_from_iso(
                provider_data['last_login'])
            provider_data['date_joined'] = datetime_from_iso(
                provider_data['date_joined'])
            role_slug = role_matrix.get(provider_data['role'])
            provider_data['role'] = Role.objects.get(slug=role_slug)

            del(provider_data['entity'])
            del(provider_data['pwhash'])
            del(provider_data['phone_number'])
            del(provider_data['phone_number_extra'])

            fd = provider_data['first_name'].split()
            if len(fd) and fd[0] in maiden_names:
                provider_data.update({'maiden_name': fd[0]})
                fd = fd[1:]
                provider_data.update({'first_name': " ".join(fd)})

            if len(fd) > 1:
                provider_data.update({'first_name': fd[0],
                                      'middle_name': " ".join(fd[1:])})

            if provider_data['first_name'] in female_firstnames:
                provider_data.update({
                    'gender': Provider.FEMALE,
                    'title': Provider.MISTRESS})
            else:
                provider_data.update({
                    'gender': Provider.MALE,
                    'title': Provider.MISTER})

            if role_slug == 'dtc' or \
                provider_data['username'] in ('mkonat1', 'itraor', 'ktraor',
                                              'sfomba', 'sfomba1', 'olya',
                                              'olya1', 'tdackouo', 'bcamara',
                                              'akonate',):
                provider_data.update({'title': Provider.DOCTOR})

            if provider_data['username'] == 'maaa':
                provider_data['gender'] = Provider.FEMALE
                provider_data['first_name'] = "Baba"
                provider_data['last_name'] = "Moller"

            if provider_data['username'] == 'baaa':
                provider_data['first_name'] = "Faraba"
                provider_data['last_name'] = "Samaké"

            if provider_data['username'] == 'aaga':
                provider_data['first_name'] = "Abderhamane"
                provider_data['last_name'] = "Ag Alhousséiini"

            if provider_data['username'] == 'saaa':
                provider_data['gender'] = Provider.FEMALE
                provider_data['first_name'] = "Suzi"
                provider_data['last_name'] = "Svaen-oven"
                provider_data['title'] = Provider.MISS

            if provider_data['username'] == 'btraore':
                provider_data['is_active'] = False
                phone_number = phone_number2
                phone_number2 = normalized_phonenumber(None)

            if provider_data['username'] in ('shounton', 'sfomba',
                                             'olya1', 'mdiabat', 'blya1',
                                             'afadiga', 'jdoe', 'ttest',
                                             'tolytest'):
                continue

            provider = Provider(**provider_data)
            provider.save()

            for num in (phone_number, phone_number2):
                if num is not None \
                        and num not in ('+22300000000', '+22312345678'):
                    try:
                        p = PhoneNumber.from_guess(num, provider)
                        if num.startswith('+2237229'):
                            p.category = PhoneNumberType.objects.get(
                                slug='flotte')
                            p.save()
                    except IntegrityError:
                        duplicates.update({
                            num: (provider, PhoneNumber.by_identity(num))})
            print(provider)

        print("Updating Providers...")
        # if updating (2012-07-31), change location and save
        DEBUG_change_system_date(july, True)
        for entry in users_matrix:
            print(entry)
            provider = Provider.objects.get(username=entry['new_username'])
            print(provider)

            provider.location = entity_from(
                new_slug_matrix[entry['new_entity']])
            provider.save()

        DEBUG_change_system_date(None, True)


text:
if [ "$OLD_PATH" == "" ]
then
	export OLD_PATH=$PATH;
	PATH="$PWD/bin:$PWD/vendor/bin:$PATH"
	echo "New path is ready to go"
else
	PATH=$OLD_PATH
	OLD_PATH=""
	echo "Project path is deleted"
fi


text:
author: slaffer
title: Sophia's Test Post Nitrous
layout: post
date: 2014-02-19
---

Test post from Nitrous. Learning to write in command line!

{% include python %}

print("This is awesomeness")

{% include endpython %}


text:
1. 从资源中获取位图
可以使用BitmapDrawable或者BitmapFactory来获取资源中的位图。
```
Resources res=getResources();
Resources res=getResources();
```
使用BitmapDrawable (InputStream is)构造一个BitmapDrawable;
```
InputStream is = res.openRawResource(R.drawable.pic180);
BitmapDrawable bmpDraw = new BitmapDrawable(is);
Bitmap bmp = bmpDraw.getBitmap();
```
使用BitmapDrawable类的getBitmap()获取得到位图;
```
InputStream is = res.openRawResource(R.drawable.pic180);
BitmapDrawable bmpDraw = new BitmapDrawable(is);
Bitmap bmp = bmpDraw.getBitmap();
```
2. 获取位图的信息
要获取位图信息,比如位图大小、像素、density、透明度、颜色格式等。
3. 显示位图
```
// 获取位图
Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.pic180);
// 转换为BitmapDrawable对象
BitmapDrawable bmpDraw = new BitmapDrawable(bmp);
// 显示位图
ImageView iv2 = (ImageView) findViewById(R.id.ImageView02);
iv2.setImageDrawable(bmpDraw);
// 获取位图
Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.pic180);
// 转换为BitmapDrawable对象
BitmapDrawable bmpDraw = new BitmapDrawable(bmp);
// 显示位图
ImageView iv2 = (ImageView) findViewById(R.id.ImageView02);
iv2.setImageDrawable(bmpDraw);
// 使用Canvas类显示位图
// 这儿采用一个继承自View的子类Panel,在子类的OnDraw中显示
@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(new Panel(this));
}

class Panel extends View {
	public Panel(Context context) {
		super(context);
	}

	public void onDraw(Canvas canvas) {
		Bitmap bmp = BitmapFactory.decodeResource(getResources(),
				R.drawable.pic180);
		canvas.drawColor(Color.BLACK);
		canvas.drawBitmap(bmp, 10, 10, null);
	}
}
```


text:
The RMs (rms) project implements a [reasonably] high-performance multi-threaded
"pub/sub" messaging system, designed around a shared-memory approach to storing
messages awaiting delivery.  This was chosen so that multi-process publication
and distribution would be simplified - other than the discovered (or allocated)
per-process "base" pointer to the shared memory segment, there are NO pointers
stored in any in-memory structures.  This would make sharing - even if mapped to
different virtual address ranges in different processes - quite simple.

HINT: think "indices, all the way down". :sunglasses:

As things actually worked out, over the decade this package has been in use, the
"multi-process" aspects of this architecture were never built out, both because
of the substantially higher costs of resource coordination/locking INTER-process
*vs* INTRA-process, but more subtly, the paradigm of "many cooperating lightweight
threads" utlimately seemed more useful than one of "many cooperating heavyweight
processes" - at least on a single machine.

An additional "novel" aspect of RMs (rms) is the actual representation used for
"pointers" to stored messages and metadata - given the goal above of being able
to share in-memory structures - possibly mapped to different addresses while in
use - a 32-bit format was employed that simultaneously encodes location, typing,
AND length information - really(*).  This design has provided high-performance
allocation, releasing, and management of resources for the rest of the system.

- a *possible* trade-off here has been the "limitation" of message buffer memory
to 256 MB (total), as well as individual message "payloads" to 4 KB... see below
for possible future work in this area.

It is written in fairly idiomatic modern C++ 17... although since it was in
its original version built from "old-school" C/C++, there may be portions of the
code that are still awaiting a "re-imagining" (again, see below).

The primary "user" (as well as "developer") documentation for rms is present
in the rms.h header file.  Note that there is a single [non-system] dependency:

[UTF-8 Pattern-matcher "sibling" project](https://github.com/robertroessler/rglob)

... the VS2019 project files are expecting RGlob/RMs to be in "sibling" folders,
with rglob in a folder [roughly] at "../RGlob-trunk" - but of course, feel free
to re-arrange any of the project/folder layout.  And, due to its size, the rglob
library should (as in the included VS files) likely be kept as a "static" lib.

Besides being "pure" C++, the code is believed to be both 32/64 -bit "safe", and
contains only 2 dependencies on Windows (easily "ported" to other environments):

* ::rms_initialize of course needs to set up an area of mapped/shared memory,
principally handled in Windows by ::MapViewOfFile and ::VirtualAlloc

* the ::dump{Root,Queue,Exported,Check} variadic template diagnostic functions
expect a high-perf / non-blocking logging sink (::OutputDebugString in Windows)

... again, both of the above are [almost] trivially re-hosted in modern OSes.

## ToDo

Possible items to work on - for myself or collaborators include

* [DONE!] additonal (and properly laid out) test cases, both to serve as actual tests
and to show examples of usage - PARTICULARLY displaying multi-threaded use

* [DONE!] investigating a lightweight (lambda-based?) form of "subscription targets"

* investigating (probably in a "version 2") a 64-bit version for RMs "pointers"

* as only Visual Studio 2019 project and solution files are initially present,
control files for building in non-Windows environments could be useful

## ProbablyNot

Things that most likely should NOT happen include

* any attempt to return to or re-emphasize the ancient "version 0.5" lower-level
interface... really, any work on the interface(s) should be in extending the
"modern" template-based version, and/or taking advantage of any new RMs pointers


text:
QtWebEngineView::QtWebEngineView(QWidget *parent) : QWebEngineView(parent)
{
    connect(page(), SIGNAL(linkHovered(QString)), this, SLOT(linkHovered(QString)));
}

void QtWebEngineView::linkHovered(QString url)
{
    emit linkClicked(QUrl(url));
}


text:
% channelSubset = GetSaveChansIm( myobj )
%
%     Returns a vector containing the indices of
%     IMEC channels being saved.
%
function [ret] = GetSaveChansIm( s )

    ret = str2num( DoQueryCmd( s, 'GETSAVECHANSIM' ) );
end


text:
package com.android.tools.idea.welcome.install;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Signals a failure in the wizard.
 */
public class WizardException extends Exception {
  public WizardException(@NotNull String message) {
    super(message);
  }

  public WizardException(@NotNull String message, @Nullable Throwable cause) {
    super(message, cause);
  }
}


text:
Download a starter template with **ASP.NET Core** and **Entity Framework Core** to integrate SQLite.
[Multi-page template with **ASP.NET Core 2.x** + **.NET Core Framework** + **Authentication**](https://aspnetboilerplate.com/Templates)
will be explained in this document.

### Install

Install the [`Microsoft.EntityFrameworkCore.Sqlite`](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Sqlite/) NuGet package to the **\*.EntityFrameworkCore** project.

### Configuration

Some configuration and workarounds are needed to use SQLite with ASP.NET Core and Entity Framework Core.

#### Configure DbContext

Since SQLite doesn't support multithreading, transactions should be disabled in the `SQLiteDemoEntityFrameworkModule.PreInitialize()` method.

> NOTE:Check [here](https://github.com/XdX-Software/EasyDDD/issues/1) for more info and workarounds.

```c#
[DependsOn(
    typeof(SQLiteDemoCoreModule),
    typeof(AbpZeroCoreEntityFrameworkCoreModule))]
public class SQLiteDemoEntityFrameworkModule : AbpModule
{
    public override void PreInitialize()
    {
        ...
        // add this line to disable transactions
        Configuration.UnitOfWork.IsTransactional = false;
        ...
    }
}
```

Replace `YourProjectNameDbContextConfigurer.cs` with the following lines

```c#
public static class SqliteDemoDbContextConfigurer
{
    public static void Configure(DbContextOptionsBuilder<SqliteDemoDbContext> builder, string connectionString)
    {
        builder.UseSqlite(connectionString);
    }

    public static void Configure(DbContextOptionsBuilder<SqliteDemoDbContext> builder, DbConnection connection)
    {
        builder.UseSqlite(connection);
    }
 }
 ```

#### Configure connection string

Change the connection string to your SQLite connection in ***.Web.Mvc/appsettings.json**. Example:

```js
{
  "ConnectionStrings": {
    "Default": "Data Source=SqliteDemoDb.db"
  },
  ...
}

```

#### A workaround

To prevent EF Core from calling `Program.BuildWebHost()` rename `BuildWebHost`. For example, change it to `InitWebHost`.
To understand why it needs to be renamed check the following issues,

> **Reason** : [EF Core 2.0: design-time DbContext discovery changes](https://github.com/aspnet/EntityFrameworkCore/issues/9033)
>
> **Workaround** : [Design: Allow IDesignTimeDbContextFactory to short-circuit service provider creation](https://github.com/aspnet/EntityFrameworkCore/issues/9076#issuecomment-313278753)
>
> **NOTE :** If you don't rename BuildWebHost, you'll get an error running the BuildWebHost method.

### Create Database

Remove all migration classes under **\*.EntityFrameworkCore/Migrations** folder before creating database.
`Microsoft.EntityFrameworkCore.Sqlite` will add some of its own configuration to work with Entity Framework Core.

Now it's ready to build the database.

- Select **\*.Web.Mvc** as the startup project.
- Open **Package Manager Console** and select the **\*.EntityFrameworkCore** project.
- Run the `add-migration Initial_Migration` command
- Run the `update-database` command

The SQLite integration is now complete. You can now run your project with SQLite.


text:
package appModel;

import java.awt.image.BufferedImage;

import javafx.beans.value.ChangeListener;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.EventHandler;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import photonApi.FrameRegion;
import photonApi.Rectangle;
import util.AABB2D;
import util.Vector2f;
import util.Vector3f;

public class StaticCanvasDisplay extends Display
{
	private WritableImage m_image;
	private Canvas        m_canvas;

	public StaticCanvasDisplay()
	{
		this(1, 1);
	}

	public StaticCanvasDisplay(int widthPx, int heightPx)
	{
		super();

		m_image  = new WritableImage(widthPx, heightPx);
		m_canvas = new Canvas(widthPx, heightPx);

		ChangeListener<Number> sizeChangeListener = (ovservable, oldValue, newValue) ->
		{
			drawFlood();
			drawFrame(new Rectangle(0, 0, getFrameWidthPx(), getFrameHeightPx()));

			getDisplayInfoView().showDisplayResolution(
				(int)(m_canvas.getWidth() + 0.5), (int)(m_canvas.getHeight() + 0.5));
		};

		m_canvas.widthProperty().addListener(sizeChangeListener);
		m_canvas.heightProperty().addListener(sizeChangeListener);

//		m_canvas.widthProperty().addListener((ovservable, oldValue, newValue) -> m_canvas.widthProperty().set(Math.floor(m_canvas.getWidth())));
//		m_canvas.heightProperty().addListener((ovservable, oldValue, newValue) -> m_canvas.heightProperty().set(Math.floor(m_canvas.getHeight())));

//		ChangeListener<Number> redrawListener = (ovservable, oldValue, newValue) ->
//			{clear(); drawFrame()};
//		m_canvas.widthProperty().addListener(redrawListener);
//		m_canvas.heightProperty().addListener(redrawListener);

		m_canvas.setOnMouseMoved(new EventHandler<MouseEvent>()
		{
			@Override
			public void handle(MouseEvent event)
			{
				Vector2f canvasCoordPx = new Vector2f((float)event.getX(), (float)event.getY());
				Vector2f frameCoordPx  = getFrameCoordPx(canvasCoordPx);

				getDisplayInfoView().showCursorCoord(
					Math.min((int)frameCoordPx.x, getFrameWidthPx() - 1),
					Math.min((int)frameCoordPx.y, getFrameHeightPx() - 1));

				int x = (int)frameCoordPx.x;
				int y = (int)(m_image.getHeight() - frameCoordPx.y);
				x = Math.min(x, getFrameWidthPx() - 1);
				y = Math.min(y, getFrameHeightPx() - 1);

				Color color = m_image.getPixelReader().getColor(x, y);
				getDisplayInfoView().showCursorColor(
					(int)(color.getRed() * 255.0),
					(int)(color.getGreen() * 255.0),
					(int)(color.getBlue() * 255.0));
			}
		});

		getDisplayInfoView().showFrameResolution(widthPx, heightPx);
		getDisplayInfoView().showDisplayResolution(widthPx, heightPx);
	}

	@Override
	public void loadFrame(FrameRegion frame)
	{
		copyFrameToImage(frame);
	}

	@Override
	public void drawFrame(Rectangle region)
	{
		// XXX: Slightly increase the region that is drawn onto canvas, so that
		// seams caused by filtering of original image and background color can
		// be overwrite. This hack causes indicators missing some edges.
		region.x -= 1;
		region.y -= 1;
		region.w += 2;
		region.h += 2;

		AABB2D rect = toCanvasRegion(region);

		final GraphicsContext g = m_canvas.getGraphicsContext2D();
		g.drawImage(m_image,
			region.x, getFrameHeightPx() - (region.y + region.h),
			region.w, region.h,
			rect.min.x, rect.min.y,
			rect.getWidth(), rect.getHeight());
	}

	@Override
	public void drawIndicator(Rectangle region, int r255, int g255, int b255)
	{
		final GraphicsContext g = m_canvas.getGraphicsContext2D();
		g.setFill(new Color(r255 / 255.0, g255 / 255.0, b255 / 255.0, 1));

		AABB2D rect = toCanvasRegion(region);

		float verticalWidth = Math.min(2, rect.getHeight());
		float horizontalWidth = Math.min(2, rect.getWidth());

		g.fillRect(rect.min.x, rect.min.y, rect.getWidth(), verticalWidth);
		g.fillRect(rect.min.x, rect.max.y - verticalWidth, rect.getWidth(), verticalWidth);
		g.fillRect(rect.min.x, rect.min.y, horizontalWidth, rect.getHeight());
		g.fillRect(rect.max.x - horizontalWidth, rect.min.y, horizontalWidth, rect.getHeight());
	}

	@Override
	public void drawFlood()
	{
		GraphicsContext g = m_canvas.getGraphicsContext2D();
		g.setFill(Color.DARKBLUE);
//		g.setFill(Color.TRANSPARENT);
		g.fillRect(0, 0, m_canvas.getWidth(), m_canvas.getHeight());
	}

	@Override
	public BufferedImage getImage()
	{
		return SwingFXUtils.fromFXImage(m_image, null);
	}

	public Canvas getView()
	{
		return m_canvas;
	}

	public int getFrameWidthPx()
	{
		return (int)(m_image.getWidth());
	}

	public int getFrameHeightPx()
	{
		return (int)(m_image.getHeight());
	}

	private Vector2f getFittedDrawResPx()
	{
		final float canvasWidth       = (float)(m_canvas.getWidth());
		final float canvasHeight      = (float)(m_canvas.getHeight());
		final float canvasAspectRatio = canvasWidth / canvasHeight;
		final float frameAspectRatio  = (float)(m_image.getWidth()) / (float)(m_image.getHeight());

		Vector2f resPx = new Vector2f();
		if(frameAspectRatio > canvasAspectRatio)
		{
			resPx.x = canvasWidth;
			resPx.y = canvasWidth / frameAspectRatio;
		}
		else
		{
			resPx.x = canvasHeight * frameAspectRatio;
			resPx.y = canvasHeight;
		}

		return resPx;
	}

	private Vector2f getCenteredOriginPx(Vector2f drawSizePx)
	{
		return new Vector2f(
			(float)(m_canvas.getWidth() - drawSizePx.x) * 0.5f,
			(float)(m_canvas.getHeight() - drawSizePx.y) * 0.5f);
	}

	private Vector2f getFrameCoordPx(Vector2f canvasCoordPx)
	{
		// FIXME: centered and fitted frame assumed
		Vector2f drawResPx = getFittedDrawResPx();
		Vector2f originPx  = getCenteredOriginPx(drawResPx);

		// flipping canvas y
		Vector2f coordPx = new Vector2f(canvasCoordPx.x, (float)m_canvas.getHeight() - canvasCoordPx.y);

		// relative to drawed frame
		coordPx = coordPx.sub(originPx);

		// normalize and scale to match actual frame size
		Vector2f frameSizePx = new Vector2f((float)m_image.getWidth(), (float)m_image.getHeight());
		coordPx = coordPx.div(drawResPx).mul(frameSizePx);

		// clamp to edge
		coordPx.x = Math.max(Math.min(coordPx.x, frameSizePx.x), 0);
		coordPx.y = Math.max(Math.min(coordPx.y, frameSizePx.y), 0);

		return coordPx;
	}

	private AABB2D toCanvasRegion(Rectangle region)
	{
		// FIXME: centered and fitted frame assumed
		Vector2f drawResPx = getFittedDrawResPx();
		Vector2f originPx  = getCenteredOriginPx(drawResPx);

		AABB2D canvasRegion = new AABB2D(
			new Vector2f(
					originPx.x + ((float)region.x / getFrameWidthPx()) * drawResPx.x,
					originPx.y + (1.0f - (float)(region.y + region.h) / getFrameHeightPx()) * drawResPx.y),
			new Vector2f(
				originPx.x + ((float)(region.x + region.w) / getFrameWidthPx()) * drawResPx.x,
				originPx.y + (1.0f - (float)(region.y) / getFrameHeightPx()) * drawResPx.y));
		return canvasRegion;
	}

	private float getDrawnScale(Vector2f drawSizePx)
	{
		// FIXME: retained aspect ratio assumed
		return (float)(drawSizePx.x / m_image.getWidth());
	}

	private void copyFrameToImage(FrameRegion frame)
	{
		if(!frame.isValid() || frame.getNumComp() != 3)
		{
			System.err.println("unexpected frame format; unable to load");
			return;
		}

		if(m_image.getWidth()  != frame.getFullWidthPx() ||
		   m_image.getHeight() != frame.getFullHeightPx())
		{
			m_image = new WritableImage(frame.getFullWidthPx(), frame.getFullHeightPx());

//			for(int y = 0; y < m_image.getHeight(); ++y)
//			{
//				for(int x = 0; x < m_image.getWidth(); ++x)
//				{
//					m_image.getPixelWriter().setColor(x, y, new Color(0, 0, 0, 1));
//				}
//			}

			getDisplayInfoView().showFrameResolution(frame.getFullWidthPx(), frame.getFullHeightPx());
			getDisplayInfoView().showZoom(getDrawnScale(getFittedDrawResPx()) * 100.0f);
		}

		final PixelWriter pixelWriter = m_image.getPixelWriter();
//		final PixelWriter pixelWriter = m_canvas.getGraphicsContext2D().getPixelWriter();
		final Rectangle region = frame.getRegion();
		final int endX = region.x + region.w;
		final int endY = region.y + region.h;
		final Vector3f color = new Vector3f();

		for(int y = region.y; y < endY; ++y)
		{
			for(int x = region.x; x < endX; ++x)
			{
				color.set(frame.getRgb(x, y));
				if(!Float.isFinite(color.x) ||
				   !Float.isFinite(color.y) ||
				   !Float.isFinite(color.z))
				{
					System.err.println("color is not finite: " + color);
					color.set(0, 0, 0);
				}

				color.clampLocal(0.0f, 1.0f);

				int inversedY = frame.getFullHeightPx() - y - 1;
				Color fxColor = new Color(color.x, color.y, color.z, 1.0);
				pixelWriter.setColor(x, inversedY, fxColor);
			}
		}
	}
}


text:
if [ "$(id -u)" -ne 0 ]; then
        echo 'This script must be run by root' >&2
        exit 1
fi

# upgrade ec2 instance
apt-get update -y
apt-get upgrade -y

# install maria-db client
apt-get install -y apache2 mariadb-client

# add our user to the apache group
usermod -a -G www-data ubuntu

# modify web directory permissions
chown -R ubuntu:www-data /var/www

# ensure all future files are created correctly
chmod 2775 /var/www && find /var/www -type d -exec sudo chmod 2775 {} \;

# change all current files
find /var/www -type f -exec sudo chmod 0664 {} \;

# install PHP Extras
apt-get install -y php php-zip php-mbstring php-curl php-xml libapache2-mod-php php-mysql git composer

apt autoremove -y

# restart the web server
service apache2 restart


text:
package org.cloudera.sa.hbaseFastSmallToLargeTableCopy.utils;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;

/**
* Input format that creates a configurable number of map tasks
* each provided with a single row of NullWritables. This can be
* useful when trying to write mappers which don't have any real
* input (eg when the mapper is simply producing random data as output)
*/
public class NMapInputFormat extends InputFormat<NullWritable, NullWritable> {
 private static final String NMAPS_KEY = "nmapinputformat.num.maps";

 @Override
 public RecordReader<NullWritable, NullWritable> createRecordReader(
     InputSplit split,
     TaskAttemptContext tac) throws IOException, InterruptedException {
   return new SingleRecordReader<NullWritable, NullWritable>(
       NullWritable.get(), NullWritable.get());
 }

 @Override
 public List<InputSplit> getSplits(JobContext context) throws IOException,
     InterruptedException {
   int count = getNumMapTasks(context.getConfiguration());
   List<InputSplit> splits = new ArrayList<InputSplit>(count);
   for (int i = 0; i < count; i++) {
     splits.add(new NullInputSplit());
   }
   return splits;
 }

 public static void setNumMapTasks(Configuration conf, int numTasks) {
   conf.setInt(NMAPS_KEY, numTasks);
 }

 public static int getNumMapTasks(Configuration conf) {
   return conf.getInt(NMAPS_KEY, 1);
 }

 private static class NullInputSplit extends InputSplit implements Writable {
   @Override
   public long getLength() throws IOException, InterruptedException {
     return 0;
   }

   @Override
   public String[] getLocations() throws IOException, InterruptedException {
     return new String[] {};
   }

   @Override
   public void readFields(DataInput in) throws IOException {
   }

   @Override
   public void write(DataOutput out) throws IOException {
   }
 }

 private static class SingleRecordReader<K, V>
   extends RecordReader<K, V> {

   private final K key;
   private final V value;
   boolean providedKey = false;

   SingleRecordReader(K key, V value) {
     this.key = key;
     this.value = value;
   }

   @Override
   public void close() {
   }

   @Override
   public K getCurrentKey() {
     return key;
   }

   @Override
   public V getCurrentValue(){
     return value;
   }

   @Override
   public float getProgress() {
     return 0;
   }

   @Override
   public void initialize(InputSplit split, TaskAttemptContext tac) {
   }

   @Override
   public boolean nextKeyValue() {
     if (providedKey) return false;
     providedKey = true;
     return true;
   }

 }
}


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28875_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Directional Survey Certification Form

    <p class="styleSans17.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Company Name
33-025-02607

    <p class="styleSans18.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Cathedral Energy Services
WPX - Mandaree 30-31HA - OH
Operator/Client Name

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">145327
WPX Energy

    <p class="styleSans18.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Well Surface Location by Footage 8. Lat/Long 8. Datum 1M 1/4 Sec T & R & County

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Lat 47.788946/ Long -102.641033 ; NAD83; NWNW 30 T150N R93W; McKenzie County

    <p class="styleSans18.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Final Report Date

    <p class="styleSans17.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Surveyed from MD of A feet to 8 feet m

    <p class="styleSans17.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Drilling Rig Contractor Name Nabors #323 Rig KB 2214 MWD/Directionai Surveyor's Name Aaron Evans/Jason Davis

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">"The data and calculations for this survey have been checked by me and conform to the calibration standards and operational procedures set forth by Cathedral Energy Services. I am
authorized and qualified to review the data. calculations and this report, and that the report represents a true and correct Directional Survey of this well based on the original data corrected to True North and obtained at the well site. Wellbore coordinates are calculated using
minimum curvature method.

    <p class="styleSans18.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Printed Name
Signature
Date Signed

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">11/5/2014

    <p class="styleSans17.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Scot; Crosley )

    <p class="styleSans2.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">5-Nov- 14

    <p class="styleSans18.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">MWDISurvey Run Date

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">14,128

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">9/26-10/12, 2014


text:
package androidx.webkit;

import android.webkit.SafeBrowsingResponse;

import androidx.annotation.RequiresFeature;
import androidx.annotation.RestrictTo;

/**
 * Compatibility version of {@link SafeBrowsingResponse}.
 */
public abstract class SafeBrowsingResponseCompat {
    /**
     * Display the default interstitial.
     *
     *

     * This method should only be called if
     * {@link WebViewFeature#isFeatureSupported(String)}
     * returns true for {@link WebViewFeature#SAFE_BROWSING_RESPONSE_SHOW_INTERSTITIAL}.
     *
     * @param allowReporting {@code true} if the interstitial should show a reporting checkbox.
     */
    @RequiresFeature(name = WebViewFeature.SAFE_BROWSING_RESPONSE_SHOW_INTERSTITIAL,
            enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
    public abstract void showInterstitial(boolean allowReporting);

    /**
     * Act as if the user clicked the "visit this unsafe site" button.
     *
     *

     * This method should only be called if
     * {@link WebViewFeature#isFeatureSupported(String)}
     * returns true for {@link WebViewFeature#SAFE_BROWSING_RESPONSE_PROCEED}.
     *
     * @param report {@code true} to enable Safe Browsing reporting.
     */
    @RequiresFeature(name = WebViewFeature.SAFE_BROWSING_RESPONSE_PROCEED,
            enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
    public abstract void proceed(boolean report);

    /**
     * Act as if the user clicked the "back to safety" button.
     *
     *

     * This method should only be called if
     * {@link WebViewFeature#isFeatureSupported(String)}
     * returns true for {@link WebViewFeature#SAFE_BROWSING_RESPONSE_BACK_TO_SAFETY}.
     *
     * @param report {@code true} to enable Safe Browsing reporting.
     */
    @RequiresFeature(name = WebViewFeature.SAFE_BROWSING_RESPONSE_BACK_TO_SAFETY,
            enforcement = "androidx.webkit.WebViewFeature#isFeatureSupported")
    public abstract void backToSafety(boolean report);

    /**
     * This class cannot be created by applications.
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY)
    public SafeBrowsingResponseCompat() {
    }
}


text:
.class public abstract Landroid/security/keystore/AndroidKeyStoreKeyGeneratorSpi$HmacBase;
.super Landroid/security/keystore/AndroidKeyStoreKeyGeneratorSpi;
.source "AndroidKeyStoreKeyGeneratorSpi.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/security/keystore/AndroidKeyStoreKeyGeneratorSpi;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x40c
    name = "HmacBase"
.end annotation

# direct methods
.method protected constructor <init>(I)V
    .locals 2

    invoke-static {p1}, Landroid/security/keystore/KeymasterUtils;->getDigestOutputSizeBits(I)I

    move-result v0

    const/16 v1, 0x80

    invoke-direct {p0, v1, p1, v0}, Landroid/security/keystore/AndroidKeyStoreKeyGeneratorSpi;-><init>(III)V

    return-void
.end method


text:
title:  "About me"
excerpt: "About me"
permalink: /about/index.html
cssfile: "/assets/css/pages/about.css"
---

I am Paolo.
Software engineer. [Python](https://www.python.org/) enthusiast,
[Django](https://www.djangoproject.com/) lover,
[Open Source contributor](#open-source-contributions) and
[Google Summer of Code]({% post_url 2014-04-21-gsoc2014 %}) participant.
Digital privacy paranoid.
Co–author of "[Security and Usability](http://books.google.com/books?id=wDVhy9EyEAEC&lpg=PP1&pg=PA221#v=onepage&q&f=false)", published by O'Reilly Media.

 More about my professional experience and expertise in my [LinkedIn](http://www.linkedin.com/in/pcoffetti) and [GitHub](https://github.com/puntonim) profiles.

Bio
===
I grew up in *Italy*. After one of the best [science high schools](http://www.liceolussana.com)
in town, I attended *Computer Engineering* at [University of Bergamo](http://www.unibg.it/).
I graduated with *top marks* and YES, *I am very proud of it*!

I lived in *Prague, Czech Republic* for a year during my [Erasmus Programme](http://en.wikipedia.org/wiki/Erasmus_Programme)
and loved their original [Pilsner](http://en.wikipedia.org/wiki/Pilsner_Urquell)
and [Svickova](http://en.wikipedia.org/wiki/Sv%C3%AD%C4%8Dkov%C3%A1).

In 2013 I spent wonderful months in *Washington, DC, USA*
while attending [SPRINT](http://www.advanse.com/training/sprint-faqs/)
a summer program in international business.

I am currently based in *Amsterdam, the Netherlands* where I learned to love bikes,
sliced bread and, after a few years, even... the rain!

Work
====

## [Eutron](http://www.eutron.it/)
While in university, during the final year of bachelor's studies, I worked as *IT Security Engineer Intern* in the field of *usability of security devices*
at [Eutron](http://www.eutron.it/) in Italy.
There I got the opportunity to co–author
the book "[Security and Usability](http://books.google.com/books?id=wDVhy9EyEAEC&lpg=PP1&pg=PA221#v=onepage&q&f=false)", published by O'Reilly Media and written together with some highly regarded professors and professionals:
[S. Garfinkel](http://en.wikipedia.org/wiki/Simson_Garfinkel),
[L. Cranor](https://www.cylab.cmu.edu/education/faculty/cranor.html),
[P. Salvaneschi](http://www.unibg.it/struttura/struttura.asp?cerca=rubrica&rubrica=1&persona=1091&nome=Paolo&cognome=Salvaneschi&titolo=Prof.) and
[U. Piazzalunga](https://www.linkedin.com/profile/view?id=49766601&authType=NAME_SEARCH&authToken=jGyK&locale=en_US&srchid=2869284821413996825098&srchindex=1&srchtotal=2&trk=vsrp_people_res_name&trkInfo=VSRPsearchId%3A2869284821413996825098%2CVSRPtargetId%3A49766601%2CVSRPcmpt%3Aprimary).

[Eutron](http://www.eutron.it/) is an electronic manufacturing services (EMS) enterprise.

## Salvaneschi & Partners
During my master's studies I joined *Salvaneschi & Partners* as *Quality Assurance Engineer*.
I was responsible for monitoring every phase of the software development process so as to ensure
design quality, making sure that the software adheres to the standards and requirements agreed
with stakeholders.

*Salvaneschi & Partners* is small-sized software engineering company run by
knowledgeable professionals offering auditing and consulting services.

## [United Academics](http://www.united-academics.org/)
In 2010 I entered *United Academics* as *Web Developer* and soon became the *Lead Software Developer*.
In 4 years at *United Academics*, among other things, we built a web crawler and full-text search
engine for Open Access papers,
a [printing on demand website](http://www.print2book.com) and web service,
a job portal
and an online bookshop.

[United Academics](http://www.united-academics.org/) is an international start-up which promotes
Open Access publishing amongst researchers.

## [Google]({% post_url 2014-04-21-gsoc2014 %})
In 2014 I took part in the prestigious *Google Summer of Code* program as *Full-stack Web Developer*
for [NeuroStars](http://neurostars.org) and [BioStars](https://www.biostars.org).
Read more about this experience in my [Google Summer of Code post]({% post_url 2014-04-21-gsoc2014 %}).

To know more about my professional experience and expertise, check out
[my LinkedIn profile](http://www.linkedin.com/in/pcoffetti).

Technologies
=============
A list of technologies I like to work and play with:

- [Python](https://www.python.org/): I learned coding with *Java*, but
felt in love with *Python* and its elegance
- Web frameworks as [Django](https://www.djangoproject.com), [Flask](http://flask.pocoo.org), [Pyramid](http://www.pylonsproject.org)
- [JavaScript](http://en.wikipedia.org/wiki/JavaScript)
- [Full-text search](http://en.wikipedia.org/wiki/Full_text_search) engines like
[Apache Solr](http://lucene.apache.org/solr/) and [Elasticsearch](http://www.elasticsearch.org/)
- [RESTful webservice](http://en.wikipedia.org/wiki/Representational_state_transfer#Applied_to_web_services)
- [NoSQL](http://en.wikipedia.org/wiki/NoSQL) technologies as [MongoDB](http://en.wikipedia.org/wiki/MongoDB) and data stores as [Redis](http://redis.io)
- [Ansible](http://www.ansible.com), [Docker](https://www.docker.com), [Amazon Web Services](http://aws.amazon.com)

Open Source Contributions
=========================
2014 was a very intense year, my GitHub contribution graph says...

All the free and open-source projects already listed in the [projects page]({{ site.baseurl }}/projects/):

- [Moogle]({{ site.baseurl }}/moogle/)
- [Promptastic]({{ site.baseurl }}/promptastic/)
- [NeuroStars]({{ site.baseurl }}/neurostars/)
- [Docker-PostgreSQL]({{ site.baseurl }}/docker-postgresql/)
- [Ansible-Biostar]({{ site.baseurl }}/ansible-biostar/)
- [Google Summer of Code]({% post_url 2014-04-21-gsoc2014 %})

Plus minor contributions to the following projects:

- [Bookie](https://bookie.io/): wrote a couple of fixes, a recipe about how to [setup
a development environment in Mac OS X](https://gist.github.com/puntonim/9746746)
and a [development proposal]({% post_url 2014-04-21-gsoc2014 %}#bookie-i-classfa-fa-times-stylecolor-rgb189-65-28i)
- [Django-allauth](https://github.com/pennersr/django-allauth): implemented the
[support for ORCID provider]({% post_url 2014-08-07-django-allauth-orcid %})

Other minor contributions that I lost track about:

- [Sqlalchemy](https://github.com/zzzeek/sqlalchemy)
- [Open-vagrant-boxes](https://github.com/phusion/open-vagrant-boxes)
- [Baseimage-docker](https://github.com/phusion/baseimage-docker)
- [Django-rest-framework](https://github.com/tomchristie/django-rest-framework)


text:
package gobblin.runtime;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;

import com.google.common.collect.Lists;

/**
 * Unit tests for {@link BoundedBlockingRecordQueue}.
 *
 * @author ynli
 */
@Test(groups = {"gobblin.runtime"})
public class BoundedBlockingRecordQueueTest {

  private static final String METRIC_NAME_PREFIX = "test";

  private BoundedBlockingRecordQueue<Integer> boundedBlockingRecordQueue;

  @BeforeClass
  public void setUp() {
    this.boundedBlockingRecordQueue = BoundedBlockingRecordQueue.<Integer>newBuilder()
        .hasCapacity(2)
        .useTimeout(100)
        .useTimeoutTimeUnit(TimeUnit.MILLISECONDS)
        .collectStats()
        .build();
  }

  @Test
  public void testPutAndGet() throws InterruptedException {
    final List<Integer> produced = Lists.newArrayList();
    Thread producer = new Thread(new Runnable() {
      @Override
      public void run() {
        for (int i = 0; i < 6; i++) {
          try {
            boundedBlockingRecordQueue.put(i);
            produced.add(i);
          } catch (InterruptedException ie) {
            throw new RuntimeException(ie);
          }
        }
      }
    });

    final List<Integer> consumed = Lists.newArrayList();
    Thread consumer = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          for (int i = 0; i < 6; i++) {
            consumed.add(boundedBlockingRecordQueue.get());
          }
        } catch (InterruptedException ie) {
          throw new RuntimeException(ie);
        }
      }
    });

    producer.start();
    consumer.start();

    producer.join();
    consumer.join();

    Assert.assertEquals(produced, consumed);
    Assert.assertNull(this.boundedBlockingRecordQueue.get());
  }

  @Test(dependsOnMethods = "testPutAndGet")
  public void testQueueStats() throws InterruptedException {
    BoundedBlockingRecordQueue.QueueStats stats = this.boundedBlockingRecordQueue.stats().get();
    Assert.assertEquals(stats.queueSize(), 0);
    Assert.assertEquals(stats.fillRatio(), 0d);
    Assert.assertEquals(stats.getAttemptCount(), 7);
    Assert.assertEquals(stats.putAttemptCount(), 6);

    this.boundedBlockingRecordQueue.put(0);
    this.boundedBlockingRecordQueue.put(1);

    Assert.assertEquals(stats.queueSize(), 2);
    Assert.assertEquals(stats.fillRatio(), 1d);
    Assert.assertEquals(stats.getAttemptCount(), 7);
    Assert.assertEquals(stats.putAttemptCount(), 8);
  }

  @Test(dependsOnMethods = "testQueueStats")
  public void testRegisterAll() {
    MetricRegistry metricRegistry = new MetricRegistry();
    this.boundedBlockingRecordQueue.stats().get().registerAll(metricRegistry, METRIC_NAME_PREFIX);
    Map<String, Gauge> gauges = metricRegistry.getGauges();
    Assert.assertEquals(gauges.size(), 2);
    Assert.assertEquals(
        gauges.get(MetricRegistry.name(METRIC_NAME_PREFIX, BoundedBlockingRecordQueue.QueueStats.QUEUE_SIZE))
            .getValue(), 2);
    Assert.assertEquals(
        gauges.get(MetricRegistry.name(METRIC_NAME_PREFIX, BoundedBlockingRecordQueue.QueueStats.FILL_RATIO))
            .getValue(), 1d);
    Assert.assertEquals(metricRegistry.getMeters().size(), 2);
    Assert.assertEquals(metricRegistry
        .meter(MetricRegistry.name(METRIC_NAME_PREFIX, BoundedBlockingRecordQueue.QueueStats.GET_ATTEMPT_RATE))
        .getCount(), 7);
    Assert.assertEquals(metricRegistry
        .meter(MetricRegistry.name(METRIC_NAME_PREFIX, BoundedBlockingRecordQueue.QueueStats.PUT_ATTEMPT_RATE))
        .getCount(), 8);
  }

  @AfterClass
  public void tearDown() throws InterruptedException {
    this.boundedBlockingRecordQueue.clear();
    Assert.assertNull(this.boundedBlockingRecordQueue.get());
  }
}


text:
Maven
*****

Maven 2
=======

::

  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>3.8.1</version>
    <scope>test</scope>
  </dependency>


text:
.. automodule:: UUTrack.View.Camera.specialTaskWorker
    :members:
    :show-inheritance:


text:
=begin
INPUT: Array of integers
OUTPUT: Array with the following substitutions:
- Multiples of 3 should be replaced with the string "Fizz"
- Multiples of 5 should be replaced with the string "Buzz"
- Multiples of 15 should be replaced with the string "FizzBuzz"

- Iterate through each element of the Array
- IF the element is divisible by 3 but not 5, return "Fizz" for the element
- ELSIF the element is divisible by 5 but not 3, return "Buzz"
- ELSIF the element is divisible by 15 (5 and 3), return "FizzBuzz"
- ELSE the element should remain as itself
- END IF
- Return the Array
=end

# Initial Solution

# def super_fizzbuzz(array)
#   array.map! { |num|
#     if num % 3 == 0 && num % 5 != 0
#       num = "Fizz"
#     elsif num % 5 == 0 && num % 3 != 0
#       num = "Buzz"
#     elsif num % 15 == 0
#       num = "FizzBuzz"
#     else
#       num = num
#     end
#   }
#   return array
# end

# super_fizzbuzz([0, 1, 2, 3])

# Refactored Solution
# Cleaned up the conditional statements within the block

def super_fizzbuzz(array)
  array.map! { |num|
    if num % 15 == 0
      num = "FizzBuzz"
    elsif num % 5 == 0
      num = "Buzz"
    elsif num % 3 == 0
      num = "Fizz"
    else
      num = num
    end
  }
  return array
end

super_fizzbuzz([0, 1, 2, 3])

# Reflection
=begin
What concepts did you review in this challenge?

I reviewed how to iterate through an array and alter values
using a conditional IF statement.

What is still confusing to you about Ruby?

This challenge was pretty straightforward, so here not too much is confusing.
However, I think some of the more advanced Ruby concepts and application
are confusing (making games, programs).

What are you going to study to get more prepared for Phase 1?

I want to keep practicing! I think with both JavaScript and Ruby I want to
redo the game challenges because those were the most difficult applications
for me.

=end


text:
require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module RailsGraphql
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.
    config.autoload_paths += [
      Rails.root.join('lib'),
      Rails.root.join('lib/graphql/helpers'),
      Rails.root.join('lib/graphql/middlewares'),
      Rails.root.join('app/api'),
      Rails.root.join('app/api/types'),
      Rails.root.join('app/api/queries'),
      Rails.root.join('app/api/mutations'),
      Rails.root.join('app/api/middlewares'),
      Rails.root.join('app/api/helpers'),
      Rails.root.join('app/api/resolvers'),
    ]
  end
end


text:
/**
 * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
 * @version v25.1.0
 * @link http://www.ag-grid.com/
 * @license MIT
 */
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
import { SelectCellEditor } from "./selectCellEditor";
var PopupSelectCellEditor = /** @class */ (function (_super) {
    __extends(PopupSelectCellEditor, _super);
    function PopupSelectCellEditor() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PopupSelectCellEditor.prototype.isPopup = function () {
        return true;
    };
    return PopupSelectCellEditor;
}(SelectCellEditor));
export { PopupSelectCellEditor };


text:
from django.db import connection
from nani.test_utils.context_managers import LanguageOverride
from nani.test_utils.testcase import NaniTestCase
from testproject.app.models import Normal
from nani.test_utils.fixtures import TwoTranslatedNormalMixin

class FallbackTests(NaniTestCase, TwoTranslatedNormalMixin):
    def test_single_instance_fallback(self):
        # fetch an object in a language that does not exist
        with LanguageOverride('de'):
            with self.assertNumQueries(2):
                obj = Normal.objects.untranslated().use_fallbacks('en', 'ja').get(pk=1)
                self.assertEqual(obj.language_code, 'en')
                self.assertEqual(obj.translated_field, 'English1')

    def test_shared_only(self):
        with LanguageOverride('de'):
            with self.assertNumQueries(2):
                obj = Normal.objects.untranslated().get(pk=1)
                self.assertEqual(obj.shared_field, 'Shared1')
                self.assertRaises(Normal._meta.translations_model.DoesNotExist,
                                  getattr, obj, 'translated_field')

    def test_mixed_fallback(self):
        with LanguageOverride('de'):
            pk = Normal.objects.language('ja').create(
                shared_field='shared3',
                translated_field=u'日本語三',
            ).pk
            with self.assertNumQueries(2):
                objs = list(Normal.objects.untranslated().use_fallbacks('en', 'ja'))
                self.assertEqual(len(objs), 3)
                obj = dict([(obj.pk, obj) for obj in objs])[pk]
                self.assertEqual(obj.language_code, 'ja')
            with self.assertNumQueries(2):
                objs = list(Normal.objects.untranslated().use_fallbacks('en'))
                self.assertEqual(len(objs), 2)
#                We dont return unstranslated instances in django-hvad
#                obj = dict([(obj.pk, obj) for obj in objs])[pk]
#                cached = getattr(obj, obj._meta.translations_cache, None)
#                self.assertEqual(cached, None)


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

    <TextView
        android:layout_alignParentTop="true"
        android:background="@color/logo_bg"
        android:layout_width="match_parent"
        android:layout_height="100dp"/>

    <ImageView
        android:id="@+id/logo"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/ic_launcher"
        android:layout_width="100dp"
        android:layout_height="100dp"/>

    <TextView
        android:id="@+id/summary"
        android:layout_below="@id/logo"
        android:text="Only Pebble apps you permit here can write to Android APIs with the Dash API. Turn an app on below to allow it permission if it needs it.\n\nApps that only read data do not require this permission."
        android:textSize="15sp"
        android:textColor="#000000"
        android:paddingTop="5dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/title"
        android:text="Recent Apps"
        android:textStyle="bold"
        android:textSize="20sp"
        android:textColor="#000000"
        android:layout_below="@id/summary"
        android:paddingTop="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/no_apps"
        android:text="No recent apps"
        android:textColor="#999999"
        android:textSize="20sp"
        android:paddingTop="15dp"
        android:gravity="center_horizontal"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <ListView
        android:id="@+id/app_list"
        android:layout_below="@id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>

</RelativeLayout>


text:
from OpenGLCffi.GL import params
@params(api='gl', prms=['value'])
def glMinSampleShadingARB(value):
	pass


text:
package main

import (
	"encoding/base64"
	"fmt"
	"net/http"
	"strings"

	"github.com/go-martini/martini"
	"github.com/martini-contrib/sessions"
)

const ANON_USER string = "guest"

// Type which, through reflection, Martini uses to dependency inject the user
// found by the Authentication middleware
type User interface{}

func main() {
	// Starting a standard martini server,
	// with logging and panic recovery middleware built in
	m := martini.Classic()

	// Register middleware for storing session details in cookies
	// NOTE: In a real world example, you do NOT want to store all your session
	// data in cookies.  Just an ID or Token, and store everything else in a DB.
	// Other session store implementations at: https://github.com/gorilla/sessions
	store := sessions.NewCookieStore([]byte("secret123"))
	m.Use(sessions.Sessions("github.com/rolaveric/GoHttp", store))

	// Register middleware which authenticates the client
	m.Use(Authentication)

	// Register a route which does something with the authenticated user,
	// but doesn't care for security reasons (ie. No authorization check)
	m.Get("/", func(u User) string {
		return fmt.Sprintf("Hello %s!", u)
	})

	// Register a route which requires the client to use Basic Authentication.
	// If they don't, respond with 401 status and a WWW-Authenticate header
	m.Get("/login", func(u User, req *http.Request, res http.ResponseWriter) {
		// If they're already logged in, redirect to "/"
		if u != ANON_USER {
			http.Redirect(res, req, "/", 302)
			return
		}

		// Otherwise, prompt for login
		res.Header().Set("WWW-Authenticate", "Basic realm=\"Authentication Required\"")
		http.Error(res, "Basic Authentication Required", http.StatusUnauthorized)
	})

	// Register a route which requires the authenticated user to have specific authorization
	m.Get("/secret", Authorization("secret access"), func(u User) string {
		return fmt.Sprintf("Hello Secret Agent %s!", u)
	})

	// Start the server
	m.Run()
}

// Middleware for Martini which tries to identify the request user by the Authorization header.
// If no such header exists, it checks the session cookie.  If that also fails, it assumes the user is a guest.
// If the header exists but can't be decoded, it returns a 401 status.
// It uses Martini's dependency injection system to register the user for later consumption.
func Authentication(c martini.Context, req *http.Request, res http.ResponseWriter, session sessions.Session) {
	// Get the Authorization header
	a := req.Header.Get("Authorization")
	if a == "" {
		// No header - Check for a session
		u := session.Get("user")
		if u == nil {
			// No session either, set the user as a guest
			c.MapTo(ANON_USER, (*User)(nil))
		} else {
			// Register the user from the session
			c.MapTo(u, (*User)(nil))
		}
		return
	}

	// Remove the 'Basic ' prefix
	a = strings.TrimPrefix(a, "Basic ")

	// Decode the Authorization header
	data, err := base64.StdEncoding.DecodeString(a)
	if err != nil {
		// Bad Authorization value - return 401 Unauthorized
		http.Error(res, "Could not decode Authorization header", http.StatusUnauthorized)
		// Note: If the response gets written to, Martini doesn't call any subsequent handlers
		return
	}

	// Split out the username and password
	s := strings.Split(string(data), ":")
	if len(s) < 2 {
		// Bad Authorization value - return 401 Unauthorized
		http.Error(res, "Authorization header requires a username and password", http.StatusUnauthorized)
		// Note: If the response gets written to, Martini doesn't call any subsequent handlers
		return
	}

	// At this point, you would normally lookup a user database
	// Since this is an example - we're just accepting the username as is
	c.MapTo(s[0], (*User)(nil))

	// Set the user in the session
	session.Set("user", s[0])
}

// Returns a handler function which checks that the authenticated user for the request
// has a particular type of access.
// If they don't, a 401 status resposne is made.
// Otherwise, nothing happens - letting the next handler in the chain do it's work
func Authorization(access string) func(User, http.ResponseWriter) {
	// Returning a handler function that checks for the required access
	return func(u User, res http.ResponseWriter) {
		// For brevity, we're just checking that the username is 'admin'
		if u != "admin" {
			// If not, return a response that stops Martini calling the next handler
			http.Error(res, "Not Authorized", http.StatusUnauthorized)
		}
	}
}


text:
package assignment.candidate.greenroad.com.emiladjiev;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

/**
 * Created by Emil on 09/05/2016.
 */

public class LocationLoggerServiceManager extends BroadcastReceiver {

    protected final static String UPDATES_KEY = "updates_key";
    private SharedPreferences mPrefs;
    public static final String TAG = "LoggerServiceManager";

    @Override
    public void onReceive(Context context, Intent intent) {
        // Make sure we are getting the right intent
        if( "android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            boolean mUpdatesRequested = false;

            //checking shared preferences for updating key.
            mPrefs = context.getSharedPreferences("SharedPreferences", Context.MODE_PRIVATE);
            if (mPrefs.contains(UPDATES_KEY)) {
                mUpdatesRequested = mPrefs.getBoolean(UPDATES_KEY, false);
            }
            if(mUpdatesRequested){
                ComponentName comp = new ComponentName(context.getPackageName(), BackgroundLocationService.class.getName());
                ComponentName service = context.startService(new Intent().setComponent(comp));
                if (null == service){
                    // something really wrong here
                    Log.e(TAG, "Could not start service " + comp.toString());
                }
            }

        } else {
            Log.e(TAG, "Received unexpected intent " + intent.toString());
        }
    }
}


text:
@ echo off
set base_dir=%~dp0
%base_dir:~0,2%
pushd %base_dir%
cd data
copy /y network.db network.db.backup
popd


text:
<?php

// No direct access.
defined('_HZEXEC_') or die();

// Include the HTML helpers.
Html::behavior('tooltip');
Html::behavior('formvalidation');
Html::behavior('keepalive');

$this->js('config.js');
?>
<form action="<?php echo Route::url('index.php?option=com_messages&controller=configs'); ?>" method="post" name="adminForm" id="config-form" class="editform form-validate" data-invalid-msg="<?php echo $this->escape(Lang::txt('JGLOBAL_VALIDATION_FORM_FAILED'));?>">
	<fieldset>

				<button type="button" id="action_save"><?php echo Lang::txt('JSAVE');?></button>
				<button type="button" id="action_cancel"><?php echo Lang::txt('JCANCEL');?></button>

			<?php echo Lang::txt('COM_MESSAGES_MY_SETTINGS') ?>

	</fieldset>

	<fieldset class="adminform">
		<fieldset>
			<legend><?php echo Lang::txt('COM_MESSAGES_FIELD_LOCK_LABEL'); ?></legend>

				<input type="radio" name="lock" id="cfg-lock-yes" value="1"<?php if ($this->item->get('lock', 0)) { echo ' checked="checked"'; } ?> />
				<?php echo Lang::txt('JYes'); ?>

				<input type="radio" name="lock" id="cfg-lock-no" value="0"<?php if ($this->item->get('lock', 0)) { echo ' checked="checked"'; } ?> />
				<?php echo Lang::txt('JNo'); ?>

		</fieldset>

		<fieldset>
			<legend><?php echo Lang::txt('COM_MESSAGES_FIELD_MAIL_ON_NEW_LABEL'); ?></legend>

				<input type="radio" name="mail_on_new" id="cfg-mail_on_new-yes" value="1"<?php if ($this->item->get('mail_on_new', 1)) { echo ' checked="checked"'; } ?> />
				<?php echo Lang::txt('JYes'); ?>

				<input type="radio" name="mail_on_new" id="cfg-mail_on_new-no" value="0"<?php if ($this->item->get('mail_on_new', 1)) { echo ' checked="checked"'; } ?> />
				<?php echo Lang::txt('JNo'); ?>

		</fieldset>

		<div class="input-wrap" data-hint="<?php echo Lang::txt('COM_MESSAGES_FIELD_AUTO_PURGE_DESC'); ?>">
			<?php echo Lang::txt('COM_MESSAGES_FIELD_AUTO_PURGE_LABEL'); ?>
			<input type="text" name="auto_purge" id="cfg-auto_purge" value="<?php echo $this->item->get('auto_purge', 7); ?>" />
			<?php echo Lang::txt('COM_MESSAGES_FIELD_AUTO_PURGE_DESC'); ?>

		<input type="hidden" name="option" value="com_messages" />
		<input type="hidden" name="controller" value="configs" />
		<input type="hidden" name="task" value="" />
		<?php echo Html::input('token'); ?>
	</fieldset>
</form>