text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.poly.v1.model;

/**
 * The same asset can be represented in different formats, for example, a [WaveFront
 * .obj](//en.wikipedia.org/wiki/Wavefront_.obj_file) file with its corresponding .mtl file or a
 * [Khronos glTF](//www.khronos.org/gltf) file with its corresponding .glb binary data. A format
 * refers to a specific representation of an asset and contains all information needed to retrieve
 * and describe this representation.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Poly API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class Format extends com.google.api.client.json.GenericJson {

  /**
   * Complexity stats about this representation of the asset.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private FormatComplexity formatComplexity;

  /**
   * A short string that identifies the format type of this representation. Possible values are:
   * `FBX`, `GLTF`, `GLTF2`, `OBJ`, and `TILT`.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String formatType;

  /**
   * A list of dependencies of the root element. May include, but is not limited to, materials,
   * textures, and shader programs.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<File> resources;

  static {
    // hack to force ProGuard to consider File used, since otherwise it would be stripped out
    // see https://github.com/google/google-api-java-client/issues/543
    com.google.api.client.util.Data.nullOf(File.class);
  }

  /**
   * The root of the file hierarchy. This will always be populated. For some format_types - such as
   * `TILT`, which are self-contained - this is all of the data.
   *
   * Other types - such as `OBJ` - often reference other data elements. These are contained in the
   * resources field.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private File root;

  /**
   * Complexity stats about this representation of the asset.
   * @return value or {@code null} for none
   */
  public FormatComplexity getFormatComplexity() {
    return formatComplexity;
  }

  /**
   * Complexity stats about this representation of the asset.
   * @param formatComplexity formatComplexity or {@code null} for none
   */
  public Format setFormatComplexity(FormatComplexity formatComplexity) {
    this.formatComplexity = formatComplexity;
    return this;
  }

  /**
   * A short string that identifies the format type of this representation. Possible values are:
   * `FBX`, `GLTF`, `GLTF2`, `OBJ`, and `TILT`.
   * @return value or {@code null} for none
   */
  public java.lang.String getFormatType() {
    return formatType;
  }

  /**
   * A short string that identifies the format type of this representation. Possible values are:
   * `FBX`, `GLTF`, `GLTF2`, `OBJ`, and `TILT`.
   * @param formatType formatType or {@code null} for none
   */
  public Format setFormatType(java.lang.String formatType) {
    this.formatType = formatType;
    return this;
  }

  /**
   * A list of dependencies of the root element. May include, but is not limited to, materials,
   * textures, and shader programs.
   * @return value or {@code null} for none
   */
  public java.util.List<File> getResources() {
    return resources;
  }

  /**
   * A list of dependencies of the root element. May include, but is not limited to, materials,
   * textures, and shader programs.
   * @param resources resources or {@code null} for none
   */
  public Format setResources(java.util.List<File> resources) {
    this.resources = resources;
    return this;
  }

  /**
   * The root of the file hierarchy. This will always be populated. For some format_types - such as
   * `TILT`, which are self-contained - this is all of the data.
   *
   * Other types - such as `OBJ` - often reference other data elements. These are contained in the
   * resources field.
   * @return value or {@code null} for none
   */
  public File getRoot() {
    return root;
  }

  /**
   * The root of the file hierarchy. This will always be populated. For some format_types - such as
   * `TILT`, which are self-contained - this is all of the data.
   *
   * Other types - such as `OBJ` - often reference other data elements. These are contained in the
   * resources field.
   * @param root root or {@code null} for none
   */
  public Format setRoot(File root) {
    this.root = root;
    return this;
  }

  @Override
  public Format set(String fieldName, Object value) {
    return (Format) super.set(fieldName, value);
  }

  @Override
  public Format clone() {
    return (Format) super.clone();
  }

}


text:
@implementation PXLMenuControllerAnimator

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
	PXLMenuController *menuController;
	UIViewController *ownerViewController;

	if (! self.reverse) {
		menuController = (PXLMenuController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
		ownerViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
	} else {
		menuController = (PXLMenuController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
		ownerViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
	}

	UIView *containerView = [transitionContext containerView];
	containerView.backgroundColor = [UIColor blackColor];

	UIView *ownerViewSnapshot;
	if (! self.reverse) {
		ownerViewSnapshot = [ownerViewController.view snapshotViewAfterScreenUpdates:NO];

		[containerView addSubview:ownerViewSnapshot];
		[containerView addSubview:menuController.view];
	} else {
		ownerViewSnapshot = [containerView.subviews firstObject];
	}

	NSUInteger rowCount = menuController.items.count;
	CGFloat neededTableViewHeight = rowCount * menuController.tableView.rowHeight;

	if (! self.reverse) {
		menuController.tableView.clipsToBounds = YES;
		menuController.view.frame = containerView.frame;
		menuController.view.layer.opacity = 0.f;
		switch (menuController.placement) {
			case PXLMenuControllerPlacementBottom:
				menuController.tableView.contentInset = UIEdgeInsetsMake((CGRectGetHeight(containerView.frame) - neededTableViewHeight), 0, 0, 0);
				menuController.view.frame = CGRectMake(containerView.frame.origin.x, containerView.frame.size.height, containerView.frame.size.width, containerView.frame.size.height);
				break;
			case PXLMenuControllerPlacementRight:
				menuController.tableView.contentInset = UIEdgeInsetsMake(((CGRectGetHeight(containerView.frame) - neededTableViewHeight) / 2), 0, 0, 0);
				menuController.view.frame = CGRectMake(containerView.frame.size.width - neededTableViewHeight, containerView.frame.origin.y, containerView.frame.size.width, containerView.frame.size.height);
				break;
			case PXLMenuControllerPlacementLeft:
				menuController.tableView.contentInset = UIEdgeInsetsMake(((CGRectGetHeight(containerView.frame) - neededTableViewHeight) / 2), 0, 0, 0);
				menuController.view.frame = CGRectMake(-containerView.frame.size.width, containerView.frame.origin.y, containerView.frame.size.width, containerView.frame.size.height);
				break;
		}
	}

	if (! self.reverse) {
		[UIView animateWithDuration:[self transitionDuration:transitionContext] / 2 animations:^{
			menuController.view.layer.opacity = 1.f;
		}];
		[UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0 usingSpringWithDamping:0.6f initialSpringVelocity:1.0f options:kNilOptions animations:^{
			menuController.view.frame = containerView.frame;
		} completion:^(BOOL finished) {
			[transitionContext completeTransition:finished];
		}];
	} else {
		[UIView animateWithDuration:[self transitionDuration:transitionContext] / 2.15 animations:^{
			menuController.view.layer.opacity = 0.f;
		} completion:^(BOOL finished) {
			[transitionContext completeTransition:finished];
		}];
	}

}

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
	return 0.55;
}

@end

redpajama_set_name: RedPajamaGithub


text:
import express from 'express';
import * as restaurantDAL from '../DAL/restaurantDAL';
import * as feedbackDAL from '../DAL/feedbackDAL';
import { handleError } from '../utils/routeHelper';

const router = express.Router();

// Get all basic information about all the restaurants
router.get('/', handleError((req, res) => {
    return restaurantDAL.getAllRestaurantsPartialData()
    .then((restaurants) => res.send(restaurants));
}));

// Serach restaurants by name (case insensitive)
router.get('/name/:restaurantName', handleError((req, res) => {
    return restaurantDAL.searchRestaurantByName(req.params.restaurantName)
    .then((restaurants) => res.send(restaurants));
}));

// Get restaurant by ID
router.get('/id/:id', handleError((req, res) => {
    return restaurantDAL.getRestaurantFullDataById(req.params.id)
    .then((restaurant) => res.send(restaurant));
}));

// Create new feedback
router.post('/feedback', handleError((req, res) => {
    return feedbackDAL.insertRestaurantFeedback(req.body)
    .then(() => res.send({
      message: 'Feedback created successfully'
    }));
}));

// Remove a feedback
router.delete('/feedback/id/:id', handleError((req, res) => {
  return feedbackDAL.removeRestaurantFeedback(req.params.id)
  .then(() => res.send({
    message: 'Feedback removed successfully'
  }));
}));

// Update a feedback
router.put('/feedback', handleError((req, res) => {
    const feedbackLikeObject = {
      id: req.body.id,
      text: req.body.text,
      rank: req.body.rank
    };

    return feedbackDAL.updateRestaurantFeedback(feedbackLikeObject)
    .then(() => res.send({
        message : 'Feedback updated successfully'
      }));
}));

export default router;


text:
'use strict';

// var helpers = require('./helpers');
// var ProgressBar = require('../ProgressBar');

var SOURCE_PATH = 'spec/fixtures/source';
var DEST_PATH = 'spec/fixtures/dest';

// var progressBar = new ProgressBar({
//   total: 1000,
//   size: 30,
//   frequency: 100,
// });

// progressBar.on('finish', function() {
//   console.log('Finished!1');
// });

// var c = 0;
// var t = setInterval(function() {
//   c++;
//   progressBar.progress();

//   if (c === 1000) clearInterval(t);
// }, 10);


text:
/////////////////////////////////////////////////////////////////////
// = NMatrix
//
// A linear algebra library for scientific computation in Ruby.
// NMatrix is part of SciRuby.
//
// NMatrix was originally inspired by and derived from NArray, by
// Masahiro Tanaka: http://narray.rubyforge.org
//
// == Copyright Information
//
// SciRuby is Copyright (c) 2010 - 2014, Ruby Science Foundation
// NMatrix is Copyright (c) 2012 - 2014, John Woods and the Ruby Science Foundation
//
// Please see LICENSE.txt for additional copyright notices.
//
// == Contributing
//
// By contributing source code to SciRuby, you agree to be bound by
// our Contributor Agreement:
//
// * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement
//
// == data.cpp
//
// Functions and data for dealing the data types.

/*
 * Standard Includes
 */

#include <ruby.h>
#include <stdexcept>

/*
 * Project Includes
 */

#include "types.h"
#include "data.h"

/*
 * Global Variables
 */

namespace nm {
  const char* const EWOP_OPS[nm::NUM_EWOPS] = {
    "+",
    "-",
    "*",
    "/",
    "**",
    "%",
    "==",
    "!=",
    "<",
    ">",
    "<=",
    ">="
  };

  const std::string EWOP_NAMES[nm::NUM_EWOPS] = {
    "add",
    "sub",
    "mul",
    "div",
    "pow",
    "mod",
    "eqeq",
    "neq",
    "lt",
    "gt",
    "leq",
    "geq"
  };

  const std::string NONCOM_EWOP_NAMES[nm::NUM_NONCOM_EWOPS] = {
    "atan2",
    "ldexp",
    "hypot"
  };

  const std::string UNARYOPS[nm::NUM_UNARYOPS] = {
    "sin", "cos", "tan",
    "asin", "acos", "atan",
    "sinh", "cosh", "tanh",
    "asinh", "acosh", "atanh",
    "exp", "log2",
    "log10", "sqrt", "erf",
    "erfc", "cbrt", "gamma",
    "negate", "floor", "ceil", "round"
  };

  /*
   * Create a RubyObject from a regular C value (given a dtype). Does not return a VALUE! To get a VALUE, you need to
   * look at the rval property of what this function returns.
   */
  nm::RubyObject rubyobj_from_cval(void* val, nm::dtype_t dtype) {
    using namespace nm;
    switch (dtype) {
      case BYTE:
        return RubyObject(*reinterpret_cast<uint8_t*>(val));

      case INT8:
        return RubyObject(*reinterpret_cast<int8_t*>(val));

      case INT16:
        return RubyObject(*reinterpret_cast<int16_t*>(val));

      case INT32:
        return RubyObject(*reinterpret_cast<int32_t*>(val));

      case INT64:
        return RubyObject(*reinterpret_cast<int64_t*>(val));

      case FLOAT32:
        return RubyObject(*reinterpret_cast<float32_t*>(val));

      case FLOAT64:
        return RubyObject(*reinterpret_cast<float64_t*>(val));

      case COMPLEX64:
        return RubyObject(*reinterpret_cast<Complex64*>(val));

      case COMPLEX128:
        return RubyObject(*reinterpret_cast<Complex128*>(val));

      default:
        try {
          throw std::logic_error("Cannot create ruby object");
        }
        catch (std::logic_error err) {
          printf("%s\n", err.what());
        }

        rb_raise(nm_eDataTypeError, "Conversion to RubyObject requested from unknown/invalid data type (did you try to convert from a VALUE?)");
    }
    return Qnil;
  }
} // end of namespace nm

