text:
// Copyright (C) 2007 Google Inc.
//
// 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.

package com.google.enterprise.connector.otex;

import com.google.enterprise.connector.otex.client.lapi.LapiClientFactory;

import junit.framework.TestCase;

import java.util.ArrayList;

/**
 * Tests some properties of the LapiClientFactory with various
 * sets of configuration parameters. The test is intended to
 * verify that, if the right setters are called (by
 * LivelinkConnector), that the right parameters are passed to
 * the LLSession constructor. At the moment, the test simply
 * allows LapiClientFactory to log the parameters; the parameters
 * aren't exposed in any way that would allow us to read them
 * here.
 */
public class LapiClientFactoryTest extends TestCase {
  /** The factory instance under test. */
  private LapiClientFactory factory;

  /**
   * Establishes a session and obtains an AuthenticationManager
   * for testing.
   *
   * @throws RepositoryException if login fails
   */
  @Override
  protected void setUp() throws Exception {
    factory = new LapiClientFactory();
    factory.setServer(getName());
    factory.setPort(1111);
    factory.setConnection("testConnection");
  }

  /**
   * Tests properties for a direct LAPI connection. The config
   * object should be null.
   */
  public void testDirectConnection() throws Exception {
    factory.setUsername("testUsername");
    factory.setPassword("testPassword");
    factory.createClient();
  }

  /**
   * Tests adding a domain.
   */
  public void testDirectConnectionWithDomain() throws Exception {
    factory.setUsername("testUsername");
    factory.setPassword("testPassword");
    factory.setDomainName("testDomainName");
    factory.createClient();
  }

  /**
   * Tests tunnelling.
   */
  public void testTunnel() throws Exception {
    factory.setUsername("testUsername");
    factory.setPassword("testPassword");
    factory.setLivelinkCgi("/testLivelinkCgi/livelink");
    factory.createClient();
  }

  /**
   * Tests tunnelling with HTTP authentication.
   */
  public void testTunnelAndAuthenticate() throws Exception {
    factory.setUsername("testUsername");
    factory.setPassword("testPassword");
    factory.setLivelinkCgi("/testLivelinkCgi/livelink");
    factory.setHttpUsername("testHttpUsername");
    factory.setHttpPassword("testHttpPassword");
    factory.createClient();
  }

  /**
   * Tests disabling NTLM.
   */
  public void testDisableNtlm() throws Exception {
    factory.setUsername("testUsername");
    factory.setPassword("testPassword");
    factory.setEnableNtlm(false);
    factory.createClient();
  }

  /**
   * Tests enabling HTTPS.
   */
  public void testTunnelWithHttps() throws Exception {
    factory.setUsername("testUsername");
    factory.setPassword("testPassword");
    factory.setLivelinkCgi("/testLivelinkCgi/livelink");
    factory.setHttpUsername("testHttpUsername");
    factory.setHttpPassword("testHttpPassword");
    factory.setHttps(true);
    factory.createClient();
  }

  /**
   * Tests VerifyServer.
   */
  public void testTunnelVerify() throws Exception {
    factory.setUsername("testUsername");
    factory.setPassword("testPassword");
    factory.setLivelinkCgi("/testLivelinkCgi/livelink");
    factory.setHttpUsername("testHttpUsername");
    factory.setHttpPassword("testHttpPassword");
    factory.setHttps(true);
    factory.setVerifyServer(true);
    ArrayList<String> certs = new ArrayList<String>();
    certs.add("test cert");
    factory.setCaRootCerts(certs);
    factory.createClient();
  }

  /**
   * Tests the properties used by createClient(username,
   * password). Used to verify that the values in the method
   * arguments are used, not the previously-configured values.
   */
  public void testOverrideIdentity() throws Exception {
    factory.setUsername("*** ERROR ***");
    factory.setPassword("*** ERROR ***");
    factory.createClient("newUsername", "newPassword");
  }

  /**
   * Tests the properties used by createClient(username,
   * password). Used to verify that the values in the method
   * arguments are used, not the previously-configured values.
   */
  public void testOverrideIdentityHttp() throws Exception {
    factory.setUsername("*** ERROR ***");
    factory.setPassword("*** ERROR ***");
    factory.setHttpUsername("*** ERROR ***");
    factory.setHttpPassword("*** ERROR ***");
    factory.setUseUsernamePasswordWithWebServer(true);
    factory.createClient("newUsername", "newPassword");
  }

  /**
   * Tests the properties used by createClient(username,
   * password). Used to verify that the values in the method
   * arguments are used, not the previously-configured values.
   */
  public void testRemoveIdentityHttp() throws Exception {
    factory.setUsername("*** ERROR ***");
    factory.setPassword("*** ERROR ***");
    factory.setHttpUsername("*** ERROR ***");
    factory.setHttpPassword("*** ERROR ***");
    factory.setUseUsernamePasswordWithWebServer(false);
    factory.createClient("newUsername", "newPassword");
  }
}


text:
using System;
using System.Reflection;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.IO;

namespace MultiConfig
{
	[AttributeUsage (AttributeTargets.Property)]
	public class ConfigAttribute : Attribute
	{
		/// <summary>
		/// Config filename
		/// </summary>
		/// <value>The filename.</value>
		public string Filename { get; set; }

		public ConfigAttribute (string filename)
		{
			this.Filename = filename;
		}
	}

	public class FileUtil
	{
		public static List<string> LoadFile (string filename)
		{
			var values = new List<string> ();

			using (var sr = new StreamReader (filename)) {
				while (!sr.EndOfStream) {
					var line = sr.ReadLine ();
					if (string.IsNullOrWhiteSpace (line))
						continue;
					values.Add (line);
				}
			}

			return values;
		}
	}

	public abstract class MultiConfigBase
	{
		public string Path { get; private set; }

		public MultiConfigBase ()
		{
		}

		/// <summary>
		/// Load the configs under the given path
		/// </summary>
		/// <param name="path">Path.</param>
		public void LoadConfigs (string path)
		{

			this.Path = path;

			Console.WriteLine ("start loading configs from {0}", path);

			// get all properties
			var props = this.GetType ().GetProperties ().ToList ();

			props.ForEach (this.LoadConfig);
		}

		/// <summary>
		/// Loads the config for a given property.
		/// </summary>
		/// <param name="propInfo">Property info.</param>
		private void LoadConfig (PropertyInfo propInfo)
		{
			var attr = (ConfigAttribute[])propInfo.GetCustomAttributes (typeof(ConfigAttribute), true);
			if (attr == null || attr.Length == 0)
				return;

			var configFilename = attr [0].Filename;
			var ppt = propInfo.PropertyType;

			Console.WriteLine ("propName = {0} type = {1} config filename = {2}", propInfo.Name, ppt, configFilename);

			var values = FileUtil.LoadFile (this.Path + configFilename);

			// is a container
			if (ppt.GetInterfaces ().Any (x =>
				x.IsGenericType &&
			    x.GetGenericTypeDefinition () == typeof(IList<>))) {

				var valuetype = ppt.GetGenericArguments () [0];

				var listInstance = (IList)typeof(List<>)
					.MakeGenericType (valuetype)
					.GetConstructor (Type.EmptyTypes)
					.Invoke (null);

				values.ForEach (v => {
					var vv = Convert.ChangeType (v, valuetype);
					listInstance.Add (vv);
				});

				propInfo.SetValue (this, listInstance, null);
			} else {
				// single value
				var valueInPropType = Convert.ChangeType (values [0], ppt);

				propInfo.SetValue (this, valueInPropType, null);
			}

		}
	}

	public class GreenDataCenterConfig : MultiConfigBase
	{
		[Config ("timeslots.txt")]
		public int TimeSlots { get; private set; }

		[Config ("servercount.txt")]
		public int ServerCount { get; private set; }

		[Config ("servernames.txt")]
		public List<string> ServerNames { get; private set; }

		[Config ("brown_enegy_price_list.txt")]
		public List<double> BrownPrices { get; private set; }

		[Config ("green-enegy.txt")]
		public List<int> GreenEnegies { get; private set; }

