text:
OpenVPN [road warrior](http://en.wikipedia.org/wiki/Road_warrior_%28computing%29) installer for Debian-based distros.

This script will let you setup your own VPN server in no more than one minute, even if you haven't used OpenVPN before. It isn't bulletproof but it has been designed to be as unobtrusive and universal as possible.

###Installation
Run the script and follow the assistant:

`wget http://git.io/vpn --no-check-certificate -O openvpn-install.sh; chmod +x openvpn-install.sh; ./openvpn-install.sh`

Once it ends, you can run it again to add more users.

###I want to run my own VPN but don't have a server for that
You can get a little VPS for just $6/year at [Bandwagon Host](https://bandwagonhost.com/aff.php?aff=575&pid=21).

If you don't care about sharing an IP address with more people, check out the awesome [LowEndSpirit](http://lowendspirit.com/) project too. They are providing IPv6 VPS with NATed IPv4 for only 3€/year.


text:
/*-----------------------------------------------------------------------------
| Variables
|----------------------------------------------------------------------------*/

:root {
  --jp-private-menubar-height: 28px;
  --jp-private-menu-item-height: 24px;
}

/*-----------------------------------------------------------------------------
| MenuBar
|----------------------------------------------------------------------------*/

.lm-MenuBar {
  background: var(--jp-layout-color1);
  color: var(--jp-ui-font-color1);
  font-size: var(--jp-ui-font-size1);
}

.lm-MenuBar:hover {
  overflow-x: auto;
}

.lm-MenuBar-menu {
  transform: translateY(calc(-2 * var(--jp-border-width)));
}

.lm-MenuBar-item {
  padding: 0px 8px;
  border-left: var(--jp-border-width) solid transparent;
  border-right: var(--jp-border-width) solid transparent;
  border-top: var(--jp-border-width) solid transparent;
  line-height: calc(var(--jp-private-menubar-height) - var(--jp-border-width));
}

.lm-MenuBar-item.lm-mod-active {
  background: var(--jp-layout-color2);
}

.lm-MenuBar.lm-mod-active .lm-MenuBar-item.lm-mod-active {
  z-index: 10001;
  background: var(--jp-layout-color0);
  border-left: var(--jp-border-width) solid var(--jp-border-color1);
  border-right: var(--jp-border-width) solid var(--jp-border-color1);
  box-shadow: var(--jp-elevation-z6);
}

.jp-LabShell[data-shell-mode='single-document']
  .lm-MenuBar.lm-mod-active
  .lm-MenuBar-item.lm-mod-active {
  border-top: var(--jp-border-width) solid var(--jp-border-color1);
}

.lm-MenuBar-item.lm-mod-disabled {
  color: var(--jp-ui-font-color3);
}

.lm-MenuBar-item.lm-type-separator {
  margin: 2px;
  padding: 0;
  border: none;
  border-left: var(--jp-border-width) solid var(--jp-border-color2);
}

.lm-MenuBar-itemMnemonic {
  text-decoration: underline;
}

/*-----------------------------------------------------------------------------
| Menu
|----------------------------------------------------------------------------*/

.lm-Menu {
  z-index: 10000;
  padding: 4px 0px;
  background: var(--jp-layout-color0);
  color: var(--jp-ui-font-color1);
  border: var(--jp-border-width) solid var(--jp-border-color1);
  font-size: var(--jp-ui-font-size1);
  box-shadow: var(--jp-elevation-z6);
}

.lm-Menu-item {
  min-height: var(--jp-private-menu-item-height);
  max-height: var(--jp-private-menu-item-height);
  padding: 0px;
  line-height: var(--jp-private-menu-item-height);
}

.lm-Menu-item.lm-mod-active {
  background: var(--jp-layout-color2);
}

.lm-Menu-item.lm-mod-disabled {
  color: var(--jp-ui-font-color3);
}

.lm-Menu-itemIcon {
  width: 21px;
  padding: 0px 2px 0px 4px;
  margin-top: -2px;
}

.lm-Menu-itemLabel {
  padding: 0px 32px 0px 2px;
}

.lm-Menu-itemMnemonic {
  text-decoration: underline;
}

.lm-Menu-itemShortcut {
  padding: 0px;
}

.lm-Menu-itemSubmenuIcon {
  width: 18px;
  padding: 0px 4px 0px 0px;
}

.lm-Menu-item[data-type='separator'] > div {
  padding: 0;
  height: 9px;
}

.lm-Menu-item[data-type='separator'] > div::after {
  content: '';
  display: block;
  position: relative;
  top: 4px;
  border-top: var(--jp-border-width) solid var(--jp-layout-color2);
}

/* gray out icon/caret for disable menu items */
.lm-Menu-item.lm-mod-disabled > .lm-Menu-itemIcon,
.lm-Menu-item[data-type='submenu'].lm-mod-disabled > .lm-Menu-itemSubmenuIcon {
  opacity: 0.4;
}

redpajama_set_name: RedPajamaGithub


text:
package v1alpha3

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

type ServiceEntry struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata,omitempty"`

	Spec ServiceEntrySpec `json:"spec"`
}

type ServiceEntrySpec struct {
	Hosts      []string                `json:"hosts,omitempty"`
	Addresses  []string                `json:"addresses,omitempty"`
	Ports      []Port                  `json:"ports,omitempty"`
	Location   int32                   `json:"location,omitempty"`
	Resolution int32                   `json:"resolution,omitempty"`
	Endpoints  []ServiceEntry_Endpoint `json:"endpoints,omitempty"`
}

type ServiceEntry_Endpoint struct {
	Address string            `json:"address,omitempty"`
	Ports   map[string]uint32 `json:"ports,omitempty"`
	Labels  map[string]string `json:"labels,omitempty"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

type ServiceEntryList struct {
	metav1.TypeMeta `json:",inline"`
	metav1.ListMeta `json:"metadata"`

	Items           []ServiceEntry `json:"items"`
}


text:
import * as _ from 'lodash';

import { IAnnouncement, IPasswordResetCode, IVerificationCode, IVolunteerAnnouncement, User } from './user';
import * as utils from './utils';

export class Volunteer extends User {
  constructor(userId?: number, username?: string) {
    super(userId, username);
  }

  /**
   * Creates a new volunteer in the volunteer table with the email, name, password, salt and
   * username
   * @param password the volunteer password
   */
  public async createVolunteer(password: string): Promise<number> {
    if (_.isNil(this.name) || _.isNil(this.username) || _.isNil(this.email)) {
      return Promise.reject(
        new Error(`name, username, email and password are required, name=${this.name}, username=${this.username}, email=${this.email}`),
      );
    }

    if (_.isNil(password)) {
      return Promise.reject(new Error(`You must provide a password to create the volunteer=${this.username}`));
    }

    const hashedPassword: { salt: string, hashedPassword: string } = utils.saltAndHash(password);
    const date: Date = new Date();

    const volunteer = {
      created_datetime: date,
      data_entry_user_id: 1,
      email: this.email,
      name: this.name,
      password: hashedPassword.hashedPassword,
      salt: hashedPassword.salt,
      username: this.username,
    };

    return this.knex('volunteer')
      .insert(volunteer)
      .then((id) => {
        const { 0: userId } = id;

        this.password = hashedPassword.hashedPassword;
        this.userId = userId;
        this.salt = hashedPassword.salt;

        const code = this.createVerificationCode();
        return Promise.resolve(code);
      }).catch((error: Error) => Promise.reject(error));
  }

  /**
   * Marks the current volunter as verified in the database
   */
  public async verifyVolunteer(): Promise<boolean> {
    if (_.isNil(this.userId)) {
      return Promise.reject(new Error(`Cannot verify when userId is null or undefined, userId=${this.userId}`));
    }

    return this.knex('volunteer')
      .where('volunteer_id', this.userId)
      .update({ verified: true })
      .then(() => { this.verified = true; return Promise.resolve(true); })
      .catch((error: Error) => Promise.reject(error));
  }

  /**
   * Creates a new verification code used for validation of the users email address, this is stored
   * in the database for checking when they click the validation email
   */
  public async createVerificationCode(): Promise<number> {
    const maxNumber: number = 9999999999999;
    const minNumber: number = 1000000000000;

    const number: number = Math.floor((Math.random() * ((maxNumber - minNumber) + 1000000000000)));
    const hashedNumber: { salt: string; hashedPassword: string; } = utils.saltAndHash(number.toString());
    const date: Date = new Date();

    const verificationCode: IVerificationCode = {
      code: hashedNumber.hashedPassword,
      created_datetime: date,
      salt: hashedNumber.salt,
      verification_code_id: this.userId,
    };

    return this.removeVerificationCode()
      .then(() => this.knex('verification_code').insert(verificationCode))
      .then(() => Promise.resolve(number))
      .catch((error: Error) => Promise.reject(error));
  }

  /**
   * Does the same as createVerificationCode but for when a user requests a password reset code.
   */
  public async createPasswordResetCode(): Promise<number> {
    const maxNumber: number = 9999999999999;
    const minNumber: number = 1000000000000;

    const number: number = Math.floor((Math.random() * ((maxNumber - minNumber) + 1000000000000)));
    const hashedNumber: { salt: string; hashedPassword: string; } = utils.saltAndHash(number.toString());
    const date: Date = new Date();

    const passwordResetCode: IPasswordResetCode = {
      code: hashedNumber.hashedPassword,
      created_datetime: date,
      password_reset_code_id: this.userId,
      salt: hashedNumber.salt,
    };

    return this.removePasswordResetCode()
      .then(() => this.knex('password_reset_code').insert(passwordResetCode))
      .then(() => Promise.resolve(number))
      .catch((error: Error) => Promise.reject(error));
  }

  /**
   * Validates a verification code if a code exists in the database otherwise does a promise
   * rejection
   */
  public async doesVerificationCodeExist(): Promise<number> {
    if (!_.isNumber(this.userId)) {
      return Promise.reject(new Error(`userId "${this.userId}" passed is not a valid number`));
    }

    return this.knex('verification_code').select('verification_code_id').where('verification_code_id', this.userId).first()
      .then((result: IVerificationCode) => {
        if (_.isNil(result) || _.isNil(result.verification_code_id)) {
          return Promise.reject(new Error(`No verification code exists for user ${this.userId}`));
        }
        return Promise.resolve(result.verification_code_id);
      })
      .catch((error: Error) => Promise.reject(error));
  }

  /**
   * Checks to see if the password reset code exists in the database.
   */
  public async doesPasswordResetCodeExist(): Promise<number> {
    if (!_.isNumber(this.userId)) {
      return Promise.reject(new Error(`userId "${this.userId}" passed is not a valid number`));
    }

    return this.knex('password_reset_code')
      .select('password_reset_code_id')
      .where('password_reset_code_id', this.userId)
      .first()
      .then((result: IPasswordResetCode) => {
        if (_.isNil(result) || _.isNil(result.password_reset_code_id)) {
          return Promise.reject(new Error(`No password reset code exists for user ${this.userId}`));
        }
        return Promise.resolve(result.password_reset_code_id);
      })
      .catch((error: Error) => Promise.reject(error));
  }

  /**
   * updates the volunteer password with the new password given, salts and hashes and stores
   * @param password the new password to salt and hash / update
   */
  public async updatePassword(password: string): Promise<boolean> {
    if (!_.isNumber(this.userId) || !_.isString(password)) {
      return Promise.reject(new Error('password or id passed was not a valid number or string'));
    }

    const salted = utils.saltAndHash(password);

    return this.knex('volunteer').where('volunteer_id', this.userId).update({
      password: salted.hashedPassword,
      salt: salted.salt,
    })
      .then(() => Promise.resolve(true))
      .catch((error: Error) => Promise.reject(error));
  }

  /**
   * Resolves all active notifications for the current volunteer
   */
  public async getActiveNotifications(): Promise<IAnnouncement[]> {
    return this.knex('volunteer_announcement')
      .where('volunteer_id', this.userId)
      .andWhere('read', false)
      .select('announcement')
      .then((announcementIds: IVolunteerAnnouncement[]) => {
        if (!_.isNil(announcementIds[0])) {
          const justIds = _.map(announcementIds, announcementId => announcementId.announcement);
          return this.knex('announcement').whereIn('announcement_id', justIds).select();
        }
        return Promise.resolve([]);
      })
      .then((announcements: IAnnouncement[]) => Promise.resolve(announcements))
      .catch((error: Error) => Promise.reject(error));
  }

  /**
   * marks the passed notification id as read in the databasej
   * @param announcementId The announcementId to remove
   */
  public async dismissNotification(announcementId: number): Promise<boolean> {
    if (_.isNil(announcementId) || !_.isNumber(announcementId)) {
      return Promise.reject(new Error(`Announcement Id must be passed and also a valid number, announcement id=${announcementId}`));
    }

    if (!_.isNumber(this.userId)) {
      return Promise.reject(new Error(`userId "${this.userId}" passed is not a valid number`));
    }

    return this.knex('volunteer_announcement').where({
      volunteer_announcement_id: announcementId,
      volunteer_id: this.userId,
    }).update({
      read: true,
      read_date: new Date(),
    })
      .then(() => Promise.resolve(true))
      .catch((error: Error) => Promise.reject(error));
  }

  /**
   * Removes any existing password reset code from the database
   */
  public async removePasswordResetCode(): Promise<boolean> {
    if (!_.isNumber(this.userId)) {
      return Promise.reject(new Error(`userId "${this.userId}" passed is not a valid number`));
    }

    return this.knex('password_reset_code').where('password_reset_code_id', this.userId).del()
      .then(() => Promise.resolve(true))
      .catch((error: Error) => Promise.reject(error));
  }

  /**
   * Removes any existing verification code from the database for that user
   */
  public async removeVerificationCode(): Promise<boolean> {
    if (!_.isNumber(this.userId)) {
      return Promise.reject(new Error(`userId "${this.userId}" passed is not a valid number`));
    }

    return this.knex('verification_code').where('verification_code_id', this.userId).del()
      .then(() => Promise.resolve(true))
      .catch((error: Error) => Promise.reject(error));
  }

  /**
   * Gets the current verification code for the current volunteer
   */
  public async getVerificationCode(): Promise<IVerificationCode> {
    if (!_.isNumber(this.userId)) {
      return Promise.reject(new Error(`userId "${this.userId}" passed is not a valid number`));
    }

    return this.knex('verification_code').where('verification_code_id', this.userId).first()
    .then((details: IVerificationCode) => Promise.resolve(details))
    .catch((error: Error) => Promise.reject(error));
  }

  /**
   * getrs the current password reset code for the volunteer
   */
  public async getPasswordResetCode(): Promise<IPasswordResetCode> {
    if (!_.isNumber(this.userId)) {
      return Promise.reject(new Error(`userId "${this.userId}" passed is not a valid number`));
    }

    return this.knex('password_reset_code').where('password_reset_code_id', this.userId).first()
    .then((details: IPasswordResetCode) => Promise.resolve(details))
    .catch((error: Error) => Promise.reject(error));
  }
}


text:
Responsive Bootstrap Toolkit provides an easy way of breakpoint detection in JavaScript, detecting changes in currently active breakpoint, as well as executing any breakpoint-specific JavaScript code.

The SASS module enables quick and simple styling for elements needing different property values for each screen resolution.

Current version: 2.1.0

[See a live example on CodePen](http://codepen.io/dih/full/ivECj)

### JavaScript
#### Checking which breakpoint is active

````javascript
if (viewport.is('xs')) {
  // do stuff in the lowest resolutions only!
}

if (viewport.is('lg')) {
  // do stuff on huge screens only
}
````

#### Executing a script whenever window is resized
##### Default interval, 300 ms

````javascript
$(window).bind('resize', function() {
    viewport.changed(function() {

      // do some other stuff!

    })
});
````

##### Custom interval

````javascript
$(window).bind('resize', function() {
    viewport.changed(function() {

      // do some other stuff!

    }, 600)
});
````

### SASS
#### Set different CSS property value per breakpoint

````css
h1 {
    @include set(font-size, (xs: 20px, sm: 24px, md: 24px, lg: 30px) );
}
````

You don't need to specify a value for each of the breakpoints. One is enough, four is the max. Example below will work just as well:

````css
h1 {
    @include set(font-size, (xs: 20px, lg: 30px) );
}
````

Output:

````css
@media (max-width: 767px) {
  h1 {
    font-size: 20px;
  }
}
@media (min-width: 1200px) {
  h1 {
    font-size: 30px;
  }
}
````

### How do I include it in my project?
#### JavaScript

Include just before `</body>`

````html
<!-- Mandatory for Responsive Bootstrap Toolkit to operate -->
<div class="device-xs visible-xs"></div>
<div class="device-sm visible-sm"></div>
<div class="device-md visible-md"></div>
<div class="device-lg visible-lg"></div>

<!-- Responsive Bootstrap Toolkit -->
<script src="js/bootstrap-toolkit.min.js"></script>

<!-- Your scripts using Bootstrap Toolkit -->
<script src="js/main.js"></script>
````

#### SASS

Copy contents of `compass/bootstrap-toolkit` directory into your project. File `style.scss` contains lines that need to be in your own style.scss for the mixin to work. You'll need SASS 3.3+.

### Dependencies

**JavaScript features:**
  1. Bootstrap's responsive utility css classes included in its standard stylesheet package
  2. jQuery library

**CSS features:**
  1. SASS 3.3+
  2. Compass


text:
describe Screengrab::Runner do
  let(:config) { {} }
  let(:ui) { Screengrab::UI }
  let(:mock_android_environment) { double(Screengrab.android_environment) }
  let(:mock_executor) { class_double('FastlaneCore::CommandExecutor') }

  before do
    @runner = Screengrab::Runner.new(mock_executor, config, mock_android_environment)
  end

  def set_mock_adb_response(command, mock_response)
    expect(mock_executor).to receive(:execute)
      .with(hash_including(command: command))
      .and_return(mock_response)
  end

  describe :validate_apk do
    context 'no aapt' do
      it 'prints an error unless aapt can be found' do
        expect(mock_android_environment).to receive(:aapt_path).and_return nil
        expect(mock_executor).not_to receive(:execute)
        expect(ui).to receive(:important).with(/.*aapt.*could not be found/)

        @runner.validate_apk('fake_apk_path')
      end
    end

    context 'no permissions' do
      it 'prints if permissions are missing' do
        allow(mock_android_environment).to receive(:aapt_path).and_return 'fake_aapt_path'
        set_mock_adb_response('fake_aapt_path dump permissions fake_apk_path', '')

        expect(ui).to receive(:user_error!).with(/permission.* could not be found/).and_call_original

        expect { @runner.validate_apk('fake_apk_path') }.to raise_fastlane_error
      end
    end
  end

  describe :select_device do
    let (:adb_list_devices_command) { 'adb devices -l' }

    context 'no devices' do
      it 'does not find any active devices' do
        adb_response = <<-ADB_OUTPUT.strip_heredoc
        List of devices attached

        ADB_OUTPUT
        set_mock_adb_response(adb_list_devices_command, adb_response)

        expect(ui).to receive(:user_error!).with(/no connected.* devices/).and_call_original

        expect { @runner.select_device }.to raise_fastlane_error
      end
    end

    context 'one device' do
      it 'finds an active device' do
        adb_response = <<-ADB_OUTPUT.strip_heredoc
          List of devices attached
          T065002LTT             device usb:437387264X product:ghost_retail model:XT1053 device:ghost

        ADB_OUTPUT
        set_mock_adb_response(adb_list_devices_command, adb_response)

        expect(@runner.select_device).to eq('T065002LTT')
      end
    end

    context 'multiple devices' do
      it 'finds an active device' do
        adb_response = <<-ADB_OUTPUT.strip_heredoc
          List of devices attached
          emulator-5554          device product:sdk_phone_x86_64 model:Android_SDK_built_for_x86_64 device:generic_x86_64
          T065002LTT             device usb:437387264X product:ghost_retail model:XT1053 device:ghost

        ADB_OUTPUT

        set_mock_adb_response(adb_list_devices_command, adb_response)
        expect(@runner.select_device).to eq('emulator-5554')
      end
    end

    context 'one device booting' do
      it 'finds an active device' do
        adb_response = <<-ADB_OUTPUT.strip_heredoc
          List of devices attached
          emulator-5554 offline
          T065002LTT  device

        ADB_OUTPUT

        set_mock_adb_response(adb_list_devices_command, adb_response)

        expect(@runner.select_device).to eq('T065002LTT')
      end
    end
  end

  describe :run_adb_command do
    it 'filters out lines which are ADB warnings' do
      adb_response = <<-ADB_OUTPUT.strip_heredoc
            adb: /home/me/rubystack-2.3.1-4/common/lib/libcrypto.so.1.0.0: no version information available (required by adb)
            List of devices attached
            e1dbf228               device usb:1-1.2 product:a33gdd model:SM_A300H device:a33g

          ADB_OUTPUT

      set_mock_adb_response("test", adb_response)

      expect(@runner.run_adb_command("test").lines.any? { |line| line.start_with?('adb: ') }).to eq(false)
    end
  end
end


text:
Idea Saver | {{ editModeLabel }} Idea | {{ wizardModeLabel }} Mode

        <alert type="info" close="closeAlert()" ng-show="showAlert==true && editMode==false">Start filling out your idea:</alert>
        <alert type="info" close="closeAlert()" ng-show="showAlert==true && editMode==true">Edit out your idea:</alert>

        My idea is to develop a:

        <input type="text" class="form-control" ng-model="ideaData.technology"
            placeholder="mobile application" tooltip="The most relevant choices will be suggested as you type"></input>

        <textarea class="form-control" placeholder="for iOS and Android phones"  ng-model="ideaData.techDetails"
            tooltip="Enter free form text"></textarea>

        to help

        <input type="text" class="form-control" placeholder="creative people"  ng-model="ideaData.purpose"
            tooltip="The most relevant choices will be suggested as you type"></input>

        solve a problem

        <textarea class="form-control" placeholder="write down their ideas quickly"  ng-model="ideaData.problem"
            tooltip="Enter free form text"></textarea>

        with (secret sauce)

        <textarea class="form-control" placeholder="using mad libs template"  ng-model="ideaData.sauce"
            tooltip="Enter free form text"></textarea>

        <textarea class="form-control" placeholder="ideas description" rows="8"  ng-model="ideaData.plainDescription"
            tooltip="Enter free form text"></textarea>

        <button type="button" class="form-control btn btn-md btn-success" ng-click="saveIdea()">

            Save Idea
        </button>

        <button type="button" class="form-control btn btn-md btn-warning"  ng-click="startOver()"
            tooltip="Reset content and start over">

            Reset
        </button>

    	<button type="button" class="form-control btn btn-md btn-default" ng-click="trainWizard()"
            tooltip="Improve Idea Wizard by training it">

            Train Idea Wizard
        </button>

    	<button type="button" class="form-control btn btn-md btn-default"  ng-click="listIdeas()"
            tooltip="List saved ideas">

            Saved Ideas
        </button>

        <button type="button" class="form-control btn btn-md btn-default"  ng-click="toggleEditor()"
            tooltip="Switch to plain text editor" ng-show="textWizard==true">

            Switch to text
        </button>
        <button type="button" class="form-control btn btn-md btn-default"  ng-click="toggleEditor()"
            tooltip="Switch to Wizard editor" ng-show="textWizard==false">

            Switch to Wiazard
        </button>


text:
package org.yeastrc.xlink.www.user_account_webservices;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.LoggerFactory;  import org.slf4j.Logger;
import org.yeastrc.xlink.www.constants.WebServiceErrorMessageConstants;
import org.yeastrc.xlink.www.user_session_management.UserSessionManager;

@Path("/user")
public class LogoutService {

	private static final Logger log = LoggerFactory.getLogger( LogoutService.class);

	@POST
	@Consumes( MediaType.APPLICATION_FORM_URLENCODED )
	@Produces(MediaType.APPLICATION_JSON)
	@Path("/logout")
	public Response loginService(
			@Context HttpServletRequest request )
	throws Exception {
//		if (true)
//		throw new Exception("Forced Error");
		try {
			UserSessionManager.getSinglesonInstance().invalidateUserSession(request);
		} catch ( WebApplicationException e ) {
			throw e;
		} catch ( Exception e ) {
			String msg = "Exception caught: " + e.toString();
			log.error( msg, e );
			throw new WebApplicationException(
					Response.status( WebServiceErrorMessageConstants.INTERNAL_SERVER_ERROR_STATUS_CODE )  //  Send HTTP code
					.entity( WebServiceErrorMessageConstants.INTERNAL_SERVER_ERROR_TEXT ) // This string will be passed to the client
					.build()
					);
		}
		return Response.ok().build();
	}
}


text:
<?php

namespace Molajo\Fieldhandler\Constraint;

use CommonApi\Fieldhandler\ConstraintInterface;

/**
 * Scalar Constraint
 *
 * Scalar variables are those containing an integer, float, string or boolean.
 * Types array, object and resource are not scalar.
 *
 * @link       http://php.net/manual/en/function.is-scalar.php
 * @package    Molajo
 * @copyright  2014-2015 Amy Stephen. All rights reserved.
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @since      1.0.0
 */
class Scalar extends AbstractConstraintTests implements ConstraintInterface
{
    /**
     * Message Code
     *
     * @var    integer
     * @since  1.0.0
     */
    protected $message_code = 1000;

    /**
     * Validation
     *
     * @return  boolean
     * @since   1.0.0
     */
    protected function validation()
    {
        if (is_scalar($this->field_value)) {
            return true;
        }

        return false;
    }
}


text:
<?php

namespace Students\Router;

use Students\Entity\Route;
use Students\Utility\Collection;
use Students\Interfaces\Router\RouteInterface;
use Students\Interfaces\Router\RouteCollectionInterface;

/**
 * A collection to store routes.
 *
 * @todo Think about using SplObjectStorage here.
 */
class RouteCollection extends Collection implements RouteCollectionInterface
{
    /**
     * Constructor.
     *
     * @todo Validate every element in the $routes array so nothing unwanted gets through.
     *
     * @param array $routes Routes to store in the collection.
     */
    public function __construct(array $routes)
    {
        parent::__construct($routes);
    }

    /**
     * This method does nothing in order to retain proper encapsulation.
     * Use addRoute() for route addition.
     */
    public function set($key, $value = null)
    {
        // Do nothing
    }

    /**
     * {@inheritdoc}
     */
    public function addRoute(Route $route)
    {
        if(parent::has($this->getStorageName($route))) {
            throw new \InvalidArgumentException("Route to '{$route->getPath()}'"
                ." with method(s) {$route->getMethodsAsString()} already exists.");
        }
        parent::set($this->getStorageName($route), $route);
    }

    /**
     * {@inheritdoc}
     */
    public function getRoutesForTarget($target)
    {
        $routes = [];
        foreach($this->data as $hash => $route) {
            if($route->matchPlaceholders($target)) {
                array_push($routes, $route);
            }
        }
        return $routes;
    }

    /**
     * Returns a md5 hash of route path and route methods.
     *
     * @param Route $route Route for which storage name will be generated.
     *
     * @return string md5 hash of route path and route methods.
     */
    protected function getStorageName(Route $route)
    {
        return md5($route->getPath() . $route->getMethodsAsString());
    }
}


text:
#include <aws/lookoutmetrics/model/DeleteAlertResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::LookoutMetrics::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

DeleteAlertResult::DeleteAlertResult()
{
}

DeleteAlertResult::DeleteAlertResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

DeleteAlertResult& DeleteAlertResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  AWS_UNREFERENCED_PARAM(result);

  return *this;
}


text:
id: 1381
title: '¡Mi primer Hack a la Bici! guardabarros caseros con botellas #bikehack'
date: 2012-03-23T21:08:38+00:00
author: Alvar
layout: post
guid: http://www.acercadelaeducacion.com.ar/?p=1381
permalink: /2012/03/mi-primer-hack-a-la-bici-guardabarros-caseros-con-botellas-bikehack/
dsq_thread_id:
  - "1805816146"
bitly_url:
  - http://bit.ly/1ZukTBe
bitly_hash:
  - 1ZukTBe
bitly_long_url:
  - http://www.acercadelaeducacion.com.ar/2012/03/mi-primer-hack-a-la-bici-guardabarros-caseros-con-botellas-bikehack/
image: /wp-content/uploads/2012/03/19032012034.jpg
categories:
  - Cultura Libre
  - Destacados
tags:
  - bicicletas
  - hack
  - hagalo usted mismo
---
A partir de ver esto por la web Another Bottle Bike Fender - BikeHacks, me largué a hacer mis primeros hacks a la bci, ahora no me voy a embarrar más :D


text:
layout: "docs"
page_title: "Policies"
sidebar_current: "docs-concepts-policies"
description: |-
  Policies are how authorization is done in Vault, allowing you to restrict which parts of Vault a user can access.
---

# Access Control Policies

After [authenticating](/docs/concepts/auth.html) with Vault, the
next step is authorization. This is the process of determining what
a user is allowed to do. Authorization is unified in Vault in the form
of _policies_.

Policies are [HCL](https://github.com/hashicorp/hcl) or JSON documents
that describe what parts of Vault a user is allowed to access. An example
of a policy is shown below:

```javascript
path "sys/*" {
  policy = "deny"
}

path "secret/*" {
  policy = "write"
}

path "secret/foo" {
  policy = "read"
  capabilities = ["create", "sudo"]
}

path "secret/super-secret" {
  capabilities = ["deny"]
}
```

Policies use path based matching to apply rules. A policy may be an exact
match, or might be a glob pattern which uses a prefix. Vault operates in a
whitelisting mode, so if a path isn't explicitly allowed, Vault will reject
access to it.  This works well due to Vault's architecture of being like a
filesystem: everything has a path associated with it, including the core
configuration mechanism under "sys".

~> Policy paths are matched using the most specific defined policy. This may
be an exact match or the longest-prefix match of a glob. This means if you
define a policy for `"secret/foo*"`, the policy would also match `"secret/foobar"`.
The glob character is only supported at the end of the path specification.

## Capabilities and Policies

Paths have an associated set of capabilities that provide fine-grained control
over operations. The capabilities are:

  * `create` - Create a value at a path. (At present, few parts of Vault
    distinguish between `create` and `update`, so most operations require
    `update`. Parts of Vault that provide such a distinction, such as
    the `generic` backend, are noted in documentation.)

  * `read` - Read the value at a path.

  * `update` - Change the value at a path. In most parts of Vault, this also
    includes the ability to create the initial value at the path.

  * `delete` - Delete the value at a path.

  * `list` - List key names at a path. Note that the keys returned by a
    `list` operation are *not* filtered by policies.  Do not encode sensitive
    information in key names.

  * `sudo` - Gain access to paths that are _root-protected_. This is _additive_
    to other capabilities, so a path that requires `sudo` access will also
    require `read`, `update`, etc. as appropriate.

  * `deny` - No access allowed. This always takes precedence regardless of any
    other defined capabilities, including `sudo`.

The only non-obvious capability is `sudo`. Some routes within Vault and mounted
backends are marked as _root-protected_ paths. Clients aren't allowed to access
root paths unless they are a root user (have the special policy "root" attached
to their token) or have access to that path with the `sudo` capability (in
addition to the other necessary capabilities for performing an operation
against that path, such as `read` or `delete`).

For example, modifying the audit log backends is done via root paths.
Only root or `sudo` privilege users are allowed to do this.

Prior to Vault 0.5, the `policy` keyword was used per path rather than a set of
`capabilities`. In Vault 0.5+ these are still supported as shorthand and to
maintain backwards compatibility, but internally they map to a set of
capabilities. These mappings are as follows:

  * `deny` - `["deny"]`

  * `sudo` - `["create", "read", "update", "delete", "list", "sudo"]`

  * `write` - `["create", "read", "update", "delete", "list"]`

  * `read` - `["read", "list"]`

## Root Policy

The "root" policy is a special policy that can not be modified or removed.
Any user associated with the "root" policy becomes a root user. A root
user can do _anything_ within Vault.

There always exists at least one root user (associated with the token
when initializing a new server). After this root user, it is recommended
to create more strictly controlled users. The original root token should
be protected accordingly.

## Managing Policies

Policy management can be done via the API or CLI. The CLI commands are
`vault policies` and `vault policy-write`. Please see the help associated
with these commands for more information. They are very easy to use.

## Associating Policies

To associate a policy with a user, you must consult the documentation for
the authentication backend you're using.

For tokens, they are associated at creation time with `vault token-create`
and the `-policy` flags. Child tokens can be associated with a subset of
a parent's policies. Root users can assign any policies.

There is no way to modify the policies associated with a token once the token
has been issued. The token must be revoked and a new one acquired to receive a
new set of policies.

However, the _contents_ of policies are parsed in real-time at every token use.
As a result, if a policy is modified, the modified rules will be in force the
next time a token with that policy attached is used to make a call to Vault.


text:
'''
Created on Dec 29, 2012

@author: dstrauss
Copyright 2013 David Strauss

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

method definition for doing CG solves with a pipelined matrix-vector multiplication

'''

import numpy as np

def cg(A,b,maxiter=30,tol=1e-6,pll=False):
    ''' run CG iterations in order to solve the equation Ax=b,
    A ==> a function that implements "matrix vector" multiplication, must be Positive Semidefinite
    b ==> right hand side in Ax=b
    maxiter ==> maximum number of CG iterations
    tol ==> exit tolerance, if ||Ax-b|| < tol the program exits
    pll ==> boolean flag for doing plotting or not
    '''

    x = np.zeros(b.size,dtype=b.dtype)

    r=b-A(x)
    p=r
    rsold=np.dot(r.T,r)
    rsn = list()

    ix = 0
    while ix < maxiter:
        ix += 1
        Ap = A(p);
        alpha=rsold/np.dot(p.T,Ap);
        x=x+alpha*p;
        r=r-alpha*Ap
        rsnew = np.dot(r.T,r)

        rsn.append(np.sqrt(rsnew))
        if np.sqrt(rsnew)<tol:
            break

        p = r+ (rsnew/rsold)*p;
        rsold=rsnew;

    if pll:
        import matplotlib.pyplot as plt
        plt.figure(1)
        plt.plot(rsn)
        plt.title('rsn')
        plt.show()

    return x,ix

def test():
    import scipy.sparse

    opr = -np.ones((3,20))
    opr[1,:] = 2

    M = scipy.sparse.spdiags(opr, [-1,0,1], 20,20);

    b = np.zeros(20)
    b[9] = 1

    cg(lambda x: M*x,b)


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("7f29fbaa-d2b3-4011-b34f-5a109bc282af")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
chkconfig tftp off

yum remove tftp-server -y


text:
ipinfo - Get your public IP
Targetted for IoT applications to communicate without DYN DNS.

Apache reverse proxying setup: see conf file for virtual host config


text:
NoFlo components for JQ.

## Components

### Select

#### In ports:

- IN: something

#### Out ports:

- OUT: something


text:
package com.veil.ai;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.PixmapIO;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.ScreenUtils;

public class ScreenshotUtility {

	public static void takeScreenshot(FileHandle dir, String filename){
		byte[] pixels = ScreenUtils.getFrameBufferPixels(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);
		Pixmap pixmap = new Pixmap(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), Pixmap.Format.RGBA8888);
		BufferUtils.copy(pixels, 0, pixmap.getPixels(), pixels.length);

		PixmapIO.writePNG(dir.child(filename+".png"), pixmap);
		pixmap.dispose();
	}
}


text:
Test for bug #797: XDebug terminates (or Eclipse loses it?) when viewing variables
--FILE--
<?php
require 'dbgp/dbgpclient.php';
$data = file_get_contents(dirname(__FILE__) . '/bug00797.inc');

$commands = array(
	'step_into',
	'step_into',
	'step_into',
	'context_get -d 0',
);

dbgpRun( $data, $commands );
?>
--EXPECTF--
<?xml version="1.0" encoding="iso-8859-1"?>
<init xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" fileuri="file:///tmp/xdebug-dbgp-test.php" language="PHP" protocol_version="1.0" appid="" idekey=""><engine version=""><![CDATA[Xdebug]]></engine><author><![CDATA[Derick Rethans]]></author><url><![CDATA[http://xdebug.org]]></url><copyright><![CDATA[Copyright (c) 2002-%d by Derick Rethans]]></copyright></init>

-> step_into -i 1
<?xml version="1.0" encoding="iso-8859-1"?>
<response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="step_into" transaction_id="1" status="break" reason="ok"><xdebug:message filename="file:///tmp/xdebug-dbgp-test.php" lineno="2"></xdebug:message></response>

-> step_into -i 2
<?xml version="1.0" encoding="iso-8859-1"?>
<response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="step_into" transaction_id="2" status="break" reason="ok"><xdebug:message filename="file:///tmp/xdebug-dbgp-test.php" lineno="8"></xdebug:message></response>

-> step_into -i 3
<?xml version="1.0" encoding="iso-8859-1"?>
<response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="step_into" transaction_id="3" status="break" reason="ok"><xdebug:message filename="file:///tmp/xdebug-dbgp-test.php" lineno="16"></xdebug:message></response>

-> context_get -i 4 -d 0
<?xml version="1.0" encoding="iso-8859-1"?>
<response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="context_get" transaction_id="4" context="0"><property name="::" fullname="::" type="object" classname="B" children="0" numchildren="0"></property></response>


text:
using System;

namespace GeneticTanks.Game.Events
{
  /// <summary>
  /// The base class for all events in the game.
  /// </summary>
  abstract class Event
    : EventArgs
  {
    /// <summary>
    /// Creates the event.
    /// </summary>
    protected Event()
    {
      TimeStamp = DateTime.Now.Ticks;
    }

    /// <summary>
    /// The creation timestamp of the event in system ticks.
    /// </summary>
    public long TimeStamp { get; private set; }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ExceptionCode (apache-cassandra API)</title>
<meta name="date" content="2015-06-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

org.apache.cassandra.exceptions

Enum ExceptionCode

java.lang.Object

java.lang.Enum<ExceptionCode>

org.apache.cassandra.exceptions.ExceptionCode

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<ExceptionCode>

public enum ExceptionCode
extends java.lang.Enum<ExceptionCode>

Exceptions code, as defined by the binary protocol.

Enum Constant Summary

Enum Constants

Enum Constant and Description

ALREADY_EXISTS

BAD_CREDENTIALS

CONFIG_ERROR

INVALID

IS_BOOTSTRAPPING

OVERLOADED

PROTOCOL_ERROR

READ_TIMEOUT

SERVER_ERROR

SYNTAX_ERROR

TRUNCATE_ERROR

UNAUTHORIZED

UNAVAILABLE

UNPREPARED

WRITE_TIMEOUT

Field Summary

Fields

Modifier and Type
Field and Description

int
value

Method Summary

Methods

Modifier and Type
Method and Description

static ExceptionCode
fromValue(int value)

static ExceptionCode
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static ExceptionCode[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

SERVER_ERROR

public static final ExceptionCode SERVER_ERROR

PROTOCOL_ERROR

public static final ExceptionCode PROTOCOL_ERROR

BAD_CREDENTIALS

public static final ExceptionCode BAD_CREDENTIALS

UNAVAILABLE

public static final ExceptionCode UNAVAILABLE

OVERLOADED

public static final ExceptionCode OVERLOADED

IS_BOOTSTRAPPING

public static final ExceptionCode IS_BOOTSTRAPPING

TRUNCATE_ERROR

public static final ExceptionCode TRUNCATE_ERROR

WRITE_TIMEOUT

public static final ExceptionCode WRITE_TIMEOUT

READ_TIMEOUT

public static final ExceptionCode READ_TIMEOUT

SYNTAX_ERROR

public static final ExceptionCode SYNTAX_ERROR

UNAUTHORIZED

public static final ExceptionCode UNAUTHORIZED

INVALID

public static final ExceptionCode INVALID

CONFIG_ERROR

public static final ExceptionCode CONFIG_ERROR

ALREADY_EXISTS

public static final ExceptionCode ALREADY_EXISTS

UNPREPARED

public static final ExceptionCode UNPREPARED

Field Detail

value

public final int value

Method Detail

values

public static ExceptionCode[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (ExceptionCode c : ExceptionCode.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in the order they are declared

valueOf

public static ExceptionCode valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant with the specified name

java.lang.NullPointerException - if the argument is null

fromValue

public static ExceptionCode fromValue(int value)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

Copyright © 2015 The Apache Software Foundation


text:
$(document).ready(function () {
    var id = getId();
    $.ajax({
        method:'GET',
        url:"/shop/view",
        data:{"id":id},
        complete:function (data) {
            var product = JSON.parse(data.responseText);
            var form='<form  id="edit_product" method="post">';
            form+='
';
            form+='
Название товара<input type="text" name="form_title" id="form_title" value="'+product.name+'"/>
';
            form+='
Цена<input type="text" name="form_price" value="'+product.price+'"/>
';
            form+='
Количество<input type="text" name="form_amount" value="'+product.amount+'"/>

';
            form+='
Краткое описание товара
';
            form+='
';
            form+='<textarea id="editor1" name="txt1" cols="90" rows="10">'+product.miniDescription+'</textarea>
';
            form+='
Описание товара
';
            form+='
';
            form+='<textarea id="editor2" name="txt2" cols="90" rows="15">'+product.description+'</textarea>
';
            form+='
<input type="hidden" name="id" value="'+ id +'">
';
            form+='
<input type="hidden" name="action" value="update">
';
            form+='
<input type="submit" id="submit_form" name="submit_add" value="Изменить товар"/>
</form>';

            //
            // form+='
<input type="hidden" name="account_number" value="15">
';
           $('#edit').html(form);
        }
    });
     $(document).on('submit','#edit_product', function () {
         var form = $(this).serialize();
         $.ajax({
             method:"POST",
             url:"/shop/products",
             data:form,
             complete:function (d) {
                 var res = JSON.parse(d.responseText);
                 if (res == "ok") {
                     $("#edit_product").fadeOut(300,function() {
                         $("#message").addClass("message_good").fadeIn(400).html("Товар успешно обновлен.");
                         $("#form_submit").hide();
                     });
                 }
                 else {
                     $("#message").addClass("message_error").fadeIn(400).html(res);
                 }
             }
         });
         return false;
     })
});
function getId() {
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('=');
    return sURLVariables[1];
}


text:
<!DOCTYPE html>

    <title>Timber  Reference</title>
    <link rel="stylesheet" type="text/css" href="css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="css/highlight.css" />
    <meta charset='utf-8'>

Timber Docs (80% documented)

View on GitHub

        Timber Reference

        Timber  Reference

            Classes

                LogFormatter

                – Attributes

                Logger

                – LogLevel

            Extensions

                String

            Functions

                <(_:_:)

                <=(_:_:)

                ==(_:_:)

                ==(_:_:)

                ==(_:_:)

                >(_:_:)

                >=(_:_:)

            Structs

                LogFormat

Timber

Timber is a lightweight logging framework written in Swift. It is very performant and runs all logging-based operations away from the main-thread, ensuring that the UI or any other operations remain unaffected.

Timber is also insanely flexible. It provides a LogFormat class which allows you to specify how the log messages should look, and includes custom date formats, and various information related to the file that the log message was executed in, such as the file-name, function and line.

Timber even provides the means to move your logs away from the console, by providing your own pipe to store the log messages elsewhere such as in a file or on your own server.

Unlike a number of other available logging frameworks, Timber lets you specify log-levels for any/all of your files. Say, for instance, you wanted to disable the logging of network requests while testing a separate feature, by calling Logger.registerMinLevel(.None) in your networking class, you can disable the log messages from being output.

Installation

Cocoapods

Simply add the following to your Podfile. Please be aware that the name of the cocoapod is TimberSwift and not Timber.

pod 'TimberSwift'

Manually

Clone the repository and add all the files found in /Timber/Classes to your project.

Running unit tests

It is recommended that you run the unit tests before integrating Timber into your project. This can be done by performing the following in Timber’s root directory. Please ensure that you have bundler installed, and if not run gem install bundler first.

$ bundle install
$ make test

Basic usage

Logger.registerMinLevel(.Error) // Set the log-level for the current file if needed

Logger.debug("This will not be logged as the debug log level is < error")
Logger.error("Oh dear... An error occurred: \(some_error)")
Logger.info("The network request succeeded with status code \(status code)")
Logger.warn("The network response contains some unexpected data")
// etc...

Custom log formats

In order to override the default log format used by Timber, which is [Level Date Filename:Line] Message, you must first instantiate your own LogFormat and pass it into either the global Logger or your own.

    let logFormat = LogFormat(template: "[%@ %@ %@:%@] %@", attributes: [
        LogFormatter.Attributes.Level,
        LogFormatter.Attributes.Date(format: "HH:mm:ss"),
        LogFormatter.Attributes.FileName(fullPath: false, fileExtension: true),
        LogFormatter.Attributes.Line,
        LogFormatter.Attributes.Message
     ])

     // Attach it to the global Logger
     Logger.setFormat(logFormat)

     // Or attach it to your own logger
     someLogger.logFormat = logFormat

     // Or pass it in when you instantiate your logger
     let someLogger = Logger(minLevel: .All, logFormat: logFormat)

Documentation

Timber is fully documented, and the documentation can be found at http://maxkramer.github.io/Timber/.

Log Levels

As mentioned in Logger+LogLevels.swift, we uniformly use the same log priorities as Apache’s log4j. The is as follows:

ALL < DEBUG < TRACE < INFO < WARN < ERROR < FATAL < OFF.

Therefore, a log request of level p in a logger with level q is enabled if p >= q.

Level
Description

ALL
All levels including custom levels.

DEBUG
Designates fine-grained informational events that are most useful to debug an application.

ERROR
Designates error events that might still allow the application to continue running.

FATAL
Designates very severe error events that will presumably lead the application to abort.

INFO
Designates informational messages that highlight the progress of the application at coarse-grained level.

OFF
The highest possible rank and is intended to turn off logging.

TRACE
Designates finer-grained informational events than the DEBUG.

WARN
Designates potentially harmful situations.

Visually:

Reference: Log4j’s architecture page.

TODO:

Swift PM integration

Higher level functions for logging to file(s) including log rotation

Colours!!!

© 2016 Max Kramer

Generated by jazzy ♪♫ v0.7.0, a Realm project.


text:
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents**  *generated with [DocToc](https://github.com/thlorenz/doctoc)*

- [xml](#xml)
  - [XML 1.0](#xml-10)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

xml
===

## XML 1.0

[standard words](http://qiita.com/mpyw/items/939c526dd5de6619b565)
```php
return htmlspecialchars($str, ENT_QUOTES | ENT_XML1 | ENT_DISALLOWED, 'UTF-8');
```


text:
<component name="libraryTable">
  <library name="SBT: org.springframework:spring-tx:4.3.8.RELEASE:jar">
    <CLASSES>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.springframework/spring-tx/jars/spring-tx-4.3.8.RELEASE.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.springframework/spring-tx/srcs/spring-tx-4.3.8.RELEASE-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
<?php
//定义命令行为
interface ICommand
{
    function onCommand( $name, $args );
}
//负责命令链的存储,命令的匹配执行
class CommandChain
{
    private $_commands = array();

    public function addCommand( $cmd )
    {
        $this->_commands []= $cmd;
    }

    public function runCommand( $name, $args )
    {
        foreach( $this->_commands as $cmd )
        {
            if ( $cmd->onCommand( $name, $args ) )
                return;
            }
    }
}
//定义添加用户命令
class UserCommand implements ICommand
{
    public function onCommand( $name, $args )
    {
        if ( $name != 'addUser' ) return false;
        echo( "UserCommand handling 'addUser'\n" );
        return true;
    }
}
//定义邮件命令
class MailCommand implements ICommand
{
    public function onCommand( $name, $args )
    {
        if ( $name != 'mail' ) return false;
        echo( "MailCommand handling 'mail'\n" );
        return true;
    }
}

$cc = new CommandChain();
$cc->addCommand( new UserCommand() );
$cc->addCommand( new MailCommand() );
$cc->runCommand( 'addUser', null );
$cc->runCommand( 'mail', null );
?>


text:
int main() {
	ofAppGlutWindow window;
	ofSetupOpenGL(&window, 1280, 960, OF_WINDOW);
	ofRunApp(new ofApp());
}


text:
<?php

namespace Forge\Config;

use Forge\Config\File\Reader;

class File extends Reader
{
    // @see Config_File_Reader
}


text:
//====================================================================================================================
// Copyright (c) 2012 IdeaBlade
//====================================================================================================================
// 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.
//====================================================================================================================
// USE OF THIS SOFTWARE IS GOVERENED BY THE LICENSING TERMS WHICH CAN BE FOUND AT
// http://cocktail.ideablade.com/licensing
//====================================================================================================================

using System.ComponentModel.Composition;
using System.Threading.Tasks;
using Caliburn.Micro;
using Cocktail;
using Common.Actions;

namespace AccoBooking.ViewModels
{
  [Export]
  public class SupportViewModel : Conductor<IScreen>, IDiscoverableViewModel
  {
    private MenuGroup _menuGroup;

    protected readonly INavigator _navigator;
    private ExportFactory<HelpdeskViewModel> _helpdeksFactory;
    private ExportFactory<VideoViewModel> _videoFactory;
    private ExportFactory<FAQViewModel> _faqFactory;

    [ImportingConstructor]
    public SupportViewModel(
      ExportFactory<HelpdeskViewModel> helpdeskFactory,
      ExportFactory<VideoViewModel> videoFactory,
      ExportFactory<FAQViewModel> faqFactory)
    {
      EventFns.Subscribe(this);

      _helpdeksFactory = helpdeskFactory;
      _videoFactory = videoFactory;
      _faqFactory = faqFactory;

      _navigator = new Navigator(this);
    }

    /// <summary>
    /// Toolbar placeholder
    /// </summary>
    public MenuViewModel TopHomeMenu { get; private set; }
    public MenuViewModel BottomHomeMenu { get; private set; }

    protected override void OnActivate()
    {
      base.OnActivate();
       Start();
    }

    public async void Start()
    {
      try
      {
        var home = _helpdeksFactory.CreateExport().Value;

        await _navigator.NavigateToAsync(home.GetType(),
          target =>
          {

            (target as HelpdeskViewModel).Parent = this; // @@@@
            ((IActivate)target).Activate();
            //(target as HelpdeskViewModel).Start();
          });
      }
      catch (TaskCanceledException)
      {

      }
    }

    public async void FAQ()
    {
      try
      {
        var home = _faqFactory.CreateExport().Value;

        await _navigator.NavigateToAsync(home.GetType(),
          target =>
          {

            (target as FAQViewModel).Parent = this; // @@@@
            ((IActivate)target).Activate();
            //(target as FAQViewModel).Start();
          });
      }
      catch (TaskCanceledException)
      {

      }
    }

    public async void Videos()
    {
      try
      {
        var home = _videoFactory.CreateExport().Value;

        await _navigator.NavigateToAsync(home.GetType(),
          target =>
          {

            (target as VideoViewModel).Parent = this; // @@@@
            ((IActivate)target).Activate();
            //(target as VideoViewModel).Start();
          });
      }
      catch (TaskCanceledException)
      {

      }
    }

  }
}


text:
import {
  Anno,
  X
} from './resources/setup.js';

function AnnotatedTypedParam(@Anno x:X) {}

assert.deepEqual([[X, new Anno]], AnnotatedTypedParam.parameters);


text: require('./styleUrl');


text:
#ifndef ANDROID_AUDIO_POLICY_CORE_H
#define ANDROID_AUDIO_POLICY_CORE_H

#include <stdint.h>
#include <sys/cdefs.h>
#include <sys/types.h>

#include <cutils/bitops.h>

__BEGIN_DECLS

/* The enums were moved here mostly from
 * frameworks/base/include/media/AudioSystem.h
 */

/* request to open a direct output with get_output() (by opposition to
 * sharing an output with other AudioTracks)
 */
typedef enum {
    AUDIO_POLICY_OUTPUT_FLAG_INDIRECT = 0x0,
    AUDIO_POLICY_OUTPUT_FLAG_DIRECT = 0x1
} audio_policy_output_flags_t;

/* device categories used for audio_policy->set_force_use() */
typedef enum {
    AUDIO_POLICY_FORCE_NONE,
    AUDIO_POLICY_FORCE_SPEAKER,
    AUDIO_POLICY_FORCE_HEADPHONES,
    AUDIO_POLICY_FORCE_BT_SCO,
    AUDIO_POLICY_FORCE_BT_A2DP,
    AUDIO_POLICY_FORCE_WIRED_ACCESSORY,
    AUDIO_POLICY_FORCE_BT_CAR_DOCK,
    AUDIO_POLICY_FORCE_BT_DESK_DOCK,
    AUDIO_POLICY_FORCE_ANALOG_DOCK,
    AUDIO_POLICY_FORCE_DIGITAL_DOCK,

    AUDIO_POLICY_FORCE_CFG_CNT,
    AUDIO_POLICY_FORCE_CFG_MAX = AUDIO_POLICY_FORCE_CFG_CNT - 1,

    AUDIO_POLICY_FORCE_DEFAULT = AUDIO_POLICY_FORCE_NONE,
} audio_policy_forced_cfg_t;

/* usages used for audio_policy->set_force_use() */
typedef enum {
    AUDIO_POLICY_FORCE_FOR_COMMUNICATION,
    AUDIO_POLICY_FORCE_FOR_MEDIA,
    AUDIO_POLICY_FORCE_FOR_RECORD,
    AUDIO_POLICY_FORCE_FOR_DOCK,

    AUDIO_POLICY_FORCE_USE_CNT,
    AUDIO_POLICY_FORCE_USE_MAX = AUDIO_POLICY_FORCE_USE_CNT - 1,
} audio_policy_force_use_t;

/* device connection states used for audio_policy->set_device_connection_state()
 */
typedef enum {
    AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
    AUDIO_POLICY_DEVICE_STATE_AVAILABLE,

    AUDIO_POLICY_DEVICE_STATE_CNT,
    AUDIO_POLICY_DEVICE_STATE_MAX = AUDIO_POLICY_DEVICE_STATE_CNT - 1,
} audio_policy_dev_state_t;

typedef enum {
    /* Used to generate a tone to notify the user of a
     * notification/alarm/ringtone while they are in a call. */
    AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION = 0,

    AUDIO_POLICY_TONE_CNT,
    AUDIO_POLICY_TONE_MAX                  = AUDIO_POLICY_TONE_CNT - 1,
} audio_policy_tone_t;

static inline bool audio_is_low_visibility(audio_stream_type_t stream)
{
    switch (stream) {
    case AUDIO_STREAM_SYSTEM:
    case AUDIO_STREAM_NOTIFICATION:
    case AUDIO_STREAM_RING:
        return true;
    default:
        return false;
    }
}

__END_DECLS

#endif  // ANDROID_AUDIO_POLICY_CORE_H


text:
import json

from _pytest.python import raises
from requests import HTTPError
import httpretty
from iso8601 import iso8601

from solve360 import Solve360

__author__ = 'Daniel Nibon <daniel@nibon.se>'

crm = None

def setup_module():
    global crm
    crm = Solve360('email', 'token')

def test_init_solve_missing_cred():
    with raises(TypeError):
        Solve360()
    with raises(ValueError):
        Solve360(None, None)

def test_init_solve():
    Solve360('email', 'token')

def test_invalid_entity():
    with raises(ValueError):
        # noinspection PyProtectedMember
        crm._list(entity='invalid_entity')

def test_invalid_method():
    with raises(ValueError):
        # noinspection PyProtectedMember
        crm._request('invalid_method', 'localhost', (None, None), {})

@httpretty.activate
def test_list_ownership():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='ownership/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.list_ownership()
    assert response['status'] == 'success'

@httpretty.activate
def test_list_page_no_number():
    with raises(ValueError):
        crm.list_contacts(pages='3')

@httpretty.activate
def test_list_page_non_positive():
    with raises(ValueError):
        crm.list_contacts(pages=-1)

# --------------------------------------
# CONTACTS
# --------------------------------------

@httpretty.activate
def test_contact_create():
    httpretty.register_uri(httpretty.POST, crm.url.format(url='contacts/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    contact = crm.create_contact({'firstname': 'A', 'lastname': 'B'})
    assert contact['status'] == 'success'

@httpretty.activate
def test_contact_non_200():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='contacts/10000/'), status=404)
    with raises(HTTPError):
        crm.show_contact(10000)

@httpretty.activate
def test_contact_create_categories():
    httpretty.register_uri(httpretty.POST, crm.url.format(url='contacts/categories/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    category = crm.create_contacts_category('C1')
    assert category['status'] == 'success'

@httpretty.activate
def test_contact_list_categories():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='contacts/categories/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    categories = crm.list_contacts_categories()
    assert categories['status'] == 'success'

@httpretty.activate
def test_show_contact():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='contacts/131/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    contact = crm.show_contact(131)
    assert contact['status'] == 'success'

@httpretty.activate
def test_update_contact():
    httpretty.register_uri(httpretty.PUT, crm.url.format(url='contacts/151/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    contact = crm.update_contact(151, {'lastname': 'D'})
    assert contact['status'] == 'success'

@httpretty.activate
def test_list_contacts():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='contacts/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    contacts = crm.list_contacts()
    assert contacts['status'] == 'success'

@httpretty.activate
def test_list_contacts_paginate_stop_on_pages():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='contacts/'),
                           responses=[
                               httpretty.Response(body='{"status": "success", "count": 3,'
                                                       ' "obj1": {}}',
                                                  content_type='application/json'),
                               httpretty.Response(body='{"status": "success", "count": 3,'
                                                       ' "obj2": {}}',
                                                  content_type='application/json'),
                               httpretty.Response(body='{"status": "success", "count": 3,'
                                                       ' "obj3": {}}',
                                                  content_type='application/json')
                           ])
    contacts = crm.list_contacts(limit=1, pages=2)
    assert contacts['status'] == 'success'
    assert contacts['count'] == 3
    assert contacts['obj1'] == {}
    assert contacts['obj2'] == {}
    assert 'obj3' not in contacts
    assert len(contacts) == 2 + 2  # 'status' + 'count' + <results>

@httpretty.activate
def test_list_contacts_paginate_stop_on_objects():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='contacts/'),
                           responses=[
                               httpretty.Response(body='{"status": "success", "count": 2,'
                                                       ' "obj1": {},  "obj2": {}}',
                                                  content_type='application/json'),
                               httpretty.Response(body='{"status": "success", "count": 2,'
                                                       ' "obj3": {}, "obj4": {}}',
                                                  content_type='application/json')
                           ])
    contacts = crm.list_contacts(limit=2, pages=3)
    assert contacts['status'] == 'success'
    assert contacts['count'] == 2
    assert contacts['obj1'] == {}
    assert contacts['obj2'] == {}
    assert 'obj3' not in contacts
    assert 'obj4' not in contacts
    assert len(contacts) == 2 + 2  # 'status' + 'count' + <results>

@httpretty.activate
def test_contact_activity_create():
    httpretty.register_uri(httpretty.POST, crm.url.format(url='contacts/note/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.create_contact_activity(131, 'note', {'details': 'test'})
    assert response['status'] == 'success'

@httpretty.activate
def test_contact_activity_update():
    httpretty.register_uri(httpretty.PUT, crm.url.format(url='contacts/note/111/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.update_contact_activity('note', 111, {'details': 'test2'})
    assert response['status'] == 'success'

@httpretty.activate
def test_contact_activity_destroy():
    httpretty.register_uri(httpretty.DELETE, crm.url.format(url='contacts/note/112/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.destroy_contact_activity('note', 112)
    assert response['status'] == 'success'

@httpretty.activate
def test_contact_destroy():
    httpretty.register_uri(httpretty.DELETE, crm.url.format(url='contacts/151/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    contact = crm.destroy_contact(151)
    assert contact['status'] == 'success'

@httpretty.activate
def test_list_contacts_fields():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='contacts/fields/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    fields = crm.list_contacts_fields()
    assert fields['status'] == 'success'

@httpretty.activate
def test_list_contacts_categories():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='contacts/categories/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    categories = crm.list_contacts_categories()
    assert categories['status'] == 'success'

# --------------------------------------
# COMPANIES
# --------------------------------------

@httpretty.activate
def test_company_create():
    httpretty.register_uri(httpretty.POST, crm.url.format(url='companies/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    contact = crm.create_company({'firstname': 'A', 'lastname': 'B'})
    assert contact['status'] == 'success'

@httpretty.activate
def test_company_non_200():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='companies/10000/'), status=404)
    with raises(HTTPError):
        crm.show_company(10000)

@httpretty.activate
def test_company_create_categories():
    httpretty.register_uri(httpretty.POST, crm.url.format(url='companies/categories/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    category = crm.create_company_category('C1')
    assert category['status'] == 'success'

@httpretty.activate
def test_company_list_categories():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='companies/categories/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    categories = crm.list_companies_categories()
    assert categories['status'] == 'success'

@httpretty.activate
def test_show_company():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='companies/131/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.show_company(131)
    assert response['status'] == 'success'

@httpretty.activate
def test_update_company():
    httpretty.register_uri(httpretty.PUT, crm.url.format(url='companies/151/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.update_company(151, {'lastname': 'D'})
    assert response['status'] == 'success'

@httpretty.activate
def test_list_companies():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='companies/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.list_companies()
    assert response['status'] == 'success'

@httpretty.activate
def test_company_activity_create():
    httpretty.register_uri(httpretty.POST, crm.url.format(url='companies/note/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.create_company_activity(131, 'note', {'details': 'test'})
    assert response['status'] == 'success'

@httpretty.activate
def test_company_activity_update():
    httpretty.register_uri(httpretty.PUT, crm.url.format(url='companies/note/111/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.update_company_activity('note', 111, {'details': 'test2'})
    assert response['status'] == 'success'

@httpretty.activate
def test_company_activity_destroy():
    httpretty.register_uri(httpretty.DELETE, crm.url.format(url='companies/note/112/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.destroy_company_activity('note', 112)
    assert response['status'] == 'success'

@httpretty.activate
def test_company_destroy():
    httpretty.register_uri(httpretty.DELETE, crm.url.format(url='companies/151/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.destroy_company(151)
    assert response['status'] == 'success'

@httpretty.activate
def test_list_companies_fields():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='companies/fields/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    fields = crm.list_companies_fields()
    assert fields['status'] == 'success'

@httpretty.activate
def test_list_companies_categories():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='companies/categories/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    categories = crm.list_companies_categories()
    assert categories['status'] == 'success'

# --------------------------------------
# PROJECTBLOGS
# --------------------------------------

@httpretty.activate
def test_projectblog_create():
    httpretty.register_uri(httpretty.POST, crm.url.format(url='projectblogs/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.create_projectblog({'firstname': 'A', 'lastname': 'B'})
    assert response['status'] == 'success'

@httpretty.activate
def test_projectblog_non_200():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='projectblogs/10000/'), status=404)
    with raises(HTTPError):
        crm.show_projectblog(10000)

@httpretty.activate
def test_projectblog_create_categories():
    httpretty.register_uri(httpretty.POST, crm.url.format(url='projectblogs/categories/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    category = crm.create_projectblog_category('C1')
    assert category['status'] == 'success'

@httpretty.activate
def test_projectblog_list_categories():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='projectblogs/categories/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    categories = crm.list_projectblogs_categories()
    assert categories['status'] == 'success'

@httpretty.activate
def test_show_projectblog():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='projectblogs/131/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.show_projectblog(131)
    assert response['status'] == 'success'

@httpretty.activate
def test_update_projectblog():
    httpretty.register_uri(httpretty.PUT, crm.url.format(url='projectblogs/151/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.update_projectblog(151, {'lastname': 'D'})
    assert response['status'] == 'success'

@httpretty.activate
def test_list_projectblogs():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='projectblogs/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    projectblogs = crm.list_projectblogs()
    assert projectblogs['status'] == 'success'

@httpretty.activate
def test_projectblog_activity_create():
    httpretty.register_uri(httpretty.POST, crm.url.format(url='projectblogs/note/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.create_projectblog_activity(131, 'note', {'details': 'test'})
    assert response['status'] == 'success'

@httpretty.activate
def test_projectblog_activity_update():
    httpretty.register_uri(httpretty.PUT, crm.url.format(url='projectblogs/note/111/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.update_projectblog_activity('note', 111, {'details': 'test2'})
    assert response['status'] == 'success'

@httpretty.activate
def test_projectblog_activity_destroy():
    httpretty.register_uri(httpretty.DELETE, crm.url.format(url='projectblogs/note/112/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.destroy_projectblog_activity('note', 112)
    assert response['status'] == 'success'

@httpretty.activate
def test_projectblog_destroy():
    httpretty.register_uri(httpretty.DELETE, crm.url.format(url='projectblogs/151/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.destroy_projectblog(151)
    assert response['status'] == 'success'

@httpretty.activate
def test_list_projectblogs_fields():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='projectblogs/fields/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    fields = crm.list_projectblogs_fields()
    assert fields['status'] == 'success'

@httpretty.activate
def test_list_projectblogs_categories():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='projectblogs/categories/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    categories = crm.list_projectblogs_categories()
    assert categories['status'] == 'success'

# --------------------------------------
# DATES
# --------------------------------------

@httpretty.activate
def test_parse_dates():
    ISO8601 = "2014-12-12T15:19:21+01:00"
    PARSED = iso8601.parse_date(ISO8601)
    response_body = {'status': 'success', 'count': 1,
                     'obj1': {'updated': ISO8601}}
    httpretty.register_uri(httpretty.GET, crm.url.format(url='companies/'),
                           body=json.dumps(response_body),
                           content_type='application/json')
    response = crm.list_companies()
    assert response['status'] == 'success'
    assert response['obj1']['updated'] == ISO8601
    assert response['obj1']['updated_parsed'] == PARSED

@httpretty.activate
def test_parse_faulty_dates():
    response_body = {'status': 'success', 'count': 1,
                     'obj1': {'id': 42}}
    httpretty.register_uri(httpretty.GET, crm.url.format(url='companies/'),
                           body=json.dumps(response_body),
                           content_type='application/json')
    response = crm.list_companies(date_fields=['id'])
    assert response['status'] == 'success'
    assert response['obj1']['id'] == 42
    assert 'id_parsed' not in response['obj1']

@httpretty.activate
def test_parse_nondefaultfields_dates():
    ISO8601 = "2014-12-12T15:19:21+01:00"
    response_body = {'status': 'success', 'count': 1,
                     'obj1': {'id': 42, 'updated': ISO8601}}
    httpretty.register_uri(httpretty.GET, crm.url.format(url='companies/'),
                           body=json.dumps(response_body),
                           content_type='application/json')
    response = crm.list_companies(date_fields=['id'])
    assert response['status'] == 'success'
    assert response['obj1']['id'] == 42
    assert response['obj1']['updated'] == ISO8601
    assert 'updated_parsed' not in response['obj1']

@httpretty.activate
def test_parse_show_entity_dates():
    ISO8601_1 = "2014-12-12T15:19:21+01:00"
    ISO8601_2 = "2014-12-13T15:19:21+01:00"
    ISO8601_3 = "2014-12-14T15:19:21+01:00"
    PARSED_1 = iso8601.parse_date(ISO8601_1)
    PARSED_2 = iso8601.parse_date(ISO8601_2)
    PARSED_3 = iso8601.parse_date(ISO8601_3)

    response_body = {'status': 'success', 'count': 1,
                     'obj1': {'id': 42,
                              'created': ISO8601_1,
                              'item': {'updated': ISO8601_2,
                                       'fields': {'viewed': ISO8601_3},
                                       'activities': {'act1': {'viewed': ISO8601_3}}}}}
    httpretty.register_uri(httpretty.GET, crm.url.format(url='companies/42/'),
                           body=json.dumps(response_body),
                           content_type='application/json')
    response = crm.show_company(42)
    assert response['status'] == 'success'
    assert response['obj1']['id'] == 42
    assert response['obj1']['created'] == ISO8601_1
    assert response['obj1']['created_parsed'] == PARSED_1
    assert response['obj1']['item']['updated'] == ISO8601_2
    assert response['obj1']['item']['updated_parsed'] == PARSED_2
    assert response['obj1']['item']['fields']['viewed'] == ISO8601_3
    assert response['obj1']['item']['fields']['viewed_parsed'] == PARSED_3
    assert response['obj1']['item']['activities']['act1']['viewed'] == ISO8601_3
    assert response['obj1']['item']['activities']['act1']['viewed_parsed'] == PARSED_3

# --------------------------------------
# REPORTS
# --------------------------------------

@httpretty.activate
def test_report_nextaction():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='report/nextactions/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.show_report_nextactions(filter_=0)
    assert response['status'] == 'success'

@httpretty.activate
def test_report_calendar():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='report/calendar/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.show_report_calendar('2014-01-01', '2014-02-01')
    assert response['status'] == 'success'

@httpretty.activate
def test_report_followup():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='report/followups/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.show_report_followups(responsible=0)
    assert response['status'] == 'success'

@httpretty.activate
def test_report_opportunities():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='report/opportunities/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.show_report_opportunities(filter_=0)
    assert response['status'] == 'success'

@httpretty.activate
def test_report_activities():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='report/activities/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.show_report_activities('2014-01-01', '2014-02-01', 'updated')
    assert response['status'] == 'success'

@httpretty.activate
def test_report_timetracking():
    httpretty.register_uri(httpretty.GET, crm.url.format(url='report/timetracking/'),
                           body='{"status": "success"}',
                           content_type='application/json')
    response = crm.show_report_timetracking('2014-01-01', '2014-02-01', 'updated')
    assert response['status'] == 'success'


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Payment</title>

Braintree Payment Form

<form id="checkout-form" method="post">
  {% csrf_token %}
  {{ form.first_name.errors }}
  {{ form.first_name.label_tag }}
  {{ form.first_name }}
  {{ form.last_name.errors }}
  {{ form.last_name.label_tag }}
  {{ form.last_name }}

  {{ form.amount.errors }}
  {{ form.amount.label_tag }}
  {{ form.amount }}

  <input type="submit" value="Pay $10">
</form>


text:
CTools' form tool is a replacement for drupal_get_form() that includes some additional functionality:

 It takes $form_state as an argument, which is accepted as a reference; meaning when the form is complete, you can examine the $form_state to see what the form did.

 It can handle $_GET as an input source, or the input can be provided from some other source.

 It can be told not to render or not to redirect, which can be important during AJAX operations.

 It can provide a special 'wrapper' form which is used by the wizard tool to provide a standard set of buttons to a form.

Usage:

ctools_include('form');
$output = ctools_build_form($form_id, $form_state);

Previously, arguments to the form builder were passed into drupal_get_form; this is no longer true. You have two options for passing arguments to the form with ctools_build_form: set $form_state['args'] to an array which will then be passed to the builder as before. Or simply set $form_state values and refer to them in the builder.

Values you can set on $form_state

no_redirect

If set to TRUE, completely disables redirecting, no matter what $form_state['redirect'] has been set to.

rerender

Defaults to TRUE. If set, the form will be rerendered after submit if not redirected. If set to FALSE the form will not be rerendered after submit and $output will be NULL.

method

Defaults to 'post'. May be set to 'get'. If 'get' is in use, form ids and tokens will not be used, and all get forms will automatically be assumed to be submitted. Beware as this can have unexpected effects on default values as fapi doesn't quite know how to handle this state.

input

Defaults to $_POST. If using 'get' you should set this to $_GET.

wrapper callback

If this is set to a function name, the form will be 'wrapped' in another form. This changes how the builder callback work! First, $form is set to a blank array. Then the wrapper callback is called with &$form and &$form_state as arguments. Then the form builder is called with &$form and &$form_state as arguments. No other arguments are given.

args

An array of arguments that will be passed to the form builder callback just as though they were passed as arguments to drupal_get_form().

want form

Defaults to FALSE. If set, instead of rendering, the return value will be the $form array. It can then be rendered via drupal_render() normally. This is particularly useful for AJAX operations that may need to process a form and then only render a part of it.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Hygrocybe occidentalis var. occidentalis

### Remarks
null


text:
package com.thinkbiganalytics.annotations;

import com.fasterxml.jackson.annotation.JsonIgnore;

import org.apache.commons.lang3.builder.ToStringBuilder;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * Class used to extract field annotations and return as an object describing the annotation and its purpose as well as the Field data
 * A helper class is usually used in conjunction with this class to build up this object parsing Field annotations for a given object/class
 *
 * @see AnnotationFieldNameResolver
 */
public class AnnotatedFieldProperty<T extends Annotation> {

    private String name;
    private String description;
    @JsonIgnore
    private Field field;
    private String dataType;

    private T annotation;

    public AnnotatedFieldProperty() {

    }

    /**
     * Returns the name of the field or the dot notation of a field if its derived as a child element from a parent class
     *
     * @return the name of the field.  When used with the {@link AnnotationFieldNameResolver} it will resolve to the name of the field as it pertains to the parent object separated by a "."
     */
    public String getName() {
        return name;
    }

    /**
     * Set the field name used for this annotation.
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Return an optional description about the field
     *
     * @return the description for the field.  This is optional and can be null
     */
    public String getDescription() {
        return description;
    }

    /**
     * set the description for the field
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * Return the Java Field reference
     *
     * @return the Java Field reference to the annotated field
     */
    public Field getField() {
        return field;
    }

    /**
     * set the field containing the annotation
     */
    public void setField(Field field) {
        this.field = field;
    }

    /**
     * Return the Java datatype of the field
     */
    public String getDataType() {
        return dataType;
    }

    /**
     * set the Java datatype
     */
    public void setDataType(String dataType) {
        this.dataType = dataType;
    }

    /**
     * Return the Annotation used when parsing this field
     */
    public T getAnnotation() {
        return annotation;
    }

    /**
     * set the annotation reference
     */
    public void setAnnotation(T annotation) {
        this.annotation = annotation;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
            .append("name", name)
            .append("description", description)
            .toString();
    }
}


text:
package org.pac4j.play.http;

import org.pac4j.core.context.HttpConstants;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.http.HttpActionAdapter;
import org.pac4j.play.PlayWebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static play.mvc.Results.*;

/**
 * Default implementation.
 *
 * @author Jerome Leleu
 * @since 2.0.0
 */
public class DefaultHttpActionAdapter implements HttpActionAdapter {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public Object adapt(final int code, final WebContext context) {
        final PlayWebContext webContext = (PlayWebContext) context;
        logger.debug("requires HTTP action: {}", code);
        if (code == HttpConstants.UNAUTHORIZED) {
            return unauthorized("authentication required");
        } else if (code == HttpConstants.FORBIDDEN) {
            return forbidden("forbidden");
        } else if (code == HttpConstants.TEMP_REDIRECT) {
            return redirect(webContext.getResponseLocation());
        } else if (code == HttpConstants.OK) {
            final String content = webContext.getResponseContent();
            logger.debug("render: {}", content);
            return ok(content).as(HttpConstants.HTML_CONTENT_TYPE);
        }
        final String message = "Unsupported HTTP action: " + code;
        logger.error(message);
        throw new TechnicalException(message);
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.purview.fluent;

import com.azure.core.http.HttpPipeline;
import java.time.Duration;

/** The interface for PurviewManagementClient class. */
public interface PurviewManagementClient {
    /**
     * Gets The subscription identifier.
     *
     * @return the subscriptionId value.
     */
    String getSubscriptionId();

    /**
     * Gets server parameter.
     *
     * @return the endpoint value.
     */
    String getEndpoint();

    /**
     * Gets Api Version.
     *
     * @return the apiVersion value.
     */
    String getApiVersion();

    /**
     * Gets The HTTP pipeline to send requests through.
     *
     * @return the httpPipeline value.
     */
    HttpPipeline getHttpPipeline();

    /**
     * Gets The default poll interval for long-running operation.
     *
     * @return the defaultPollInterval value.
     */
    Duration getDefaultPollInterval();

    /**
     * Gets the AccountsClient object to access its operations.
     *
     * @return the AccountsClient object.
     */
    AccountsClient getAccounts();

    /**
     * Gets the DefaultAccountsClient object to access its operations.
     *
     * @return the DefaultAccountsClient object.
     */
    DefaultAccountsClient getDefaultAccounts();

    /**
     * Gets the OperationsClient object to access its operations.
     *
     * @return the OperationsClient object.
     */
    OperationsClient getOperations();

    /**
     * Gets the PrivateEndpointConnectionsClient object to access its operations.
     *
     * @return the PrivateEndpointConnectionsClient object.
     */
    PrivateEndpointConnectionsClient getPrivateEndpointConnections();

    /**
     * Gets the PrivateLinkResourcesClient object to access its operations.
     *
     * @return the PrivateLinkResourcesClient object.
     */
    PrivateLinkResourcesClient getPrivateLinkResources();
}


text:
define(function(require, exports, module) {
    var touch = require('touch');

    function touchZoom(opts) {
        this.wrap = opts.wrap;
        this.subwrap = opts.subwrap;
        this.offsetX = opts.offsetX || 0;
        this.offsetY = opts.offsetY || 0;
        this.scale = opts.scale || 1;
        this.curScale = 1;
        this.minScale = opts.minScale || 1;
        this.maxScale = opts.maxScale || 2;
        this.init();
    }

    touchZoom.prototype = {
        init: function() {
            this.setThreshold();
            this.matrix(this.curScale, this.offsetX, this.offsetY);
            this.drag();
            this.pinch();
        },

        setThreshold: function() {
            this.wrapHeight = $(this.wrap).height();
            this.wrapWidth = $(this.wrap).width();
            this.subwrapHeight = $(this.subwrap).height();
            this.subwrapWidth = $(this.subwrap).width();
            this.maxtranslateX = this.wrapWidth - this.subwrapWidth;
            this.maxtranslateY = this.wrapHeight - this.subwrapHeight;
        },

        getCurOffset: function() {
            this.offsetX = $(this.subwrap).offset().left;
            this.offsetY = $(this.subwrap).offset().top;
        },

        isRange: function(coor, min, max) {
            if (coor < min) {
                return min;
            } else if (coor > max) {
                return max;
            } else {
                return coor
            }
        },

        matrix: function(scale, translateX, translateY, originX, originY) {
            var a = scale || 1,
                d = scale || 1,
                e = translateX || 0,
                f = translateY || 0,
                x = originX ? originX + 'px' : '0px',
                y = originY ? originX + 'px' : '0px';
            $(this.subwrap).css({
                'transform': 'matrix(' + a + ',0 , 0 ,' + d + ',' + e + ',' + f + ')',
                '-webkit-transform': 'matrix(' + a + ',0 , 0 ,' + d + ',' + e + ',' + f + ')',
                'transform-origin': x + ' ' + y,
                '-webkit-transform-origin': x + ' ' + y
            });
        },

        drag: function() {
            var _that = this;

            touch.on(_that.subwrap, 'dragstart', function(e) {
                _that.getCurOffset();
            });

            touch.on(_that.subwrap, 'drag', function(e) {
                _that.translateX = _that.isRange(_that.offsetX + e.x, _that.maxtranslateX, 0);
                _that.translateY = _that.isRange(_that.offsetY + e.y, _that.maxtranslateY, 0);
                _that.matrix(_that.curScale, _that.translateX, _that.translateY);
            });

            touch.on(_that.subwrap, 'dragend', function(e) {
                _that.offsetX = _that.translateX;
                _that.offsetY = _that.translateY;
            });
        },

        pinch: function() {
            var _that = this;

            // touch.on(_that.subwrap, 'pinchout', function(e) {
            //     // _that.getCurOffset();
            //     if (_that.curScale == _that.maxScale) {
            //         return;
            //     }
            //     var scale = _that.scale + e.scale - 1,
            //         curScale = _that.isRange(scale, _that.minScale, _that.maxScale);
            //     var centerX = (_that.wrapWidth / 2) - _that.offsetX,
            //         centerY = (_that.wrapHeight / 2) - _that.offsetY;
            //     var translateX = _that.isRange((1 - curScale) * centerX + (_that.offsetX / _that.curScale), (_that.wrapWidth - (_that.subwrapWidth * curScale)), 0),
            //         translateY = _that.isRange((1 - curScale) * centerY + (_that.offsetY / _that.curScale), (_that.wrapHeight - (_that.subwrapHeight * curScale)), 0);
            //     _that.matrix(curScale, translateX, translateY);
            //     _that.scale = curScale;
            // });
            touch.on(_that.subwrap, 'pinchend', function(e) {
                _that.getCurOffset();
                var centerX = (_that.wrapWidth / 2) - _that.offsetX,
                    centerY = (_that.wrapHeight / 2) - _that.offsetY;
                if (e.scale > 1 && !_that.isSale) {
                    var translateX = _that.isRange(-1 * centerX + _that.offsetX, (_that.wrapWidth - (_that.subwrapWidth * 2)), 0),
                        translateY = _that.isRange(-1 * centerY + _that.offsetY, (_that.wrapHeight - (_that.subwrapHeight * 2)), 0);
                    _that.matrix(2, translateX, translateY);
                    _that.curScale = 2;
                    _that.isSale = true;
                } else if (e.scale < 1 && _that.isSale) {
                    var translateX = _that.isRange(0.5 * centerX + _that.offsetX, (_that.wrapWidth - (_that.subwrapWidth / 2)), 0),
                        translateY = _that.isRange(0.5 * centerY + _that.offsetY, (_that.wrapHeight - (_that.subwrapHeight / 2)), 0);
                    _that.matrix(1, translateX, translateY);
                    _that.curScale = 1;
                    _that.isSale = false;
                }
                _that.setThreshold();

            });
        }
    };

    exports.touchZoom = touchZoom;
})