extern "C" {

const char* const DTYPE_NAMES[nm::NUM_DTYPES] = {
  "byte",
  "int8",
  "int16",
  "int32",
  "int64",
  "float32",
  "float64",
  "complex64",
  "complex128",
  "object"
};

const size_t DTYPE_SIZES[nm::NUM_DTYPES] = {
  sizeof(uint8_t),
  sizeof(int8_t),
  sizeof(int16_t),
  sizeof(int32_t),
  sizeof(int64_t),
  sizeof(float32_t),
  sizeof(float64_t),
  sizeof(nm::Complex64),
  sizeof(nm::Complex128),
  sizeof(nm::RubyObject)
};

const nm::dtype_t Upcast[nm::NUM_DTYPES][nm::NUM_DTYPES] = {
  { nm::BYTE, nm::INT16, nm::INT16, nm::INT32, nm::INT64, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RUBYOBJ},
  { nm::INT16, nm::INT8, nm::INT16, nm::INT32, nm::INT64, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RUBYOBJ},
  { nm::INT16, nm::INT16, nm::INT16, nm::INT32, nm::INT64, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RUBYOBJ},
  { nm::INT32, nm::INT32, nm::INT32, nm::INT32, nm::INT64, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RUBYOBJ},
  { nm::INT64, nm::INT64, nm::INT64, nm::INT64, nm::INT64, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RUBYOBJ},
  { nm::FLOAT32, nm::FLOAT32, nm::FLOAT32, nm::FLOAT32, nm::FLOAT32, nm::FLOAT32, nm::FLOAT64, nm::COMPLEX64, nm::COMPLEX128, nm::RUBYOBJ},
  { nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::FLOAT64, nm::COMPLEX128, nm::COMPLEX128, nm::RUBYOBJ},
  { nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX64, nm::COMPLEX128, nm::COMPLEX64, nm::COMPLEX128, nm::RUBYOBJ},
  { nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::COMPLEX128, nm::RUBYOBJ},
  { nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ, nm::RUBYOBJ}
};

/*
 * Forward Declarations
 */

/*
 * Functions
 */

/*
 * Converts a RubyObject
 */
void rubyval_to_cval(VALUE val, nm::dtype_t dtype, void* loc) {
  using namespace nm;
  switch (dtype) {
    case BYTE:
      *reinterpret_cast<uint8_t*>(loc)      = static_cast<uint8_t>(RubyObject(val));
      break;

    case INT8:
      *reinterpret_cast<int8_t*>(loc)        = static_cast<int8_t>(RubyObject(val));
      break;

    case INT16:
      *reinterpret_cast<int16_t*>(loc)      = static_cast<int16_t>(RubyObject(val));
      break;

    case INT32:
      *reinterpret_cast<int32_t*>(loc)      = static_cast<int32_t>(RubyObject(val));
      break;

    case INT64:
      *reinterpret_cast<int64_t*>(loc)      = static_cast<int64_t>(RubyObject(val));
      break;

    case FLOAT32:
      *reinterpret_cast<float32_t*>(loc)    = static_cast<float32_t>(RubyObject(val));
      break;

    case FLOAT64:
      *reinterpret_cast<float64_t*>(loc)    = static_cast<float64_t>(RubyObject(val));
      break;

    case COMPLEX64:
      *reinterpret_cast<Complex64*>(loc)    = RubyObject(val).to<Complex64>();
      break;

    case COMPLEX128:
      *reinterpret_cast<Complex128*>(loc)    = RubyObject(val).to<Complex128>();
      break;

    case RUBYOBJ:
      *reinterpret_cast<VALUE*>(loc)        = val;
      //rb_raise(rb_eTypeError, "Attempting a bad conversion from a Ruby value.");
      break;

    default:
      rb_raise(rb_eTypeError, "Attempting a bad conversion.");
      break;
  }
}

/*
 * Allocate and return a piece of data of the correct dtype, converted from a
 * given RubyObject.
 */
void* rubyobj_to_cval(VALUE val, nm::dtype_t dtype) {
  size_t size =  DTYPE_SIZES[dtype];
  NM_CONSERVATIVE(nm_register_value(&val));
  void* ret_val = NM_ALLOC_N(char, size);

  rubyval_to_cval(val, dtype, ret_val);
  NM_CONSERVATIVE(nm_unregister_value(&val));
  return ret_val;
}

void nm_init_data() {
  volatile VALUE t = INT2FIX(1);
  volatile nm::RubyObject obj(t);
  volatile nm::Complex64 a(const_cast<nm::RubyObject&>(obj));
  volatile nm::Complex128 b(const_cast<nm::RubyObject&>(obj));
}

} // end of extern "C" block


text:
package org.apache.commons.jcs3;

import org.apache.commons.jcs3.access.CacheAccess;

import junit.framework.TestCase;

/**
 * Runs a few thousand queries.
 */
public class JCSLightLoadUnitTest
    extends TestCase
{
    /** number to use for the test */
    private static final int items = 20000;

    /**
     * Test setup
     * @throws Exception
     */
    @Override
    public void setUp()
        throws Exception
    {
        JCS.setConfigFilename( "/TestSimpleLoad.ccf" );
        JCS.getInstance( "testCache1" );
    }

    /**
     * A unit test for JUnit
     * @throws Exception Description of the Exception
     */
    public void testSimpleLoad()
        throws Exception
    {
        final CacheAccess<String, String> jcs = JCS.getInstance( "testCache1" );
        //        ICompositeCacheAttributes cattr = jcs.getCacheAttributes();
        //        cattr.setMaxObjects( 20002 );
        //        jcs.setCacheAttributes( cattr );

        for ( int i = 1; i <= items; i++ )
        {
            jcs.put( i + ":key", "data" + i );
        }

        for ( int i = items; i > 0; i-- )
        {
            final String res = jcs.get( i + ":key" );
            assertNotNull( "[" + i + ":key] should not be null", res );
        }

        // test removal
        jcs.remove( "300:key" );
        assertNull( jcs.get( "300:key" ) );
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title></title>
<#include "/jeecms_sys/head.html"/>

<@s.m "global.position"/>: <@s.m "cmsComment.function"/> - <@s.m "global.list"/>

	<form class="ropt">
	</form>

<form id="tableForm" method="post">
<input type="hidden" name="pageNo" value="${pageNo!}"/>
<@p.table value=pagination;cmsComment,i,has_next><#rt/>
	<@p.column title="<input type='checkbox' onclick='Pn.checkbox(\"ids\",this.checked)'/>" width="25" align="center">
		<input type='checkbox' name='ids' value='${cmsComment.id}' onclick="Pn.selectCheckBox('${cmsComment.id}',this.checked)"/><#t/>
	</@p.column><#t/>
	<@p.column title="ID" align="center">${cmsComment.id}</@p.column><#t/>
	<@p.column code="cmsComment.text" align="center">
		<#if !cmsComment.checked>[<@s.m "cmsComment.uncheck"/>]
</#if>
		<#if cmsComment.recommend>[<@s.m "cmsComment.recommend"/>]</#if>
		${cmsComment.text?html}
		<#if cmsComment.reply??>
${cmsComment.reply?html}</#if>
	</@p.column><#t/>
	<@p.column code="cmsComment.doc" align="center">
		${cmsComment.content.title}
	</@p.column><#t/>
	<@p.column code="cmsComment.commentUser" align="center">
		<#if (cmsComment.commentUser.username)??>${cmsComment.commentUser.username}<#else><@s.m "cmsComment.anonymity"/></#if>

		${cmsComment.ip}
${cmsComment.createTime}
	</@p.column><#t/>
	<@p.column code="global.operate" align="center">
		<@s.m "global.edit"/> | <#rt/>
		<@s.m "global.delete"/><#t/>
	</@p.column><#t/>
</@p.table>

<input type="button" value="<@s.m "cmsGuestbook.checked"/>" onclick="optCheck();" class="check"/ style="float:left; border-right:1px solid #ffffff;">
<input type="button" class="cancellation-audit" value="<@s.m "cmsGuestbook.checked.cancel"/>" onclick="optCheckCancel();"/ style="float:left; border-right:1px solid #ffffff;">
<input class="del-button" type="button" value="<@s.m "global.delete"/>" onclick="optDelete();"/ style="float:left; border-right:1px solid #ffffff;">

</form>

<#include "/common/alert_message.html"/>


text:
<?php

/**
 * Statigram Widget Database Class
 *
 * @category Wordpress
 * @package  Statigram_Wordpress
 * @author   rydgel <gcc@statigr.am>
 * @author   gaetan <gaetan@statigr.am>
 * @license  GPLv2 http://www.gnu.org/licenses/gpl-2.0.html
 * @version  1.0.4
 * @link     http://statigr.am
 **/
class StatigramWidgetDb
{
    /**
     * Get the Statigram Widget Database Table Name
     *
     * @return string table name
     */
    public static function getTableName()
    {
        global $wpdb;
        return $wpdb->prefix . "statigram_widget";
    }

    /**
     * Create database table for widget
     *
     * call register_activation_hook(__FILE__,'dbInstall'); in activation plugin file
     *
     * @return null
     */
    public static function dbInstall()
    {
        $table_name = self::getTableName();

        $sql = "CREATE TABLE IF NOT EXISTS `$table_name` (
                `choice` enum('myfeed','hashtag') NOT NULL DEFAULT 'myfeed',
                `username` varchar(255) NOT NULL,
                `hashtag` varchar(255) NOT NULL DEFAULT 'statigram',
                `linking` enum('statigram','instagram') NOT NULL DEFAULT 'statigram',
                `show_infos` enum('true','false') NOT NULL DEFAULT 'true',
                `width` int(6) NOT NULL DEFAULT '380',
                `height` int(6) NOT NULL DEFAULT '420',
                `mode` enum('grid','slideshow') NOT NULL DEFAULT 'grid',
                `pace` int(6) NOT NULL DEFAULT '10',
                `layout_x` int(1) NOT NULL DEFAULT '3',
                `layout_y` int(1) NOT NULL DEFAULT '2',
                `padding` int(6) NOT NULL DEFAULT '10',
                `photo_border` enum('true','false') NOT NULL DEFAULT 'true',
                `background` varchar(6) NOT NULL DEFAULT 'FFFFFF',
                `text` varchar(6) NOT NULL DEFAULT '777777',
                `widget_border` enum('true','false') NOT NULL DEFAULT 'true',
                `radius` int(11) NOT NULL DEFAULT '5',
                `borderColor` varchar(6) NOT NULL DEFAULT 'DDDDDD',
                PRIMARY KEY (`choice`)
                );";

        include_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);

        self::dbInsert('username', 'statigram');
    }

    /**
     * Remove database table for widget
     *
     * call register_deactivation_hook(__FILE__,'dbRemove'); in activation plugin file
     *
     * @return null
     */
    public static function dbRemove()
    {
        global $wpdb;

        $table_name = self::getTableName();

        $sql = "DROP TABLE $table_name;";
        $wpdb->query($sql);
    }

    /**
     * Single update in database
     *
     * call register_activation_hook(__FILE__,'dbInsert'); in activation plugin file
     *
     * @param type $field field
     * @param type $value value
     *
     * @return null
     */
    public static function dbUpdateOneField($field, $value)
    {
        if (isset($field) && isset($value)) {
            global $wpdb;

            $table_name = self::getTableName();

            $querystr = "UPDATE $table_name SET `$field` =  '$value' ;";
            $wpdb->query($querystr);
        }
    }

    /**
     * Multiple update on the database
     *
     * @param array $postDatas Form data
     *
     * @return null
     */
    public static function dbUpdateMultiFields($postDatas)
    {
        if (isset($postDatas)) {
            self::dbUpdateOneField('choice', $postDatas['choice']);
            self::dbUpdateOneField('username', $postDatas['username']);
            if ($postDatas['show_infos'] == 'on') {
                self::dbUpdateOneField('show_infos', true);
            } else {
                self::dbUpdateOneField('show_infos', false);
            }
            self::dbUpdateOneField('hashtag', $postDatas['hashtag']);
            self::dbUpdateOneField('linking', $postDatas['linking']);
            self::dbUpdateOneField('width', $postDatas['width']);
            self::dbUpdateOneField('height', $postDatas['height']);
            self::dbUpdateOneField('mode', $postDatas['choose-mode']);
            self::dbUpdateOneField('layout_x', $postDatas['layout_x']);
            self::dbUpdateOneField('layout_y', $postDatas['layout_y']);
            self::dbUpdateOneField('padding', $postDatas['padding']);
            self::dbUpdateOneField('pace', $postDatas['pace']);
            if ($postDatas['photo_border'] == 'on') {
                self::dbUpdateOneField('photo_border', true);
            } else {
                self::dbUpdateOneField('photo_border', false);
            }
            self::dbUpdateOneField('background', $postDatas['background']);
            self::dbUpdateOneField('text', $postDatas['text']);
            if ($postDatas['widget_border'] == 'on') {
                self::dbUpdateOneField('widget_border', true);
            } else {
                self::dbUpdateOneField('widget_border', false);
            }
            self::dbUpdateOneField('radius', $postDatas['radius']);
            self::dbUpdateOneField('borderColor', $postDatas['border-color']);

            return true;
        } else {
            return false;
        }
    }

    /**
     * Mise à jour du champ $field avec la valeur $value
     *
     * @param type $field field
     * @param type $value value
     *
     * @global type $wpdb
     *
     * @return null
     */
    public static function dbInsert($field, $value)
    {
        if (isset($field) && isset($value)) {
            global $wpdb;

            $table_name = self::getTableName();

            $wpdb->insert($table_name, array("$field" => $value));
        }
    }

    /**
     * Get the data stored in database
     *
     * @return array widget datas
     */
    public static function getPluginValues()
    {
        global $wpdb;

        $table_name = self::getTableName();

        $querystr = "SELECT * FROM $table_name";

        $pluginValues = $wpdb->get_row($querystr, OBJECT);

        return $pluginValues;
    }

    /**
     * Parse values of database to build the iframe code
     *
     * @param array $pluginValues getPluginValues() data
     *
     * @return string iframe
     */
    public static function parseValues($pluginValues)
    {
        $values = array();
        foreach ($pluginValues as $key => $value) {

            if ($key === 'borderColor') {
                $values['border-color'] = $value;
                continue;
            }

            $values[$key] = $value;
        }

        if (!$values['username']) {
            unset($values['username']);
        }

        if (!$values['hashtag']) {
            unset($values['hashtag']);
        }

        $url = "http://statigr.am/widget.php?" . http_build_query($values);
        return '<iframe src="'.$url.'" allowTransparency="true" frameborder="0" scrolling="no" style="border:none; overflow:hidden; width:'.$values['width'].'px; height:'.$values['height'].'px;"></iframe>';
    }

    /**
     * Render iframe
     *
     * @return string
     */
    public static function renderIframe()
    {
        $pluginValues = self::getPluginValues();
        $value = StatigramWidgetDb::parseValues($pluginValues);

        return $value;
    }
}