		public GreenDataCenterConfig ()
		{

		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
var importCreatureCtrl = function ($scope, bestiary, $mdDialog, $mdToast, DataAdapter, Creature, updateBestiaryCreaturesFunction) {
    $scope.loading = true;
    $scope.importFormats = {
        "CritterDB Creature": {
            name: "CritterDB Creature",
            description: "Import a single CritterDB creature. Paste a single creature below, in CritterDB JSON format.",
            adapterFormat: DataAdapter.Format["CRITTERDB"],
            getCreatureListFunction: function (importData) {
                const creatureList = [];
                if (importData) {
                    creatureList.push(importData);
                }
                return creatureList;
            }
        },
        "CritterDB Bestiary": {
            name: "CritterDB Bestiary",
            description: "Import all of the creatures from a CritterDB bestiary. Paste a single bestiary below, in CritterDB JSON format.",
            adapterFormat: DataAdapter.Format["CRITTERDB"],
            getCreatureListFunction: function (importData) {
                const creatureList = [];
                if (importData && importData.creatures) {
                    creatureList.push(...importData.creatures);
                }
                return creatureList;
            }
        }
    }
    $scope.importFormatIds = Object.keys($scope.importFormats);
    $scope.creaturesToImport = [];

    function getSelectedImportFormat() {
        return $scope.importFormats[$scope.selectedImportFormatId];
    }

    $scope.import = function () {
        if ($scope.loading) {
            console.error("Unable to import while text conversion is still processing.");
            return;
        }
        if (!$scope.creaturesToImport) {
            console.error("No creatures found to import.");
            return;
        }
        if (!bestiary || !bestiary._id) {
            console.error("Invalid bestiary.");
            return;
        }

        var numCreaturesCreated = 0;
        var numCreaturesToCreate = 0;
        $scope.creaturesToImport.forEach(creature => {
            const newCreature = {
                name: creature.name,
                flavor: creature.flavor,
                stats: creature.stats,
                bestiaryId: bestiary._id
            };
            numCreaturesToCreate++;
            Creature.create(newCreature, function (data) {
                numCreaturesCreated++;
                if (numCreaturesCreated >= numCreaturesToCreate) {
                    updateBestiaryCreaturesFunction();
                    $mdToast.show(
                        $mdToast.simple()
                            .textContent(`${numCreaturesCreated} creatures imported!`)
                            .position("bottom right")
                            .parent(document.getElementById('import-dialog'))
                            .hideDelay(2000)
                    );
                }
            }, function (err) {
                numCreaturesToCreate--;
                console.error("Error creating creature: " + err);
            });
        });
        $scope.importText = "";
    }

    function update() {
        $scope.loading = true;
        if (!$scope.selectedImportFormatId || !$scope.importText) {
            return;
        } else {
            $scope.importForm.importText.$error = {};
            try {
                const importData = DataAdapter.import($scope.importText, getSelectedImportFormat().adapterFormat);
                $scope.creaturesToImport = getSelectedImportFormat().getCreatureListFunction(importData);
                if (!$scope.creaturesToImport || $scope.creaturesToImport.count === 0) {
                    $scope.importForm.importText.$error.empty = true;
                    return;
                }
                $scope.loading = false;
            } catch (err) {
                $scope.importForm.importText.$error.format = true;
            }
        }
    }

    $scope.$watch("importText", function (newValue, oldValue) {
        if (oldValue != newValue) {
            update();
        }
    });
    $scope.$watch("selectedImportFormatId", function (newValue, oldValue) {
        if (oldValue != newValue) {
            update();
        }
    });

    $scope.cancel = function () {
        $mdDialog.cancel();
    };

};

angular.module('myApp').controller('importCreatureCtrl', importCreatureCtrl);


text:
<?php

class ApiCache {

  /**
   * Clear a specified item from cache.
   *
   * @param  mixed  $id
   * @param  mixed  $action
   * @param  mixed  $parameters
   * @return bool
   */
  function clear($id = NULL, $action = NULL, $parameters = NULL) {
    if (!$id) {
      if ($action && $parameters) {
        $id = $this->generate_id($action, $parameters);
      }
      else {
        return FALSE;
      }
    }

    cache_clear_all($id, 'cache_dosomething_api');

    return TRUE;
  }

  /**
   * Get data from cache based on id from endpoint and URL parameters.
   *
   * @param  string  $action
   * @param  array   $parameters
   * @return mixed
   */
  public function get($action, $parameters) {
    $id = $this->generate_id($action, $parameters);

    $cache = cache_get($id, 'cache_dosomething_api');

    if ($cache) {
      if (isset($parameters['cache']) && !dosomething_helpers_convert_string_to_boolean($parameters['cache'])) {
        $this->clear($id);

        return FALSE;
      }

      // Temporary cache expire is equal to -1.
      // Permanent cache expire is equal to 0.
      if ($cache->expire > 0 && $cache->expire < REQUEST_TIME) {
        $this->clear($id);

        return FALSE;
      }
    }

    return $cache;
  }

  /**
   * Set data in cache for 24 hours with id based on endpoint and URL parameters.
   *
   * @param  string  $action
   * @param  array   $parameters
   * @param  mixed   $data
   * @param  mixed   $expiration
   * @return bool
   */
  public function set($action, $parameters, $data, $expiration = NULL) {
    if (isset($parameters['cache']) && !dosomething_helpers_convert_string_to_boolean($parameters['cache'])) {
      return FALSE;
    }

    $id = $this->generate_id($action, $parameters);

    if (is_bool($expiration) && $expiration === FALSE) {
      $expiration = CACHE_PERMANENT;
    }
    elseif (is_int($expiration)) {
      $expiration = REQUEST_TIME + (60 * 60 * $expiration);
    }
    else {
      $expiration = CACHE_TEMPORARY;
    }

    cache_set($id, $data, 'cache_dosomething_api', $expiration);

    return TRUE;
  }

  /**
   * Generate an id from resource endpoint type and URL parameters.
   *
   * @param  string  $action
   * @param  array   $parameters
   * @return string
   */
  private function generate_id($action, $parameters) {
    if (is_array($parameters) && isset($parameters['cache'])) {
      unset($parameters['cache']);
    }

    $id = $action . '_api_request' . $this->stringify($parameters);

    watchdog('dosomething_api', $id, [], WATCHDOG_DEBUG);

    return $id;
  }

  /**
   * Create a concatenated string from URL parameters.
   *
   * @param  array  $parameters
   * @return string
   * @todo: may want to allow passing nested array instead of one-dimensional array.
   */
  private function stringify($parameters) {
    $string = '';

    if (!is_array($parameters)) {
      if (is_int(intval($parameters))) {
        $parameters = ['id' => $parameters];
      }
    }

    // Remove empty values from array.
    $items = array_filter($parameters);

    foreach ($items as $key => $value) {
      $string .= '|' . $key . '=' . $value;
    }

    return $string;
  }
}


text:
'use strict';

var d3 = require('@plotly/d3');
var Lib = require('../../lib');
var strTranslate = Lib.strTranslate;
var xmlnsNamespaces = require('../../constants/xmlns_namespaces');
var constants = require('./constants');

var unsupportedBrowsers = Lib.isIOS() || Lib.isSafari() || Lib.isIE();

module.exports = function plot(gd, plotinfo, cdimage, imageLayer) {
    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    var supportsPixelatedImage = !(unsupportedBrowsers || gd._context._exportedPlot);

    Lib.makeTraceGroups(imageLayer, cdimage, 'im').each(function(cd) {
        var plotGroup = d3.select(this);
        var cd0 = cd[0];
        var trace = cd0.trace;
        var realImage = (
            ((trace.zsmooth === 'fast') || (trace.zsmooth === false && supportsPixelatedImage)) &&
            !trace._hasZ && trace._hasSource && xa.type === 'linear' && ya.type === 'linear'
        );
        trace._realImage = realImage;

        var z = cd0.z;
        var x0 = cd0.x0;
        var y0 = cd0.y0;
        var w = cd0.w;
        var h = cd0.h;
        var dx = trace.dx;
        var dy = trace.dy;

        var left, right, temp, top, bottom, i;
        // in case of log of a negative
        i = 0;
        while(left === undefined && i < w) {
            left = xa.c2p(x0 + i * dx);
            i++;
        }
        i = w;
        while(right === undefined && i > 0) {
            right = xa.c2p(x0 + i * dx);
            i--;
        }
        i = 0;
        while(top === undefined && i < h) {
            top = ya.c2p(y0 + i * dy);
            i++;
        }
        i = h;
        while(bottom === undefined && i > 0) {
            bottom = ya.c2p(y0 + i * dy);
            i--;
        }

        if(right < left) {
            temp = right;
            right = left;
            left = temp;
        }

        if(bottom < top) {
            temp = top;
            top = bottom;
            bottom = temp;
        }

        // Reduce image size when zoomed in to save memory
        if(!realImage) {
            var extra = 0.5; // half the axis size
            left = Math.max(-extra * xa._length, left);
            right = Math.min((1 + extra) * xa._length, right);
            top = Math.max(-extra * ya._length, top);
            bottom = Math.min((1 + extra) * ya._length, bottom);
        }

        var imageWidth = Math.round(right - left);
        var imageHeight = Math.round(bottom - top);

        // if image is entirely off-screen, don't even draw it
        var isOffScreen = (imageWidth <= 0 || imageHeight <= 0);
        if(isOffScreen) {
            var noImage = plotGroup.selectAll('image').data([]);
            noImage.exit().remove();
            return;
        }

        // Create a new canvas and draw magnified pixels on it
        function drawMagnifiedPixelsOnCanvas(readPixel) {
            var canvas = document.createElement('canvas');
            canvas.width = imageWidth;
            canvas.height = imageHeight;
            var context = canvas.getContext('2d');

            var ipx = function(i) {return Lib.constrain(Math.round(xa.c2p(x0 + i * dx) - left), 0, imageWidth);};
            var jpx = function(j) {return Lib.constrain(Math.round(ya.c2p(y0 + j * dy) - top), 0, imageHeight);};

            var cr = constants.colormodel[trace.colormodel];
            var colormodel = (cr.colormodel || trace.colormodel);
            var fmt = cr.fmt;
            var c;
            for(i = 0; i < cd0.w; i++) {
                var ipx0 = ipx(i); var ipx1 = ipx(i + 1);
                if(ipx1 === ipx0 || isNaN(ipx1) || isNaN(ipx0)) continue;
                for(var j = 0; j < cd0.h; j++) {
                    var jpx0 = jpx(j); var jpx1 = jpx(j + 1);
                    if(jpx1 === jpx0 || isNaN(jpx1) || isNaN(jpx0) || !readPixel(i, j)) continue;
                    c = trace._scaler(readPixel(i, j));
                    if(c) {
                        context.fillStyle = colormodel + '(' + fmt(c).join(',') + ')';
                    } else {
                        // Return a transparent pixel
                        context.fillStyle = 'rgba(0,0,0,0)';
                    }
                    context.fillRect(ipx0, jpx0, ipx1 - ipx0, jpx1 - jpx0);
                }
            }

            return canvas;
        }

        var image3 = plotGroup.selectAll('image')
            .data([cd]);

        image3.enter().append('svg:image').attr({
            xmlns: xmlnsNamespaces.svg,
            preserveAspectRatio: 'none'
        });

        image3.exit().remove();

        var style = (trace.zsmooth === false) ? constants.pixelatedStyle : '';

        if(realImage) {
            var xRange = Lib.simpleMap(xa.range, xa.r2l);
            var yRange = Lib.simpleMap(ya.range, ya.r2l);

            var flipX = xRange[1] < xRange[0];
            var flipY = yRange[1] > yRange[0];
            if(flipX || flipY) {
                var tx = left + imageWidth / 2;
                var ty = top + imageHeight / 2;
                style += 'transform:' +
                    strTranslate(tx + 'px', ty + 'px') +
                    'scale(' + (flipX ? -1 : 1) + ',' + (flipY ? -1 : 1) + ')' +
                    strTranslate(-tx + 'px', -ty + 'px') + ';';
            }
        }
        image3.attr('style', style);

        var p = new Promise(function(resolve) {
            if(trace._hasZ) {
                resolve();
            } else if(trace._hasSource) {
                // Check if canvas already exists and has the right data
                if(
                    trace._canvas &&
                    trace._canvas.el.width === w &&
                    trace._canvas.el.height === h &&
                    trace._canvas.source === trace.source
                ) {
                    resolve();
                } else {
                    // Create a canvas and transfer image onto it to access pixel information
                    var canvas = document.createElement('canvas');
                    canvas.width = w;
                    canvas.height = h;
                    var context = canvas.getContext('2d');

                    trace._image = trace._image || new Image();
                    var image = trace._image;
                    image.onload = function() {
                        context.drawImage(image, 0, 0);
                        trace._canvas = {
                            el: canvas,
                            source: trace.source
                        };
                        resolve();
                    };
                    image.setAttribute('src', trace.source);
                }
            }
        })
        .then(function() {
            var href, canvas;
            if(trace._hasZ) {
                canvas = drawMagnifiedPixelsOnCanvas(function(i, j) {return z[j][i];});
                href = canvas.toDataURL('image/png');
            } else if(trace._hasSource) {
                if(realImage) {
                    href = trace.source;
                } else {
                    var context = trace._canvas.el.getContext('2d');
                    var data = context.getImageData(0, 0, w, h).data;
                    canvas = drawMagnifiedPixelsOnCanvas(function(i, j) {
                        var index = 4 * (j * w + i);
                        return [
                            data[index],
                            data[index + 1],
                            data[index + 2],
                            data[index + 3]
                        ];
                    });
                    href = canvas.toDataURL('image/png');
                }
            }

            image3.attr({
                'xlink:href': href,
                height: imageHeight,
                width: imageWidth,
                x: left,
                y: top
            });
        });

        gd._promises.push(p);
    });
};


text:
@interface NSManagedObject (MAGCoreData)

//Key mapping of local names and web service names, key of dictionary is local name and value is web service name
+ (NSDictionary *)keyMapping;
+ (void)setKeyMapping:(NSDictionary*)mapping;
//Inline relation classes for recursive instantiation
+ (NSDictionary *)relationClasses;
+ (void)setRelationClasses:(NSDictionary *)newRelationClasses;
//DefaultDateFormat
//regarding:
//https://developer.apple.com/library/ios/documentation/cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1
//http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns for iOS6
//http://www.unicode.org/reports/tr35/tr35-19.html#Date_Format_Patterns for iOS6
//http://www.unicode.org/reports/tr35/tr35-17.html#Date_Format_Patterns for iOS4.3
+ (NSString *)defaultDateFormat;
+ (void)setDefaultDateFormat:(NSString *)dateFormat;
//DateFormatForEveryField
+ (NSDictionary *)dateFormats;
+ (void)setDateFormats:(NSDictionary *)datesFormat;

//Object unique of external data format
//When it found an object in local model, the object edited instead of inserting,
//if no object found - new object creating
+ (id)primaryKeyName;
+ (void)setPrimaryKeyName:(id)primaryKey;

+ (id)updateDateKeyName;
+ (void)setUpdateDateKeyName:(id)updateKeyName;

//custom values transformers
+ (NSDictionary *)valueTransformers;
+ (void)setValueTransformers:(NSDictionary *)valueTransformers;

- (void)safeSetValuesForKeysWithDictionary:(NSDictionary *)keyedValues;
- (void)safeSetValuesForKeysWithDictionary:(NSDictionary *)keyedValues inContext:(NSManagedObjectContext *)context;

+ (instancetype)objectWithID:(NSManagedObjectID *)managedObjectID;
+ (instancetype)objectWithID:(NSManagedObjectID *)managedObjectID inContext:(NSManagedObjectContext *)context;

+ (instancetype)objectForPrimaryKey:(id)primaryKey inContext:(NSManagedObjectContext *)context;
+ (instancetype)objectForPrimaryKey:(id)primaryKey;

+ (instancetype)getOrCreateObjectForPrimaryKey:(id)primaryKey;
+ (instancetype)getOrCreateObjectForPrimaryKey:(id)primaryKey inContext:(NSManagedObjectContext *)context;

+ (instancetype)safeCreateOrUpdateWithDictionary:(NSDictionary *)keyedValues;
+ (instancetype)safeCreateOrUpdateWithDictionary:(NSDictionary *)keyedValues inContext:(NSManagedObjectContext *)context;

+ (instancetype)create;
+ (instancetype)createInContext:(NSManagedObjectContext *)context;
+ (instancetype)createFromDictionary:(NSDictionary *)dictionary;
+ (instancetype)createFromDictionary:(NSDictionary *)dictionary inContext:(NSManagedObjectContext *)context;

#pragma mark - fetching objects
+ (NSArray *)all;
+ (NSArray *)allForPredicate:(NSPredicate *)predicate;
+ (NSArray *)allForPredicate:(NSPredicate *)predicate orderBy:(NSString *)key ascending:(BOOL)ascending;
+ (NSArray *)allOrderedBy:(NSString *)key ascending:(BOOL)ascending;
+ (NSArray *)allInContext:(NSManagedObjectContext*)context;
+ (NSArray *)allForPredicate:(NSPredicate *)predicate inContext:(NSManagedObjectContext *)context;
+ (NSArray *)allForPredicate:(NSPredicate *)predicate orderBy:(NSString *)key ascending:(BOOL)ascending inContext:(NSManagedObjectContext *)context;
+ (NSArray *)allOrderedBy:(NSString *)key ascending:(BOOL)ascending inContext:(NSManagedObjectContext *)context;

+ (id)first;
+ (id)firstWithKey:(NSString *)key value:(id)value;
+ (id)firstForPredicate:(NSPredicate *)predicate orderBy:(NSString *)key ascending:(BOOL)ascending;
+ (id)firstForPredicate:(NSPredicate *)predicate orderBy:(NSString *)key ascending:(BOOL)ascending inContext:(NSManagedObjectContext *)context;

+ (id)firstInContext:(NSManagedObjectContext *)context;
+ (id)firstWithKey:(NSString *)key value:(id)value inContext:(NSManagedObjectContext *)context;

#pragma mark - deleting objects
+ (void)deleteAll;
+ (void)deleteAllInContext:(NSManagedObjectContext *)context;
- (void)delete;

#pragma mark - refreshing object
- (void)refreshMerging:(BOOL)merging;

@end


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

<title>Deprecated List (ParseFacebookUtilsV3 1.10.3 API)</title>
<meta name="date" content="2015-11-11">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Deprecated API

Contents

Deprecated Methods

Deprecated Methods

Method and Description

com.parse.ParseFacebookUtils.extendAccessToken(ParseUser, Context, SaveCallback)

This is now handled automatically by the Facebook SDK.

com.parse.ParseFacebookUtils.extendAccessTokenIfNeeded(ParseUser, Context, SaveCallback)

This is now handled automatically by the Facebook SDK.

com.parse.ParseFacebookUtils.getFacebook()

Please use ParseFacebookUtils.getSession() and related Facebook SDK 3.0+ APIs instead.

com.parse.ParseFacebookUtils.initialize()

Please use ParseFacebookUtils.initialize(Context) instead.

com.parse.ParseFacebookUtils.initialize(String)

Please use ParseFacebookUtils.initialize(Context, String) instead.

com.parse.ParseFacebookUtils.link(ParseUser, Activity)

Please use ParseFacebookUtils.linkInBackground(ParseUser, android.app.Activity) instead.

com.parse.ParseFacebookUtils.link(ParseUser, Activity, int)

Please use ParseFacebookUtils.linkInBackground(ParseUser, android.app.Activity, int) instead.

com.parse.ParseFacebookUtils.link(ParseUser, Collection<String>, Activity)

Please use ParseFacebookUtils.linkInBackground(ParseUser, java.util.Collection,
 android.app.Activity) instead.

com.parse.ParseFacebookUtils.link(ParseUser, Collection<String>, Activity, int)

Please use ParseFacebookUtils.linkInBackground(ParseUser, java.util.Collection,
 android.app.Activity, int) instead.

com.parse.ParseFacebookUtils.link(ParseUser, String, String, Date)

Please use ParseFacebookUtils.linkInBackground(ParseUser, String, String, java.util.Date)
 instead.

com.parse.ParseFacebookUtils.saveLatestSessionData(ParseUser)

Please use ParseFacebookUtils.saveLatestSessionDataInBackground(ParseUser) instead.

com.parse.ParseFacebookUtils.shouldExtendAccessToken(ParseUser)

This is now handled automatically by the Facebook SDK.

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
function about()
    local result = {}
    result.author = "Kwan Lee"
    result.name   = "Chronograph Face"
    return result
end

COLOR_BATTERY_LOW  = 0xfff72124
COLOR_BATTERY_MED  = 0xffee7a24
COLOR_BATTERY_HIGH = 0xff69ba44
COLOR_NOTIFICATION = 0xff28bbeb

function init()
    local atlas = face:loadAtlas('all.atlas')
    backdrop = atlas:createSprite("backdrop")
    face:add(backdrop)
    face:add(atlas:createSprite("clockface"))

    stopwatchMinute = atlas:createSprite("small_hand")
    stopwatchMinute:setPivot(5, 24)
    stopwatchMinute:setPosition(164, 89)
    face:add(stopwatchMinute)

    stopwatchSecond = atlas:createSprite("small_hand")
    stopwatchSecond:setPivot(5, 24)
    stopwatchSecond:setPosition(76, 89)
    face:add(stopwatchSecond)

    hourHandBackdrop = atlas:createSprite("hour_hand_backdrop")
    hourHandBackdrop:setPivot(8, 73)
    hourHandBackdrop:setPosition(120, 120)
    face:add(hourHandBackdrop)

    hourHand = atlas:createSprite("hour_hand")
    hourHand:setPivot(8, 73)
    hourHand:setPosition(120, 120)
    face:add(hourHand)

    minuteHandBackdrop = atlas:createSprite("minute_hand_backdrop")
    minuteHandBackdrop:setPivot(6, 103)
    minuteHandBackdrop:setPosition(120, 120)
    face:add(minuteHandBackdrop)

    minuteHand = atlas:createSprite("minute_hand")
    minuteHand:setPivot(6, 103)
    minuteHand:setPosition(120, 120)
    face:add(minuteHand)

    secondHand = atlas:createSprite("second_hand")
    secondHand:setPivot(5, 102)
    secondHand:setPosition(120, 120)
    face:add(secondHand)
end

function update()
    local hour   = time:get(Calendar.HOUR)
    local minute = time:get(Calendar.MINUTE)
    local second = time:get(Calendar.SECOND)

    local batteryPercent = deviceStatus:getBatteryPercent()
    local color;
    if batteryPercent <= 20 then
        color = COLOR_BATTERY_LOW
    elseif batteryPercent < 80 then
        color = COLOR_BATTERY_MED
    else
        color = COLOR_BATTERY_HIGH
    end

    backdrop:setColor(color)
    hourHandBackdrop:setColor(color)
    minuteHandBackdrop:setColor(color)
    secondHand:setColor(color)
    stopwatchMinute:setColor(color)
    stopwatchSecond:setColor(color)

    hourHand  :setRotation(360 / 12 * (hour + minute / 60))
    minuteHand:setRotation(360 / 60 * (minute + second / 60))
    secondHand:setRotation(360 / 60 * second)
    hourHandBackdrop  :setRotation(360 / 12 * (hour + minute / 60))
    minuteHandBackdrop:setRotation(360 / 60 * (minute + second / 60))

    secondHand:setVisible(deviceStatus:isShowSeconds())
end


text:
import { AccordionClassKey } from './Accordion';

export type AccordionClasses = Record<AccordionClassKey, string>;

declare const accordionClasses: AccordionClasses;

export function getAccordionUtilityClass(slot: string): string;

export default accordionClasses;


text:
/**
 * Autogenerated by Thrift Compiler (0.9.2)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
#ifndef job_model_TYPES_H
#define job_model_TYPES_H

#include <iosfwd>

#include <thrift/Thrift.h>
#include <thrift/TApplicationException.h>
#include <thrift/protocol/TProtocol.h>
#include <thrift/transport/TTransport.h>

#include <thrift/cxxfunctional.h>
#include "status_models_types.h"

namespace apache { namespace airavata { namespace model { namespace job {

class JobModel;

typedef struct _JobModel__isset {
  _JobModel__isset() : creationTime(false), jobStatus(false), computeResourceConsumed(false), jobName(false), workingDir(false), stdOut(false), stdErr(false), exitCode(false) {}
  bool creationTime :1;
  bool jobStatus :1;
  bool computeResourceConsumed :1;
  bool jobName :1;
  bool workingDir :1;
  bool stdOut :1;
  bool stdErr :1;
  bool exitCode :1;
} _JobModel__isset;

class JobModel {
 public:

  static const char* ascii_fingerprint; // = "EFFF4955898CBB369996B994565E85FE";
  static const uint8_t binary_fingerprint[16]; // = {0xEF,0xFF,0x49,0x55,0x89,0x8C,0xBB,0x36,0x99,0x96,0xB9,0x94,0x56,0x5E,0x85,0xFE};

  JobModel(const JobModel&);
  JobModel& operator=(const JobModel&);
  JobModel() : jobId(), taskId(), processId(), jobDescription(), creationTime(0), computeResourceConsumed(), jobName(), workingDir(), stdOut(), stdErr(), exitCode(0) {
  }

  virtual ~JobModel() throw();
  std::string jobId;
  std::string taskId;
  std::string processId;
  std::string jobDescription;
  int64_t creationTime;
   ::apache::airavata::model::status::JobStatus jobStatus;
  std::string computeResourceConsumed;
  std::string jobName;
  std::string workingDir;
  std::string stdOut;
  std::string stdErr;
  int32_t exitCode;

  _JobModel__isset __isset;

  void __set_jobId(const std::string& val);

  void __set_taskId(const std::string& val);

  void __set_processId(const std::string& val);

  void __set_jobDescription(const std::string& val);

  void __set_creationTime(const int64_t val);

  void __set_jobStatus(const  ::apache::airavata::model::status::JobStatus& val);

  void __set_computeResourceConsumed(const std::string& val);

  void __set_jobName(const std::string& val);

  void __set_workingDir(const std::string& val);

  void __set_stdOut(const std::string& val);

  void __set_stdErr(const std::string& val);

  void __set_exitCode(const int32_t val);

  bool operator == (const JobModel & rhs) const
  {
    if (!(jobId == rhs.jobId))
      return false;
    if (!(taskId == rhs.taskId))
      return false;
    if (!(processId == rhs.processId))
      return false;
    if (!(jobDescription == rhs.jobDescription))
      return false;
    if (__isset.creationTime != rhs.__isset.creationTime)
      return false;
    else if (__isset.creationTime && !(creationTime == rhs.creationTime))
      return false;
    if (__isset.jobStatus != rhs.__isset.jobStatus)
      return false;
    else if (__isset.jobStatus && !(jobStatus == rhs.jobStatus))
      return false;
    if (__isset.computeResourceConsumed != rhs.__isset.computeResourceConsumed)
      return false;
    else if (__isset.computeResourceConsumed && !(computeResourceConsumed == rhs.computeResourceConsumed))
      return false;
    if (__isset.jobName != rhs.__isset.jobName)
      return false;
    else if (__isset.jobName && !(jobName == rhs.jobName))
      return false;
    if (__isset.workingDir != rhs.__isset.workingDir)
      return false;
    else if (__isset.workingDir && !(workingDir == rhs.workingDir))
      return false;
    if (__isset.stdOut != rhs.__isset.stdOut)
      return false;
    else if (__isset.stdOut && !(stdOut == rhs.stdOut))
      return false;
    if (__isset.stdErr != rhs.__isset.stdErr)
      return false;
    else if (__isset.stdErr && !(stdErr == rhs.stdErr))
      return false;
    if (__isset.exitCode != rhs.__isset.exitCode)
      return false;
    else if (__isset.exitCode && !(exitCode == rhs.exitCode))
      return false;
    return true;
  }
  bool operator != (const JobModel &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const JobModel & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  friend std::ostream& operator<<(std::ostream& out, const JobModel& obj);
};

void swap(JobModel &a, JobModel &b);

}}}} // namespace

#endif


text:
const path = require('path')
const glob = require('glob')
const menubar = require('./lib/menubar')
const electron = require('electron')
const dialog = electron.dialog
const fs = require('fs')

const id3Parser = require('id3-parser')
const Server = require('electron-rpc/server')
const LastFM = require('./plugins/lastfm')
const Chromecast = require('./plugins/chromecast')
const modules = { }

const DEBUG = process.env.DEBUG
const MODULES_PATH = path.join(__dirname, 'modules')
const TRAY_ICON = path.join(__dirname, 'images', 'tray.png')
const TRAY_ICON_HIGHLIGHTED = path.join(__dirname, 'images', 'tray_inverted.png')

var opts = {
  dir: __dirname,
  icon: TRAY_ICON,
  tooltip: 'MP3/Radio tray player',
  width: DEBUG ? 1000 : 440,
  height: 420,
  preloadWindow: true,
  resizable: false
}

if (process.platform === 'darwin') {
  opts.y = 26
}

var menu = menubar(opts)
var app = new Server()

process.on('uncaughtException', function (err) {
  console.error('Exception', err)
  menu.app.quit()
})

menu.on('ready', function ready () {
  app.on('sources', function sources () {
    glob.sync(MODULES_PATH + '/*.js').forEach(function (file) {
      var name = path.parse(file).base.replace('.js', '')
      console.log('*** Found module:', name, 'in file:', file)
      modules[name] = require(file) // eslint-disable-line global-require
    })

    app.send('sources', { sources: Object.getOwnPropertyNames(modules) })
  })

  app.on('cover', function cover (ev) {
    LastFM.getCover(ev.body).then((cover) => {
      console.log('*** COCVER', cover)
      app.send('cover', { image: cover })
    }).catch((err) => {
      console.log(err)
    })
  })

  app.on('chromecast', () => {
    Chromecast.startScan()
    Chromecast.browser.on('serviceUp', (service) => {
      console.log('found device "%s" at %s:%d', service.txtRecord.fn, service.addresses[0], service.port)
      app.send('device', { name: service.txtRecord.fn, address: service.addresses[0] })

      setTimeout(function () {
        Chromecast.browser.stop()
      }, 10000)
    })
  })

  app.on('chromecast-play', (payload) => {
    console.log('NOTE: Chromcast play', payload.body)
    Chromecast.play(payload.body.device.address, payload.body.stream)
  })

  // FIXME: Move to plugin
  app.on('open', function open () {
    var dir = dialog.showOpenDialog({
      properties: ['openDirectory']
    })

    if (!dir) return

    var directory = dir[0]
    var playlist = []

    var files = fs.readdirSync(directory).filter(function (file) {
      return file.endsWith('.mp3')
    })

    files.forEach(function (item, index) {
      var track = path.join(directory, item)
      id3Parser.parse(fs.readFileSync(track)).then(function (tags) {
        console.log(tags)
        const song = {}
        song.stream = track

        if (tags.title && tags.artist) {
          song.title = tags.title
          song.artist = tags.artist
          song.name = tags.artist + ' - ' + tags.title
          song.image = (tags.image && tags.image.data) ? `data:image/png;base64,${tags.image.data.toString('base64')}` : null
        } else {
          console.warn('No tags')
          song.title = item
        }

        playlist.push(song)

        if (files.length === index + 1) {
          app.send('show', { playlist: playlist })
        }
      })
    })
  })

  app.on('load', function load (ev) {
    var key = ev.body
    console.log(modules)
    const module = modules[key]
    if (module) {
      modules[key].load().then(function (playlist) {
        app.send('show', { playlist: playlist })
      })
    } else {
      console.warn('WARN:', 'Playlist/module:', key, 'not found!')
    }
  })

  app.on('terminate', function terminate () {
    menu.app.quit()
  })
})

menu.once('show', function () {
  if (DEBUG) {
    menu.window.openDevTools({ detach: false })
  }
})

menu.on('show', function show () {
  console.log('show')
  menu.tray.setImage(TRAY_ICON_HIGHLIGHTED)
  app.configure(menu.window.webContents)
})

menu.on('hide', () => {
  console.log('window hide')
  menu.tray.setImage(TRAY_ICON)
})

menu.on('after-create-window', function () {
  app.configure(menu.window.webContents)
})


text:
all: build
pdf:
	./dist/build/make-pdf/make-pdf > sample.tex
	pdflatex sample.tex

include common.mk


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SharpHelper
{
    /// <summary>
    /// Helper to count frame per seconds
    /// </summary>
    public class SharpFPS
    {
        /// <summary>
        /// Last computed FPS
        /// </summary>
        public int FPS { get; private set; }

        private int n1;
        private long timeout;

        private System.Diagnostics.Stopwatch watch;

        /// <summary>
        /// Constructor
        /// </summary>
        public SharpFPS()
        {
            watch=new System.Diagnostics.Stopwatch();
            Reset();
        }

        /// <summary>
        /// Reset Counter
        /// </summary>
        public void Reset()
        {
            watch.Reset();
            n1 = 0;
            timeout = watch.ElapsedMilliseconds;
            FPS = 0;
            watch.Start();
        }

        /// <summary>
        /// Update counter. This must be executed every frame in render loop
        /// </summary>
        public void Update()
        {
            n1++;
            if (watch.ElapsedMilliseconds - timeout >= 1000)
            {
                FPS = n1;
                n1 = 0;
                timeout = watch.ElapsedMilliseconds;
            }
        }

    }
}


text:
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
-- |
-- Module:       Network.SIP.Type.Error
-- Description:  Type used for error exceptions raised from whole SIP.
-- Copyright:    Copyright (c) 2015-2016 Jan Sipr
-- License:      MIT
--
-- Type used for error exceptions raised from whole SIP.
-- This was taken from warp package and slightly modified.
-- https://github.com/yesodweb/wai/blob/master/warp/Network/Wai/Handler/Warp/Types.hs
module Network.SIP.Type.Error where

import Control.Exception (Exception)
import Data.Eq (Eq)
import Data.Monoid ((<>))
import Data.String (String)
import Data.Typeable (Typeable)
import Text.Show (Show, show)

-- | Error types for bad 'SIP message.
data InvalidMessage
    = BadContentLength
    | BadFirstLine String
    | BadProxyHeader String
    | ConnectionClosedByPeer
    | IncompleteHeaders
    | NonSip
    | NotEnoughLines [String]
    | OverLargeHeader
    | WrongHeader
  deriving (Eq, Typeable)

instance Show InvalidMessage where
    show (NotEnoughLines xs) = "Incomplete request headers, received: "
        <> show xs
    show BadContentLength = "Content Length is in wrong format"
    show (BadFirstLine s) = "Invalid first line of message: " <> show s
    show NonSip = "Request/Response line is not regognized; non-SIP message"
    show IncompleteHeaders =
        "Message headers did not finish transmission"
    show ConnectionClosedByPeer = "Client closed connection prematurely"
    show OverLargeHeader = "Message headers too large, possible memory\
        \ attack detected."
    show (BadProxyHeader s) = "Invalid PROXY protocol header: "
        <> show s
    show WrongHeader = "Wrong header"

instance Exception InvalidMessage


text:
namespace MvvmFx.Bindings.Data
{
    /// <summary>
    /// Provides binding options for single-source binding fluent expressions.
    /// </summary>
    public interface ISingleSourceBindingOptions : IConverterSelection<ISingleSourceBindingOptions, IValueConverter>,
                                                   IModeSelection<ISingleSourceBindingOptions>, IActivation
    {
    }
}


text:
package graphene.hts.keywords;

import graphene.hts.entityextraction.AbstractExtractor;
import graphene.model.idl.G_CanonicalPropertyType;
import graphene.model.idl.G_CanonicalRelationshipType;
import graphene.model.idl.G_EntityTag;

import java.util.List;
import java.util.regex.Pattern;

public class KeywordExtractorImpl extends AbstractExtractor {
	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * graphene.hts.keywords.KeywordExtractor#getSimpleKeywords(java.lang.String
	 * )
	 */
	private final static String RE_1 = "([\\w\\d]{3,})";

	// @Override
	// public SortedSet<String> getSimpleKeywords(String narrative) {
	// TreeSet<String> keyWords = new TreeSet<String>(
	// Arrays.asList(((String) narrative).split("([\\w\\d]{3,})")));
	// for (Iterator<String> iter = keyWords.iterator(); iter.hasNext();) {
	// String k = iter.next();
	// if (k.length() < 2) {
	// iter.remove();
	// }
	// }
	// return keyWords;
	// }

	public KeywordExtractorImpl() {
		p = Pattern.compile(RE_1);
	}

	@Override
	public List<G_EntityTag> getEntityTags() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getIdType() {
		return "Keyword";
	}

	@Override
	public String getNodetype() {
		return "Extracted" + G_CanonicalPropertyType.ANY.name();
	}

	@Override
	public String getRelationType() {
		return G_CanonicalRelationshipType.IN_DOCUMENT.name();
	}

	@Override
	public String getRelationValue() {
		return "Keyword in document";
	}

}


text:
<?php

namespace RiakClientFunctionalTest\Command\MapReduce;

/**
 * @group proto
 * @group functional
 */
class BucketMapReduceProtoTest extends BucketMapReduceTest
{
    /**
     * {@inheritdoc}
     */
    protected function createClient()
    {
        return $this->createRiakProtoClient();
    }
}


text:
$A.bind(window, "load", function() {
  var createMenuIcon = function(lbl, triggerObj, descId) {
    // Create a menu icon for touch screen devices to ensure accessibility for screen reader users, must have a textual label, and a triggerObj to be bound to.
    if (!lbl || !triggerObj) return;

    var a = $A.createEl(
      "a",
      {
        role: "button",
        href: "#",
        "aria-label": lbl,
        "aria-describedby": descId
      },
      {
        position: "absolute"
      },
      "menu-icon",
      $A.createEl("span")
    );

    $A.bind(a, {
      click: function(ev) {
        ev.stopPropagation();
        ev.preventDefault();
        $A.trigger(triggerObj, "popupmenu");
      }
    });
    return a;
  };

  // Configure menu functionality

  $A.setMenu(
    "#blackboardId",
    "hiddenDivId",
    "context-menu",
    function(ev, dc) {
      // Ignore menu item nodes that include aria-disabled="true" when clicked
      if ($A.getAttr(this, "aria-disabled") == "true") return false;
      else alert('Do something with this.href or id="' + this.id + '"');

      // dc.top.triggerObj is the right clicked edit field DOM node
      alert(dc.top.triggerObj.id);
    },
    true,
    document,
    {
      // Enable right click functionality
      // Automatically configures keyboard support using Shift+F10 and the Applications key
      rightClick: true,

      // Set the accessible help description that will be announced for screen reader users
      rightClickText:
        "Press Shift+F10 or the Applications key to open the popup menu",

      // Specify the menu tag name in the markup
      menuTag: "ol",

      // Specify the active element that will be used as each menu item node
      // Important, if nesting A tags within LIs, only the A tag should be used for this purpose
      // Active elements should never be nested.
      // The following tag will receive keyboard focus within the menu structure when using the arrow keys to navigate
      // Event bindings are also tied to this tag
      itemTag: "a",

      // Disable auto positioning for submenus
      autoPosition: 0,

      // Set AccDC API overrides to customize functionality
      overrides: {
        // Set inline styling that will be included within each menu instance
        // z-index is automatically incremented using +=1 for proper layering
        cssObj: {
          position: "absolute",
          zIndex: 1
        },

        // Run script while each menu is rendering, occurs before DOM insertion
        runDuring: function(dc) {
          // Set specific styling for the parent Div if this is the top level menu instance
          // Set initial positioning before DOM insertion to prevent screen flicker from occuring
          if (dc.top == dc) {
            dc.top.css({
              top: $A.xOffset(dc.top.triggerObj).top + 50,
              left:
                $A.xOffset(dc.top.triggerObj).left +
                dc.top.triggerObj.offsetWidth * 0.4
            });
          } else {
            // Otherwise, set the container styling that is applied to all submenu instances
            // In this case, dc.triggerObj references the parent menu triggering element
            if (dc.triggerObj)
              dc.css({
                "margin-left": dc.triggerObj.offsetWidth / 2 + "px",
                "margin-top": -(dc.triggerObj.offsetHeight / 2) + "px"
              });
          }
        },

        // Run script after each menu finishes rendering
        runAfter: function(dc) {
          // Do other stuff after the menu finishes rendering
        }
      }
    }
  );

  // Create a clickable hamburger icon for touch screen device users, and bind one for each triggering element
  if ("ontouchstart" in window) {
    $A.query("#blackboardId", document, function(i, tgr) {
      var mI = createMenuIcon("Open Menu", tgr, "titleId"),
        position = function() {
          $A.css(mI, {
            left: $A.xOffset(tgr).left + tgr.offsetWidth + 3,
            top: $A.xOffset(tgr).top
          });
        };

      position();
      tgr.parentNode.appendChild(mI);
      $A.bind(window, "resize", position);
    });
  }
});


text:
{- |
Module      :  Camfort.Specification.Units.ModFile
Description :  Helpers for working with units-relevant ModFiles.
Copyright   :  (c) 2017, Dominic Orchard, Andrew Rice, Mistral Contrastin, Matthew Danish
License     :  Apache-2.0

Maintainer  :  dom.orchard@gmail.com
Stability   :  experimental
-}

{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric      #-}

module Camfort.Specification.Units.ModFile
  (
    genUnitsModFile
  , initializeModFiles
  , runCompileUnits
  ) where

import           Control.Monad.State (get, gets, lift)
import           Data.Binary (Binary, decodeOrFail, encode)
import qualified Data.ByteString.Lazy.Char8 as LB
import           Data.Data (Data)
import           Data.Generics.Uniplate.Operations (universeBi)
import           Data.List (partition)
import qualified Data.Map.Strict            as M
import           Data.Typeable (Typeable)
import           GHC.Generics (Generic)

import qualified Language.Fortran.AST as F
import           Language.Fortran.Util.ModFile

import Camfort.Analysis (analysisModFiles)
import Camfort.Specification.Units.Annotation (UA)
import Camfort.Specification.Units.Environment (Constraint(..), foldUnits, UnitInfo(..), colSort)
import Camfort.Specification.Units.InferenceBackend (flattenConstraints, flattenUnits, genUnitAssignments, genUnitAssignments')
import Camfort.Specification.Units.Monad

-- | The data-structure stored in 'fortran-src mod files'
data CompiledUnits = CompiledUnits
  { cuTemplateMap  :: TemplateMap
  , cuNameParamMap :: NameParamMap
  } deriving (Ord, Eq, Show, Data, Typeable, Generic)

instance Binary CompiledUnits

emptyCompiledUnits :: CompiledUnits
emptyCompiledUnits = CompiledUnits M.empty M.empty

combinedCompiledUnits :: ModFiles -> CompiledUnits
combinedCompiledUnits mfs = CompiledUnits { cuTemplateMap = M.unions tmaps
                                          , cuNameParamMap = M.unions nmaps }
  where
    cus = map mfCompiledUnits mfs
    tmaps = map cuTemplateMap cus
    nmaps = map cuNameParamMap cus

-- | Name of the labeled data within a ModFile containing unit-specific info.
unitsCompiledDataLabel :: String
unitsCompiledDataLabel = "units-compiled-data"

mfCompiledUnits :: ModFile -> CompiledUnits
mfCompiledUnits mf = case lookupModFileData unitsCompiledDataLabel mf of
  Nothing -> emptyCompiledUnits
  Just bs -> case decodeOrFail (LB.fromStrict bs) of
    Left _ -> emptyCompiledUnits
    Right (_, _, cu) -> cu

-- | Initialize units-relevant ModFile information.
initializeModFiles :: UnitSolver ()
initializeModFiles = do
  mfs <- lift . lift $ analysisModFiles
  let compiledUnits = combinedCompiledUnits mfs
  modifyTemplateMap  . const . cuTemplateMap  $ compiledUnits
  modifyNameParamMap . const . cuNameParamMap $ compiledUnits

-- | Produce information for a "units-mod" file.
runCompileUnits :: UnitSolver CompiledUnits
runCompileUnits = do
  cons <- usConstraints `fmap` get

  let unitAssigns = flattenConstraints cons
  let epsilon = 0.001 -- arbitrary
  let approxEq a b = abs (b - a) < epsilon

  let variables = M.fromList [ (NPKVariable var, units) | ([UnitPow (UnitVar var) k], units) <- unitAssigns
                                                        , k `approxEq` 1 ]

  tmap <- M.map optimiseTemplate `fmap` gets usTemplateMap
  let npm = variables

  -- D.traceM $ "npm = " ++ unlines (map show (M.toList npm))
  -- D.traceM $ "tmap = \n" ++ unlines [ f ++ "\n" ++ unlines (map show cons) | (f, cons) <- M.toList tmap ]
  pure CompiledUnits { cuTemplateMap = tmap, cuNameParamMap = variables }

optimiseTemplate cons = map (\ (l, r) -> ConEq (foldUnits l) r) optimised
  where
    unitAssigns  = genUnitAssignments' (compileColSort) cons
    unitPows     = map (fmap flattenUnits) unitAssigns
    optimised    = filter cull $ map (fmap foldUnits . shiftTerms) unitPows

    cull (lhs, _) = or [ True | (UnitPow (UnitParamPosAbs _) _) <- universeBi lhs ]

    isUnitRHS (UnitPow (UnitName _) _)        = True
    isUnitRHS (UnitPow (UnitParamEAPAbs _) _) = True
    isUnitRHS (UnitPow (UnitParamImpAbs _) _) = True
    isUnitRHS (UnitPow (UnitParamPosAbs _) _) = False
    isUnitRHS _                               = False

    negateCons = map (\ (UnitPow u k) -> UnitPow u (-k))

    shiftTerms :: ([UnitInfo], [UnitInfo]) -> ([UnitInfo], [UnitInfo])
    shiftTerms (lhs, rhs) = (lhsOk ++ negateCons rhsShift, rhsOk ++ negateCons lhsShift)
      where
        (lhsOk, lhsShift) = partition (not . isUnitRHS) lhs
        (rhsOk, rhsShift) = partition isUnitRHS rhs

    compileColSort = flip colSort

-- | Generate a new ModFile containing Units information.
genUnitsModFile :: F.ProgramFile UA -> CompiledUnits -> ModFile
genUnitsModFile pf cu = alterModFileData f unitsCompiledDataLabel $ genModFile pf
  where
    f _ = Just . LB.toStrict $ encode cu


text:
namespace HallScheduler.Data.Migrations.Seed.Seeders
{
    using Common.Enumerations;
    using Contexts;
    using HallScheduler.Common.Constants;
    using Models;
    using System;
    using System.Collections.Generic;
    using System.Data.Entity.Migrations;
    using System.Linq;

    public class EventsSeeder : ISeeder
    {
        public int Priority { get; set; } = 4;

        public Random Generator { get; set; } = new Random();

        public void Seed(HallSchedulerDbContext context)
        {
            if (!context.Events.Any())
            {
                var professorRole = context.Roles.Where(x => x.Name == Roles.Professor).FirstOrDefault();

                var eventTopics = new string[]
                {
                    "Introduction to Programming with C",
                    "Object-oriented programming with Java",
                    "Data structures and algorithms",
                    "Relational databases",
                    "Desktop applications with WPF",
                    "Mobile applications",
                    "Cross-platform mobile applications with Xamarin",
                    "Cross-platform mobile applications with NativeScript",
                    "Concurrent and parallel programming with C#"
                };

                var halls = context.Halls.Where(x => x.Type != HallType.Cabinet).ToList();
                var users = context.Users.Where(x => x.Roles.Any(z => z.RoleId == professorRole.Id)).ToList();
                var daysOfWeek = new List<DayOfWeek>(5)
                {
                    DayOfWeek.Monday,
                    DayOfWeek.Tuesday,
                    DayOfWeek.Wednesday,
                    DayOfWeek.Thursday,
                    DayOfWeek.Friday
                };

                TimeSpan[] start = new TimeSpan[] {
                    new TimeSpan(7,30,0),
                    new TimeSpan(9,30,0),
                    new TimeSpan(11,30,0),
                    new TimeSpan(13,45,0),
                    new TimeSpan(15,45,0),
                    new TimeSpan(17,45,0),
                    new TimeSpan(19,45,0),
                };

                TimeSpan[] end = new TimeSpan[] {
                    new TimeSpan(9,15,0),
                    new TimeSpan(11,15,0),
                    new TimeSpan(13,15,0),
                    new TimeSpan(15,30,0),
                    new TimeSpan(17,30,0),
                    new TimeSpan(19,30,0),
                    new TimeSpan(21,30,0),
                };

                for (int i = 0; i < 50; i++)
                {
                    var hall = halls[i];

                    for (int k = 0; k < daysOfWeek.Count; k++)
                    {
                        var day = daysOfWeek[k];

                        for (int j = 0; j < start.Length; j++)
                        {
                            var lecturer = users[this.Generator.Next(0, users.Count)];
                            var topic = eventTopics[this.Generator.Next(0, eventTopics.Length)];
                            var hallEvent = new Event()
                            {
                                HallId = hall.Id,
                                LecturerId = lecturer.Id,
                                DayOfWeek = day,
                                StartsAt = start[j],
                                EndsAt = end[j],
                                Topic = topic
                            };

                            context.Events.AddOrUpdate(hallEvent);
                        }
                    }

                    context.SaveChanges();
                }
            }
        }
    }
}


text:
namespace Cassandra.Requests
{
    internal class ValidHost
    {
        private ValidHost(Host host, HostDistance distance)
        {
            Host = host;
            Distance = distance;
        }

        public Host Host { get; }

        public HostDistance Distance { get; }

        ///
        /// Builds a <see cref="ValidHost"/> instance.
        ///
        /// <returns>Newly built instance if valid or null if not valid
        /// (e.g. the host is ignored or the driver sees it as down)</returns>
        public static ValidHost New(Host host, HostDistance distance)
        {
            if (distance == HostDistance.Ignored)
            {
                // We should not use an ignored host
                return null;
            }

            if (!host.IsUp)
            {
                // The host is not considered UP by the driver.
                // We could have filtered earlier by hosts that are considered UP, but we must
                // check the host distance first.
                return null;
            }

            return new ValidHost(host, distance);
        }
    }
}


text:
package org.jboss.weld.tests.unit.reflection.util;

import java.io.Serializable;
import java.io.Writer;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;

import javax.enterprise.util.TypeLiteral;

import org.junit.Assert;

import org.jboss.weld.resolution.AssignabilityRules;
import org.jboss.weld.resolution.BeanTypeAssignabilityRules;
import org.jboss.weld.util.reflection.Reflections;
import org.junit.Test;

/**
 * @author Marko Luksa
 * @author Jozef Hartinger
 */
@SuppressWarnings("serial")
public class BeanTypeAssignabilityTest {

    protected AssignabilityRules getRules() {
        return BeanTypeAssignabilityRules.instance();
    }

    @Test
    public void testGetRawType() throws Exception {
        Assert.assertEquals(Foo.class, Reflections.getRawType(new TypeLiteral<Foo<Integer>>() {
        }.getType()));
    }

    @Test
    public void testGetRawTypeOfArray() throws Exception {
        Assert.assertEquals(Foo[].class, Reflections.getRawType(new TypeLiteral<Foo<Integer>[]>() {
        }.getType()));
    }

    @Test
    public void testIntegerFooMatchesItself() throws Exception {
        Type type = new TypeLiteral<Foo<Integer>>() {
        }.getType();
        Assert.assertTrue("type should match itself", getRules().matches(type, type));
    }

    @Test
    public void testIntegerFooDoesNotMatchStringFoo() throws Exception {
        Type type1 = new TypeLiteral<Foo<Integer>>() {
        }.getType();
        Type type2 = new TypeLiteral<Foo<String>>() {
        }.getType();
        Assert.assertFalse("Foo<Integer> should not match Foo<String>", getRules().matches(type1, type2));
    }

    @Test
    public void testFooMatchesItself() throws Exception {
        Type type = Foo.class;
        Assert.assertTrue("type should match itself", getRules().matches(type, type));
    }

    @Test
    public void testParameterizedArrayDoesNotMatchComponentOfArray() throws Exception {
        Type arrayType = new TypeLiteral<Foo<String>[]>() {
        }.getType();
        Type componentType = new TypeLiteral<Foo<String>>() {
        }.getType();
        Assert.assertFalse("array type should not match its component type", getRules().matches(arrayType, componentType));
    }

    @Test
    public void testParameterizedArrayMatches() throws Exception {
        Type type = new TypeLiteral<Foo<Integer>[]>() {
        }.getType();
        Assert.assertTrue("type should match itself", getRules().matches(type, type));
    }

    @Test
    public void testArraysDontMatch() throws Exception {
        Type type1 = new TypeLiteral<Foo<Integer>[]>() {
        }.getType();
        Type type2 = new TypeLiteral<Foo<String>[]>() {
        }.getType();
        Assert.assertFalse("Foo<Integer>[] should not match Foo<String>[]", getRules().matches(type1, type2));
    }

    @Test
    public void testWildcardFooMatchesStringFoo() throws Exception {
        Type stringFooType = new TypeLiteral<Foo<String>>() {
        }.getType();
        Type wildcardFooType = new TypeLiteral<Foo<?>>() {
        }.getType();
        Assert.assertTrue("Foo<?> should be assignable from Foo<String>", getRules().matches(wildcardFooType, stringFooType));
    }

    @Test
    public void testWildcardFooArrayMatchesStringFooArray() throws Exception {
        Type stringFooArrayType = new TypeLiteral<Foo<String>[]>() {
        }.getType();
        Type wildcardFooArrayType = new TypeLiteral<Foo<?>[]>() {
        }.getType();
        Assert.assertTrue("Foo<?>[] should be assignable from Foo<String>[]", getRules().matches(wildcardFooArrayType, stringFooArrayType));
    }

    @Test
    public void testStringFooArrayDoesNotMatchWildcardFooArray() throws Exception {
        Type stringFooArrayType = new TypeLiteral<Foo<String>[]>() {
        }.getType();
        Type wildcardFooArrayType = new TypeLiteral<Foo<?>[]>() {
        }.getType();
        Assert.assertFalse("Foo<String>[] should not be assignable from Foo<?>[]", getRules().matches(stringFooArrayType, wildcardFooArrayType));
    }

    @Test
    public <E> void testVariableFooMatchesItself() throws Exception {
        Type type = new TypeLiteral<Foo<E>>() {
        }.getType();
        Assert.assertTrue("Foo<E> should be assignable from Foo<E>", getRules().matches(type, type));
    }

    @Test
    public <E> void testStringFooMatchesVariableFoo() throws Exception {
        Type stringFooType = new TypeLiteral<Foo<String>>() {
        }.getType();
        Type variableFooType = new TypeLiteral<Foo<E>>() {
        }.getType();
        Assert.assertTrue("Foo<String> should match Foo<E>", getRules().matches(stringFooType, variableFooType));
    }

    @Test
    public <E> void testVariableFooArrayMatchesItself() throws Exception {
        Type type = new TypeLiteral<Foo<E>[]>() {
        }.getType();
        Assert.assertTrue("Foo<E>[] should be assignable from Foo<E>[]", getRules().matches(type, type));
    }

    @Test
    public void testRawRequiredTypeMatchesParameterizedBeanWithObjectTypeParameter() throws Exception {
        Assert.assertTrue("Foo<Object> should be assignable to Foo", getRules().matches(Foo.class, new TypeLiteral<Foo<Object>>() {
        }.getType()));
    }

    @Test
    public <E> void testRawRequiredTypeMatchesParameterizedBeanWithUnboundedVariableTypeParameter() throws Exception {
        Assert.assertTrue("Foo<E> should be assignable to Foo", getRules().matches(Foo.class, new TypeLiteral<Foo<E>>() {
        }.getType()));
    }

    @Test
    public <F extends Number> void testParameterizedBeanWithBoundedVariableTypeParameter() throws Exception {
        Assert.assertFalse("Foo<F extends Number> should not be assignable to Foo", getRules().matches(Foo.class, new TypeLiteral<Foo<F>>() {
        }.getType()));
    }

    @Test
    public void testArrays() {
        Assert.assertTrue("int[][] should be assignable to int[][]", getRules().matches(new int[0][].getClass(), new int[0][].getClass()));
        Assert.assertTrue("Integer[][] should be assignable to Integer[][]", getRules().matches(new Integer[0][].getClass(), new Integer[0][].getClass()));
        Assert.assertTrue("List<Integer[][]> should be assignable to List<Integer[][]>", getRules().matches(new TypeLiteral<List<Integer[][]>>() {}.getType(), new TypeLiteral<List<Integer[][]>>() {}.getType()));
        Assert.assertFalse("List<Integer[][]> should not be assignable to List<Number[][]>", getRules().matches(new TypeLiteral<List<Number[][]>>() {}.getType(), new TypeLiteral<List<Integer[][]>>() {}.getType()));
    }

    @Test
    public void testArrayBoxing() {
        /*
         * This is not explicitly said in the CDI spec however Java SE does not support array boxing so neither should CDI.
         */
        Assert.assertFalse("Integer[] should not be assignable to int[]", getRules().matches(new int[0].getClass(), new Integer[0].getClass()));
        Assert.assertFalse("int[] should not be assignable to Integer[]", getRules().matches(new Integer[0].getClass(), new int[0].getClass()));
    }

    @Test
    public <T1 extends Number, T2 extends T1> void testTypeVariableWithTypeVariableBound() {
        Assert.assertTrue("List<T2 extends T1 extends Number> should be assignable to List<Number>", getRules().matches(new TypeLiteral<List<Number>>() {}.getType(), new TypeLiteral<List<T2>>() {}.getType()));
        Assert.assertFalse("List<T2 extends T1 extends Number> should not be assignable to List<Runnable>", getRules().matches(new TypeLiteral<List<Runnable>>() {}.getType(), new TypeLiteral<List<T2>>() {}.getType()));

        Assert.assertTrue("List<T2 extends T1 extends Number> should be assignable to List<T1 extends Number>", getRules().matches(new TypeLiteral<List<T1>>() {}.getType(), new TypeLiteral<List<T2>>() {}.getType()));
        Assert.assertTrue("List<T1 extends Number> should be assignable to List<T2 extends T1 extends Number>", getRules().matches(new TypeLiteral<List<T2>>() {}.getType(), new TypeLiteral<List<T1>>() {}.getType()));
    }

    @Test
    public <T1 extends Exception, T2 extends T1, T3 extends Exception, T4 extends T3, T5 extends Throwable> void testTypeVariablesWithTypeVariableBounds() {
        Assert.assertTrue("List<T2 extends T1 extends Exception> should be assignable to List<T4 extends T3 extends Exception>", getRules().matches(new TypeLiteral<List<T4>>() {}.getType(), new TypeLiteral<List<T2>>() {}.getType()));
        Assert.assertTrue("List<T5 extends Throwable> should be assignable to List<T4 extends T3 extends Exception>", getRules().matches(new TypeLiteral<List<T4>>() {}.getType(), new TypeLiteral<List<T5>>() {}.getType()));
        Assert.assertFalse("List<T4 extends T3 extends Exception> should not be assignable to List<T5 extends Throwable>", getRules().matches(new TypeLiteral<List<T5>>() {}.getType(), new TypeLiteral<List<T4>>() {}.getType()));
    }

    @Test
    public <T1 extends Number, T2 extends T1> void testWildcardWithTypeVariableBound() {
        Assert.assertTrue("List<Number> should be assignable to List<? extends T2 extends T1 extends Number>", getRules().matches(new TypeLiteral<List<? extends T2>>() {}.getType(), new TypeLiteral<List<Number>>() {}.getType()));
        Assert.assertTrue("List<Integer> should be assignable to List<? extends T2 extends T1 extends Number>", getRules().matches(new TypeLiteral<List<? extends T2>>() {}.getType(), new TypeLiteral<List<Integer>>() {}.getType()));
        Assert.assertFalse("List<Object> should not be assignable to List<? extends T2 extends T1 extends Number>", getRules().matches(new TypeLiteral<List<? extends T2>>() {}.getType(), new TypeLiteral<List<Object>>() {}.getType()));

        Assert.assertTrue("List<Number> should be assignable to List<? super T2 extends T1 extends Number>", getRules().matches(new TypeLiteral<List<? super T2>>() {}.getType(), new TypeLiteral<List<Number>>() {}.getType()));
        Assert.assertFalse("List<Integer> should not be assignable to List<? super T2 extends T1 extends Number>", getRules().matches(new TypeLiteral<List<? super T2>>() {}.getType(), new TypeLiteral<List<Integer>>() {}.getType()));
        Assert.assertTrue("List<Object> should be assignable to List<? super T2 extends T1 extends Number>", getRules().matches(new TypeLiteral<List<? super T2>>() {}.getType(), new TypeLiteral<List<Object>>() {}.getType()));
    }

    @Test
    public <T1 extends List<?> & Appendable, T2 extends Writer & Serializable & Collection<?>, T3 extends T2, T4 extends Appendable & Iterable<?>, T5 extends T4> void testTypeVariableWithMultipleBounds() {
        Assert.assertTrue("List<T4 extends Appendable & Iterable<?>> should be assignable to List<T1 extends List<?> & Appendable>", getRules().matches(new TypeLiteral<List<T1>>() {}.getType(), new TypeLiteral<List<T4>>() {}.getType()));
        Assert.assertTrue("List<T4 extends Appendable & Iterable<?>> should be assignable to List<T2 extends Writer & Serializable & Collection<?>>", getRules().matches(new TypeLiteral<List<T2>>() {}.getType(), new TypeLiteral<List<T4>>() {}.getType()));
        Assert.assertTrue("List<T5 extends T4 extends Appendable & Iterable<?>> should be assignable to List<T3 extends T2 extends Writer & Serializable & Collection<?>>", getRules().matches(new TypeLiteral<List<T3>>() {}.getType(), new TypeLiteral<List<T5>>() {}.getType()));
        // copy & paste with wildcard
        Assert.assertTrue("List<T4 extends Appendable & Iterable<?>> should be assignable to List<? extends T1 extends List<?> & Appendable>", getRules().matches(new TypeLiteral<List<? extends T1>>() {}.getType(), new TypeLiteral<List<T4>>() {}.getType()));
        Assert.assertTrue("List<T4 extends Appendable & Iterable<?>> should be assignable to List<? extends T2 extends Writer & Serializable & Collection<?>>", getRules().matches(new TypeLiteral<List<? extends T2>>() {}.getType(), new TypeLiteral<List<T4>>() {}.getType()));
        Assert.assertTrue("List<T5 extends T4 extends Appendable & Iterable<?>> should be assignable to List<? extends T3 extends T2 extends Writer & Serializable & List<?>>", getRules().matches(new TypeLiteral<List<? extends T3>>() {}.getType(), new TypeLiteral<List<T5>>() {}.getType()));

        Assert.assertFalse("List<T1 extends List<?> & Appendable> should not be assignable to List<T4 extends Appendable & Iterable<?>>", getRules().matches(new TypeLiteral<List<T4>>() {}.getType(), new TypeLiteral<List<T1>>() {}.getType()));
        Assert.assertFalse("List<T1 extends List<?> & Appendable> should not be assignable to List<T2 extends Writer & Serializable & Collection<?>>", getRules().matches(new TypeLiteral<List<T2>>() {}.getType(), new TypeLiteral<List<T1>>() {}.getType()));
        Assert.assertFalse("List<T2 extends Writer & Serializable & Collection<?>> should not be assignable to List<T4 extends Appendable & Iterable<?>>", getRules().matches(new TypeLiteral<List<T4>>() {}.getType(), new TypeLiteral<List<T2>>() {}.getType()));

        // neither one type variable has stricter bounds than the other
        Assert.assertFalse("List<T2 extends Writer & Serializable & Collection<?>> should not be assignable to List<T1 extends List<?> & Appendable>", getRules().matches(new TypeLiteral<List<T1>>() {}.getType(), new TypeLiteral<List<T2>>() {}.getType()));
        Assert.assertFalse("List<T1 extends List<?> & Appendable> should not be assignable to List<T2 extends Writer & Serializable & Collection<?>>", getRules().matches(new TypeLiteral<List<T2>>() {}.getType(), new TypeLiteral<List<T1>>() {}.getType()));
        // copy & paste with wildcard
        Assert.assertFalse("List<T2 extends Writer & Serializable & Collection<?>> should not be assignable to List<? extends T1 extends List<?> & Appendable>", getRules().matches(new TypeLiteral<List<? extends T1>>() {}.getType(), new TypeLiteral<List<T2>>() {}.getType()));
        Assert.assertFalse("List<T1 extends List<?> & Appendable> should not be assignable to List<? extends T2 extends Writer & Serializable & Collection<?>>", getRules().matches(new TypeLiteral<List<? extends T2>>() {}.getType(), new TypeLiteral<List<T1>>() {}.getType()));
    }

    // test that java assignability rules are used to compare parameters of parameterized types
    @Test
    public <T1, T2 extends T1, T3 extends Collection<T1>, T4 extends Collection<T2>, T5 extends Collection<Number>, T6 extends Collection<Integer>, T7 extends Collection<?>> void testTypeVariableWithParameterizedTypesAsBounds() {
        Assert.assertTrue("List<T5 extends Collection<Number>> should be assignable to itself", getRules().matches(new TypeLiteral<List<T5>>() {}.getType(), new TypeLiteral<List<T5>>() {}.getType()));
        Assert.assertFalse("List<T5 extends Collection<Number>> should not be assignable to List<T6 extends Collection<Integer>>", getRules().matches(new TypeLiteral<List<T6>>() {}.getType(), new TypeLiteral<List<T5>>() {}.getType()));
        Assert.assertFalse("List<T6 extends Collection<Integer>> should not be assignable to List<T5 extends Collection<Number>>", getRules().matches(new TypeLiteral<List<T5>>() {}.getType(), new TypeLiteral<List<T6>>() {}.getType()));
        Assert.assertFalse("List<T5 extends Collection<Number>> should not be assignable to List<T7 extends Collection<?>>", getRules().matches(new TypeLiteral<List<T7>>() {}.getType(), new TypeLiteral<List<T5>>() {}.getType()));

        Assert.assertTrue("List<T3 extends Collection<T1>> should be assignable to itself", getRules().matches(new TypeLiteral<List<T3>>() {}.getType(), new TypeLiteral<List<T3>>() {}.getType()));
        Assert.assertFalse("List<T3 extends Collection<T1>> should not be assignable to List<T4 extends Collection<T2 extends T1>>", getRules().matches(new TypeLiteral<List<T4>>() {}.getType(), new TypeLiteral<List<T3>>() {}.getType()));
        Assert.assertFalse("List<T4 extends Collection<T2 extends T1>> should not be assignable to List<T3 extends Collection<T1>>", getRules().matches(new TypeLiteral<List<T3>>() {}.getType(), new TypeLiteral<List<T4>>() {}.getType()));
        Assert.assertFalse("List<T3 extends Collection<T1>> should not be assignable to List<T7 extends Collection<?>>", getRules().matches(new TypeLiteral<List<T7>>() {}.getType(), new TypeLiteral<List<T3>>() {}.getType()));
    }
}


text:
module Uploader
  module Helpers
    class FieldTag
      attr_reader :template, :object, :theme

      delegate :uploader, :to => :template

      # Wrapper for render uploader field
      # Usage:
      #
      #   uploader = FieldTag.new(object_name, method_name, template, options)
      #   uploader.render
      #
      def initialize(object_name, method_name, template, options = {}) #:nodoc:
        options = { :object_name => object_name, :method_name => method_name }.merge(options)

        @template, @options = template, options.dup

        @theme = (@options.delete(:theme) || "default")
        @value = @options.delete(:value) if @options.key?(:value)

        @object = @options.delete(:object) if @options.key?(:object)
        @object ||= @template.instance_variable_get("@#{object_name}")
      end

      def render(locals = {}) #:nodoc:
        locals = { :field => self }.merge(locals)
        @template.render :partial => "uploader/#{@theme}/container", :locals => locals
      end

      def id
        @id ||= @template.dom_id(@object, [method_name, 'uploader'].join('_'))
      end

      def method_name
        @options[:method_name]
      end

      def object_name
        @options[:object_name]
      end

      def multiple?
        @options[:multiple].nil? ? @object.fileupload_multiple?(method_name) : @options[:multiple]
      end

      def value
        @value ||= @object.fileupload_asset(method_name)
      end

      def values
        Array.wrap(value)
      end

      def exists?
        values.map(&:persisted?).any?
      end

      def sortable?
        @options[:sortable] == true
      end

      def versionable?
        @options[:versionable] == true
      end

      def klass
        @klass ||= @object.class.fileupload_klass(method_name)
      end

      def attachments_path(options = {})
        options = {
          :guid => @object.fileupload_guid,
          :assetable_type => @object.class.base_class.name.to_s,
          :klass => klass.to_s
        }.merge(options)

        options[:assetable_id] = @object.id if @object.persisted? && !versionable?

        uploader.attachments_path(options)
      end

      def input_html
        @input_html ||= {
          :"data-url" => attachments_path,
          :multiple => multiple?,
          :class => "uploader"
        }.merge(@options[:input_html] || {})
      end
    end
  end
end


text:
""""
count_k_mers.py
count six-mers of seqs in fasta file

usage:
    python count_k_mers.py <in_fasta_file>
"""

from collections import defaultdict
from Bio import SeqIO
import sys

# function to count the k-mers --------------------------------------------

def generate_codones():
    """ generates the codons"""
    nuc = ['A', 'C', 'G', 'T']
    codons = list()
    for x in nuc:
        for y in nuc:
            for z in nuc:
                codons.append(x + y + z)
    return codons

def generate_dicodones():
    for x in generate_codones():
        for y in generate_codones():
            yield x + y

def iterate_over_kmer(dna, k):
    """
    returns a generator that iterates over the kmers
    """

    for i in range(0, len(dna) - k + 1):
        yield dna[i: i + k]

def count_k_mers(dna, k):
    """
    counts the k-mers in dna
    Returns:
        a counter dict with counts
    """
    counts = defaultdict(int)
    for kmer in iterate_over_kmer(dna, k):
        counts[kmer.upper()] += 1
    return [counts[x] for x in generate_dicodones()]

# code --------------------------------------------------------------------

fasta_file = sys.argv[1]
out_counts = open('counts.tab', 'w')
header = ['seq_id'] + [x for x in generate_dicodones()]
out_counts.write('\t'.join(x for x in header))
out_counts.write('\n')

for record in SeqIO.parse(fasta_file, 'fasta'):
    print('counting %s ...' % record.id)
    row = [record.id]
    counts = count_k_mers(str(record.seq), 6)
    row = row + counts
    out_counts.write('\t'.join(str(x) for x in row) + '\n')

out_counts.close()


text:
title: learning Fabric
author: zhuf
layout: post
published: true
permalink:
category: tech, python, Fabirc
tags: python, fabric
---

[Fabric Documentation](http://docs.fabfile.org/en/1.6/index.html)

## About

Fabric is a Python (2.5 or higher) library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks.

It provides a basic suite of operations for executing local or remote shell commands (normally or via sudo) and uploading/downloading files, as well as auxiliary functionality such as prompting the running user for input, or aborting execution.

**********

### Typical use

from fabric.api import run
def host_type():
    run('uname -a')

> fabric.api includes almost functions.

**********

root@ubuntu:~# fab -H ubuntu-2 host_type
[ubuntu-2] Executing task 'host_type'
[ubuntu-2] run: uname -a
[ubuntu-2] Login password for 'root':
[ubuntu-2] out: Linux ubuntu-2 3.2.0-23-generic-pae #36-Ubuntu SMP Tue Apr 10 22:19:09 UTC 2012 i686 i686 i386 GNU/Linux
[ubuntu-2] out:

Done.
Disconnecting from ubuntu-2... done.

> Usage: fab [options] <command>[:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ...
>
> Options:
>
> >-H HOSTS, --hosts=HOSTS		 comma-separated list of hosts to operate on
>
> >-P, --parallel		default to parallel execution method
>
> >-R ROLES, --roles=ROLES	comma-separated list of roles to operate on
>
> >-l, --list            print list of possible commands and exit
>
> >-f PATH, --fabfile=PATH	config the path of  fabfile.py

def mysql_install():
    with lcd('/root'):
        put('mysql-5.6.12-linux-glibc2.5-i686.tar.gz', '/root')
        put('my.cnf', '/root/mysql')
    with cd('/root'):
        run('tar zxf mysql-5.6.12-linux-glibc2.5-i686.tar.gz')
        run('/root/mysql-5.6.12-linux-glibc2.5-i686/scripts/mysql_install_db --defaults-file=/root/mysql/my.cnf --basedir=/root/mysql-5.6.12-linux-glibc2.5-i686')
        run('nohup /root/mysql-5.6.12-linux-glibc2.5-i686/bin/mysqld_safe --defaults-file=/root/mysql/my.cnf >& /dev/null < /dev/null &')

# it doesn't work!!!
### The reason is:
>Because Fabric executes a shell on the remote end for each invocation of run or sudo (see also), backgrounding a process via the shell will not work as expected. Backgrounded processes may still prevent the calling shell from exiting until they stop running, and this in turn prevents Fabric from continuing on with its own execution.

**********

## the solution

def mysql_install():
    with lcd('/root'):
        put('mysql-5.6.12-linux-glibc2.5-i686.tar.gz', '/root')
        put('my.cnf', '/root/mysql')
    with cd('/root'):
        run('tar zxf mysql-5.6.12-linux-glibc2.5-i686.tar.gz')
        run('/root/mysql-5.6.12-linux-glibc2.5-i686/scripts/mysql_install_db --defaults-file=/root/mysql/my.cnf --basedir=/root/mysql-5.6.12-linux-glibc2.5-i686')
        run("nohup /root/start.sh >& /dev/null < /dev/null &", pty=False)

# start.sh
nohup /root/mysql-5.6.12-linux-glibc2.5-i686/bin/mysqld_safe --defaults-file=/root/mysql/my.cnf &

**********

### .fabricrc

some default config for fabric

# .fabricrc
port = 22
user = kevin
warn_only = True
...

> the default fabricrc path: ~/.fabricrc

**********

### tasks

local('pwd') -- exec local cmd
lcd('/tmp') --  switch to local path
cd('/tmp') --  switch to remote path
run('uname -a') --  exec remote cmd
sudo('/etc/init.d/nginx start') -- exec remote cmd as sudo privileges, shell=False sometimes may usefull!
put('my.cnf', '/root/mysql') -- put the local file to remote path

#### sub-task

from fabric.api import task

@task
def migrate():
    pass

@task
def push():
    pass

@task
def provision():
    pass

@task
def full_deploy():
    if not provisioned:
        provision()
    push()
    migrate()


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Cryptog. Mycol. 29(3): 254 (2008)

#### Original name
Radulum crustulinum Bres.

### Remarks
null


text:
redis-cli flushall

pids=""

for i in `seq 0 49`; do
  php stress.php &
  pids="$pids $!"
done

wait $pids

echo ""
echo ""
echo "Expecting a count of 5000:"
echo ""

redis-cli get foo

echo ""
echo "Number of locking attempts needed:"
echo ""

redis-cli get attempts


text:
import { OverrideProps } from '@mui/types';
import * as React from 'react';

export type NativeFormControlElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;

export interface FormControlUnstyledComponentsPropsOverrides {}

export interface FormControlUnstyledOwnProps {
  /**
   * The content of the component.
   */
  children?: React.ReactNode;
  /**
   * Class name applied to the root element.
   */
  className?: string;
  /**
   * The components used for each slot inside the FormControl.
   * Either a string to use a HTML element or a component.
   * @default {}
   */
  components?: {
    Root?: React.ElementType;
  };
  componentsProps?: {
    root?: React.HTMLAttributes<HTMLDivElement> & FormControlUnstyledComponentsPropsOverrides;
  };
  defaultValue?: unknown;
  /**
   * If `true`, the label, input and helper text should be displayed in a disabled state.
   * @default false
   */
  disabled?: boolean;
  /**
   * If `true`, the label is displayed in an error state.
   * @default false
   */
  error?: boolean;
  /**
   * Extra properties to be placed on the FormControlContext.
   * @default {}
   */
  extraContextProperties?: object;
  /**
   * If `true`, the component is displayed in focused state.
   * @default false
   */
  focused?: boolean;
  onChange?: React.ChangeEventHandler<NativeFormControlElement>;
  /**
   * If `true`, the label will indicate that the `input` is required.
   * @default false
   */
  required?: boolean;
  value?: unknown;
}

export interface FormControlUnstyledTypeMap<P = {}, D extends React.ElementType = 'div'> {
  props: P & FormControlUnstyledOwnProps;
  defaultComponent: D;
}

type FormControlUnstyledProps<
  D extends React.ElementType = FormControlUnstyledTypeMap['defaultComponent'],
  P = {},
> = OverrideProps<FormControlUnstyledTypeMap<P, D>, D> & {
  /**
   * The component used for the Root slot.
   * Either a string to use a HTML element or a component.
   * This is equivalent to `components.Root`. If both are provided, the `component` is used.
   */
  component?: D;
};

export default FormControlUnstyledProps;


text:
#define CONFIG_TEXT 1
#define CONFIG_MENU 2
#define CONFIG_BORDER 3
#define CONFIG_BUTTON 4
#define CONFIG_DESKTOP 5
#define CONFIG_ICONBOX 6
#define CONFIG_KEYBIND 8
#define CONFIG_SOUND 9
#define CONFIG_ACTIONCLASS 11
#define CONFIG_IMAGECLASS 12
#define CONFIG_WINDOWMATCH 14
#define CONFIG_COLORMOD 15
#define CONFIG_SLIDEOUT 16
#define CONFIG_TOOLTIP 17
#define CONFIG_IBOX 19

#define CONFIG_CLASSNAME 100
#define CONFIG_MODIFIER  101
#define CONFIG_TYPE 102
#define CONFIG_ANYMOD 103
#define CONFIG_ACTION 104
#define CONFIG_NEXT 105
#define CONFIG_INHERIT 106
#define CONFIG_ACTION_TOOLTIP 107

#define TEXT_ORIENTATION 200
#define TEXT_JUSTIFICATION 201
#define TEXT_EFFECT 204
#define TEXT_FG_COL 205
#define TEXT_BG_COL 206

#define ICLASS_NAME 350
#define ICLASS_NORMAL 351
#define ICLASS_CLICKED 352
#define ICLASS_HILITED 353
#define ICLASS_ACTIVE_NORMAL 354
#define ICLASS_ACTIVE_CLICKED 355
#define ICLASS_ACTIVE_HILITED 356
#define ICLASS_LRTB 357
#define ICLASS_PADDING 358
#define ICLASS_STICKY_NORMAL 359
#define ICLASS_STICKY_CLICKED 360
#define ICLASS_STICKY_HILITED 361
#define ICLASS_STICKY_ACTIVE_NORMAL 362
#define ICLASS_STICKY_ACTIVE_CLICKED 363
#define ICLASS_STICKY_ACTIVE_HILITED 364
#define ICLASS_DISABLED 366
#define ICLASS_ACTIVE_DISABLED 367
#define ICLASS_STICKY_DISABLED 368
#define ICLASS_STICKY_ACTIVE_DISABLED 369
#define ICLASS_COLORMOD 370
#define ICLASS_FILLRULE 371
#define ICLASS_TRANSPARENT 372
#define ICLASS_ROTATE 373
#define ICLASS_BEVEL 374

#define DESKTOP_DRAGDIR 400
#define DESKTOP_DRAGBAR_WIDTH 401
#define DESKTOP_DRAGBAR_ORDERING 402
#define DESKTOP_DRAGBAR_LENGTH 403
#define DESKTOP_SLIDEIN 404
#define DESKTOP_SLIDESPEED 405
#define DESKTOP_HIQUALITYBG 406
#define DESKTOP_AREA_SIZE 407

#define ACLASS_NAME 420
#define ACLASS_TYPE 421
#define ACLASS_MODIFIER 422
#define ACLASS_ANYMOD 423
#define ACLASS_ANYBUT 424
#define ACLASS_BUT 425
#define ACLASS_ANYKEY 426
#define ACLASS_KEY 427
#define ACLASS_EVENT_TRIGGER 428
#define ACLASS_ACTION 429

#define ACLASS_TYPE_ACLASS 5

#define BORDERPART_ICLASS 450
#define BORDERPART_ACLASS 451
#define BORDERPART_TEXTCLASS 452
#define BORDERPART_ONTOP 453
#define BORDERPART_FLAGS 454
#define BORDERPART_ISREGION 455
#define BORDERPART_WMIN 456
#define BORDERPART_WMAX 457
#define BORDERPART_TXP 458
#define BORDERPART_TXA 459
#define BORDERPART_TYP 460
#define BORDERPART_TYA 461
#define BORDERPART_BORIGIN 462
#define BORDERPART_BXP 463
#define BORDERPART_BXA 464
#define BORDERPART_BYP 465
#define BORDERPART_BYA 466
#define BORDERPART_TORIGIN 467
#define BORDERPART_HMIN 468
#define BORDERPART_HMAX 469
#define BORDERPART_KEEPSHADE 470

#define WINDOWMATCH_USEBORDER 480
#define WINDOWMATCH_MATCHNAME 481
#define WINDOWMATCH_MATCHCLASS 482
#define WINDOWMATCH_MATCHTITLE 483
#define WINDOWMATCH_WIDTH 484
#define WINDOWMATCH_HEIGHT 485
#define WINDOWMATCH_TRANSIENT 486
#define WINDOWMATCH_NO_RESIZE_H 487
#define WINDOWMATCH_NO_RESIZE_V 488
#define WINDOWMATCH_SHAPED 489
#define WINDOWMATCH_ICON 490
#define WINDOWMATCH_DESKTOP 491
#define WINDOWMATCH_MAKESTICKY 492

#define BORDER_NAME 500
#define BORDER_LEFT 501
#define BORDER_RIGHT 502
#define BORDER_TOP 503
#define BORDER_BOTTOM 504
#define BORDER_INIT 505
#define BORDER_SHADEDIR 506
#define BORDER_CHANGES_SHAPE 507
#define BORDER_GROUP_NAME 508

#define BUTTON_XO 528
#define BUTTON_YO 529
#define BUTTON_XA 530
#define BUTTON_XR 531
#define BUTTON_YA 532
#define BUTTON_YR 533
#define BUTTON_XSR 534
#define BUTTON_YSR 535
#define BUTTON_XSA 536
#define BUTTON_YSA 537
#define BUTTON_SIMG 538
#define BUTTON_DESK 539
#define BUTTON_STICKY 540
#define BUTTON_INTERNAL 541
#define BUTTON_SHOW 542
#define BUTTON_LABEL 543

#define BG_RGB 560
#define BG_BG1 561
#define BG_BG2 562
#define BG_NAME 563
#define BG_DESKNUM 564
#define BG_BG_FILE 565
#define BG_BG_PARAM 566
#define BG_TOP_FILE 567
#define BG_TOP_PARAM 568

#define COLORMOD_RED 600
#define COLORMOD_GREEN 601
#define COLORMOD_BLUE 602

#define SLIDEOUT_DIRECTION 620

#define TOOLTIP_DRAWICLASS 640
#define TOOLTIP_BUBBLE1 641
#define TOOLTIP_BUBBLE2 642
#define TOOLTIP_BUBBLE3 643
#define TOOLTIP_BUBBLE4 644
#define TOOLTIP_DISTANCE 645
#define TOOLTIP_HELP_PIC 646

#define MENU_STYLE 699
#define MENU_BG_ICLASS 700
#define MENU_ITEM_ICLASS 701
#define MENU_SUBMENU_ICLASS 702
#define MENU_USE_ITEM_BACKGROUND 703
#define MENU_MAX_COLUMNS 704
#define MENU_MAX_ROWS 705
#define MENU_USE_STYLE 706
#define MENU_ITEM 707
#define MENU_SUBMENU 708
#define MENU_ACTION 709
#define MENU_PREBUILT 710
#define MENU_TITLE 711

#define MASK_NONE  0
#define MASK_SHIFT 900
#define MASK_LOCK 901
#define MASK_CTRL 902
#define MASK_MOD1 903
#define MASK_MOD2 904
#define MASK_MOD3 905
#define MASK_MOD4 906
#define MASK_MOD5 907
#define MASK_CTRL_ALT 910
#define MASK_CTRL_SHIFT 911
#define MASK_SHIFT_ALT 912
#define MASK_CTRL_SHIFT_ALT 913
#define MASK_CTRL_META4 914
#define MASK_SHIFT_META4 915
#define MASK_CTRL_META4_SHIFT 916
#define MASK_CTRL_META5 917
#define MASK_SHIFT_META5 918
#define MASK_CTRL_META5_SHIFT 919
#define MASK_WINDOWS_SHIFT 920
#define MASK_WINDOWS_CTRL 921
#define MASK_WINDOWS_ALT 922

#define CONFIG_ANYBUT 930
#define CONFIG_ANYKEY 931
#define CONFIG_OPEN  999
#define CONFIG_CLOSE 1000

#define CONFIG_CURSOR 800
#define CURS_BG_RGB 801
#define CURS_FG_RGB 802
#define XBM_FILE 803
#define NATIVE_ID 804

#define CONFIG_VERSION 1001
#define CONFIG_INVALID 9999

#define CONFIG_TRANSPARENCY 2001
#define CONFIG_SHOW_NAMES 2002
#define CONFIG_ICON_SIZE 2003
#define CONFIG_ICON_MODE 2004
#define CONFIG_SCROLLBAR_SIDE 2005
#define CONFIG_SCROLLBAR_ARROWS 2006
#define CONFIG_AUTOMATIC_RESIZE 2007
#define CONFIG_SHOW_ICON_BASE 2008
#define CONFIG_SCROLLBAR_AUTOHIDE 2009
#define CONFIG_COVER_HIDE 2010
#define CONFIG_RESIZE_ANCHOR 2011
#define CONFIG_IB_ANIMATE 2012


text:
Contact

	  {% if site.email %}

	    {% include icon-email.html username=site.email %}

	  {% endif %}
	  {% if site.email2 %}

	      {% include icon-email.html username=site.email2 %}

	  {% endif %}

          {% if site.github_username %}

            {% include icon-github.html username=site.github_username %}

          {% endif %}

{{ site.description }}

 Go to top


text:
package vagrantcloud

import (
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

const (
	baseUrl = "https://vagrantcloud.com"
	apiUri  = "/api/v1"
)

type Api struct {
	token string
}

// All requests must be authenticated with an access_token and sent as a URL parameter.
// This token can be generated or revoked on the account tokens page.
// Your token will have access to all resources your account has access to.
func New(token string) *Api {
	a := &Api{
		token: token,
	}
	return a
}

func NewFromFile(fname string) (*Api, error) {
	token, err := ioutil.ReadFile("token.txt")
	if err != nil {
		return nil, err
	}
	return New(string(token)), nil
}

func (a *Api) buildUrl(url string) string {
	return baseUrl + apiUri + url
}

func (a *Api) contentType(header http.Header) {
	header.Set("Content-Type", "application/x-www-form-urlencoded")
}

func (a *Api) response(resp *http.Response) ([]byte, error) {
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != 200 {
		return body, NewError(resp.Status, string(body))
	}
	return body, nil
}

func (a *Api) Get(uri string) ([]byte, error) {
	u, err := url.ParseRequestURI(a.buildUrl(uri))
	if err != nil {
		return nil, err
	}
	q := u.Query()
	q.Set("access_token", a.token)
	u.RawQuery = q.Encode()
	resp, err := http.Get(u.String())
	if err != nil {
		return nil, err
	}
	return a.response(resp)
}

func (a *Api) Download(uri string, data io.Writer) error {
	u, err := url.ParseRequestURI(baseUrl + uri)
	if err != nil {
		return err
	}
	q := u.Query()
	q.Set("access_token", a.token)
	u.RawQuery = q.Encode()
	resp, err := http.Get(u.String())
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	_, err = io.Copy(data, resp.Body)
	return err
}

func (a *Api) Post(uri string, params url.Values) ([]byte, error) {
	u, err := url.ParseRequestURI(a.buildUrl(uri))
	if err != nil {
		return nil, err
	}
	params.Set("access_token", a.token)
	resp, err := http.PostForm(u.String(), params)
	if err != nil {
		return nil, err
	}
	return a.response(resp)
}

func (a *Api) Put(uri string, params url.Values) ([]byte, error) {
	u, err := url.ParseRequestURI(a.buildUrl(uri))
	if err != nil {
		return nil, err
	}
	params.Set("access_token", a.token)
	req, err := http.NewRequest("PUT", u.String(), strings.NewReader(params.Encode()))
	if err != nil {
		return nil, err
	}
	a.contentType(req.Header)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	return a.response(resp)
}

func (a *Api) Upload(uri string, data io.Reader) ([]byte, error) {
	u, err := url.ParseRequestURI(a.buildUrl(uri))
	if err != nil {
		return nil, err
	}
	q := u.Query()
	q.Set("access_token", a.token)
	u.RawQuery = q.Encode()
	req, err := http.NewRequest("PUT", u.String(), data)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "multipart/form-data")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	return a.response(resp)
}

func (a *Api) Delete(uri string) ([]byte, error) {
	u, err := url.ParseRequestURI(a.buildUrl(uri))
	if err != nil {
		return nil, err
	}
	params := url.Values{}
	params.Add("access_token", a.token)
	req, err := http.NewRequest("DELETE", u.String(), strings.NewReader(params.Encode()))
	if err != nil {
		return nil, err
	}
	a.contentType(req.Header)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	return a.response(resp)
}