text:
layout: post
title: E-governance sites and bad web design, and how-to setup E-Mudhra/e2gov on windows
  7
date: 2011-05-09 02:29:00.000000000 +05:30
categories:
- random
- tech
tags: []
status: publish
type: post
published: true
meta:
  _edit_last: '1'
  _wp_old_slug: ''
author:
  login: admin
  email: anil.verve@gmail.com
  display_name: admin
  first_name: ''
  last_name: ''
---

So local Indian laws requires tenders to be filed online. This required buying a 3000Rs (!!), about 60$ USB dongle that has a "Class 3 Platinum" certificate signed by the CA E-Mudhra. There's zero documentation online on setting it up, and sites that process tenders work on "IE6 or IE7 only". They do not work with Windows 7/IE8 by default. Below are the steps on how-to get things working on Windows 7, followed by a rant.

Setting up E-Mudhra on Windows 7/ IE 8

Pop in the CD that came with the dongle and install the driver. Skip the other reader and download manager crapware.

Once installed (and rebooted if you wish), plug in the USB. Windows will ask you if you want to add the root CA E-Mudhra. Answer yes.

Now to setup IE8 to behave well with the tender sites. Note this will render IE8 highly insecure. Once you make the below changes, use IE8 only for tenders. For all other internet activities use Google Chrome or Mozilla Firefox.

The tender sites require full ActiveX control to work correctly. Do the below to setup IE8 to behave like earlier versions.

Goto Internet options in IE8, and set compatibility mode to on. Next click under security, and choose the lowest level (which is Medium). Click on "Advanced", and enable all the disabled ActiveX features. You will note that these new options are labelled "Insecure" and will turn red when you choose them.

Save, Reboot. You will have done all the things correctly if you are not presented with any "ActiveX popup warnings" when browsing a site, i.e, all ActiveX requires are accepted by default.

Rant

Why the hell do the Indian government website designers choose the most lax practices of the lot. They need to be strung up and given a lesson on webdesign after the year 2003. Jesus fusking christ.

And what's behind the REQUIREMENT to use e2gov.in for digital certificates. There's free ones, or others with a nominal fee available. One which don't bloddy require you to add a FRIGGING ROOT CERTIFICATE to your machine.

And activeX?!!!@!!!!!! Microsoft has basically disavowed it. And I counted 2-3 different controls that are loaded. May I introduce you to much more modern alternatives, like perhaps a reasonable java applet, or even better, a native app? Or just don't require a login process that requires a friggin digital certificate. There's simpler way of digital identity that what's currently setup. Like squishing out the fluid from my eyeballs and mailing it out to you.

FUCK!


text:
package net.sourceforge.plantuml.cucadiagram.dot;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import net.sourceforge.plantuml.cucadiagram.CucaDiagram;
import net.sourceforge.plantuml.cucadiagram.IGroup;
import net.sourceforge.plantuml.cucadiagram.LeafType;
import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.svek.GroupPngMakerActivity;
import net.sourceforge.plantuml.svek.IEntityImage;

public final class CucaDiagramSimplifierActivity {

	private final CucaDiagram diagram;
	private final StringBounder stringBounder;

	public CucaDiagramSimplifierActivity(CucaDiagram diagram, List<String> dotStrings, StringBounder stringBounder)
			throws IOException, InterruptedException {
		this.diagram = diagram;
		this.stringBounder = stringBounder;
		boolean changed;
		do {
			changed = false;
			final Collection<IGroup> groups = new ArrayList<>(diagram.getGroups(false));
			for (IGroup g : groups) {
				if (diagram.isAutarkic(g)) {
					// final EntityType type;
					// if (g.zgetGroupType() == GroupType.INNER_ACTIVITY) {
					// type = EntityType.ACTIVITY;
					// } else if (g.zgetGroupType() == GroupType.CONCURRENT_ACTIVITY) {
					// type = EntityType.ACTIVITY_CONCURRENT;
					// } else {
					// throw new IllegalStateException();
					// }

					final IEntityImage img = computeImage(g);
					g.overrideImage(img, LeafType.ACTIVITY);

					changed = true;
				}
			}
		} while (changed);
	}

	// private void computeImageGroup(EntityMutable g, EntityMutable proxy, List<String> dotStrings) throws IOException,
	// InterruptedException {
	// final GroupPngMakerActivity maker = new GroupPngMakerActivity(diagram, g);
	// proxy.setSvekImage(maker.getImage());
	// }

	private IEntityImage computeImage(IGroup g) throws IOException, InterruptedException {
		final GroupPngMakerActivity maker = new GroupPngMakerActivity(diagram, g, stringBounder);
		return maker.getImage();
	}

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef dom_html_head_element_h_
#define dom_html_head_element_h_

#include <dom/html/html_element.h>

typedef struct dom_html_head_element dom_html_head_element;

dom_exception dom_html_head_element_get_profile(
		struct dom_html_head_element *element, dom_string **profile);
dom_exception dom_html_head_element_set_profile(
		struct dom_html_head_element *element, dom_string *profile);

#endif


text:
package org.yatech.jedis.collections;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

import static org.yatech.jedis.collections.Utils.toStringArray;

/**
 * A {@link Set} implementation giving an abstraction over Redis' set value type.
 *
Created on 23/05/16
 *
 * @author Yinon Avraham
 */
public class JedisSet extends JedisCollectionBase implements Set<String> {

    JedisSet(JedisPool jedisPool, int db, String key) {
        super(jedisPool, db, key);
    }

    JedisSet(Jedis jedis, String key) {
        super(jedis, key);
    }

    @Override
    public int size() {
        return Integer.valueOf("" + cardinality());
    }

    /**
     * Get the cardinality of the set (i.e. the number of elements).

     * This is similar to {@link #size()} but is preferred since redis' capacity supports long typed values
     * @return the number of elements in the set
     */
    public long cardinality() {
        return doWithJedis(new JedisCallable<Long>() {
            @Override
            public Long call(Jedis jedis) {
                return jedis.scard(getKey());
            }
        });
    }

    @Override
    public boolean isEmpty() {
        return cardinality() == 0;
    }

    @Override
    public boolean contains(final Object o) {
        return doWithJedis(new JedisCallable<Boolean>() {
            @Override
            public Boolean call(Jedis jedis) {
                return jedis.sismember(getKey(), o.toString());
            }
        });
    }

    @Override
    public Iterator<String> iterator() {
        //TODO Improve memory consumption using sscan
        return toSet().iterator();
    }

    public Set<String> toSet() {
        return doWithJedis(new JedisCallable<Set<String>>() {
            @Override
            public Set<String> call(Jedis jedis) {
                return jedis.smembers(getKey());
            }
        });
    }

    @Override
    public Object[] toArray() {
        return toSet().toArray();
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return toSet().toArray(a);
    }

    @Override
    public boolean add(final String member) {
        return addAll(member) > 0;
    }

    /**
     * Adds to this set all of the elements in the specified members array
     * @param members the members to add
     * @return the number of members actually added
     */
    public long addAll(final String... members) {
        return doWithJedis(new JedisCallable<Long>() {
            @Override
            public Long call(Jedis jedis) {
                return jedis.sadd(getKey(), members);
            }
        });
    }

    @Override
    public boolean remove(Object member) {
        return removeAll(member.toString()) > 0;
    }