text:
package com.team2502.robot2017.command.autonomous;

import com.team2502.robot2017.Robot;
import com.team2502.robot2017.subsystem.DriveTrainSubsystem;
import edu.wpi.first.wpilibj.command.Command;

@SuppressWarnings("WeakerAccess")
public class DriveTimeCommand extends Command
{
    private DriveTrainSubsystem driveTrain;
    private long runTime;
    private long startTime;

    /**
     * @param runTime Time to run for in milliseconds.
     */
    public DriveTimeCommand(long runTime)
    {
        requires(Robot.DRIVE_TRAIN);
        driveTrain = Robot.DRIVE_TRAIN;
        this.runTime = runTime;
    }

    /**
     * @param runTime Time to run for in seconds.
     */
    public DriveTimeCommand(double runTime)
    {
        this((long) (runTime * 1000));
    }

    @Override
    protected void initialize()
    {
        startTime = System.currentTimeMillis();
    }

    @Override
    protected void execute()
    {
        driveTrain.runMotors(1.0D, -1.0D);
    }

    @Override
    protected boolean isFinished()
    {
        return System.currentTimeMillis() - startTime > runTime;
    }

    @Override
    protected void end()
    {
        driveTrain.stop();
    }

    @Override
    protected void interrupted()
    {
        end();
    }
}


text:
<!doctype html>

<meta charset="utf-8">
<title>All Posts – 邵洪泉的博客</title>
<meta name="description" content="An archive of posts.">

<meta property="og:locale" content="zh_CN">
<meta property="og:type" content="article">
<meta property="og:title" content="All Posts">
<meta property="og:description" content="An archive of posts.">
<meta property="og:url" content="/posts/">
<meta property="og:site_name" content="邵洪泉的博客">
<meta property="og:image" content="/images/images/logo.png">

<link rel="canonical" href="/posts/">
<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="邵洪泉的博客 Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>

<link rel="stylesheet" href="/assets/css/main.css">
<link rel="stylesheet" href="/assets/css/jquery.mmenu.all.css">
<link rel="stylesheet" href="/assets/css/jquery.floating-social-share.min.css">

<link href="//fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic" rel="stylesheet" type="text/css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="/favicon.ico">

<link rel="shortcut icon" href="/favicon.png">

<link rel="apple-touch-icon-precomposed" href="/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/images/apple-touch-icon-144x144-precomposed.png">

           邵洪泉的博客

关于我

分类

首页

All Posts

<time> </time>

首页

分类

关于我

2017

Build Blog

2016

MySQL查询优化

MySQL索引优化

MySQL存储优化

PHP7新特性总结

    © 2017 邵洪泉. Powered by Jekyll using the Neo-HPSTR Theme.


text:
#region License

#endregion

using Apache.NMS;

namespace Spring.Messaging.Nms.Core
{
    ///  Perform operations on the given Session and MessageProducer.
    /// The message producer is not associated with any destination.
    ///
    /// <param name="session">the NMS Session object to use
    /// </param>
    /// <param name="producer">the NMS MessageProducer object to use
    /// </param>
    /// <returns> a result object from working with the Session, if any (can be null)
    /// </returns>
    public delegate object ProducerDelegate(ISession session, IMessageProducer producer);

}


text:
package io.latent.storm.rabbitmq.config;

import java.util.Map;

public class ConfigUtils
{
  public static String getFromMap(String key, Map<String, Object> map) {
    return map.get(key).toString();
  }

  public static String getFromMap(String key, Map<String, Object> map, String defaultValue) {
    Object value = map.get(key);
    if (value==null) return defaultValue;
    return map.get(key).toString();
  }

  public static int getFromMapAsInt(String key, Map<String, Object> map) {
    return Integer.valueOf(map.get(key).toString());
  }

  public static int getFromMapAsInt(String key, Map<String, Object> map, int defaultValue) {
    Object value = map.get(key);
    if (value==null) return defaultValue;
    return Integer.valueOf(map.get(key).toString());
  }

  public static boolean getFromMapAsBoolean(String key, Map<String, Object> map) {
    return Boolean.valueOf(map.get(key).toString());
  }

  public static boolean getFromMapAsBoolean(String key, Map<String, Object> map, boolean defaultValue) {
    Object value = map.get(key);
    if (value==null) return defaultValue;
    return Boolean.valueOf(map.get(key).toString());
  }

  public static void addToMap(String key, Map<String, Object> map, String value) {
    map.put(key, value);
  }

  public static void addToMap(String key, Map<String, Object> map, int value) {
    map.put(key, Integer.toString(value));
  }

  public static void addToMap(String key, Map<String, Object> map, boolean value) {
    map.put(key, Boolean.toString(value));
  }
}