    /**
     * Removes from this set all of its elements that are contained in the specified members array
     * @param members the members to remove
     * @return the number of members actually removed
     */
    public long removeAll(final String... members) {
        return doWithJedis(new JedisCallable<Long>() {
            @Override
            public Long call(Jedis jedis) {
                return jedis.srem(getKey(), members);
            }
        });
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        for (Object o : c) {
            if (!contains(o)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean addAll(Collection<? extends String> members) {
        return addAll(members.toArray(new String[members.size()])) > 0;
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        boolean changed = false;
        for (String member : toSet()) {
            if (!c.contains(member)) {
                changed |= remove(member);
            }
        }
        return changed;
    }

    @Override
    public boolean removeAll(Collection<?> members) {
        return removeAll(toStringArray(members)) > 0;
    }

    @Override
    public void clear() {
        doWithJedis(new JedisCallable<Void>() {
            @Override
            public Void call(Jedis jedis) {
                jedis.del(getKey());
                return null;
            }
        });
    }

    /**
     * Removes and returns a random element from the set.
     * @return the removed element, or null when the key does not exist.
     */
    public String pop() {
        return doWithJedis(new JedisCallable<String>() {
            @Override
            public String call(Jedis jedis) {
                return jedis.spop(getKey());
            }
        });
    }

    /**
     * Removes and returns multiple random elements from the set.

     * Note- This method is not supported in Redis versions 2.6, 2.8, 3.0 .
     * @param count the number of elements to remove and return
     * @return the removed elements, or null when the key does not exist.
     */
    public Set<String> pop(final long count) {
        return doWithJedis(new JedisCallable<Set<String>>() {
            @Override
            public Set<String> call(Jedis jedis) {
                return jedis.spop(getKey(), count);
            }
        });
    }
}


text:
#ifndef DD_SRF_MODEL
#define DD_SRF_MODEL

#include "Model.hpp"
#include <functional>
#include "OneFeatureModel.hpp"
#include <boost/multi_array.hpp>
#include "GeneralizedHoughTransform.hpp"
#include "PCA_Pose.hpp"
#include "RandomHoughFeature.hpp"
#include "RandomForest.hpp"
#include "Detection.hpp"

namespace deformable_depth
{
  class SRFModel;

  ///
  /// Single Structural Random Tree
  ///
  class HoughTree
  {
  public:
    // stop splitting if the det of the covariance falls below
    static constexpr int MIN_CoVar_DET = 5;
    // stop splitting if the number of examples at a node falls below
    static constexpr int MIN_EXAMPLES = 500;
    static constexpr int MIN_POS_EXAMPLES = 25;
    static constexpr int MIN_NEG_EXAMPLES = 25;
    // stop splitting at MAX_DEPTH
    static constexpr int MAX_DEPTH = 10;
    static constexpr int FEATURES_PER_SPLIT = 128;

  protected:
    HoughTree(SRFModel&model);
    int depth;
    unique_ptr<RandomHoughFeature> predictor;
    unique_ptr<HoughTree> true_branch;
    unique_ptr<HoughTree> false_branch;
    SRFModel&model;

    bool allow_split_true() const;
    bool allow_split_false() const;

  public:
    VoteResult vote(HoughOutputSpace&output,
		const StructuredWindow&swin,
		RandomHoughFeature*predictor = nullptr) const;
    const SRFModel& getModel() const;
    SRFModel& getModel();

    friend void write(cv::FileStorage&, std::string&, const deformable_depth::HoughTree&);
    friend void read(const cv::FileNode&, deformable_depth::HoughTree&);
    friend void read(const cv::FileNode&, deformable_depth::SRFModel&, deformable_depth::SRFModel);
  };

  void read(const cv::FileNode&, deformable_depth::HoughTree&);
  void write(cv::FileStorage&, std::string&, const deformable_depth::HoughTree&);

  ///
  /// Single Structural Random Tree for Hough Transforms
  ///
  class StructuralHoughTree : public HoughTree
  {
  public:
    StructuralHoughTree(SRFModel&model,vector< StructuredExample >& training_examples, int depth = 0);
  };

  ///
  /// single Discriminative Hough Tree
  ///
  class DiscriminativeHoughTree : public HoughTree
  {
  public:
    DiscriminativeHoughTree(
      SRFModel&model,
      vector< StructuredExample >& training_examples, int depth = 0);

  protected:
    vector< StructuredExample > training_examples;

    enum ObjType
    {
      Spearman,
      Shannon,
      Differential,
      Pose_Entropy
    };

    static void discriminative_split(
      list<DiscriminativeHoughTree*>&unsplit_nodes,
      map<string,HoughOutputSpace::Matrix3D>&target_output);
    static void discriminative_try_split(
      DiscriminativeHoughTree* node,
      double&best_info_gain,
      DiscriminativeHoughTree**best_node,
      vector<StructuredExample>&exs_true,
      vector<StructuredExample>&exs_false,
      unique_ptr<RandomHoughFeature>&best_feature,
      map<string,HoughOutputSpace::Matrix3D>&target_output,
      ObjType obj_type);
    static void discriminative_split_choose
      (list<DiscriminativeHoughTree*>&unsplit_nodes,
      map<string,HoughOutputSpace::Matrix3D>&target_output,
      DiscriminativeHoughTree** best_node,
      double&best_info_gain,
      unique_ptr<RandomHoughFeature>&best_feature,
      vector<StructuredExample>&exs_true,
      vector<StructuredExample>&exs_false);
    static void discriminative_split_update_tree
      (list<DiscriminativeHoughTree*>&unsplit_nodes,
      DiscriminativeHoughTree* best_node,
      double&best_info_gain,
      unique_ptr<RandomHoughFeature>&best_feature,
      vector<StructuredExample>&exs_true,
      vector<StructuredExample>&exs_false);
  };

  //
  // Structural Random Forest Model, makes
  //
  class SRFModel : public Model
  {
  protected:
    Size gtSize, ISize;
    shared_ptr<HoughTree> tree_root;
    PCAPose pca_pose;

    void augment_features();

  public: // Model overrides
    SRFModel();
    SRFModel(Size gtSize, Size ISize);
    virtual DetectionSet detect(const ImRGBZ&im,DetectionFilter filter) const;
    virtual void train(vector<shared_ptr<MetaData>>&training_set,
		       TrainParams train_params = TrainParams());
    virtual Mat show(const string&title = "Model");
    virtual ~SRFModel(){};
    virtual bool write(FileStorage&fs);

    const PCAPose&getPCApose() const;
    PCAPose&getPCApose();

    friend void read(const cv::FileNode&, deformable_depth::SRFModel&, deformable_depth::SRFModel);
  };
  void read(const cv::FileNode&, deformable_depth::SRFModel&, deformable_depth::SRFModel);

  class SRFModel_Model_Builder : public Model_Builder
  {
  public:
    SRFModel_Model_Builder(double C = OneFeatureModel::DEFAULT_C,
			  double area = OneFeatureModel::DEFAULT_AREA,
			  shared_ptr<IHOGComputer_Factory> fc_factory =
			  shared_ptr<IHOGComputer_Factory>(new COMBO_FACT),
			  double minArea = Model_RigidTemplate::default_minArea,
			  double world_area_variance =
			      OneFeatureModel::DEFAULT_world_area_variance);
    virtual Model* build(Size gtSize,Size imSize) const;
    virtual string name() const;
  };
}

#endif


text:
♥ [ANE-Google-Analytics](https://alebianco.github.io/ANE-Google-Analytics) and want to get involved?
Thanks! There are plenty of ways you can help!

## Donations

I'am working on the project on my spare time and that means that I can't always find the time to give it the amount of time it would need or that I would like to give.

If you love this project and the possibilities it offer, if you used it on a commercial project and you think I saved you some hundred hours of coding, show some appreciation :)

You can send a donation through [Paypal](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=cyberpunk82%40gmail%2ecom&lc=IT&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted) or, better yet, if you live in London you can offer me a beer.

## Tests

Due to the nature of the project, I can't possibly own all the necessary devices and os versions necessary to perform a comprehensive round of tests.
So far I personally tested it on:

* Android 2.3
* Android 4.2
* iOS 5 simulator

It's your turn now to test it on as many devices as possible and let me know if there's still any problem to fix. I'll try to provide a simple demo project, that will cover all the extension features, to make this task easier.

Refer to the [Bugs](#Bugs) section for information about reporting issues.

## Bugs

A bug is a _demonstrable problem_ that is caused by the code in the
repository. Good bug reports are extremely helpful - thank you!

Guidelines for bug reports:

1. **Use the GitHub issue search** — check if the issue has already been
   reported.

2. **Check if the issue has been fixed** — try to reproduce it using the
   latest `master` branch in the repository.

3. **Isolate the problem** — ideally create a reduced test
   case and a live example.

A good bug report shouldn't leave others needing to chase you up for more
information. Please try to be as detailed as possible in your report. What is
your environment? What steps will reproduce the issue? What Platform(s) and OS
experience the problem? What would you expect to be the outcome? All these
details will help me to fix any potential bugs.

Example:

> Short and descriptive example bug report title
>
> A summary of the issue and the platform/OS environment in which it occurs. If
> suitable, include the steps required to reproduce the bug.
>
> 1. This is the first step
> 2. This is the second step
> 3. Further steps, etc.
>
> `<url>` (a link to the reduced test case)
>
> Any other information you want to share that is relevant to the issue being
> reported. This might include the lines of code that you have identified as
> causing the bug, and potential solutions (and your opinions on their
> merits).

**[File a bug report](https://github.com/alebianco/ANE-Google-Analytics/issues/)**

## Pull requests

Good pull requests - patches, improvements, new features - are a fantastic
help. They should remain focused in scope and avoid containing unrelated
commits. If your contribution involves a significant amount of work or substantial
changes to any part of the project, please open an issue to discuss it first.

Make sure to adhere to the coding conventions used throughout a project
(indentation, accurate comments, etc.). Please update any documentation that is
relevant to the change you're making.

Please follow this process; it's the best way to get your work included in the
project:

1. [Fork](http://help.github.com/fork-a-repo/) the project, clone your fork,
   and configure the remotes:

   ```bash
   # Clones your fork of the repo into the current directory in terminal
   git clone https://github.com/<your-username>/ANE-Google-Analytics.git
   # Navigate to the newly cloned directory
   cd ANE-Google-Analytics
   # Assigns the original repo to a remote called "upstream"
   git remote add upstream https://github.com/alebianco/ANE-Google-Analytics.git
   ```

2. If you cloned a while ago, get the latest changes from upstream:

   ```bash
   git checkout master
   git pull upstream master
   ```

3. Create a new topic branch to contain your feature, change, or fix:

   ```bash
   git checkout -b <topic-branch-name>
   ```

4. Commit your changes in logical chunks. Please adhere to these [git commit
   message
   guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
   or your pull request is unlikely be merged into the main project. Use git's
   [interactive rebase](https://help.github.com/articles/interactive-rebase)
   feature to tidy up your commits before making them public.

5. Locally merge (or rebase) the upstream development branch into your topic branch:

   ```bash
   git pull [--rebase] upstream master
   ```

6. Push your topic branch up to your fork:

   ```bash
   git push origin <topic-branch-name>
   ```

10. [Open a Pull Request](https://help.github.com/articles/using-pull-requests) with a
    clear title and description.

## Do not…

Please **do not** use the issue tracker for personal support requests.
Please **do not** derail or troll issues. Keep the
discussion on topic and respect the opinions of others.


text:
package microsoft.exchange.webservices.data.exception;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class InvalidOrUnsupportedTimeZoneDefinitionExceptionTest {

  private final String msg = "some message";
  private final Exception rootCause = new Exception();

  @Test public void testInvalidOrUnsupportedTimeZoneDefinitionExceptionStringException() {
    InvalidOrUnsupportedTimeZoneDefinitionException
        impl =
        new InvalidOrUnsupportedTimeZoneDefinitionException(msg, rootCause);
    assertEquals(msg, impl.getMessage());
    assertSame(rootCause, impl.getCause());
  }

  @Test public void testInvalidOrUnsupportedTimeZoneDefinitionExceptionString() {
    InvalidOrUnsupportedTimeZoneDefinitionException
        impl =
        new InvalidOrUnsupportedTimeZoneDefinitionException(msg);
    assertEquals(msg, impl.getMessage());
    assertNull(impl.getCause());
  }

  @Test public void testInvalidOrUnsupportedTimeZoneDefinitionException() {
    InvalidOrUnsupportedTimeZoneDefinitionException
        impl =
        new InvalidOrUnsupportedTimeZoneDefinitionException();
    assertNull(impl.getMessage());
    assertNull(impl.getCause());
  }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Speech.Synthesis;
using libsecondlife;
using libsecondlife.Packets;
using libsecondlife.AssetSystem;

// Since this requires .Net 3.0 I've left it out of the project by default.
// To use this: include it in the project and add a reference to the System.Speech.dll

namespace libsecondlife.TestClient
{
    public class TtsCommand : Command
    {
		SpeechSynthesizer _speechSynthesizer;

		public TtsCommand(TestClient testClient)
        {
            Name = "tts";
            Description = "Text To Speech.  When activated, client will echo all recieved chat messages out thru the computer's speakers.";
        }

        public override string Execute(string[] args, LLUUID fromAgentID)
        {
			if (!Active)
			{
				if (_speechSynthesizer == null)
					_speechSynthesizer = new SpeechSynthesizer();
				Active = true;
				Client.Self.OnChat += new MainAvatar.ChatCallback(Self_OnChat);
				return "TTS is now on.";
			}
			else
			{
				Active = false;
				Client.Self.OnChat -= new MainAvatar.ChatCallback(Self_OnChat);
				return "TTS is now off.";
			}
        }

		void Self_OnChat(string message, byte audible, byte type, byte sourcetype, string fromName, LLUUID id, LLUUID ownerid, LLVector3 position)
		{
			if (message.Length > 0)
			{
				_speechSynthesizer.SpeakAsync(message);
			}
		}
	}
}


text:
var html_barra = '

' + titulo + '
<image class="logo" src="images/logo_tegnix_w100.png">
';
if ( window.location.search.match( /print-pdf/gi ) ) {
    $('section').append(html_barra);
}
else {
    $('div.reveal').append(html_barra);
}


text:
package es.moki.ratelimij.dropwizard.filter;

import es.moki.ratelimitj.core.limiter.request.RequestRateLimiter;
import es.moki.ratelimitj.core.limiter.request.RequestRateLimiterFactory;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;

@ExtendWith({
        DropwizardExtensionsSupport.class,
        MockitoExtension.class
})
public class RateLimit429EnforcerFilterTest {

    @Mock private static RequestRateLimiterFactory requestRateLimiterFactory;
    @Mock private RequestRateLimiter requestRateLimiter;

    private final ResourceExtension resources = ResourceExtension.builder()
            .setTestContainerFactory(new GrizzlyWebTestContainerFactory())
            .addProvider(new AbstractBinder() {
                @Override
                protected void configure() {
                    bind(requestRateLimiterFactory).to(RequestRateLimiterFactory.class);
                }
            })
            .addProvider(new RateLimited429EnforcerFeature())
            .addResource(new TestResource())
            .build();

    @Test
    @DisplayName("should not limit request")
    public void shouldNotLimit() {
        when(requestRateLimiterFactory.getInstance(anySet())).thenReturn(requestRateLimiter);
        when(requestRateLimiter.overLimitWhenIncremented(anyString())).thenReturn(false);

        Response response = resources.getJerseyTest().target("/test/{id}").resolveTemplate("id", 1)
                .request(MediaType.APPLICATION_JSON_TYPE)
                .get();

        assertThat(response.getStatus()).isEqualTo(200);
    }

    @Test
    @DisplayName("should limit request returning a 429")
    public void shouldLimit() {
        when(requestRateLimiterFactory.getInstance(anySet())).thenReturn(requestRateLimiter);
        when(requestRateLimiter.overLimitWhenIncremented(anyString())).thenReturn(true);

        Response response = resources.getJerseyTest().target("/test/{id}").resolveTemplate("id", 1)
                .request(MediaType.APPLICATION_JSON_TYPE)
                .get();

        assertThat(response.getStatus()).isEqualTo(429);
    }

    @Test
    @DisplayName("should configure rate limiter")
    public void shouldReportOnly() {
        when(requestRateLimiterFactory.getInstance(anySet())).thenReturn(requestRateLimiter);
        when(requestRateLimiter.overLimitWhenIncremented(anyString())).thenReturn(true);

        Response response = resources.getJerseyTest().target("/test/reportOnly/{id}").resolveTemplate("id", 1)
                .request(MediaType.APPLICATION_JSON_TYPE)
                .get();

        assertThat(response.getStatus()).isEqualTo(200);
    }

    @Test
    @DisplayName("should not limit if the backing rate limiter throws exception")
    public void shouldNotLimitIfBackingRateLimiterFails() {
        when(requestRateLimiterFactory.getInstance(anySet())).thenReturn(requestRateLimiter);
        when(requestRateLimiter.overLimitWhenIncremented(anyString())).thenThrow(new RuntimeException());

        Response response = resources.getJerseyTest().target("/test/{id}").resolveTemplate("id", 1)
                .request(MediaType.APPLICATION_JSON_TYPE)
                .get();

        assertThat(response.getStatus()).isEqualTo(200);
    }
}


text:
<html>
  <head>
    <script>
var childFrame;
var pages;
var currentPage;
var result = {};

function init() {
  if (!window.layoutTestController) {
    alert("window.layoutTestController not defined.");
    return;
  }

  layoutTestController.dumpAsText();
  layoutTestController.waitUntilDone();

  pages = window.location.search.substring(1).split(",");
  if (!pages.length) {
    alert("please specify which pages to generate via " +
          "?<page> ... ie. generator.html?tabs,bookmarks,cookies,...");
  }

  childFrame = document.createElement('iframe');
  childFrame.style.display = "none";
  document.body.appendChild(childFrame);

  next();
}

function next() {
  currentPage = pages.shift();
  childFrame.src = "../" + currentPage + ".html?regenerate";
}

var count = 0;
function done() {
  result[currentPage] = childFrame.contentWindow.serializePage();

  if (pages.length) {
    next();
  } else {
    var preNode = document.createElement("pre");
    var textNode = document.createTextNode(
        "#BEGIN" + JSON.stringify(result) + "#END");
    preNode.appendChild(textNode);
    document.getElementsByTagName("body")[0].appendChild(preNode);
    layoutTestController.notifyDone();
  }
}
    </script>
  </head>
  <body onload="init();">
  </body>
</html>


text:
comment
(directive in module ui.comments
)

Description

The comment directive is primarily used automatically by
the comments directive, by automatically
building comment directives for each element in the collection.

When a commentController is specified in
commentsConfig, it is instantiated for each comment. The
comment data is exposed to scope through comment, and so
templates may access comment properties through expressions like comment.text.

An example template might look like the following:

<div class="comment">
  <div class="comment-header">
   <a class="comment-avatar"
      ng-href="{{comment.profileUrl}}">
     <img ng-src="{{comment.avatarUrl}}"
          alt="{{comment.name}}" />
   </a>
   <a class="comment-username"
      ng-href="{{comment.profileUrl}}"
      title="{{comment.username}}">{{comment.name}}</a>
    <span class="comment-date">{{comment.date | timeAgo}}</span>
  </div>
  <div class="comment-body" ng-bind="comment.text"></div>
</div>

IMPORANT: Do not use the comments directive in a
commentTemplate. This will cause an
infinite $compile loop, and eat a lot of
memory.

Usage

as element:
<comment
       comment-data="{expression}">
</comment>

as attribute
<div comment
     comment-data="{expression}">
   ...
</div>

Directive info

This directive creates new scope.

Parameters

comment-data – {expression} –

Data model containing the specific comment.


text:
'''
This is STS's end of the sync protocol. Listens to all controller-specific
syncers and dispatches messages to STS handlers.
'''

from sts.syncproto.base import SyncProtocolSpeaker, SyncMessage, SyncTime, SyncIODelegate

from pox.lib.util import parse_openflow_uri, connect_socket_with_backoff

import logging
log = logging.getLogger("sts_sync_proto")

class STSSyncProtocolSpeaker(SyncProtocolSpeaker):
  def __init__(self, controller, state_master, io_delegate):
    if state_master is None:
      raise ValueError("state_master is null")

    self.state_master = state_master
    self.controller = controller

    handlers = {
        ("ASYNC", "StateChange"): self._log_async_state_change,
        ("SYNC", "StateChange"): self._log_sync_state_change,
        ("REQUEST", "DeterministicValue"): self._get_deterministic_value
    }
    SyncProtocolSpeaker.__init__(self, handlers, io_delegate)

  def _log_async_state_change(self, message):
    self.state_master.state_change("ASYNC", message.xid, self.controller, message.time, message.fingerPrint, message.name, message.value)

  def _log_sync_state_change(self, message):
    # Note: control_flow needs to register a handler on state_master to ACK the
    # controller
    self.state_master.state_change("SYNC", message.xid, self.controller, message.time, message.fingerPrint, message.name, message.value)

  def _get_deterministic_value(self, message):
    self.state_master.get_deterministic_value(self.controller, message.name,
                                              message.xid)

class STSSyncConnection(object):
  """ A connection to a controller with the sts sync protocol """
  def __init__(self, controller, state_master, sync_uri):
    self.controller = controller
    (self.mode, self.host, self.port) = parse_openflow_uri(sync_uri)
    if state_master is None:
      raise ValueError("state_master is null")
    self.state_master = state_master
    self._on_disconnect = []
    self.io_delegate = None
    self.speaker = None

  def on_disconnect(self, func):
    self._on_disconnect.append(func)

  def connect(self, io_master):
    if self.mode != "tcp":
      raise RuntimeError("only tcp (active) mode supported by now")

    socket = connect_socket_with_backoff(self.host, self.port)
    self.io_delegate = SyncIODelegate(io_master, socket)
    self.speaker = STSSyncProtocolSpeaker(controller=self.controller,
        state_master=self.state_master, io_delegate=self.io_delegate)

  def disconnect(self):
    self.io_delegate.close()
    for handler in self._on_disconnect:
      handler(self)

  def close(self):
    self.disconnect()

  def get_nom_snapshot(self):
    if self.speaker:
      return self.speaker.sync_request("NOMSnapshot", "", timeout=10)
    else:
      log.warn("STSSyncConnection: not connected. cannot handle requests")

  def send_link_notification(self, link_attrs):
    # Link attrs must be a list of the form:
    # [dpid1, port1, dpid2, port2]
    if self.speaker:
      msg = SyncMessage(type="ASYNC", messageClass="LinkDiscovery",
                        value=link_attrs)
      return self.speaker.send(msg)
    else:
      log.warn("STSSyncConnection: not connected. cannot send link")

  def ack_sync_notification(self, messageClass, xid):
    if self.speaker:
      return self.speaker.ack_sync_notification(messageClass, xid)
    else:
      log.warn("STSSyncConnection: not connected. cannot ACK")

  def send_deterministic_value(self, xid, value):
    if self.speaker:
      msg = SyncMessage(type="RESPONSE", messageClass="DeterministicValue",
                        time=value, xid=xid, value=value)
      return self.speaker.send(msg)
    else:
      log.warn("STSSyncConnection: not connected. cannot ACK")

class STSSyncConnectionManager(object):
  """the connection manager for the STS sync protocols.
     TODO: finish"""
  def __init__(self, io_master, state_master):
    self.io_master  = io_master
    self.sync_connections = []
    if state_master is None:
      raise ValueError("state_master is null")
    self.state_master = state_master

  def connect(self, controller, sync_uri):
    s = STSSyncConnection(controller=controller, state_master=self.state_master, sync_uri=sync_uri)
    s.connect(self.io_master)
    s.on_disconnect(self.remove_connection)

    self.sync_connections.append(s)

    return s

  def remove_connection(self, connection):
    if connection in self.sync_connections:
      self.sync_connections.remove(connection)

class STSSyncCallback(object):
  """ override with your favorite functionality """
  def state_change(self, type, xid, controller, time, fingerprint, name, value):
    log.info("{}: controller: {} time: {} fingerprint: {} name: {} value: {}"\
             .format(type, controller, time, fingerprint, name, value))
  def get_deterministic_value(self, controller, name, xid):
    if name == "gettimeofday":
      return SyncTime.now()


text:
require.config({
	baseUrl: SITE_URL+'scripts/',
    paths: {
        "jquery": "./lib/jquery",
        "jquery-ui": "./lib/jquery-ui-1.10.0.custom.min",
		"jquery-ui-dialog-extend": "./lib/jquery-ui-dialog-extend",
        "underscore": "./lib/underscore",
        "bootstrap": "./lib/bootstrap",
		"validationEngine": "./lib/jquery.validationEngine",
		"validationEngineLang": "./lib/jquery.validationEngine-zh_CN",
		"bootstrapValidator": "./lib/bootstrapValidator",
		"formValidation": "./lib/formValidation.min",
		"aci":"./lib/aci",
		"message":"./lib/sco.message",
		"confirm":"./lib/sco.confirm",
		"modal":"./lib/sco.modal",
		"headroom":"./lib/headroom.min",
        "cookie":"./lib/jquery.cookie",
        "datetimepicker":"lib/jquery.datetimepicker"
    },
    shim: {
        "jquery-ui": {
            exports: "$",
            deps: ['jquery']
        },
        "datetimepicker": {
            exports: "$",
            deps: ['jquery']
        },
        "cookie": {
            exports: "$",
            deps: ['jquery']
        },
        "underscore": {
            exports: "_"
        },
        "bootstrapValidator": {
            exports: "$",
            deps: [ "jquery"]
        },
        "bootstrap": ['jquery'],
		"validationEngine": ['validationEngineLang'],
		"jquery-ui-dialog-extend": ['jquery-ui'],
		"aci": ['jquery'],
		"message": {
            exports: "$",
            deps: ['jquery']
        },
		"confirm": {
            exports: "$",
            deps: ['jquery']
        },
		"modal": {
            exports: "$",
            deps: ['jquery']
        },
		"headroom": {
            exports: "$",
            deps: ['jquery']
        },
    },
    waitSeconds: 0

});


text:
var mesh  = require('./mesh.json')
var tab64 = require('tab64')

// Positions are encoded in base64 to reduce their size
// significantly. Further improvements can be made by
// encoding the binary data directly.
module.exports = {
  positions: tab64.decode(mesh.positions, 'float32'),
  ranges: mesh.ranges,
  index: mesh.index,
  centroids: mesh.centroids
}


text:
#ifndef ART_COMPILER_OPTIMIZING_GRAPH_VISUALIZER_H_
#define ART_COMPILER_OPTIMIZING_GRAPH_VISUALIZER_H_

#include <ostream>

#include "arch/instruction_set.h"
#include "base/arena_containers.h"
#include "base/value_object.h"

namespace art {

class CodeGenerator;
class DexCompilationUnit;
class HGraph;
class HInstruction;
class SlowPathCode;

/**
 * This class outputs the HGraph in the C1visualizer format.
 * Note: Currently only works if the compiler is single threaded.
 */
struct GeneratedCodeInterval {
  size_t start;
  size_t end;
};

struct SlowPathCodeInfo {
  const SlowPathCode* slow_path;
  GeneratedCodeInterval code_interval;
};

// This information is filled by the code generator. It will be used by the
// graph visualizer to associate disassembly of the generated code with the
// instructions and slow paths. We assume that the generated code follows the
// following structure:
//   - frame entry
//   - instructions
//   - slow paths
class DisassemblyInformation {
 public:
  explicit DisassemblyInformation(ArenaAllocator* allocator)
      : frame_entry_interval_({0, 0}),
        instruction_intervals_(std::less<const HInstruction*>(), allocator->Adapter()),
        slow_path_intervals_(allocator->Adapter()) {}

  void SetFrameEntryInterval(size_t start, size_t end) {
    frame_entry_interval_ = {start, end};
  }

  void AddInstructionInterval(HInstruction* instr, size_t start, size_t end) {
    instruction_intervals_.Put(instr, {start, end});
  }

  void AddSlowPathInterval(SlowPathCode* slow_path, size_t start, size_t end) {
    slow_path_intervals_.push_back({slow_path, {start, end}});
  }

  GeneratedCodeInterval GetFrameEntryInterval() const {
    return frame_entry_interval_;
  }

  GeneratedCodeInterval* GetFrameEntryInterval() {
    return &frame_entry_interval_;
  }

  const ArenaSafeMap<const HInstruction*, GeneratedCodeInterval>& GetInstructionIntervals() const {
    return instruction_intervals_;
  }

  ArenaSafeMap<const HInstruction*, GeneratedCodeInterval>* GetInstructionIntervals() {
    return &instruction_intervals_;
  }

  const ArenaVector<SlowPathCodeInfo>& GetSlowPathIntervals() const { return slow_path_intervals_; }

  ArenaVector<SlowPathCodeInfo>* GetSlowPathIntervals() { return &slow_path_intervals_; }

 private:
  GeneratedCodeInterval frame_entry_interval_;
  ArenaSafeMap<const HInstruction*, GeneratedCodeInterval> instruction_intervals_;
  ArenaVector<SlowPathCodeInfo> slow_path_intervals_;
};

class HGraphVisualizer : public ValueObject {
 public:
  HGraphVisualizer(std::ostream* output,
                   HGraph* graph,
                   const CodeGenerator& codegen);

  void PrintHeader(const char* method_name) const;
  void DumpGraph(const char* pass_name, bool is_after_pass, bool graph_in_bad_state) const;
  void DumpGraphWithDisassembly() const;

 private:
  std::ostream* const output_;
  HGraph* const graph_;
  const CodeGenerator& codegen_;

  DISALLOW_COPY_AND_ASSIGN(HGraphVisualizer);
};

}  // namespace art

#endif  // ART_COMPILER_OPTIMIZING_GRAPH_VISUALIZER_H_


text: from __future__ import generator_stop


text:
package ro.isdc.wro.model.resource.processor.support;

import java.util.HashMap;
import java.util.Map;

import ro.isdc.wro.model.resource.processor.ResourcePostProcessor;
import ro.isdc.wro.model.resource.processor.ResourcePreProcessor;
import ro.isdc.wro.model.resource.processor.decorator.ProcessorDecorator;
import ro.isdc.wro.model.resource.processor.impl.css.ConformColorsCssProcessor;
import ro.isdc.wro.model.resource.processor.impl.js.JSMinProcessor;

/**
 * A custom processor provider used to test that the processors provided by this provider have precedence over default
 * processors.
 *
 * @author Alex Objelean
 */
public class UnorderedProcessorProvider
    implements ProcessorProvider {
  public static ResourcePreProcessor CUSTOM = new ProcessorDecorator(new JSMinProcessor());
  public static ResourcePreProcessor CONFORM_COLORS = new ProcessorDecorator(new ConformColorsCssProcessor());

  /**
   * {@inheritDoc}
   */
  public Map<String, ResourcePreProcessor> providePreProcessors() {
    final Map<String, ResourcePreProcessor> map = new HashMap<String, ResourcePreProcessor>();
    map.put(OrderedProcessorProvider.ALIAS, CUSTOM);
    map.put(ConformColorsCssProcessor.ALIAS, CONFORM_COLORS);
    return map;
  }

  /**
   * {@inheritDoc}
   */
  public Map<String, ResourcePostProcessor> providePostProcessors() {
    return null;
  }
}


text:
package org.support.project.knowledge.logic.notification;

import org.support.project.common.log.Log;
import org.support.project.common.log.LogFactory;
import org.support.project.common.util.StringUtils;
import org.support.project.di.Container;
import org.support.project.di.DI;
import org.support.project.di.Instance;
import org.support.project.knowledge.config.AppConfig;
import org.support.project.knowledge.dao.KnowledgesDao;
import org.support.project.knowledge.entity.KnowledgesEntity;
import org.support.project.knowledge.entity.MailLocaleTemplatesEntity;
import org.support.project.knowledge.logic.MailLogic;
import org.support.project.knowledge.logic.NotifyLogic;
import org.support.project.web.dao.MailConfigsDao;
import org.support.project.web.dao.MailsDao;
import org.support.project.web.dao.UsersDao;
import org.support.project.web.entity.MailConfigsEntity;
import org.support.project.web.entity.MailsEntity;
import org.support.project.web.entity.UsersEntity;

/**
 * 開催者(=登録者)へ参加キャンセルのメール通知
 * @author koda
 */
@DI(instance = Instance.Singleton)
public class ParticipateRemoveForSponsorNotification extends AbstractParticipateNotification{
    /** ログ */
    private static final Log LOG = LogFactory.getLog(ParticipateRemoveForSponsorNotification.class);
    /** インスタンス取得 */
    public static ParticipateRemoveForSponsorNotification get() {
        return Container.getComp(ParticipateRemoveForSponsorNotification.class);
    }

    @Override
    public void notify(Long knowledgeId, Integer userId, Integer status) {
        KnowledgesEntity knowledge = KnowledgesDao.get().selectOnKey(knowledgeId);
        if (knowledge == null) {
            LOG.info("knowledge [" + knowledgeId + "] is not exists.");
            return;
        }
        // 開催者
        UsersEntity sponsor = UsersDao.get().selectOnKey(knowledge.getInsertUser());
        // 参加者
        UsersEntity participant = UsersDao.get().selectOnKey(userId);
        if (sponsor == null || participant == null) {
            LOG.warn("sponsor or participant is not exist.");
            return;
        }

        // 通知情報生成
        insertNotification(knowledge, userId, status, MailLogic.NOTIFY_REMOVE_PARTICIPATE);

        MailConfigsDao mailConfigsDao = MailConfigsDao.get();
        MailConfigsEntity mailConfigsEntity = mailConfigsDao.selectOnKey(AppConfig.get().getSystemName());
        if (mailConfigsEntity == null) {
            // メールの設定が登録されていなければ、送信処理は終了
            LOG.info("mail config is not exists.");
            return;
        }
        if (!StringUtils.isEmailAddress(sponsor.getMailAddress())) {
            // 送信先のメールアドレスが不正なので、送信処理は終了
            LOG.warn("mail targget [" + sponsor.getMailAddress() + "] is wrong.");
            return;
        }

        MailsEntity mailsEntity = new MailsEntity();
        String mailId = idGen("Notify");
        mailsEntity.setMailId(mailId);
        mailsEntity.setStatus(MailLogic.MAIL_STATUS_UNSENT);
        mailsEntity.setToAddress(sponsor.getMailAddress());
        mailsEntity.setToName(sponsor.getUserName());

        MailLocaleTemplatesEntity template = MailLogic.get().load(sponsor.getLocale(), MailLogic.NOTIFY_REMOVE_PARTICIPATE);
        String title = template.getTitle();
        title = title.replace("{KnowledgeId}", knowledge.getKnowledgeId().toString());
        title = title.replace("{KnowledgeTitle}", StringUtils.abbreviate(knowledge.getTitle(), 80));
        mailsEntity.setTitle(title);
        String contents = template.getContent();
        contents = contents.replace("{KnowledgeId}", knowledge.getKnowledgeId().toString());
        contents = contents.replace("{KnowledgeTitle}", knowledge.getTitle());
        contents = contents.replace("{Participant}", participant.getUserName());
        contents = contents.replace("{URL}", NotifyLogic.get().makeURL(knowledge.getKnowledgeId()));

        mailsEntity.setContent(contents);
        MailsDao.get().insert(mailsEntity);
    }

}


text:
<?php
declare(strict_types=1);

namespace Lcobucci\JWT\Tests\Benchmark\Rsa;

use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Rsa\Sha384;

final class Sha384Bench extends RsaBench
{
    protected function signer(): Signer
    {
        return new Sha384();
    }
}


text:
from setuptools import setup, find_packages

setup(
    name='django-primate',
    version='0.1.1',
    description='A modular django user',
    long_description=open('README.rst').read(),
    author='Mikko Hellsing',
    author_email='mikko@aino.se',
    license='BSD',
    url='https://github.com/aino/django-primate',
    platforms='any',
    packages=find_packages(),
    zip_safe=False,
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Framework :: Django',
    ],
)


text:
module Azure::Batch::Mgmt::V2017_09_01
  module Models
    #
    # A network security group rule to apply to an inbound endpoint.
    #
    #
    class NetworkSecurityGroupRule

      include MsRestAzure

      # @return [Integer] The priority for this rule. Priorities within a pool
      # must be unique and are evaluated in order of priority. The lower the
      # number the higher the priority. For example, rules could be specified
      # with order numbers of 150, 250, and 350. The rule with the order number
      # of 150 takes precedence over the rule that has an order of 250. Allowed
      # priorities are 150 to 3500. If any reserved or duplicate values are
      # provided the request fails with HTTP status code 400.
      attr_accessor :priority

      # @return [NetworkSecurityGroupRuleAccess] The action that should be
      # taken for a specified IP address, subnet range or tag. Possible values
      # include: 'Allow', 'Deny'
      attr_accessor :access

      # @return [String] The source address prefix or tag to match for the
      # rule. Valid values are a single IP address (i.e. 10.10.10.10), IP
      # subnet (i.e. 192.168.1.0/24), default tag, or * (for all addresses).
      # If any other values are provided the request fails with HTTP status
      # code 400.
      attr_accessor :source_address_prefix

      #
      # Mapper for NetworkSecurityGroupRule class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'NetworkSecurityGroupRule',
          type: {
            name: 'Composite',
            class_name: 'NetworkSecurityGroupRule',
            model_properties: {
              priority: {
                client_side_validation: true,
                required: true,
                serialized_name: 'priority',
                type: {
                  name: 'Number'
                }
              },
              access: {
                client_side_validation: true,
                required: true,
                serialized_name: 'access',
                type: {
                  name: 'Enum',
                  module: 'NetworkSecurityGroupRuleAccess'
                }
              },
              source_address_prefix: {
                client_side_validation: true,
                required: true,
                serialized_name: 'sourceAddressPrefix',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
/*
 * @name Coordenadas
 * @description Todas las formas dibujadas en la pantalla tienen una posición que es
 * especificada como una coordenada. Todas las coordenadas son medidas como una distancia desde el origen, usando el pixel como unidad de medida.
 * El origen [0, 0] es la coordenada en la esquina superior izquierda de la ventana y la coordenada de la esquina inferior derecha es [ancho-1, altura-1].
 */
function setup() {
  // Definir lienzo de 720 pixeles de ancho y 400 pixeles de alto
  createCanvas(720, 400);
}

function draw() {
  // Definir el color del fondo como negro
  // y definir que las figuras sean pintadas sin relleno
  background(0);
  noFill();

  // Los dos parámetros del método point() especifican coordenadas.
  // El primer parámetro es la coordenada x y el segundo es la y.
  stroke(255);
  point(width * 0.5, height * 0.5);
  point(width * 0.5, height * 0.25);

  // Las coordenadas se usan para dibujar figuras, no solo puntos.
  // Los parámetros de las funciones son usados para múltiples
  // propósitos. Por ejemplo, los dos primeros parámetros
  // de line() especifican las coordenadas del primer extremo
  //y los siguientes dos parámetros del segundo extremo.
  stroke(0, 153, 255);
  line(0, height * 0.33, width, height * 0.33);

  // Por defecto, los dos primeros parámetros de rect() son
  // las coordenadas de la esquina superior izquierda y el
  // segundo par son el ancho y el alto.
  stroke(255, 153, 0);
  rect(width * 0.25, height * 0.1, width * 0.5, height * 0.8);
}


text:
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from tekton import router
from gaecookie.decorator import no_csrf
from course_app import facade
from routes.courses.admin import new, edit

def delete(_handler, course_id):
    facade.delete_course_cmd(course_id)()
    _handler.redirect(router.to_path(index))

@no_csrf
def index():
    cmd = facade.list_courses_cmd()
    courses = cmd()
    edit_path = router.to_path(edit)
    delete_path = router.to_path(delete)
    short_form = facade.course_short_form()

    def short_course_dict(course):
        course_dct = short_form.fill_with_model(course)
        course_dct['edit_path'] = router.to_path(edit_path, course_dct['id'])
        course_dct['delete_path'] = router.to_path(delete_path, course_dct['id'])
        return course_dct

    short_courses = [short_course_dict(course) for course in courses]
    context = {'courses': short_courses,
               'new_path': router.to_path(new)}
    return TemplateResponse(context)


text:
require 'socket'

with_feature :unix_socket do
  describe 'UNIXSocket#remote_address' do
    before do
      @path   = tmp('unix_socket')
      @server = UNIXServer.new(@path)
      @client = UNIXSocket.new(@path)
    end

    after do
      @client.close
      @server.close

      rm_r(@path)
    end

    it 'returns an Addrinfo' do
      @client.remote_address.should be_an_instance_of(Addrinfo)
    end

    describe 'the returned Addrinfo' do
      it 'uses AF_UNIX as the address family' do
        @client.remote_address.afamily.should == Socket::AF_UNIX
      end

      it 'uses PF_UNIX as the protocol family' do
        @client.remote_address.pfamily.should == Socket::PF_UNIX
      end

      it 'uses SOCK_STREAM as the socket type' do
        @client.remote_address.socktype.should == Socket::SOCK_STREAM
      end

      it 'uses the correct socket path' do
        @client.remote_address.unix_path.should == @path
      end

      it 'uses 0 as the protocol' do
        @client.remote_address.protocol.should == 0
      end
    end
  end
end


text:
<?php
 include '302-8.php';
$failure = 0;
$output = "";

foreach ($cookies as $cookie => $data) {
 if (isset($expectedCookies[$cookie]) && isset($_COOKIE[$cookie])) {
  $output .= "
Present
\n";
 } else if (!isset($expectedCookies[$cookie]) && isset($_COOKIE[$cookie])) {
  $output .= "
Present
\n";
  $failure = 1;
 } else if (isset($expectedCookies[$cookie]) && !isset($_COOKIE[$cookie])) {
  $output .= "
Not present
\n";
  $failure = 1;
 } else if (!isset($expectedCookies[$cookie]) && !isset($_COOKIE[$cookie])) {
  $output .= "
Not present
\n";
 }
}

function writeCookieTable($filePath) {
 global $output, $path, $failure;
?><!doctype html>

  <title>Various Paths</title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8">

<?php echo $failure?"FAIL":"PASS"?>

  <link href="<?php echo $path ?>/302/302.css" rel="stylesheet" type="text/css"/>

<?php echo $path.$filePath ?>

<?php echo $output?>

 <a href="<?php echo $path ?>/302/302.php?location=<?php echo $_SERVER['REQUEST_URI']?>">Direct link

<?php echo ($_SERVER['HTTP_COOKIE']) ?>

<?php }?>


text:
'use strict';

var util = require('util');
var articleService = require('../../services/article');
var articleSearchService = require('../../services/articleSearch');
var listOrSingle = require('./lib/listOrSingle');
var searchResults = require('./lib/searchResults');
var separator = /[+/,_: ]+/ig;

module.exports = function (req, res, next) {
  var tags = req.params.tags.split(separator);
  var title = util.format('Articles tagged "%s"', tags.join('", "'));
  var query = {
    status: 'published',
    tags: { $all: tags }
  };
  var handle = listOrSingle(res, searchResults(res, next));

  res.viewModel = {
    model: {
      title: title,
      meta: {
        canonical: '/articles/tagged/' + tags.join('+'),
        description: 'This search results page contains all of the ' + title.toLowerCase()
      },
      action: 'articles/search-results',
      query: articleSearchService.format([], tags)
    }
  };

  articleService.find(query, handle);
};


text:
__author__ = 'i@tinyms.com'

import os
import re
import codecs
import hashlib
import json
import time
import datetime
import decimal
import uuid
import shutil
from datetime import timedelta

import xlrd
from tornado.template import Template
from dateutil.relativedelta import relativedelta

class DataResult(object):
    message = ""
    success = True
    data = object()

    def dict(self):
        t = dict()
        t["message"] = self.message
        t["success"] = self.success
        t["data"] = self.data
        return t

class JsonEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        elif isinstance(o, datetime.date):
            return Utils.format_datetime_short(o)
        elif isinstance(o, datetime.datetime):
            return Utils.format_datetime_short(o)
        elif isinstance(o, datetime.time):
            return Utils.format_time(o)

        super(JsonEncoder, self).default(o)

class Utils():
    def __init__(self):
        pass

    @staticmethod
    def text_read(f_name, join=True):
        if not os.path.exists(f_name):
            return ""
        f = codecs.open(f_name, "r", "utf-8")
        all_ = f.readlines()
        f.close()
        if join:
            return "".join(all_)
        return all

    @staticmethod
    def text_write(f_name, lines=list(), suffix="\n"):
        f = codecs.open(f_name, "w+", "utf-8")
        if isinstance(lines, list):
            for line in lines:
                f.write(line + suffix)
        else:
            f.write(lines)
            f.write(suffix)
        f.close()

    @staticmethod
    def get_file_size(file_abs_path):
        """
        返回文件大小
        :param file_abs_path: 文件全路径
        :return: 文件大小,以KB为单位
        """
        st = os.stat(file_abs_path)
        return st.st_size / 1024

    @staticmethod
    def create_thumbnail(imgfile_path, saved_path, size="200x200"):
        from PIL import Image
        nums = Utils.parse_int_array(size)
        img = Image.open(imgfile_path)
        img.thumbnail((nums[0], nums[1]), Image.ANTIALIAS)
        img.save(saved_path, "JPEG")

    @staticmethod
    def read_excel(excel_file_path, by_name='Sheet1'):

        data = None
        try:
            data = xlrd.open_workbook(excel_file_path)
        except Exception as e:
            print(e)

        table = data.sheet_by_name(by_name)
        nrows = table.nrows
        ncols = table.ncols

        rows = list()
        for rownum in range(1, nrows):
            row = list()
            for colnum in range(0, ncols):
                row.append(table.cell(rownum, colnum).value)
            rows.append(row)

        return rows

    @staticmethod
    def read_excel_sheets(excel_file_path):
        data = None
        try:
            data = xlrd.open_workbook(excel_file_path)
        except Exception as e:
            print(e)
        names = list()
        for sheet in data.sheets():
            names.append(sheet.name)
        return names

    @staticmethod
    def excel_export(handler, html, dwn_file_name):
        handler.set_header("Content-Type", "application/vnd.ms-excel;charset=utf-8")
        handler.add_header("Content-Disposition", "attachment;filename=%s.xls" % dwn_file_name)
        handler.write(html)

    @staticmethod
    def word_export(handler, html, dwn_file_name):
        handler.set_header("Content-Type", "application/ms-word;charset=utf-8")
        handler.add_header("Content-Disposition", "attachment;filename=%s.doc" % dwn_file_name)
        header = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"
        handler.write(header + html)

    # @staticmethod
    # def url_with_params(url):
    # r1 = urllib.parse.urlsplit(url)
    # if r1.query != "":
    #         return True
    #     return False

    @staticmethod
    def trim(text):
        return "".join(text.split())

    @staticmethod
    def uniq_index():
        return str(uuid.uuid1())

    @staticmethod
    def render(tpl_text, **kwargs):
        """
        render a template
        :param tpl_text: template text
        :param context: dict object
        :return: str
        """
        tpl = Template(tpl_text)
        return tpl.generate(**kwargs).decode("utf-8")

    @staticmethod
    def md5(s):
        h = hashlib.new('ripemd160')
        h.update(bytearray(s.encode("utf8")))
        return h.hexdigest()

    @staticmethod
    def fix_width_num(num, size=3):
        fmt = "{0:0%i}" % size
        return fmt.format(num)

    @staticmethod
    def current_datetime():
        from datetime import datetime as tmp

        return tmp.now()

    @staticmethod
    def copydirs(path, dst):
        shutil.copytree(path, dst)

    @staticmethod
    def rmdirs(path):
        shutil.rmtree(path, True)

    @staticmethod
    def mkdirs(path):
        isexists = os.path.exists(path)
        if not isexists:
            os.makedirs(path)
            return True
        else:
            return False

    @staticmethod
    def parse_int(text):
        nums = Utils.parse_int_array(text)
        if len(nums) > 0:
            return int(nums[0])
        return None

    @staticmethod
    def parse_int_array(text):
        arr = list()
        p = re.compile("[-]?\\d+", re.M)
        nums = p.findall(text)
        if len(nums) > 0:
            arr = [int(s) for s in nums]
        return arr

    @staticmethod
    def parse_time_text(text):
        if not text:
            return ""
        p = re.compile("\\d{2}:\\d{2}")
        dates = p.findall(text)
        if len(dates) > 0:
            return dates[0]
        return ""

    @staticmethod
    def parse_time(text):
        time_text = Utils.parse_time_text(text)
        if not time_text:
            return None
        time_struct = time.strptime(time_text, "%H:%M")
        return datetime.time(time_struct.tm_hour, time_struct.tm_min)

    @staticmethod
    def parse_date_text(text):
        if not text:
            return ""
        p = re.compile("\\d{4}-\\d{2}-\\d{2}")
        dates = p.findall(text)
        if len(dates) > 0:
            return dates[0]
        return ""

    @staticmethod
    def parse_date(text):
        date_text = Utils.parse_date_text(text)
        if not date_text:
            return None
        from datetime import datetime

        return datetime.strptime(date_text, "%Y-%m-%d").date()

    @staticmethod
    def parse_datetime_text(text):
        if not text:
            return ""
        p = "\\d{4}-\\d{2}-\\d{2}\\s{1}\\d{2}:\\d{2}"
        r = re.compile(p)
        matchs = r.findall(text)
        if len(matchs) > 0:
            return matchs[0]
        return ""

    @staticmethod
    def parse_datetime(text):
        datetime_text = Utils.parse_datetime_text(text)
        if not datetime_text:
            return None
        from datetime import datetime

        return datetime.strptime(datetime_text, "%Y-%m-%d %H:%M")

    @staticmethod
    def parse_float(text):
        floats = Utils.parse_float_array(text)
        if len(floats) > 0:
            return float(floats[0])
        else:
            return float(Utils.parse_int(text))

    @staticmethod
    def parse_float_array(text):
        p = re.compile("[-]?\\d+\\.\\d+", re.M)
        return [float(s) for s in p.findall(text)]

    @staticmethod
    def parse_number_array(text):
        """
        int or float
        :param text:
        :return:
        """
        p = re.compile("[-]?\\d+[\\.]?[\\d]*", re.M)
        return [float(s) for s in p.findall(text)]

    @staticmethod
    def encode(obj):
        return json.dumps(obj, cls=JsonEncoder)

    @staticmethod
    def decode(text):
        return json.loads(text)

    @staticmethod
    def obj_to_dict(obj, field_name_arr=None):
        if not field_name_arr:
            return dict()
        tmp = dict()
        for fn in field_name_arr:
            tmp[fn] = getattr(obj, fn)
        return tmp

    # @staticmethod
    # def download(url, save_path):
    #     try:
    #         f = urllib.request.urlopen(url, timeout=15)
    #         data = f.read()
    #         with open(save_path, "wb") as cache:
    #             cache.write(data)
    #     except urllib.error.URLError as ex:
    #         info = sys.exc_info()
    #         print(info[0], ":", info[1], ex)

    @staticmethod
    def matrix_reverse(arr):
        """
        矩阵翻转
        :param arr:
        :return:
        """
        return [[r[col] for r in arr] for col in range(len(arr[0]))]

    @staticmethod
    def combine_text_files(folder, target_file_name):
        text = Utils.text_read(os.path.join(folder, "combine.list"))
        cfg = json.loads(text)
        for key in cfg.keys():
            files = cfg[key]
            if len(files) > 0:
                combine_file = os.path.join(folder, target_file_name + "." + key)
                if os.path.exists(combine_file):
                    os.remove(combine_file)
                all_ = list()
                for file_ in files:
                    path = os.path.join(folder, file_)
                    all_.append(Utils.text_read(path))
                Utils.text_write(combine_file, all_)
        pass

    @staticmethod
    def is_email(s):
        p = r"[^@]+@[^@]+\.[^@]+"
        if re.match(p, s):
            return True
        return False

    @staticmethod
    def email_account_name(s):
        #匹配@前面的字符串
        p = r".*(?=@)"
        r = re.compile(p)
        matchs = r.findall(s)
        if len(matchs) > 0:
            return matchs[0]
        return ""

    ########################################### Date Format ######################################################

    @staticmethod
    def format_year_month(date_obj, split="-"):
        """
        格式化成 yyyy-MM
        :param date_obj: 日期对象
        :param split: 年月分割符
        :return: 格式化后的字符串
        """
        if not date_obj:
            return ""
        return date_obj.strftime('%Y' + split + '%m')

    @staticmethod
    def format_datetime(date_obj, split="-"):
        """
        格式化成 yyyy-MM-dd HH:MM:SS
        :param date_obj: 日期对象
        :param split: 年月日分割符
        :return: 格式化后的字符串
        """
        if not date_obj:
            return ""
        return date_obj.strftime('%Y' + split + '%m' + split + '%d %H:%M:%S')

    @staticmethod
    def format_datetime_short(date_obj, split="-"):
        """
        格式化成 yyyy-MM-dd HH:MM
        :param date_obj: 日期对象
        :param split: 年月日分割符
        :return: 格式化后的字符串
        """
        if not date_obj:
            return ""
        return date_obj.strftime('%Y' + split + '%m' + split + '%d %H:%M')

    @staticmethod
    def format_date(date_obj, split="-"):
        """
        格式化成 yyyy-MM-dd
        :param date_obj: 日期对象
        :param split: 年月日分割符
        :return: 格式化后的字符串
        """
        if not date_obj:
            return ""
        try:
            return date_obj.strftime('%Y' + split + '%m' + split + '%d')
        except Exception as ex:
            print(ex)
        return ""

    @staticmethod
    def format_time(datetime_obj):
        """
        格式化成 HH:MM
        :param datetime_obj: 日期对象
        :return: 格式化后的字符串
        """
        if not datetime_obj:
            return ""
        if isinstance(datetime_obj, datetime.time):
            curr_date = Utils.current_datetime()
            dt = datetime.datetime.combine(curr_date, datetime_obj)
            return dt.strftime('%H:%M')
        elif isinstance(datetime_obj, datetime.datetime):
            return datetime_obj.strftime('%H:%M')
        return ""

    @staticmethod
    def list_modules(path_):
        """
        得到path_的模块名,模块名包括完整的包名
        :param path_: 扫描的路径
        :return: 模块名列表
        """
        packages = list()
        modules = list()
        iter_files = os.walk(path_)
        for root, dirs, files in iter_files:
            for f in files:
                if f.find('__init__.py') != -1:
                    packages.append(root)

        iter_files = os.walk(path_)
        for root, dirs, files in iter_files:
            for f in files:
                if packages.count(root) == 1 and f.endswith(".py") and f.find('__init__.py') == -1:
                    modules.append(os.path.join(root, f).replace(".py", ""))

        last_modules = list()
        for module in modules:
            tmp = module.replace(path_, "")
            tmp = tmp.replace(os.path.sep, ".")
            last_modules.append(tmp[1:])

        return last_modules

    ########################################### Date Add ######################################################
    @staticmethod
    def add_days(date, days):
        space = timedelta(days=days)
        return date + space

    @staticmethod
    def add_months(date, months):
        space = relativedelta(months=months)
        return date + space

    @staticmethod
    def add_minutes(date, minutes):
        space = timedelta(minutes=minutes)
        return date + space


text:
package org.switchyard.transform.ootb.io;

import org.junit.Assert;
import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @author tom.fennelly@gmail.com
 */
public class InputStreamTransformsTest {

    @Test
    public void testToString() throws Exception {
        Assert.assertEquals("Hello SwitchYard", InputStreamTransforms.TRANSFORMER.toString(newInputStream("Hello SwitchYard")));
    }

    @Test
    public void testToReader() throws Exception {
        Assert.assertNotNull(InputStreamTransforms.TRANSFORMER.toReader(newInputStream("Hello SwitchYard")));
    }

    @Test
    public void testToInputSource() throws Exception {
        Assert.assertNotNull(InputStreamTransforms.TRANSFORMER.toInputSource(newInputStream("Hello SwitchYard")));
    }

    @Test
    public void testToInteger() throws Exception {
        Assert.assertEquals((Integer)1, InputStreamTransforms.TRANSFORMER.toInteger(newInputStream("1")));
    }

    @Test
    public void testToLong() throws Exception {
        Assert.assertEquals((Long)1L, InputStreamTransforms.TRANSFORMER.toLong(newInputStream("1")));
    }

    @Test
    public void testToShort() throws Exception {
        Assert.assertEquals(new Short("1"), InputStreamTransforms.TRANSFORMER.toShort(newInputStream("1")));
    }

    @Test
    public void testToChars() throws Exception {
        Assert.assertEquals("12345", new String(InputStreamTransforms.TRANSFORMER.toChars(newInputStream("12345"))));
    }

    @Test
    public void testToCharacter() throws Exception {
        Assert.assertEquals((Character) '1', InputStreamTransforms.TRANSFORMER.toCharacter(newInputStream("12345")));
    }

    @Test
    public void testToBytes() throws Exception {
        Assert.assertNotNull(new String(InputStreamTransforms.TRANSFORMER.toBytes(newInputStream("12345"))));
    }

    @Test
    public void testToDouble() throws Exception {
        Assert.assertEquals((Double)1D, InputStreamTransforms.TRANSFORMER.toDouble(newInputStream("1")));
    }

    @Test
    public void testToFloat() throws Exception {
        Assert.assertEquals((Float)1F, InputStreamTransforms.TRANSFORMER.toFloat(newInputStream("1")));
    }

    private InputStream newInputStream(String s) {
        return new ByteArrayInputStream(s.getBytes());
    }
}


text:
package org.apache.hawq.pxf.service.utilities;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.SecurityUtil;

/*
 * This class relies heavily on Hadoop API to
 * - Check need for secure login in Hadoop
 * - Parse and load .xml configuration file
 * - Do a Kerberos login with a kaytab file
 * - convert _HOST in Kerberos principal to current hostname
 *
 * It uses Hadoop Configuration to parse XML configuration files
 * It uses Hadoop Security to modify principal and perform the login
 *
 * The major limitation in this class is its dependency
 * on Hadoop. If Hadoop security is off, no login will be performed
 * regardless of connector being used.
 */
public class SecureLogin {
    private static Log LOG = LogFactory.getLog(SecureLogin.class);
	private static final String CONFIG_KEY_SERVICE_KEYTAB = "pxf.service.kerberos.keytab";
	private static final String CONFIG_KEY_SERVICE_PRINCIPAL = "pxf.service.kerberos.principal";

	public static void login() {
		try {
			Configuration config = new Configuration();
			config.addResource("pxf-site.xml");

			SecurityUtil.login(config, CONFIG_KEY_SERVICE_KEYTAB, CONFIG_KEY_SERVICE_PRINCIPAL);
		} catch (Exception e)
		{
			LOG.error("PXF service login failed");
			throw new RuntimeException(e);
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@android:color/black"
    android:padding="10dp">
    <!-- Global -->
    <LinearLayout
        android:id="@+id/linearLayoutGlobal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="10dp">

        <TextView
            android:id="@+id/textViewLabelGlobal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textSize="25sp"
            android:textColor="@android:color/white"
            android:text="@string/label_taxi_global" />

        <ImageView
            android:id="@+id/imageViewGlobal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
             />
    </LinearLayout>

    <!-- Riva -->
    <LinearLayout
        android:id="@+id/linearLayoutRiva"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="10dp">

        <TextView
            android:id="@+id/textViewLabelRiva"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textSize="25sp"
            android:textColor="@android:color/white"
            android:text="@string/label_taxi_riva" />

        <ImageView
            android:id="@+id/imageViewRiva"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            />
    </LinearLayout>

    <!-- Pulstars -->
    <LinearLayout
        android:id="@+id/linearLayoutPulstars"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="10dp">

        <TextView
            android:id="@+id/textViewLabelPulstars"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:textColor="@android:color/white"
            android:text="@string/label_taxi_pulstars" />

        <ImageView
            android:id="@+id/imageViewPulstars"
            android:layout_marginLeft="30dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
             />
    </LinearLayout>

</LinearLayout>


text:
(function(){

angular.module('ngCordova', [
  'ngCordova.plugins'
]);

angular.module('ngCordova.plugins.barcodeScanner', [])

.factory('$cordovaBarcodeScanner', ['$q', function ($q) {

  return {
    scan: function () {
      var q = $q.defer();

      cordova.plugins.barcodeScanner.scan(function (result) {
        q.resolve(result);
      }, function (err) {
        q.reject(err);
      }, options);

      return q.promise;
    },

    encode: function (type, data) {
      var q = $q.defer();

      /* TODO needs work for type:
       make the default:  BarcodeScanner.Encode.TEXT_TYPE
       other options: .EMAIL_TYPE, .PHONE_TYPE, .SMS_TYPE

       docs: https://github.com/wildabeast/BarcodeScanner#encoding-a-barcode
       */

      cordova.plugins.barcodeScanner.encode(type, data, function (result) {
        q.resolve(result);
      }, function (err) {
        q.reject(err);
      });

      return q.promise;
    }
  }
}]);

angular.module('ngCordova.plugins.camera', [])

.factory('$cordovaCamera', ['$q', function($q) {

  return {
    getPicture: function(options) {
      var q = $q.defer();

      if(!navigator.camera) {
        q.resolve(null);
        return q.promise;
      }

      navigator.camera.getPicture(function(imageData) {
        q.resolve(imageData);
      }, function(err) {
        q.reject(err);
      }, options);

      return q.promise;
    },
    cleanup: function(options) {
      var q = $q.defer();

      navigator.camera.cleanup(function() {
        q.resolve(arguments);
      }, function(err) {
        q.reject(err);
      });

      return q.promise;
    }

  }
}]);

angular.module('ngCordova.plugins.contacts', [])

.factory('Contacts', ['$q', function ($q) {

  return {
    save: function (contact) {
      var q = $q.defer();
      var deviceContact = navigator.contacts.create(contact);

      deviceContact.save(function (result) {
          q.resolve(result);
        },
        function (err) {
          q.reject(err);
        });
      return q.promise;
    },

    remove: function (contact) {
      var q = $q.defer();
      var deviceContact = navigator.contacts.create(contact);

      deviceContact.remove(function (result) {
          q.resolve(result);
        },
        function (err) {
          q.reject(err);
        });
      return q.promise;
    },

    clone: function (contact) {
      var deviceContact = navigator.contacts.create(contact);
      return deviceContact.clone(contact)
    },

    find: function (options) {
      var q = $q.defer();
      var fields = options.fields || ['id', 'displayName'];
      delete options.fields;

      navigator.contacts.find(fields, function (results) {
          q.resolve(results);
        },
        function (err) {
          q.reject(err);
        },
        options);

      return q.promise;
    }

    /*
     getContact: function (contact) {
     var q = $q.defer();

     navigator.contacts.pickContact(function (contact) {

     })

     }
     */

    // TODO: method to set / get ContactAddress
    // TODO: method to set / get ContactError
    // TODO: method to set / get ContactField
    // TODO: method to set / get ContactName
    // TODO: method to set / get ContactOrganization

  }

}]);

angular.module('ngCordova.plugins.device', [])

.factory('$cordovaDevice', [function () {

  return {
    getDevice: function () {
      return device;
    },

    getCordova: function () {
      return device.cordova;
    },

    getModel: function () {
      return device.model;
    },

    // Waraning: device.name is deprecated as of version 2.3.0. Use device.model instead.
    getName: function () {
      return device.name;
    },

    getPlatform: function () {
      return device.platform;
    },

    getUUID: function () {
      return device.uuid;
    },

    getVersion: function () {
      return device.version;
    }
  }
}]);

angular.module('ngCordova.plugins.deviceMotion', [])

.factory('$cordovaDeviceMotion', ['$q', function($q) {

  return {
    getCurrentAcceleration: function() {
      var q = $q.defer();

      navigator.accelerometer.getCurrentAcceleration(function(result) {
        // Do any magic you need
        q.resolve(result);
      }, function(err) {
        q.reject(err);
      }, options);

      return q.promise;
    },
    watchAcceleration: function(options) {
      var q = $q.defer();

      navigator.accelerometer.watchAcceleration(function(result) {
        // Do any magic you need
        q.notify(result);
      }, function(err) {
        q.reject(err);
      }, options);

      return q.promise;
    },
    clearWatch: function(watchID) {
      return navigator.accelerometer.clearWatch(watchID);
    }
  }
}]);

angular.module('ngCordova.plugins.deviceOrientation', [])

.factory('$cordovaDeviceOrientation', ['$q', function($q) {

  return {
    watchHeading: function(options) {
      var q = $q.defer();

      navigator.compass.watchHeading(function(result) {
        q.resolve(result);
      }, function(err) {
        q.reject(err);
      }, options);

      return q.promise;
    }
  }
}]);

angular.module('ngCordova.plugins.geolocation', [])

.factory('$cordovaGeolocation', ['$q', function($q) {

  return {
    getCurrentPosition: function(options) {
      var q = $q.defer();

      navigator.geolocation.getCurrentPosition(function(result) {
        // Do any magic you need
        q.resolve(result);
      }, function(err) {
        q.reject(err);
      }, options);

      return q.promise;
    },
    watchPosition: function(options) {
      var q = $q.defer();

      navigator.geolocation.watchPosition(function(result) {
        // Do any magic you need
        q.notify(result);

      }, function(err) {
        q.reject(err);
      }, options);

      return q.promise;
    },

    clearWatch: function(watchID) {
      return navigator.geolocation.clearWatch(watchID);
    }
  }
}]);

angular.module('ngCordova.plugins.keyboard', [])

.factory('$cordovaKeyboard', [function () {

  return {
    hideAccessoryBar: function (bool) {
      return cordova.plugins.Keyboard.hideKeyboardAccessoryBar(bool);
    },

    close: function () {
      return cordova.plugins.Keyboard.close();
    },

    disableScroll: function (bool) {
      return cordova.plugins.Keyboard.disableScroll(bool);
    },

    isVisible: function () {
      return cordova.plugins.Keyboard.isVisible
    }

    //TODO: add support for native.keyboardshow + native.keyboardhide
  }
}]);

angular.module('ngCordova.plugins', [
  'ngCordova.plugins.deviceMotion',
  'ngCordova.plugins.camera',
  'ngCordova.plugins.geolocation',
  'ngCordova.plugins.deviceOrientation',
  'ngCordova.plugins.notification',
  'ngCordova.plugins.vibration',
  'ngCordova.plugins.network',
  'ngCordova.plugins.device',
  'ngCordova.plugins.barcodeScanner',
  'ngCordova.plugins.splashscreen',
  'ngCordova.plugins.keyboard',
  'ngCordova.plugins.contacts',
  'ngCordova.plugins.statusbar'
]);

angular.module('ngCordova.plugins.network', [])

.factory('$cordovaNetwork', [function () {

  return {

    getNetwork: function () {
      return navigator.connection.type;
    },

    isOnline: function () {
      var networkSate = navigator.connection.type;
      return networkSate != Connection.UNKNOWN;
    },

    isOffline: function () {
      var networkSate = navigator.connection.type;
      return networkSate == Connection.UNKNOWN;
    }
  }
}]);

angular.module('ngCordova.plugins.notification', [])

.factory('$cordovaNotification', [function() {

  return {
    alert: function(message, callback, title, buttonName) {
	    return navigator.notification.alert.apply(navigator.notification, arguments);
    },

    confirm: function(message, callback, title, buttonName) {
	    return navigator.notification.confirm.apply(navigator.notification, arguments);
    },

    prompt: function(message, promptCallback, title, buttonLabels, defaultText) {
	    return navigator.notification.prompt.apply(navigator.notification, arguments);
    },

    beep: function(times) {
	    return navigator.notification.beep(times);
    }
  }
}]);

angular.module('ngCordova.plugins.splashscreen', [])

.factory('$cordovaSplashscreen', [ function () {

  return {
    hide: function () {
      return navigator.splashscreen.hide();
    },

    show: function () {
      return navigator.splashscreen.show();
    }
  };

}]);

angular.module('ngCordova.plugins.statusbar', [])

.factory('$cordovaStatusbar', [function() {

  return {
  	overlaysWebView: function(bool) {
      return StatusBar.overlaysWebView(true);
	  },

    // styles: Default, LightContent, BlackTranslucent, BlackOpaque
    style: function (style) {
      switch (style) {
        case 0:     // Default
          return StatusBar.styleDefault();
          break;

        case 1:     // LightContent
          return StatusBar.styleLightContent();
          break;

        case 2:     // BlackTranslucent
          return StatusBar.styleBlackTranslucent();
          break;

        case 3:     // BlackOpaque
          return StatusBar.styleBlackOpaque();
          break;

        default:  // Default
          return StatusBar.styleDefault();
      }
    },

    // supported names: black, darkGray, lightGray, white, gray, red, green, blue, cyan, yellow, magenta, orange, purple, brown
    styleColor: function (color) {
      return StatusBar.backgroundColorByName(color);
    },

    styleHex: function (colorHex) {
      return StatusBar.backgroundColorByHexString(colorHex);
    },

    hide: function () {
      return StatusBar.hide();
    },

    show: function () {
      return StatusBar.show()
    },

    isVisible: function () {
      return StatusBar.isVisible();
    }
  }
}]);

angular.module('ngCordova.plugins.vibration', [])

.factory('$cordovaVibration', [function() {

  return {
  	vibrate: function(times) {
  	  return navigator.notification.vibrate(times);
	  }
  }
}]);

})();


text:
import { IMoveAction } from "battlemovr/lib/Actions";
import { IMoveEffect } from "battlemovr/lib/Effects";
import { ITeamAndAction } from "battlemovr/lib/Teams";
import { Component } from "eightbittr/lib/Component";

import { FullScreenPokemon } from "../../../../../FullScreenPokemon";

/**
 * Runs switching move animations for FullScreenPokemon instances.
 */
export class Switching<TGameStartr extends FullScreenPokemon> extends Component<TGameStartr> {
    /**
     * Runs the missed move animation for a battle move effect.
     *
     * @param teamAndAction   Team and move being performed.
     * @param effect   Effect of the move that missed.
     * @param onComplete   Handler for when this is done.
     */
    public run(teamAndAction: ITeamAndAction<IMoveAction>, effect: IMoveEffect, onComplete: () => void): void {
        console.log("Switching:", teamAndAction, effect);
        onComplete();
    }
}


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

	<title>simpleLastFM | jQuery Last.FM Plugin</title>

simpleLastFM | jQuery Plugin

A simple jQuery plugin to display what you've been listening and scrobbling to Last.fm including recent tracks, top albums, weekly charts and plenty more. For more information including docs, faq and usage examples visit http://simplelastfm.monkeecreate.com


text:
"""
GIF picture parser.

Author: Victor Stinner
"""

from lib.hachoir_parser import Parser
from lib.hachoir_core.field import (FieldSet, ParserError,
    Enum, UInt8, UInt16,
    Bit, Bits, NullBytes,
    String, PascalString8, Character,
    NullBits, RawBytes)
from lib.hachoir_parser.image.common import PaletteRGB
from lib.hachoir_core.endian import LITTLE_ENDIAN
from lib.hachoir_core.tools import humanDuration
from lib.hachoir_core.text_handler import textHandler, displayHandler, hexadecimal

# Maximum image dimension (in pixel)
MAX_WIDTH = 6000
MAX_HEIGHT = MAX_WIDTH
MAX_FILE_SIZE = 100 * 1024 * 1024

class Image(FieldSet):
    def createFields(self):
        yield UInt16(self, "left", "Left")
        yield UInt16(self, "top", "Top")
        yield UInt16(self, "width", "Width")
        yield UInt16(self, "height", "Height")

        yield Bits(self, "bpp", 3, "Bits / pixel minus one")
        yield NullBits(self, "nul", 2)
        yield Bit(self, "sorted", "Sorted??")
        yield Bit(self, "interlaced", "Interlaced?")
        yield Bit(self, "has_local_map", "Use local color map?")

        if self["has_local_map"].value:
            nb_color = 1 << (1 + self["bpp"].value)
            yield PaletteRGB(self, "local_map", nb_color, "Local color map")

        yield UInt8(self, "code_size", "LZW Minimum Code Size")
        while True:
            blen = UInt8(self, "block_len[]", "Block Length")
            yield blen
            if blen.value != 0:
                yield RawBytes(self, "data[]", blen.value, "Image Data")
            else:
                break

    def createDescription(self):
        return "Image: %ux%u pixels at (%u,%u)" % (
            self["width"].value, self["height"].value,
            self["left"].value, self["top"].value)

DISPOSAL_METHOD = {
    0: "No disposal specified",
    1: "Do not dispose",
    2: "Restore to background color",
    3: "Restore to previous",
}

NETSCAPE_CODE = {
    1: "Loop count",
}

def parseApplicationExtension(parent):
    yield PascalString8(parent, "app_name", "Application name")
    yield UInt8(parent, "size")
    size = parent["size"].value
    if parent["app_name"].value == "NETSCAPE2.0" and size == 3:
        yield Enum(UInt8(parent, "netscape_code"), NETSCAPE_CODE)
        if parent["netscape_code"].value == 1:
            yield UInt16(parent, "loop_count")
        else:
            yield RawBytes(parent, "raw", 2)
    else:
        yield RawBytes(parent, "raw", size)
    yield NullBytes(parent, "terminator", 1, "Terminator (0)")

def parseGraphicControl(parent):
    yield UInt8(parent, "size", "Block size (4)")

    yield Bit(parent, "has_transp", "Has transparency")
    yield Bit(parent, "user_input", "User input")
    yield Enum(Bits(parent, "disposal_method", 3), DISPOSAL_METHOD)
    yield NullBits(parent, "reserved[]", 3)

    if parent["size"].value != 4:
        raise ParserError("Invalid graphic control size")
    yield displayHandler(UInt16(parent, "delay", "Delay time in millisecond"), humanDuration)
    yield UInt8(parent, "transp", "Transparent color index")
    yield NullBytes(parent, "terminator", 1, "Terminator (0)")

def parseComments(parent):
    while True:
        field = PascalString8(parent, "comment[]", strip=" \0\r\n\t")
        yield field
        if field.length == 0:
            break

def parseTextExtension(parent):
    yield UInt8(parent, "block_size", "Block Size")
    yield UInt16(parent, "left", "Text Grid Left")
    yield UInt16(parent, "top", "Text Grid Top")
    yield UInt16(parent, "width", "Text Grid Width")
    yield UInt16(parent, "height", "Text Grid Height")
    yield UInt8(parent, "cell_width", "Character Cell Width")
    yield UInt8(parent, "cell_height", "Character Cell Height")
    yield UInt8(parent, "fg_color", "Foreground Color Index")
    yield UInt8(parent, "bg_color", "Background Color Index")
    while True:
        field = PascalString8(parent, "comment[]", strip=" \0\r\n\t")
        yield field
        if field.length == 0:
            break

def defaultExtensionParser(parent):
    while True:
        size = UInt8(parent, "size[]", "Size (in bytes)")
        yield size
        if 0 < size.value:
            yield RawBytes(parent, "content[]", size.value)
        else:
            break

class Extension(FieldSet):
    ext_code = {
        0xf9: ("graphic_ctl[]", parseGraphicControl, "Graphic control"),
        0xfe: ("comments[]", parseComments, "Comments"),
        0xff: ("app_ext[]", parseApplicationExtension, "Application extension"),
        0x01: ("text_ext[]", parseTextExtension, "Plain text extension")
    }
    def __init__(self, *args):
        FieldSet.__init__(self, *args)
        code = self["code"].value
        if code in self.ext_code:
            self._name, self.parser, self._description = self.ext_code[code]
        else:
            self.parser = defaultExtensionParser

    def createFields(self):
        yield textHandler(UInt8(self, "code", "Extension code"), hexadecimal)
        for field in self.parser(self):
            yield field

    def createDescription(self):
        return "Extension: function %s" % self["func"].display

class ScreenDescriptor(FieldSet):
    def createFields(self):
        yield UInt16(self, "width", "Width")
        yield UInt16(self, "height", "Height")
        yield Bits(self, "bpp", 3, "Bits per pixel minus one")
        yield Bit(self, "reserved", "(reserved)")
        yield Bits(self, "color_res", 3, "Color resolution minus one")
        yield Bit(self, "global_map", "Has global map?")
        yield UInt8(self, "background", "Background color")
        yield UInt8(self, "pixel_aspect_ratio", "Pixel Aspect Ratio")

    def createDescription(self):
        colors = 1 << (self["bpp"].value+1)
        return "Screen descriptor: %ux%u pixels %u colors" \
            % (self["width"].value, self["height"].value, colors)

class GifFile(Parser):
    endian = LITTLE_ENDIAN
    separator_name = {
        "!": "Extension",
        ",": "Image",
        ";": "Terminator"
    }
    PARSER_TAGS = {
        "id": "gif",
        "category": "image",
        "file_ext": ("gif",),
        "mime": (u"image/gif",),
        "min_size": (6 + 7 + 1 + 9)*8,   # signature + screen + separator + image
        "magic": (("GIF87a", 0), ("GIF89a", 0)),
        "description": "GIF picture"
    }

    def validate(self):
        if self.stream.readBytes(0, 6) not in ("GIF87a", "GIF89a"):
            return "Wrong header"
        if self["screen/width"].value == 0 or self["screen/height"].value == 0:
            return "Invalid image size"
        if MAX_WIDTH < self["screen/width"].value:
            return "Image width too big (%u)" % self["screen/width"].value
        if MAX_HEIGHT < self["screen/height"].value:
            return "Image height too big (%u)" % self["screen/height"].value
        return True

    def createFields(self):
        # Header
        yield String(self, "magic", 3, "File magic code", charset="ASCII")
        yield String(self, "version", 3, "GIF version", charset="ASCII")

        yield ScreenDescriptor(self, "screen")
        if self["screen/global_map"].value:
            bpp = (self["screen/bpp"].value+1)
            yield PaletteRGB(self, "color_map", 1 << bpp, "Color map")
            self.color_map = self["color_map"]
        else:
            self.color_map = None

        self.images = []
        while True:
            code = Enum(Character(self, "separator[]", "Separator code"), self.separator_name)
            yield code
            code = code.value
            if code == "!":
                yield Extension(self, "extensions[]")
            elif code == ",":
                yield Image(self, "image[]")
            elif code == ";":
                # GIF Terminator
                break
            else:
                raise ParserError("Wrong GIF image separator: 0x%02X" % ord(code))

    def createContentSize(self):
        field = self["image[0]"]
        start = field.absolute_address + field.size
        end = start + MAX_FILE_SIZE*8
        pos = self.stream.searchBytes("\0;", start, end)
        if pos:
            return pos + 16
        return None