text:
{#-
  This file was automatically generated - do not edit
-#}
{% macro t(key) %}{{ {
  "language": "ro",
  "clipboard.copy": "Copiază în clipboard",
  "clipboard.copied": "Copiat în clipboard",
  "edit.link.title": "Editeaza această pagină",
  "footer.previous": "Anterior",
  "footer.next": "Următor",
  "meta.comments": "Comentarii",
  "meta.source": "Sursă",
  "search.config.lang": "ro",
  "search.placeholder": "Căutare",
  "search.result.placeholder": "Tastează pentru a începe căutarea",
  "search.result.none": "Nu a fost găsit niciun document",
  "search.result.one": "1 document găsit",
  "search.result.other": "# documente găsite",
  "skip.link.title": "Sari la conținut",
  "source.link.title": "Accesează repository-ul",
  "source.revision.date": "Ultima actualizare",
  "toc.title": "Cuprins"
}[key] }}{% endmacro %}


text:
namespace NTwitch
{
    public interface ITokenInfo
    {
        bool IsValid { get; }
        string Token { get; }
        string Username { get; }
        string ClientId { get; }
        ulong UserId { get; }
        IAuthorization Authorization { get; }
    }
}


text:
title: OnClientResizeStart
page_title: OnClientResizeStart | RadDock for ASP.NET AJAX Documentation
description: OnClientResizeStart
slug: dock/client-side-programming/events/onclientresizestart
tags: onclientresizestart
published: True
position: 8
---

# OnClientResizeStart

The client-side event **OnClientResizeStart** fires when the RadDock's property **Resizable** is set to **true** and its resizing has started.

The event handler receives a single parameter: the instance of the RadDock control that is being resized.

The following example uses the **OnClientResizeStart** event handler to update a label when a resize operation starts:

````ASP.NET
<script type="text/javascript">
	function OnClientResizeStart(dock) {
		var label = document.getElementById("<%= lblMessage.ClientID %>");
		var now = new Date();
		var timeStr = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
		label.innerHTML = "The resizing of the RadDock with ID " + dock.get_uniqueID() + " started at " + timeStr + ".";
	}
</script>
<telerik:RadDockLayout ID="RadDockLayout1" runat="server">
	<telerik:RadDockZone ID="RadDockZone1" runat="server" Height="200px" Width="200px">
		<telerik:RadDock ID="RadDock1" runat="server" Resizable="true" OnClientResizeStart="OnClientResizeStart"
			Height="100px" Width="200px" />
	</telerik:RadDockZone>
</telerik:RadDockLayout>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
````

# See Also

 * [OnClientResizeEnd]({%slug dock/client-side-programming/events/onclientresizeend%})


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

<title>CellValue (POI API Documentation)</title>
<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 |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

org.apache.poi.ss.usermodel

Class CellValue

java.lang.Object

org.apache.poi.ss.usermodel.CellValue

public final class CellValue
extends java.lang.Object

Mimics the 'data view' of a cell. This allows formula evaluator
 to return a CellValue instead of precasting the value to String
 or Number or boolean type.

Author:

Amol S. Deshmukh < amolweb at ya hoo dot com >

Field Summary

Fields

Modifier and Type
Field and Description

static CellValue
FALSE

static CellValue
TRUE

Constructor Summary

Constructors

Constructor and Description

CellValue(double numberValue)

CellValue(java.lang.String stringValue)

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
formatAsString()

boolean
getBooleanValue()

int
getCellType()

static CellValue
getError(int errorCode)

byte
getErrorValue()

double
getNumberValue()

java.lang.String
getStringValue()

java.lang.String
toString()

static CellValue
valueOf(boolean booleanValue)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

TRUE

public static final CellValue TRUE

FALSE

public static final CellValue FALSE

Constructor Detail

CellValue

public CellValue(double numberValue)

CellValue

public CellValue(java.lang.String stringValue)

Method Detail

valueOf

public static CellValue valueOf(boolean booleanValue)

getError

public static CellValue getError(int errorCode)

getBooleanValue

public boolean getBooleanValue()

Returns:

Returns the booleanValue.

getNumberValue

public double getNumberValue()

Returns:

Returns the numberValue.

getStringValue

public java.lang.String getStringValue()

Returns:

Returns the stringValue.

getCellType

public int getCellType()

Returns:

Returns the cellType.

getErrorValue

public byte getErrorValue()

Returns:

Returns the errorValue.

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

formatAsString

public java.lang.String formatAsString()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

                Copyright 2014 The Apache Software Foundation or
        its licensors, as applicable.


text:
DEFINE_NS_MEDIA_GAMING

namespace Controls
{
	///<summary>Ö¡¶¯» Image</summary>
	[Windows::Foundation::Metadata::WebHostHiddenAttribute]
	public ref class FrameAnimationImage sealed : public Windows::UI::Xaml::Controls::UserControl
	{
	public:
		static property Windows::UI::Xaml::DependencyProperty^ SourceProperty
		{
			Windows::UI::Xaml::DependencyProperty^ get() { return _sourceProperty; }
		}

		static property Windows::UI::Xaml::DependencyProperty^ CurrentFrameProperty
		{
			Windows::UI::Xaml::DependencyProperty^ get() { return _currentFrameProperty; }
		}

		static property Windows::UI::Xaml::DependencyProperty^ FrameSizeProperty
		{
			Windows::UI::Xaml::DependencyProperty^ get() { return _frameSizeProperty; }
		}

		static property Windows::UI::Xaml::DependencyProperty^ FramesCountProperty
		{
			Windows::UI::Xaml::DependencyProperty^ get() { return _framesCountProperty; }
		}

		static property Windows::UI::Xaml::DependencyProperty^ ColumnsCountProperty
		{
			Windows::UI::Xaml::DependencyProperty^ get() { return _columnsCountProperty; }
		}

		static property Windows::UI::Xaml::DependencyProperty^ AutoPlayProperty
		{
			Windows::UI::Xaml::DependencyProperty^ get() { return _autoPlayProperty; }
		}

		static property Windows::UI::Xaml::DependencyProperty^ IsLoopingProperty
		{
			Windows::UI::Xaml::DependencyProperty^ get() { return _isLoopingProperty; }
		}

		static property Windows::UI::Xaml::DependencyProperty^ CurrentFrameIndexProperty
		{
			Windows::UI::Xaml::DependencyProperty^ get() { return _currentFrameIndexProperty; }
		}

		static property Windows::UI::Xaml::DependencyProperty^ FrameRateProperty
		{
			Windows::UI::Xaml::DependencyProperty^ get() { return _frameRateProperty; }
		}

		static property Windows::UI::Xaml::DependencyProperty^ StartFrameProperty
		{
			Windows::UI::Xaml::DependencyProperty^ get() { return _startFrameProperty; }
		}

		static property Windows::UI::Xaml::DependencyProperty^ EndFrameProperty
		{
			Windows::UI::Xaml::DependencyProperty^ get() { return _endFrameProperty; }
		}

		static property Windows::UI::Xaml::DependencyProperty^ IsPlayingProperty
		{
			Windows::UI::Xaml::DependencyProperty^ get() { return _isPlayingProperty; }
		}
	public:
		property Microsoft::Graphics::Canvas::CanvasBitmap^ Source
		{
			Microsoft::Graphics::Canvas::CanvasBitmap^ get();
			void set(Microsoft::Graphics::Canvas::CanvasBitmap^ value);
		}

		property Windows::UI::Xaml::Media::ImageSource^ CurrentFrame
		{
			Windows::UI::Xaml::Media::ImageSource^ get();
		private: void set(Windows::UI::Xaml::Media::ImageSource^ value);
		}

		property Windows::Foundation::Size FrameSize
		{
			Windows::Foundation::Size get();
			void set(Windows::Foundation::Size value);
		}

		property int FramesCount
		{
			int get();
			void set(int value);
		}

		property int ColumnsCount
		{
			int get();
			void set(int value);
		}

		property bool AutoPlay
		{
			bool get();
			void set(bool value);
		}

		property bool IsLooping
		{
			bool get();
			void set(bool value);
		}

		property int CurrentFrameIndex
		{
			int get();
			void set(int value);
		}

		property double FrameRate
		{
			double get();
			void set(double value);
		}

		property int StartFrame
		{
			int get();
			void set(int value);
		}

		property int EndFrame
		{
			int get();
			void set(int value);
		}

		property bool IsPlaying
		{
			bool get();
			void set(bool value);
		}

		FrameAnimationImage();

		void Play();
		void Stop();

		event Windows::Foundation::EventHandler<Windows::UI::Xaml::RoutedEventArgs^>^ AnimationEnded;
	private:
		property Microsoft::Graphics::Canvas::UI::Xaml::CanvasImageSource^ RenderTarget
		{
			Microsoft::Graphics::Canvas::UI::Xaml::CanvasImageSource^ get();
			void set(Microsoft::Graphics::Canvas::UI::Xaml::CanvasImageSource^ value);
		}

		void InitializeComponents();
		void ResetSource(Microsoft::Graphics::Canvas::CanvasBitmap^ source);
		void OnAnimationTick(Platform::Object ^sender, Platform::Object ^args);
		void OnLoaded(Platform::Object ^sender, Windows::UI::Xaml::RoutedEventArgs ^e);
		void OnAnimationEnded();
		void SetFrameRate(double value);
		void DrawNextFrame(bool advance = true);

		static void OnSourcePropertyChanged(Windows::UI::Xaml::DependencyObject^ sender, Windows::UI::Xaml::DependencyPropertyChangedEventArgs^ e);
		static void OnFrameRatePropertyChanged(Windows::UI::Xaml::DependencyObject^ sender, Windows::UI::Xaml::DependencyPropertyChangedEventArgs^ e);
		static void OnCurrentFrameIndexPropertyChanged(Windows::UI::Xaml::DependencyObject^ sender, Windows::UI::Xaml::DependencyPropertyChangedEventArgs^ e);
		static void OnIsPlayingPropertyChanged(Windows::UI::Xaml::DependencyObject^ sender, Windows::UI::Xaml::DependencyPropertyChangedEventArgs^ e);
	private:
		Windows::UI::Xaml::Controls::Image^ _framePresenter;
		Windows::UI::Xaml::DispatcherTimer^ _animationTimer;
		static Windows::UI::Xaml::DependencyProperty^ _sourceProperty;
		static Windows::UI::Xaml::DependencyProperty^ _currentFrameProperty;
		static Windows::UI::Xaml::DependencyProperty^ _frameSizeProperty;
		static Windows::UI::Xaml::DependencyProperty^ _framesCountProperty;
		static Windows::UI::Xaml::DependencyProperty^ _columnsCountProperty;
		static Windows::UI::Xaml::DependencyProperty^ _autoPlayProperty;
		static Windows::UI::Xaml::DependencyProperty^ _isLoopingProperty;
		static Windows::UI::Xaml::DependencyProperty^ _currentFrameIndexProperty;
		static Windows::UI::Xaml::DependencyProperty^ _frameRateProperty;
		static Windows::UI::Xaml::DependencyProperty^ _startFrameProperty;
		static Windows::UI::Xaml::DependencyProperty^ _endFrameProperty;
		static Windows::UI::Xaml::DependencyProperty^ _isPlayingProperty;

		bool _isLoaded = false;
		bool _hasResource = false;
		bool _isPlaying = false;
		int _presentFrameIndex = -1;
		int _nextFrameIndex = -1;
};
}

END_NS_MEDIA_GAMING


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<title>Python: module __init__</title>

<big><big>__init__</big></big> (version 0.6)	index
/home/berend/project/pydelicious/trunk/pydelicious/__init__.py

<tt>Library to access del.icio.us data via Python.

An introduction to the project is given in the README.

pydelicious is released under the FreeBSD License.

See license.txt for details and the copyright holders.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND

ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED

WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE

DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR

ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES

(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;

LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON

ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT

(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS

SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</tt>

<big>Modules</big>

<tt>      </tt>

datetime

feedparser

httplib

	locale

os

socket

	sys

time

urllib2

<big>Classes</big>

<tt>      </tt>

DeliciousAPI

exceptions.Exception(exceptions.BaseException)

DeliciousError

DeliciousItemExistsError

PyDeliciousException

PyDeliciousThrottled

PyDeliciousUnauthorized

urllib2.HTTPDefaultErrorHandler(urllib2.BaseHandler)

DeliciousHTTPErrorHandler

class DeliciousAPI

<tt>   </tt>
<tt>A single-user Python facade to the del.icio.us HTTP API.

See http://delicious.com/help/api.

Methods ``request`` and ``request_raw`` represent the core. For all API

paths there are furthermore methods (e.g. posts_add for 'posts/all') with

an explicit declaration of parameters and documentation.
 </tt>

Methods defined here:

__init__(self, user, passwd, codec='UTF-8', api_request=<function dlcs_api_request>, xml_parser=<function dlcs_parse_xml>, build_opener=<function dlcs_api_opener>, encode_params=<function dlcs_encode_params>, encoded=False)

<tt>Initialize access to the API for ``user`` with ``passwd``.

``codec`` sets the encoding of the arguments, which defaults to the

users preferred locale.

The ``api_request`` and ``xml_parser`` parameters by default point to

functions within this package with standard implementations which

request and parse a resource. See ``dlcs_api_request()`` and

``dlcs_parse_xml()``.

Parameter ``build_opener`` is a callable that, provided with the

credentials, should build a urllib2 opener for the delicious API server

with HTTP authentication. See ``dlcs_api_opener()`` for the default

implementation.

``encode_params`` finally preprocesses API parameters before

they are passed to ``api_request``.</tt>

__repr__(self)

bundles_all(self, **kwds)

<tt>Retrieve user bundles from del.icio.us.

::

    <bundles>

        <bundel name="..." tags=..."></tt>

bundles_delete(self, bundle, **kwds)

<tt>Delete a bundle from del.icio.us. Returns a `result` message or

raises an ``DeliciousError``. See ``request()``.

&bundle (required)

    the bundle name.</tt>

bundles_set(self, bundle, tags, **kwds)

<tt>Assign a set of tags to a single bundle, wipes away previous

settings for bundle. Returns a `result` messages or raises an

``DeliciousError``. See ``request()``.

&bundle (required)

    the bundle name.

&tags (required)

    list of tags.</tt>

get_method(self, path)

get_url(self, url)

<tt>Return the del.icio.us url at which the HTML page with posts for

``url`` can be found.</tt>

posts_add(self, url, description, extended='', tags='', dt='', replace=False, shared=True, **kwds)

<tt>Add a post to del.icio.us. Returns a `result` message or raises an

``DeliciousError``. See ``request()``.

&url (required)

    the url of the item.

&description (required)

    the description of the item.

&extended (optional)

    notes for the item.

&tags (optional)

    tags for the item (space delimited).

&dt (optional)

    datestamp of the item (format "CCYY-MM-DDThh:mm:ssZ").

    Requires a LITERAL "T" and "Z" like in ISO8601 at

    http://www.cl.cam.ac.uk/~mgk25/iso-time.html for example:

    "1984-09-01T14:21:31Z"

&replace=no (optional) - don't replace post if given url has already

    been posted.

&shared=yes (optional) - wether the item is public.</tt>

posts_all(self, tag='', start=None, results=None, fromdt=None, todt=None, meta=True, hashes=False, **kwds)

<tt>Returns all posts. Please use sparingly. Call the `posts_update`

method to see if you need to fetch this at all.

::

    <posts tag="..." user="..." update="CCYY-MM-DDThh:mm:ssZ">

        <post ...>

&tag

    (optional) Filter by this tag.

&start={#}

    (optional) Start returning posts this many results into the set.

&results={#}

    (optional) Return this many results.

&fromdt={CCYY-MM-DDThh:mm:ssZ}

    (optional) Filter for posts on this date or later

&todt={CCYY-MM-DDThh:mm:ssZ}

    (optional) Filter for posts on this date or earlier

&meta=yes

    (optional) Include change detection signatures on each item in a

    'meta' attribute. Clients wishing to maintain a synchronized local

    store of bookmarks should retain the value of this attribute - its

    value will change when any significant field of the bookmark

    changes.

&hashes

    (optional, exclusive) Do not fetch post details but a posts

    manifest with url- and meta-hashes. Other options do not apply.</tt>

posts_dates(self, tag='', **kwds)

<tt>Returns a list of dates with the number of posts at each date.

::

    <dates>

        <date date="CCYY-MM-DD" count="888">

&tag={TAG}

    (optional) Filter by this tag</tt>

posts_delete(self, url, **kwds)

<tt>Delete a post from del.icio.us. Returns a `result` message or

raises an ``DeliciousError``. See ``request()``.

&url (required)

    the url of the item.</tt>

posts_get(self, tag='', dt='', url='', hashes=[], meta=True, **kwds)

<tt>Returns posts matching the arguments. If no date or url is given,

most recent date will be used.

::

    <posts dt="CCYY-MM-DD" tag="..." user="...">

        <post ...>

&tag={TAG} {TAG} ... {TAG}

    (optional) Filter by this/these tag(s).

&dt={CCYY-MM-DDThh:mm:ssZ}

    (optional) Filter by this date, defaults to the most recent date on

    which bookmarks were saved.

&url={URL}

    (optional) Fetch a bookmark for this URL, regardless of date.

&hashes={MD5} {MD5} ... {MD5}

    (optional) Fetch multiple bookmarks by one or more URL MD5s

    regardless of date.

&meta=yes

    (optional) Include change detection signatures on each item in a

    'meta' attribute. Clients wishing to maintain a synchronized local

    store of bookmarks should retain the value of this attribute - its

    value will change when any significant field of the bookmark

    changes.</tt>

posts_recent(self, tag='', count='', **kwds)

<tt>Returns a list of the most recent posts, filtered by argument.

::

    <posts tag="..." user="...">

        <post ...>

&tag={TAG}

    (optional) Filter by this tag.

&count={1..100}

    (optional) Number of items to retrieve (Default:15, Maximum:100).</tt>

posts_update(self, **kwds)

<tt>Returns the last update time for the user. Use this before calling

`posts_all` to see if the data has changed since the last fetch.

::

    <update time="CCYY-MM-DDThh:mm:ssZ"></tt>

request(self, path, _raw=False, **params)

<tt>Sends a request message to `path` in the API, and parses the results

from XML. Use with ``_raw=True`` or ``call request_raw()`` directly

to get the filehandler and process the response message manually.

Calls to some paths will return a `result` message, i.e.::

    <result code="..." />

or::

    <result>...</result>

These should all be parsed to ``{'result':(Boolean, MessageString)}``,

this method raises a ``DeliciousError`` on negative `result` answers.

Positive answers are silently accepted and nothing is returned.

Using ``_raw=True`` bypasses all parsing and never raises

``DeliciousError``.

See ``dlcs_parse_xml()`` and ``request_raw()``.</tt>

request_raw(self, path, **params)

<tt>Calls the path in the API, returns the filehandle. Returned file-

like instances have an ``HTTPMessage`` instance with HTTP header

information available. Use ``filehandle.info()`` or refer to the

``urllib2.openurl`` documentation.</tt>

tags_delete(self, tag, **kwds)

<tt>Delete an existing tag.

&tag={TAG}

    (required) Tag to delete</tt>

tags_get(self, **kwds)

<tt>Returns a list of tags and the number of times it is used by the

user.

::

    <tags>

        <tag tag="TagName" count="888"></tt>

tags_rename(self, old, new, **kwds)

<tt>Rename an existing tag with a new tag name. Returns a `result`

message or raises an ``DeliciousError``. See ``request()``.

&old={TAG}

    (required) Tag to rename.

&new={TAG}

    (required) New tag name.</tt>

Data and other attributes defined here:

paths = {'posts/add': 'posts_add', 'posts/all': 'posts_all', 'posts/dates': 'posts_dates', 'posts/delete': 'posts_delete', 'posts/get': 'posts_get', 'posts/recent': 'posts_recent', 'posts/update': 'posts_update', 'tags/bundles/all': 'bundles_all', 'tags/bundles/delete': 'bundles_delete', 'tags/bundles/set': 'bundles_set', ...}

class DeliciousError(exceptions.Exception)

<tt>   </tt>
<tt>Raised when the server responds with a negative answer
 </tt>

Method resolution order:

DeliciousError

exceptions.Exception

exceptions.BaseException

__builtin__.object

Static methods defined here:

raiseFor(error_string, path, **params)

Data descriptors defined here:

__weakref__

<tt>list of weak references to the object (if defined)</tt>

Methods inherited from exceptions.Exception:

__init__(...)

<tt>x.__init__(...) initializes x; see x.__class__.__doc__ for signature</tt>

Data and other attributes inherited from exceptions.Exception:

__new__ = <built-in method __new__ of type object>
<tt>T.__new__(S, ...) -> a new object with type S, a subtype of T</tt>

Methods inherited from exceptions.BaseException:

__delattr__(...)

<tt>x.__delattr__('name') <==> del x.name</tt>

__getattribute__(...)

<tt>x.__getattribute__('name') <==> x.name</tt>

__getitem__(...)

<tt>x.__getitem__(y) <==> x[y]</tt>

__getslice__(...)

<tt>x.__getslice__(i, j) <==> x[i:j]

Use of negative indices is not supported.</tt>

__reduce__(...)

__repr__(...)

<tt>x.__repr__() <==> repr(x)</tt>

__setattr__(...)

<tt>x.__setattr__('name', value) <==> x.name = value</tt>

__setstate__(...)

__str__(...)

<tt>x.__str__() <==> str(x)</tt>

__unicode__(...)

Data descriptors inherited from exceptions.BaseException:

__dict__

args

message

class DeliciousHTTPErrorHandler(urllib2.HTTPDefaultErrorHandler)

<tt>   </tt>

Method resolution order:

DeliciousHTTPErrorHandler

urllib2.HTTPDefaultErrorHandler

urllib2.BaseHandler

Methods defined here:

http_error_401(self, req, fp, code, msg, headers)

http_error_503(self, req, fp, code, msg, headers)

Methods inherited from urllib2.HTTPDefaultErrorHandler:

http_error_default(self, req, fp, code, msg, hdrs)

Methods inherited from urllib2.BaseHandler:

__lt__(self, other)

add_parent(self, parent)

close(self)

Data and other attributes inherited from urllib2.BaseHandler:

handler_order = 500

class DeliciousItemExistsError(DeliciousError)

<tt>   </tt>
<tt>Raised then adding an already existing post.
 </tt>

Method resolution order:

DeliciousItemExistsError

DeliciousError

exceptions.Exception

exceptions.BaseException

__builtin__.object

Static methods inherited from DeliciousError:

raiseFor(error_string, path, **params)

Data descriptors inherited from DeliciousError:

__weakref__

<tt>list of weak references to the object (if defined)</tt>

Methods inherited from exceptions.Exception:

__init__(...)

<tt>x.__init__(...) initializes x; see x.__class__.__doc__ for signature</tt>

Data and other attributes inherited from exceptions.Exception:

__new__ = <built-in method __new__ of type object>
<tt>T.__new__(S, ...) -> a new object with type S, a subtype of T</tt>

Methods inherited from exceptions.BaseException:

__delattr__(...)

<tt>x.__delattr__('name') <==> del x.name</tt>

__getattribute__(...)

<tt>x.__getattribute__('name') <==> x.name</tt>

__getitem__(...)

<tt>x.__getitem__(y) <==> x[y]</tt>

__getslice__(...)

<tt>x.__getslice__(i, j) <==> x[i:j]

Use of negative indices is not supported.</tt>

__reduce__(...)

__repr__(...)

<tt>x.__repr__() <==> repr(x)</tt>

__setattr__(...)

<tt>x.__setattr__('name', value) <==> x.name = value</tt>

__setstate__(...)

__str__(...)

<tt>x.__str__() <==> str(x)</tt>

__unicode__(...)

Data descriptors inherited from exceptions.BaseException:

__dict__

args

message

class PyDeliciousException(exceptions.Exception)

<tt>   </tt>
<tt>Standard pydelicious error
 </tt>

Method resolution order:

PyDeliciousException

exceptions.Exception

exceptions.BaseException

__builtin__.object

Data descriptors defined here:

__weakref__

<tt>list of weak references to the object (if defined)</tt>

Methods inherited from exceptions.Exception:

__init__(...)

<tt>x.__init__(...) initializes x; see x.__class__.__doc__ for signature</tt>

Data and other attributes inherited from exceptions.Exception:

__new__ = <built-in method __new__ of type object>
<tt>T.__new__(S, ...) -> a new object with type S, a subtype of T</tt>

Methods inherited from exceptions.BaseException:

__delattr__(...)

<tt>x.__delattr__('name') <==> del x.name</tt>

__getattribute__(...)

<tt>x.__getattribute__('name') <==> x.name</tt>

__getitem__(...)

<tt>x.__getitem__(y) <==> x[y]</tt>

__getslice__(...)

<tt>x.__getslice__(i, j) <==> x[i:j]

Use of negative indices is not supported.</tt>

__reduce__(...)

__repr__(...)

<tt>x.__repr__() <==> repr(x)</tt>

__setattr__(...)

<tt>x.__setattr__('name', value) <==> x.name = value</tt>

__setstate__(...)

__str__(...)

<tt>x.__str__() <==> str(x)</tt>

__unicode__(...)

Data descriptors inherited from exceptions.BaseException:

__dict__

args

message

class PyDeliciousThrottled(exceptions.Exception)

<tt>   </tt>

Method resolution order:

PyDeliciousThrottled

exceptions.Exception

exceptions.BaseException

__builtin__.object

Data descriptors defined here:

__weakref__

<tt>list of weak references to the object (if defined)</tt>

Methods inherited from exceptions.Exception:

__init__(...)

<tt>x.__init__(...) initializes x; see x.__class__.__doc__ for signature</tt>

Data and other attributes inherited from exceptions.Exception:

__new__ = <built-in method __new__ of type object>
<tt>T.__new__(S, ...) -> a new object with type S, a subtype of T</tt>

Methods inherited from exceptions.BaseException:

__delattr__(...)

<tt>x.__delattr__('name') <==> del x.name</tt>

__getattribute__(...)

<tt>x.__getattribute__('name') <==> x.name</tt>

__getitem__(...)

<tt>x.__getitem__(y) <==> x[y]</tt>

__getslice__(...)

<tt>x.__getslice__(i, j) <==> x[i:j]

Use of negative indices is not supported.</tt>

__reduce__(...)

__repr__(...)

<tt>x.__repr__() <==> repr(x)</tt>

__setattr__(...)

<tt>x.__setattr__('name', value) <==> x.name = value</tt>

__setstate__(...)

__str__(...)

<tt>x.__str__() <==> str(x)</tt>

__unicode__(...)

Data descriptors inherited from exceptions.BaseException:

__dict__

args

message

class PyDeliciousUnauthorized(exceptions.Exception)

<tt>   </tt>

Method resolution order:

PyDeliciousUnauthorized

exceptions.Exception

exceptions.BaseException

__builtin__.object

Data descriptors defined here:

__weakref__

<tt>list of weak references to the object (if defined)</tt>

Methods inherited from exceptions.Exception:

__init__(...)

<tt>x.__init__(...) initializes x; see x.__class__.__doc__ for signature</tt>

Data and other attributes inherited from exceptions.Exception:

__new__ = <built-in method __new__ of type object>
<tt>T.__new__(S, ...) -> a new object with type S, a subtype of T</tt>

Methods inherited from exceptions.BaseException:

__delattr__(...)

<tt>x.__delattr__('name') <==> del x.name</tt>

__getattribute__(...)

<tt>x.__getattribute__('name') <==> x.name</tt>

__getitem__(...)

<tt>x.__getitem__(y) <==> x[y]</tt>

__getslice__(...)

<tt>x.__getslice__(i, j) <==> x[i:j]

Use of negative indices is not supported.</tt>

__reduce__(...)

__repr__(...)

<tt>x.__repr__() <==> repr(x)</tt>

__setattr__(...)

<tt>x.__setattr__('name', value) <==> x.name = value</tt>

__setstate__(...)

__str__(...)

<tt>x.__str__() <==> str(x)</tt>

__unicode__(...)

Data descriptors inherited from exceptions.BaseException:

__dict__

args

message

<big>Functions</big>

<tt>      </tt>

add(user, passwd, url, description, tags='', extended='', dt=None, replace=False)

<tt>Add a post for user.</tt>

apiNew(user, passwd)

<tt>Creates a new DeliciousAPI object, requires user(name) and passwd.</tt>

build_api_opener(host, user, passwd, extra_handlers=())

<tt>Build a urllib2 style opener with HTTP Basic authorization for one host

and additional error handling. If HTTP_PROXY is set a proxyhandler is also

added.</tt>

delete(user, passwd, url)

<tt>Delete the URL from the del.icio.us account.</tt>

delicious_datetime(str)

<tt>Parse a ISO 8601 formatted string to a Python datetime ...</tt>

dict0(d)

<tt>Removes empty string values from dictionary</tt>

dlcs_api_opener(user, passwd)

<tt>Build an opener for DLCS_API_HOST, see build_api_opener()</tt>

dlcs_api_request(path, params=None, user='', passwd='', throttle=True, opener=None)

<tt>Retrieve/query a path within the del.icio.us API.

This implements a minimum interval between calls to avoid

throttling. [#]_ Use param 'throttle' to turn this behaviour off.

.. [#] http://del.icio.us/help/api/</tt>

dlcs_encode_params(params, usercodec='UTF-8', encoded=False)

<tt>Turn all param values (int, list, bool) into utf8 encoded strings.</tt>

dlcs_feed(name_or_url, url_map={'alerts': '%(format)s/alerts', 'hotlist': '%(format)s', 'popular': '%(format)s/popular', 'popular_tagged': '%(format)s/popular/%(tag)s', 'recent': '%(format)s/recent', 'tagged': '%(format)s/tag/%(tag)s', 'url': '%(format)s/url/%(urlmd5)s', 'urlinfo': 'json/urlinfo/%(urlmd5)s', 'user': '%(format)s/%(username)s', 'user_inbox': '%(format)s/inbox/%(username)s?private=%(key)s', ...}, count=15, **kwds)

<tt>Request and parse a feed.

Count should be between 1 and 100, default 15.

Format values include 'rss' and 'json', defaults to json.

- http://www.delicious.com/help/feeds</tt>

dlcs_parse_xml(data, split_tags=False)

<tt>Parse any del.icio.us XML document and return Python data structure.

Recognizes all XML document formats as returned by the version 1 API and

translates to a JSON-like data structure (dicts 'n lists).

Returned instance is always a dictionary. Examples::

 {'posts': [{'url':'...','hash':'...',},],}

 {'tags':['tag1', 'tag2',]}

 {'dates': [{'count':'...','date':'...'},], 'tag':'', 'user':'...'}

 {'result':(True, "done")}

 # etcetera.</tt>

dlcs_rss_request(tag='', popular=0, user='', url='')

<tt>Parse a RSS request, old style.

This requests old (now undocumented?) URL paths that still seem to work.

- http://del.icio.us/rss/url/{urimd5}

- http://del.icio.us/rss/{user}/{tag}

- http://del.icio.us/rss/{user}

- http://del.icio.us/rss

- http://del.icio.us/rss/tag/{tag}

- http://del.icio.us/rss/popular

- http://del.icio.us/rss/popular/{tag}</tt>

get(user, passwd, tag='', dt=None, count=0, hashes=[])

<tt>Returns a list of posts for the user using the API.</tt>

get_all(user, passwd, tag='', start=0, results=100, fromdt=None, todt=None)

<tt>Returns a list with all posts. Please use sparingly. See `get_updated`</tt>

get_popular(tag='')

<tt>parse RSS for popular URLS for tag</tt>

get_tagposts(tag)

<tt>parse RSS for tag</tt>

get_tags(user, passwd)

<tt>Returns a list with all tags for user.</tt>

get_update(user, passwd)

<tt>Returns the last update time for the user.</tt>

get_urlposts(url)

<tt>parse RSS for URL</tt>

get_userposts(user)

<tt>parse RSS for user</tt>

getfeed(name, **params)

getrss(tag='', popular=0, url='', user='')

<tt>Get posts from del.icio.us via parsing RSS.

tag (opt) sort by tag

popular (opt) look for the popular stuff

user (opt) get the posts by a user, this striks popular

url (opt) get the posts by url</tt>

http_request(url, user_agent='pydelicious/0.6 http://code.google.com/p/pydelicious/', retry=4, opener=None)

<tt>Retrieve the contents referenced by the URL using urllib2.

Retries up to four times (default) on exceptions.</tt>

json_fans(user, raw=True, callback=None)

<tt>callback=NAME       wrap the object definition in a function call NAME(...)

?raw                a pure JSON object is returned, instead of an object named

                    Delicious.</tt>

json_network(user, raw=True, callback=None)

<tt>callback=NAME       wrap the object definition in a function call NAME(...)

?raw                a raw JSON object is returned, instead of an object named

                    Delicious.posts</tt>

json_tags(user, atleast, count, sort='alpha', raw=True, callback=None)

<tt>user

atleast=###         include only tags for which there are at least ###

                    number of posts.

count=###           include ### tags, counting down from the top.

sort={alpha|count}  construct the object with tags in alphabetic order

                    (alpha), or by count of posts (count).

callback=NAME       wrap the object definition in a function call NAME(...),

                    thus invoking that function when the feed is executed.

raw                 a pure JSON object is returned, instead of code that

                    will construct an object named Delicious.tags.</tt>

md5 = openssl_md5(...)

<tt>Returns a md5 hash object; optionally initialized with a string</tt>

rename_tag(user, passwd, oldtag, newtag)

<tt>Rename the tag for the del.icio.us account.</tt>

user_posts(user=None, tag=None, key=None, **params)

<tt>Bookmarks for a specific user:

    {format}/{username}

Private bookmarks for a specific user:

    {format}/{username}?private={key}

Bookmarks for a specific user by tag(s):

    {format}/{username}/{tag[+tag+...+tag]}

Private bookmarks for a specific user by tag(s):

    {format}/{username}/{tag[+tag+...+tag]}?private={key}</tt>

<big>Data</big>

<tt>      </tt>
DEBUG = 0

DLCS_API = 'https://api.del.icio.us/v1'

DLCS_API_HOST = 'api.del.icio.us'

DLCS_API_PATH = 'v1'

DLCS_API_REALM = 'del.icio.us API'

DLCS_FEEDS = 'http://feeds.delicious.com/v2/'

DLCS_OK_MESSAGES = ('done', 'ok')

DLCS_REQUEST_TIMEOUT = 444

DLCS_RSS = 'http://feeds.delicious.com/rss/'

DLCS_WAIT_TIME = 4

HTTPS_PROXY = 'http://sam:8080/'

HTTP_PROXY = 'http://sam:8080/'

ISO_8601_DATETIME = '%Y-%m-%dT%H:%M:%SZ'

PREFERRED_ENCODING = 'UTF-8'

USER_AGENT = 'pydelicious/0.6 http://code.google.com/p/pydelicious/'

Waiter = <__init__._Waiter instance>

__author__ = 'Berend (.mpe)'

__author_email__ = 'dev,pydelicious@dotmpe.com'

__credits__ = 'Frank Timmermann (original author), and in no\npa...o, me.gooz, mohangk, stumble.then.rise, clupprich'

__description__ = "Access delicious.com API's with Python"

__docformat__ = 'restructuredtext en'

__license__ = 'FreeBSD'

__long_description__ = "A complete Python interface to del.icio.us Bookmarks' HTTP API's."

__rcs_id__ = ': __init__.py 68 2010-11-21 13:58:04Z berend.van.berkum '

__url__ = 'http://code.google.com/p/pydelicious/'

__version__ = '0.6'

delicious_v2_feeds = {'alerts': '%(format)s/alerts', 'hotlist': '%(format)s', 'popular': '%(format)s/popular', 'popular_tagged': '%(format)s/popular/%(tag)s', 'recent': '%(format)s/recent', 'tagged': '%(format)s/tag/%(tag)s', 'url': '%(format)s/url/%(urlmd5)s', 'urlinfo': 'json/urlinfo/%(urlmd5)s', 'user': '%(format)s/%(username)s', 'user_inbox': '%(format)s/inbox/%(username)s?private=%(key)s', ...}

<big>Author</big>

<tt>      </tt>
Berend (.mpe)

<big>Credits</big>

<tt>      </tt>
Frank Timmermann (original author), and in no

particular order: Greg Pinero, me.gooz, mohangk, stumble.then.rise, clupprich


text:
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.

using GoogleCloudExtension.Utils.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace GoogleCloudExtensionUnitTests.Utils.Validation
{
    /// <summary>
    /// Summary description for ValidatingViewModelBaseTests
    /// </summary>
    [TestClass]
    public class ValidatingViewModelBaseTests
    {
        private const string TestPropertyName = "test property";

        private static readonly ValidationResult s_testResult = new ValidationResult(false, "message");

        private static readonly ValidationResult s_secondTestResult = new ValidationResult(false, "second message");

        private static readonly ValidationResult s_setTestValidation = new ValidationResult(false, "second message");

        private static readonly List<ValidationResult> s_testResults = new List<ValidationResult> { s_testResult };

        private static readonly List<ValidationResult> s_secondTestResults =
            new List<ValidationResult> { s_secondTestResult };

        private static readonly List<ValidationResult> s_setTestValidations =
            new List<ValidationResult> { s_setTestValidation };

        private TestModel _testObject;

        private TaskCompletionSource<string> _errorsChangedSource;
        private int _totalErrorsChanged;

        [TestInitialize]
        public void InitializeForTest()
        {
            _testObject = new TestModel();
            _errorsChangedSource = new TaskCompletionSource<string>();
            _totalErrorsChanged = 0;
            _testObject.ErrorsChanged += (sender, args) =>
            {
                _errorsChangedSource.SetResult(args.PropertyName);
                _totalErrorsChanged++;
            };
        }

        [TestMethod]
        public void TestInitialConditions()
        {
            const string propertyName = nameof(_testObject.ErrorsProperty);

            Assert.IsFalse(_testObject.HasErrors);
            Assert.IsFalse(_testObject.GetErrors(propertyName).Any());
            Assert.IsFalse(((INotifyDataErrorInfo)_testObject).GetErrors(propertyName).GetEnumerator().MoveNext());
            Assert.IsFalse(_testObject.GetErrors(null).Any());
            Assert.IsFalse(((INotifyDataErrorInfo)_testObject).GetErrors(null).GetEnumerator().MoveNext());
            Assert.AreEqual(0, _testObject.HasErrorChangedCount);
        }

        [TestMethod]
        public void TestUnfufilledConditions()
        {
            const string propertyName = nameof(_testObject.ErrorsProperty);
            _testObject.Delay = -1;
            _testObject.ErrorsProperty = s_testResults;

            Assert.IsFalse(_testObject.GetErrors(propertyName).Any());
            Assert.IsFalse(((INotifyDataErrorInfo)_testObject).GetErrors(propertyName).GetEnumerator().MoveNext());
            Assert.IsFalse(_testObject.GetErrors(null).Any());
            Assert.IsFalse(((INotifyDataErrorInfo)_testObject).GetErrors(null).GetEnumerator().MoveNext());
            Assert.IsFalse(_errorsChangedSource.Task.IsCompleted);
        }

        [TestMethod]
        public async Task TestSetValidationResults1()
        {
            _testObject.Delay = 0;
            _testObject.ErrorsProperty = s_testResults;
            string erroredProperty = await _errorsChangedSource.Task;

            Assert.AreEqual(nameof(_testObject.ErrorsProperty), erroredProperty);
            CollectionAssert.AreEqual(s_testResults, _testObject.GetErrors(erroredProperty).ToList());
            Assert.IsTrue(_testObject.HasErrors);
        }

        [TestMethod]
        public async Task TestSetValidationResults2()
        {
            _testObject.Delay = 0;
            _testObject.SetValidationResultsProxy(s_testResults, TestPropertyName);
            string erroredProperty = await _errorsChangedSource.Task;

            Assert.AreEqual(TestPropertyName, erroredProperty);
            CollectionAssert.AreEqual(s_testResults, _testObject.GetErrors(erroredProperty).ToList());
            Assert.IsTrue(_testObject.HasErrors);
        }

        [TestMethod]
        public async Task TestSetValidationResults3()
        {
            _testObject.Delay = -1;
            _testObject.SetValidationResultsProxy(null, TestPropertyName);
            Assert.IsTrue(_errorsChangedSource.Task.IsCompleted);
            string erroredProperty = await _errorsChangedSource.Task;

            Assert.AreEqual(TestPropertyName, erroredProperty);
            CollectionAssert.AreEqual(new object[0], _testObject.GetErrors(erroredProperty).ToList());
            Assert.IsFalse(_testObject.HasErrors);
        }

        [TestMethod]
        public async Task TestSetValidationResults4()
        {
            _testObject.Delay = 500;
            _testObject.SetValidationResultsProxy(s_testResults, TestPropertyName);
            await Task.Delay(100);
            Assert.IsFalse(_errorsChangedSource.Task.IsCompleted);
            _testObject.SetValidationResultsProxy(null, TestPropertyName);
            string erroredProperty = await _errorsChangedSource.Task;
            _errorsChangedSource = new TaskCompletionSource<string>();

            Task first = await Task.WhenAny(_errorsChangedSource.Task, Task.Delay(600));
            Assert.AreNotEqual(_errorsChangedSource.Task, first);
            Assert.AreEqual(1, _totalErrorsChanged);
            Assert.AreEqual(TestPropertyName, erroredProperty);
            CollectionAssert.AreEqual(new object[0], _testObject.GetErrors(erroredProperty).ToList());
            Assert.IsFalse(_testObject.HasErrors);
        }

        [TestMethod]
        public async Task TestInterfaceGetErrors()
        {
            _testObject.Delay = 0;
            _testObject.ErrorsProperty = s_testResults;
            string erroredProperty = await _errorsChangedSource.Task;
            _errorsChangedSource = new TaskCompletionSource<string>();
            _testObject.SetValidationResultsProxy(s_secondTestResults, TestPropertyName);
            string secondErroredProperty = await _errorsChangedSource.Task;

            IEnumerable interfaceErrors = ((INotifyDataErrorInfo)_testObject).GetErrors(erroredProperty);
            Assert.IsInstanceOfType(interfaceErrors, typeof(IEnumerable<ValidationResult>));
            CollectionAssert.AreEqual(
                _testObject.GetErrors(erroredProperty).ToList(),
                ((IEnumerable<ValidationResult>)interfaceErrors).ToList());

            IEnumerable secondInterfaceErrors = ((INotifyDataErrorInfo)_testObject).GetErrors(secondErroredProperty);
            Assert.IsInstanceOfType(secondInterfaceErrors, typeof(IEnumerable<ValidationResult>));
            CollectionAssert.AreEqual(
                _testObject.GetErrors(secondErroredProperty).ToList(),
                ((IEnumerable<ValidationResult>)secondInterfaceErrors).ToList());

            IEnumerable allInterfaceErrors = ((INotifyDataErrorInfo)_testObject).GetErrors(null);
            Assert.IsInstanceOfType(allInterfaceErrors, typeof(IEnumerable<ValidationResult>));
            CollectionAssert.AreEqual(
                _testObject.GetErrors(null).ToList(), ((IEnumerable<ValidationResult>)allInterfaceErrors).ToList());
        }

        [TestMethod]
        public async Task TestGetErrors()
        {
            _testObject.Delay = 0;
            _testObject.ErrorsProperty = s_testResults;
            string firstErroredProperty = await _errorsChangedSource.Task;
            _errorsChangedSource = new TaskCompletionSource<string>();
            _testObject.SetValidationResultsProxy(s_secondTestResults, TestPropertyName);
            string secondErroredProperty = await _errorsChangedSource.Task;

            CollectionAssert.AreEqual(s_testResults, _testObject.GetErrors(firstErroredProperty).ToList());
            CollectionAssert.AreEqual(s_secondTestResults, _testObject.GetErrors(secondErroredProperty).ToList());
            CollectionAssert.AreEqual(s_testResults.Concat(s_secondTestResults).ToList(), _testObject.GetErrors(null).ToList());
        }

        [TestMethod]
        public void TestHasErrors()
        {
            _testObject.Delay = -1;
            _testObject.ErrorsProperty = s_testResults;

            Assert.IsTrue(_testObject.HasErrors);
            Assert.IsFalse(_errorsChangedSource.Task.IsCompleted);
        }

        [TestMethod]
        public void TestHasErrorsChanged()
        {
            _testObject.Delay = -1;
            _testObject.SetValidationResultsProxy(s_testResults, TestPropertyName);

            Assert.AreEqual(1, _testObject.HasErrorChangedCount);
            Assert.IsFalse(_errorsChangedSource.Task.IsCompleted);
        }

        [TestMethod]
        public async Task TestSetAndRaiseWithValidations()
        {
            _testObject.Delay = 0;
            _testObject.SomeIntProperty = int.MaxValue;
            string changedProperty = await _errorsChangedSource.Task;

            Assert.AreEqual(nameof(_testObject.SomeIntProperty), changedProperty);
            Assert.AreEqual(int.MaxValue, _testObject.SomeIntProperty);
            CollectionAssert.AreEqual(s_setTestValidations, _testObject.GetErrors(changedProperty).ToList());
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException), AllowDerivedTypes = true)]
        public void TestSetValidationResultsNullProperty()
        {
            _testObject.SetValidationResultsProxy(s_testResults, null);
        }

        private class TestModel : ValidatingViewModelBase
        {
            private int _someIntProperty;

            public int Delay
            {
                set { MillisecondsDelay = value; }
            }

            public IEnumerable<ValidationResult> ErrorsProperty
            {
                set
                {
                    SetValidationResults(value);
                }
            }

            public int SomeIntProperty
            {
                get { return _someIntProperty; }
                set { SetAndRaiseWithValidation(ref _someIntProperty, value, s_setTestValidations); }
            }

            public int HasErrorChangedCount { get; private set; } = 0;

            public void SetValidationResultsProxy(IEnumerable<ValidationResult> results, string propertyName)
            {
                SetValidationResults(results, propertyName);
            }

            protected override void HasErrorsChanged()
            {
                HasErrorChangedCount++;
            }
        }
    }
}


text:
@interface PodsDummy_Pods_DrawVCUtil_Tests : NSObject
@end
@implementation PodsDummy_Pods_DrawVCUtil_Tests
@end


text:
            Total merge candidates: {{this.count}}

                        <input type="checkbox" style="opacity:10"
                                                      (change)="check(d.database,d.accession,d.database,d.accession,$event.target.checked)">

                            <input *ngIf="isChecked(d.database,d.accession,d.database,d.accession)" class="form-control"
                                   type="button" value="merge" (click)="merge(d.database,d.accession,d.database,d.accession)">
                            <input *ngIf="!isChecked(d.database,d.accession,d.database,d.accession)" class="form-control" disabled
                                   type="button" value="merge" (click)="merge(d.database,d.accession,d.database,d.accession)">

                            <input *ngIf="isChecked(d.database,d.accession,d.database,d.accession)" type="button" value="skip"
                                   (click)="skipMerge(d.database,d.accession,d.database,d.accession)" class="form-control">
                            <input *ngIf="!isChecked(d.database,d.accession,d.database,d.accession)" type="button" value="skip"
                                   (click)="skipMerge(d.database,d.accession,d.database,d.accession)" class="form-control" disabled>

                            <input *ngIf="isChecked(d.database,d.accession,d.database,d.accession)" type="button" value="multiomics"
                                   (click)="multiomicsMerge(d.database,d.accession,d.database,d.accession)" class="form-control">
                            <input *ngIf="!isChecked(d.database,d.accession,d.database,d.accession)" type="button"
                                   value="multiomics" (click)="multiomicsMerge(d.database,d.accession,d.database,d.accession)"
                                   class="form-control" disabled>

                        {{d.database}}
                        {{d.accession}}

                        {{d.name}}

                        <input type="checkbox" style="opacity:10"
                                                      (change)="check(d.database,d.accession,c.database,c.accession,$event.target.checked)">

                            <input *ngIf="isChecked(d.database,d.accession,c.database,c.accession)" type="button" value="merge"
                                   (click)="merge(d.database,d.accession,c.database,c.accession)" class="form-control">
                            <input *ngIf="!isChecked(d.database,d.accession,c.database,c.accession)" type="button" value="merge"
                                   (click)="merge(d.database,d.accession,c.database,c.accession)" class="form-control" disabled>

                            <input *ngIf="isChecked(d.database,d.accession,c.database,c.accession)" type="button" value="skip"
                                   (click)="skipMerge(d.database,d.accession,c.database,c.accession)" class="form-control">
                            <input *ngIf="!isChecked(d.database,d.accession,c.database,c.accession)" type="button" value="skip"
                                   (click)="skipMerge(d.database,d.accession,c.database,c.accession)" class="form-control" disabled>

                            <input *ngIf="isChecked(d.database,d.accession,c.database,c.accession)" type="button" value="multiomics"
                                   (click)="multiomicsMerge(d.database,d.accession,c.database,c.accession)" class="form-control">
                            <input *ngIf="!isChecked(d.database,d.accession,c.database,c.accession)" type="button"
                                   value="multiomics" (click)="multiomicsMerge(d.database,d.accession,c.database,c.accession)"
                                   class="form-control" disabled>

                        {{c.database}}
                        {{c.accession}}

                        {{c.name}}

            <pagination-controls (pageChange)="getPage($event)"
                                 class="my-pagination"
                                 id="server">
            </pagination-controls>


text:
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const apnCredentialSid = 'CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const fcmCredentialSid = 'CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const Twilio = require('twilio');

const client = new Twilio(
  accountSid,
  apnCredentialSid,
  fcmCredentialSid,
  authToken
);

client.notify.services
  .create({
    friendlyName: 'My Awesome Service',
  })
  .then(service => {
    console.log(service.friendlyName);
  })
  .catch(error => {
    console.log(error);
  })
  .done();


text:
package dropbox

import (
	"crypto/sha256"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"time"
)

// Files client for files and folders.
type Files struct {
	*Client
}

// NewFiles client.
func NewFiles(config *Config) *Files {
	return &Files{
		Client: &Client{
			Config: config,
		},
	}
}

// WriteMode determines what to do if the file already exists.
type WriteMode string

// Supported write modes.
const (
	WriteModeAdd       WriteMode = "add"
	WriteModeOverwrite           = "overwrite"
)

// Dimensions specifies the dimensions of a photo or video.
type Dimensions struct {
	Width  uint64 `json:"width"`
	Height uint64 `json:"height"`
}

// GPSCoordinates specifies the GPS coordinate of a photo or video.
type GPSCoordinates struct {
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
}

// PhotoMetadata specifies metadata for a photo.
type PhotoMetadata struct {
	Dimensions *Dimensions     `json:"dimensions,omitempty"`
	Location   *GPSCoordinates `json:"location,omitempty"`
	TimeTaken  time.Time       `json:"time_taken,omitempty"`
}

// VideoMetadata specifies metadata for a video.
type VideoMetadata struct {
	Dimensions *Dimensions     `json:"dimensions,omitempty"`
	Location   *GPSCoordinates `json:"location,omitempty"`
	TimeTaken  time.Time       `json:"time_taken,omitempty"`
	Duration   uint64          `json:"duration,omitempty"`
}

// MediaMetadata provides metadata for a photo or video.
type MediaMetadata struct {
	Photo *PhotoMetadata `json:"photo,omitempty"`
	Video *VideoMetadata `json:"video,omitempty"`
}

// MediaInfo provides additional information for a photo or video file.
type MediaInfo struct {
	Pending  bool           `json:"pending"`
	Metadata *MediaMetadata `json:"metadata,omitempty"`
}

// FileSharingInfo for a file which is contained in a shared folder.
type FileSharingInfo struct {
	ReadOnly             bool   `json:"read_only"`
	ParentSharedFolderID string `json:"parent_shared_folder_id"`
	ModifiedBy           string `json:"modified_by,omitempty"`
}

// Metadata for a file or folder.
type Metadata struct {
	Tag            string           `json:".tag"`
	Name           string           `json:"name"`
	PathLower      string           `json:"path_lower"`
	PathDisplay    string           `json:"path_display"`
	ClientModified time.Time        `json:"client_modified"`
	ServerModified time.Time        `json:"server_modified"`
	Rev            string           `json:"rev"`
	Size           uint64           `json:"size"`
	ID             string           `json:"id"`
	MediaInfo      *MediaInfo       `json:"media_info,omitempty"`
	SharingInfo    *FileSharingInfo `json:"sharing_info,omitempty"`
	ContentHash    string           `json:"content_hash,omitempty"`
}

// GetMetadataInput request input.
type GetMetadataInput struct {
	Path             string `json:"path"`
	IncludeMediaInfo bool   `json:"include_media_info"`
}

// GetMetadataOutput request output.
type GetMetadataOutput struct {
	Metadata
}

// GetMetadata returns the metadata for a file or folder.
func (c *Files) GetMetadata(in *GetMetadataInput) (out *GetMetadataOutput, err error) {
	body, err := c.call("/files/get_metadata", in)
	if err != nil {
		return
	}
	defer body.Close()

	err = json.NewDecoder(body).Decode(&out)
	return
}

// CreateFolderInput request input.
type CreateFolderInput struct {
	Path string `json:"path"`
}

// CreateFolderOutput request output.
type CreateFolderOutput struct {
	Name      string `json:"name"`
	PathLower string `json:"path_lower"`
	ID        string `json:"id"`
}

// CreateFolder creates a folder.
func (c *Files) CreateFolder(in *CreateFolderInput) (out *CreateFolderOutput, err error) {
	body, err := c.call("/files/create_folder", in)
	if err != nil {
		return
	}
	defer body.Close()

	err = json.NewDecoder(body).Decode(&out)
	return
}

// DeleteInput request input.
type DeleteInput struct {
	Path string `json:"path"`
}

// DeleteOutput request output.
type DeleteOutput struct {
	Metadata
}

// Delete a file or folder and its contents.
func (c *Files) Delete(in *DeleteInput) (out *DeleteOutput, err error) {
	body, err := c.call("/files/delete", in)
	if err != nil {
		return
	}
	defer body.Close()

	err = json.NewDecoder(body).Decode(&out)
	return
}

// PermanentlyDeleteInput request input.
type PermanentlyDeleteInput struct {
	Path string `json:"path"`
}

// PermanentlyDelete a file or folder and its contents.
func (c *Files) PermanentlyDelete(in *PermanentlyDeleteInput) (err error) {
	body, err := c.call("/files/delete", in)
	if err != nil {
		return
	}
	defer body.Close()

	return
}

// CopyInput request input.
type CopyInput struct {
	FromPath string `json:"from_path"`
	ToPath   string `json:"to_path"`
}

// CopyOutput request output.
type CopyOutput struct {
	Metadata
}

// Copy a file or folder to a different location.
func (c *Files) Copy(in *CopyInput) (out *CopyOutput, err error) {
	body, err := c.call("/files/copy", in)
	if err != nil {
		return
	}
	defer body.Close()

	err = json.NewDecoder(body).Decode(&out)
	return
}

// MoveInput request input.
type MoveInput struct {
	FromPath string `json:"from_path"`
	ToPath   string `json:"to_path"`
}

// MoveOutput request output.
type MoveOutput struct {
	Metadata
}

// Move a file or folder to a different location.
func (c *Files) Move(in *MoveInput) (out *MoveOutput, err error) {
	body, err := c.call("/files/move", in)
	if err != nil {
		return
	}
	defer body.Close()

	err = json.NewDecoder(body).Decode(&out)
	return
}

// RestoreInput request input.
type RestoreInput struct {
	Path string `json:"path"`
	Rev  string `json:"rev"`
}

// RestoreOutput request output.
type RestoreOutput struct {
	Metadata
}

// Restore a file to a specific revision.
func (c *Files) Restore(in *RestoreInput) (out *RestoreOutput, err error) {
	body, err := c.call("/files/restore", in)
	if err != nil {
		return
	}
	defer body.Close()

	err = json.NewDecoder(body).Decode(&out)
	return
}

// ListFolderInput request input.
type ListFolderInput struct {
	Path             string `json:"path"`
	Recursive        bool   `json:"recursive"`
	IncludeMediaInfo bool   `json:"include_media_info"`
	IncludeDeleted   bool   `json:"include_deleted"`
}

// ListFolderOutput request output.
type ListFolderOutput struct {
	Cursor  string `json:"cursor"`
	HasMore bool   `json:"has_more"`
	Entries []*Metadata
}

// ListFolder returns the metadata for a file or folder.
func (c *Files) ListFolder(in *ListFolderInput) (out *ListFolderOutput, err error) {
	in.Path = normalizePath(in.Path)

	body, err := c.call("/files/list_folder", in)
	if err != nil {
		return
	}
	defer body.Close()

	err = json.NewDecoder(body).Decode(&out)
	return
}

// ListFolderContinueInput request input.
type ListFolderContinueInput struct {
	Cursor string `json:"cursor"`
}

// ListFolderContinue pagenates using the cursor from ListFolder.
func (c *Files) ListFolderContinue(in *ListFolderContinueInput) (out *ListFolderOutput, err error) {
	body, err := c.call("/files/list_folder/continue", in)
	if err != nil {
		return
	}
	defer body.Close()

	err = json.NewDecoder(body).Decode(&out)
	return
}

// SearchMode determines how a search is performed.
type SearchMode string

// Supported search modes.
const (
	SearchModeFilename           SearchMode = "filename"
	SearchModeFilenameAndContent            = "filename_and_content"
	SearchModeDeletedFilename               = "deleted_filename"
)

// SearchMatchType represents the type of match made.
type SearchMatchType string

// Supported search match types.
const (
	SearchMatchFilename SearchMatchType = "filename"
	SearchMatchContent                  = "content"
	SearchMatchBoth                     = "both"
)

// SearchMatch represents a matched file or folder.
type SearchMatch struct {
	MatchType struct {
		Tag SearchMatchType `json:".tag"`
	} `json:"match_type"`
	Metadata *Metadata `json:"metadata"`
}

// SearchInput request input.
type SearchInput struct {
	Path       string     `json:"path"`
	Query      string     `json:"query"`
	Start      uint64     `json:"start,omitempty"`
	MaxResults uint64     `json:"max_results,omitempty"`
	Mode       SearchMode `json:"mode"`
}

// SearchOutput request output.
type SearchOutput struct {
	Matches []*SearchMatch `json:"matches"`
	More    bool           `json:"more"`
	Start   uint64         `json:"start"`
}

// Search for files and folders.
func (c *Files) Search(in *SearchInput) (out *SearchOutput, err error) {
	in.Path = normalizePath(in.Path)

	if in.Mode == "" {
		in.Mode = SearchModeFilename
	}

	body, err := c.call("/files/search", in)
	if err != nil {
		return
	}
	defer body.Close()

	err = json.NewDecoder(body).Decode(&out)
	return
}

// UploadInput request input.
type UploadInput struct {
	Path           string    `json:"path"`
	Mode           WriteMode `json:"mode"`
	AutoRename     bool      `json:"autorename"`
	Mute           bool      `json:"mute"`
	ClientModified string    `json:"client_modified,omitempty"`
	Reader         io.Reader `json:"-"`
}

// UploadOutput request output.
type UploadOutput struct {
	Metadata
}

// Upload a file smaller than 150MB.
func (c *Files) Upload(in *UploadInput) (out *UploadOutput, err error) {
	body, _, err := c.download("/files/upload", in, in.Reader)
	if err != nil {
		return
	}
	defer body.Close()

	err = json.NewDecoder(body).Decode(&out)
	return
}

// DownloadInput request input.
type DownloadInput struct {
	Path string `json:"path"`
}

// DownloadOutput request output.
type DownloadOutput struct {
	Body   io.ReadCloser
	Length int64
}

// Download a file.
func (c *Files) Download(in *DownloadInput) (out *DownloadOutput, err error) {
	body, l, err := c.download("/files/download", in, nil)
	if err != nil {
		return
	}

	out = &DownloadOutput{body, l}
	return
}

// ThumbnailFormat determines the format of the thumbnail.
type ThumbnailFormat string

const (
	// GetThumbnailFormatJPEG specifies a JPG thumbnail
	GetThumbnailFormatJPEG ThumbnailFormat = "jpeg"
	// GetThumbnailFormatPNG specifies a PNG thumbnail
	GetThumbnailFormatPNG = "png"
)

// ThumbnailSize determines the size of the thumbnail.
type ThumbnailSize string

const (
	// GetThumbnailSizeW32H32 specifies a size of 32 by 32 px
	GetThumbnailSizeW32H32 ThumbnailSize = "w32h32"
	// GetThumbnailSizeW64H64 specifies a size of 64 by 64 px
	GetThumbnailSizeW64H64 = "w64h64"
	// GetThumbnailSizeW128H128 specifies a size of 128 by 128 px
	GetThumbnailSizeW128H128 = "w128h128"
	// GetThumbnailSizeW640H480 specifies a size of 640 by 480 px
	GetThumbnailSizeW640H480 = "w640h480"
	// GetThumbnailSizeW1024H768 specifies a size of 1024 by 768 px
	GetThumbnailSizeW1024H768 = "w1024h768"
)

// GetThumbnailInput request input.
type GetThumbnailInput struct {
	Path   string          `json:"path"`
	Format ThumbnailFormat `json:"format"`
	Size   ThumbnailSize   `json:"size"`
}

// GetThumbnailOutput request output.
type GetThumbnailOutput struct {
	Body   io.ReadCloser
	Length int64
}

// GetThumbnail a thumbnail for a file. Currently thumbnails are only generated for the
// files with the following extensions: png, jpeg, png, tiff, tif, gif and bmp.
func (c *Files) GetThumbnail(in *GetThumbnailInput) (out *GetThumbnailOutput, err error) {
	body, l, err := c.download("/files/get_thumbnail", in, nil)
	if err != nil {
		return
	}

	out = &GetThumbnailOutput{body, l}
	return
}

// GetPreviewInput request input.
type GetPreviewInput struct {
	Path string `json:"path"`
}

// GetPreviewOutput request output.
type GetPreviewOutput struct {
	Body   io.ReadCloser
	Length int64
}

// GetPreview a preview for a file. Currently previews are only generated for the
// files with the following extensions: .doc, .docx, .docm, .ppt, .pps, .ppsx,
// .ppsm, .pptx, .pptm, .xls, .xlsx, .xlsm, .rtf
func (c *Files) GetPreview(in *GetPreviewInput) (out *GetPreviewOutput, err error) {
	body, l, err := c.download("/files/get_preview", in, nil)
	if err != nil {
		return
	}

	out = &GetPreviewOutput{body, l}
	return
}

// ListRevisionsInput request input.
type ListRevisionsInput struct {
	Path  string `json:"path"`
	Limit uint64 `json:"limit,omitempty"`
}

// ListRevisionsOutput request output.
type ListRevisionsOutput struct {
	IsDeleted bool
	Entries   []*Metadata
}

// ListRevisions gets the revisions of the specified file.
func (c *Files) ListRevisions(in *ListRevisionsInput) (out *ListRevisionsOutput, err error) {
	body, err := c.call("/files/list_revisions", in)
	if err != nil {
		return
	}
	defer body.Close()

	err = json.NewDecoder(body).Decode(&out)
	return
}

// Normalize path so people can use "/" as they expect.
func normalizePath(s string) string {
	if s == "/" {
		return ""
	}
	return s
}

const hashBlockSize = 4 * 1024 * 1024

// ContentHash returns the Dropbox content_hash for a io.Reader.
// See https://www.dropbox.com/developers/reference/content-hash
func ContentHash(r io.Reader) (string, error) {
	buf := make([]byte, hashBlockSize)
	resultHash := sha256.New()
	n, err := r.Read(buf)
	if err != nil && err != io.EOF {
		return "", err
	}
	if n > 0 {
		bufHash := sha256.Sum256(buf[:n])
		resultHash.Write(bufHash[:])
	}
	for n == hashBlockSize && err == nil {
		n, err = r.Read(buf)
		if err != nil && err != io.EOF {
			return "", err
		}
		if n > 0 {
			bufHash := sha256.Sum256(buf[:n])
			resultHash.Write(bufHash[:])
		}
	}
	return fmt.Sprintf("%x", resultHash.Sum(nil)), nil
}

// FileContentHash returns the Dropbox content_hash for a local file.
// See https://www.dropbox.com/developers/reference/content-hash
func FileContentHash(filename string) (string, error) {
	f, err := os.Open(filename)
	if err != nil {
		return "", err
	}
	defer f.Close()
	return ContentHash(f)
}