text:
@class NewsBlurAppDelegate;

@interface StoryDetailViewController : BaseViewController
<UIScrollViewDelegate, UIGestureRecognizerDelegate,
UIActionSheetDelegate> {
    NewsBlurAppDelegate *appDelegate;

    NSString *activeStoryId;
    NSMutableDictionary *activeStory;
    UIView *innerView;
    UIWebView *webView;
    NSInteger pageIndex;
    BOOL pullingScrollview;
    BOOL inTextView;
    BOOL inDoubleTap;
    BOOL hasScrolled;
    NSURL *activeLongPressUrl;
    CGSize preRotateSize;
    CGFloat scrollPct;

    UIInterfaceOrientation _orientation;
}

@property (nonatomic) IBOutlet NewsBlurAppDelegate *appDelegate;
@property (nonatomic) NSString *activeStoryId;
@property (nonatomic, readwrite) NSMutableDictionary *activeStory;
@property (nonatomic) IBOutlet UIView *innerView;
@property (nonatomic) IBOutlet UIWebView *webView;
@property (nonatomic) IBOutlet UIView *feedTitleGradient;
@property (nonatomic) IBOutlet UIView *noStoryMessage;
@property (nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;

@property (nonatomic, assign) BOOL pullingScrollview;
@property (nonatomic, assign) BOOL inTextView;
@property (nonatomic, assign) BOOL isRecentlyUnread;
@property (nonatomic) BOOL hasStory;

@property NSInteger pageIndex;
@property (nonatomic) MBProgressHUD *storyHUD;

- (void)initStory;
- (void)hideNoStoryMessage;
- (void)drawStory;
- (void)drawStory:(BOOL)force withOrientation:(UIInterfaceOrientation)orientation;
- (void)drawFeedGradient;
- (void)showStory;
- (void)clearStory;
- (void)hideStory;

- (void)toggleLikeComment:(BOOL)likeComment;
- (void)flashCheckmarkHud:(NSString *)messageType;
- (void)scrolltoComment;
- (void)tryScrollingDown:(BOOL)down;
- (void)scrollPageDown:(id)sender;
- (void)scrollPageUp:(id)sender;
- (void)changeWebViewWidth;
- (void)showUserProfile:(NSString *)userId xCoordinate:(int)x yCoordinate:(int)y width:(int)width height:(int)height;
- (void)checkTryFeedStory;
- (void)setFontStyle:(NSString *)fontStyle;
- (void)changeFontSize:(NSString *)fontSize;
- (void)changeLineSpacing:(NSString *)lineSpacing;
- (void)refreshComments:(NSString *)replyId;

- (void)openShareDialog;
- (void)openTrainingDialog:(int)x yCoordinate:(int)y width:(int)width height:(int)height;
- (void)openUserTagsDialog:(int)x yCoordinate:(int)y width:(int)width height:(int)height;
- (void)subscribeToBlurblog;
- (void)setActiveStoryAtIndex:(NSInteger)activeStoryIndex;
- (NSString *)getHeader;
- (NSString *)getShareBar;
- (NSString *)getComments;
- (NSString *)getComment:(NSDictionary *)commentDict;
- (NSString *)getReplies:(NSArray *)replies forUserId:(NSString *)commentUserId;
- (NSString *)getAvatars:(NSString *)key;
- (void)refreshHeader;
- (void)refreshSideoptions;

- (CGPoint)pointForGesture:(UIGestureRecognizer *)gestureRecognizer;

- (void)showTextOrStoryView;
- (void)showStoryView;
- (void)fetchTextView;

@end


text:
package com.tascape.reactor.webui.comm;

import org.openqa.selenium.By;

/**
 *
 * @author linsongwang
 */
public abstract class AbstractAjax implements Ajax {
    @Override
    public By getByAppear() {
        return null;
    }

    @Override
    public By getByDisapper() {
        return null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
PlayFabCommerce sample for Android
=

This sample uses Android's in-app billing API and PlayFab client API to demonstrate an in-app store that exchanges real money for virtual items in PlayFab Economy.

## Installing the sample

The app can be deployed from Android Studio to a compatible AVD, supporting SDK level 21 or above and using Google Play services (not just Google API). This is because signin with a valid Google account is required. It can also be deployed to any physical Android Device meeting the SDK requirements (5.0/Lollipop).

Due to signing requirements, the deployed app may not successfully launch the real money billing flow, resulting in responseCode 4 for onPurchasesUpdated().

[1]: https://groups.google.com/forum/#!forum/playfabcommerce-test-group
[2]: mailto:atgstore@microsoft.com?subject=Request%20access%20to%20PlayFabCommerce%20Google%20group
[3]: https://play.google.com/apps/testing/atg.xbox.PlayFabCommerce

## Usage
The app uses a virtual currency, **TC**. Each new player starts with a seed amount and you can immediately exchange these for virtual items. These are items in the list with a TC price. Inventory of purchased virtual items will show at the bottom. Selecting the buttons in the inventory will simply decrement the quantity of each.

You can replenish TC by exchanging real money, denoted by the items that have a real currency price. By default, this will use or ask for a valid payment instrument and, if available, it will actually **take your money**. You can to contact ATG Marketplace team to have your account added to the test licensing list or to request tokens.

ATG is not responsible for any charges you make. Refunds will need to go through the Google refund request process (Search "Request a refund for a Google Play purchase").

## Code overview
* `PlayFabAuthManager`: Small sign in layer that handles signing into PlayFab with various platfroms
* `PlayFabCommerceManager`: All PlayFab Commerce operations. This class handles the catalog, player inventory, and calling out to Unity IAP for real money purchases.

## For more information

More information covering how to configure for signin and addons on both Google and PlayFab sides can be found in the accompanying Tutorial doc.


text:
The repository behind https://docs.balsamiq.com - a gohugo.io-powered, S3-hosted website for the Balsamiq documentation.

If you are viewing this repository with the intention of using the theme, please note that you will have to modify the includes, removing our specific assets referenced from balsamiq.com. We use Bootstrap 3, so you can just replace the section of includes under B.COM CSS and B.COM JS in the theme file layouts/partials/header.html. Instead use, for instance the HTML in https://www.bootstrapcdn.com/

# Content
* Add new files to the content/(section name) directory with a .md extensions. Markdown is accepted, and HUGO's [front matter](http://gohugo.io/content/front-matter/) is expected for the navigation to work properly.
* It's recommended that you create new docs using the command line to add the file to the content directory with archetype templates. This inserts and formats the front matter into the article properly, including parent and creation date.
  * $ hugo new mybalsamiq/mypage.md
* To change the order of how articles appear on the Product overviews add a weight to the front matter.
* For help with Markdown, see [this cheatsheet](https://www.markdownguide.org/cheat-sheet/).
* Markdown doesn't allow markdown syntax inside an HTML block element (a \
 or \
, for example), so you can use this "hack" to convert an inline element to a block element using a Bootstrap helper class (".show") (for info and warning alert messages, for example)
	* Info alerts:
	```	{{% alert info %}}**Note:** You can also export a project to PDF from the context menu on the [All Projects (a.k.a. Home) page](/mybalsamiq/home/) in myBalsamiq.{{% /alert %}}```
	* Warning alerts:
	```	{{% alert warning %}}**Note:** You can also export a project to PDF from the context menu on the [All Projects (a.k.a. Home) page](/mybalsamiq/home/) in myBalsamiq.{{% /alert %}}```

# HUGO Usage

## Running Hugo
* Run ./launchHugo.sh (or $ hugo server --watch)
* If page hierarchy has been altered from previous build, remove public/ directory first, then run hugo.
* To build hugo without watch, just run $ hugo
* To use with LiveReload, install the extension for Chrome.
* Open http://localhost:1313 to see your site.

## Running Gulp to rebuild CSS/JS Assets

### Installing Gulp
* Make sure you have gulp installed (https://github.com/gulpjs/gulp/blob/master/docs/getting-started.md). If you don't run this:
  * $ sudo npm install -g gulp
* Or Install gulp in your project devDependencies:
  * $ npm install --save-dev gulp
* Install dev dependencies by running this from terminal in docs.balsamiq.com directory:
  * $ npm install

### Updating Gulp
* To update globally: $ npm update gulp -g
* To update a local instance: cd /your/folder/ then: $ npm update gulp

### Running Gulp Tasks Once
* All Gulp tasks
  * $ gulp
* Just CSS
  * $ gulp sass
* Just JS
  * $ gulp js

### Running Gulp during development (LiveReload)
* If you're working on SASS or JS, run gulp using "watch" to rebuild css/js files as you make changes to them.
  * $ gulp watch dev
* or you can run ./launchGulp.sh
* If you think the balsamiq.com \_config.scss file has changed, you can copy a new version here before running the sass task.
  * $gulp getsassconfig


text:
/* eslint-disable no-unused-vars */
import { observable, computed } from 'mobx';

class OrderLine {
  @observable price = 0;

  @observable amount = 1;

  @computed get total() {
    return this.price * this.amount;
  }
}


text:
import * as Box from "./Box";
import Content from "./Content";
import ContentHeader from "./ContentHeader";
import ContentWrapper from "./ContentWrapper";
import ControlSidebar from "./ControlSidebar";
import * as MainSidebar from "./MainSidebar";
import * as MainHeader from "./MainHeader";
import Wrapper from "./Wrapper";

export {
    Box,
    Content,
    ContentHeader,
    ContentWrapper,
    ControlSidebar,
    MainHeader,
    MainSidebar,
    Wrapper
};


text:
import Constants from "../constants";

function cardReducer(state = {}, action) {
  switch(action.type) {

    case Constants.ACTIONS.GET_CARDS_SUCCESS:
      return Object.assign({}, state, {
        cardList: action.cards
      })

    case Constants.ACTIONS.GET_CARDS_FAILURE:
      return state

    case Constants.ACTIONS.NEW_CARD_FAILURE:
      return state

    case Constants.ACTIONS.NEW_CARD_SUCCESS:
      const updatedCardList = state.cardList;
      updatedCardList.unshift(action.newCard);
      return Object.assign({}, state, {
        cardList: updatedCardList
      })

    case Constants.ACTIONS.SET_CURRENT_CARD:
      const currentCard = state.cardList.filter(function(card) {
        return parseInt(card.id) == parseInt(action.cardId)
      })[0];

      return Object.assign({}, state, {
        currentCard: currentCard
      })

    case Constants.ACTIONS.UPDATE_CURRENT_CARD_SUCCESS:
      const updatedCard = state.currentCard;

      for(let fieldName in action.newAttributes) {
        updatedCard[fieldName] = action.newAttributes[fieldName]
      }

      return Object.assign({}, state, {
        currentCard: updatedCard
      })

    case Constants.ACTIONS.UPDATE_CURRENT_CARD_FAILURE:
      return state

    case Constants.ACTIONS.DELETE_CARD_SUCCESS:
      const updatedList = state.cardList.filter(function(card) {
        return parseInt(card.id) != parseInt(action.cardId);
      })

      return Object.assign({}, state, {
        cardList: updatedList
      })

    case Constants.ACTIONS.DELETE_CARD_FAILURE:
      return state

    default:
      return state
  }
}

export default cardReducer


text:
require "thread"

module LiveAssets

  class SSESubscriber

    def initialize(queue = Queue.new)
      @queue = queue
      LiveAssets.subscribe(@queue)
    end

    def each
      while event = @queue.pop
        yield "event: #{event}\ndata: {}\n\n"
      end
    end

    def close
      LiveAssets.unsubscribe(@queue)
    end
  end
end


text:
namespace mesos {
namespace internal {
namespace slave {

class NamespacesPidIsolatorProcess : public MesosIsolatorProcess
{
public:
  static Try<mesos::slave::Isolator*> create(const Flags& flags);

  virtual ~NamespacesPidIsolatorProcess() {}

  virtual bool supportsNesting();

  virtual process::Future<Option<mesos::slave::ContainerLaunchInfo>> prepare(
      const ContainerID& containerId,
      const mesos::slave::ContainerConfig& containerConfig);

private:
  NamespacesPidIsolatorProcess(const Flags& flags);

  const Flags flags;
};

} // namespace slave {
} // namespace internal {
} // namespace mesos {

#endif // __NAMESPACES_PID_ISOLATOR_HPP__


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Extending Actors</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="Chapter 1. Phoenix 3.0.5">
<link rel="up" href="../examples.html" title="Advanced Examples">
<link rel="prev" href="../examples.html" title="Advanced Examples">
<link rel="next" href="adding_an_expression.html" title="Adding an expression">

Home
Libraries
People
FAQ
More

Extending Actors

        Actors are one of the main parts
        of the library, and one of the many customization points. The default actor
        implementation provides several operator() overloads which deal with the
        evaluation of expressions.

        For some use cases this might not be enough. For convenience it is thinkable
        to provide custom member functions which generate new expressions. An example
        is the if_else_
Statement
        which provides an additional else member for generating a lazy if-else expression.
        With this the actual Phoenix expression becomes more expressive.

        Another scenario is to give actors the semantics of a certain well known
        interface or concept. This tutorial like section will provide information
        on how to implement a custom actor which is usable as if it were a STL Container.

        Requirements

        Let's repeat what we want to have:

<colgroup>
<col>
<col>
</colgroup>

                  Expression

                  Semantics

                  a.begin()

                  Returns an iterator pointing to the first element in the container.

                  a.end()

                  Returns an iterator pointing one past the last element in the container.

                  a.size()

                  Returns the size of the container, that is, its number of elements.

                  a.max_size()

                  Returns the largest size that this container can ever have.

                  a.empty()

                  Equivalent to a.size() == 0. (But possibly faster.)

                  a.swap(b)

                  Equivalent to swap(a,b)

        Additionally, we want all the operator() overloads of the regular actor.

        Defining the
        actor

        The first version of our container_actor
        interface will show the general principle. This will be continually extended.
        For the sake of simplicity, every member function generator will return
        nothing
        at first.

template <typename Expr>
struct container_actor
	: actor<Expr>
{
	typedef actor<Expr> base_type;
	typedef container_actor<Expr> that_type;

	container_actor( base_type const& base )
		: base_type( base ) {}

	expression::null<mpl::void_>::type const begin() const { return nothing; }
	expression::null<mpl::void_>::type const end() const { return nothing; }
	expression::null<mpl::void_>::type const size() const { return nothing; }
	expression::null<mpl::void_>::type const max_size() const { return nothing; }
	expression::null<mpl::void_>::type const empty() const { return nothing; }

	// Note that swap is the only function needing another container.
	template <typename Container>
	expression::null<mpl::void_>::type const swap( actor<Container> const& ) const { return nothing; }
};

        Using
        the actor

        Although the member functions do nothing right now, we want to test if we
        can use our new actor.

        First, lets create a generator which wraps the container_actor
        around any other expression:

template <typename Expr>
container_actor<Expr> const
container( actor<Expr> const& expr )
{
    return expr;
}

        Now let's test this:

std::vector<int> v;
v.push_back(0);
v.push_back(1);
v.push_back(2);
v.push_back(3);

(container(arg1).size())(v);

        Granted, this is not really elegant and not very practical (we could have
        just used phoenix::begin(v) from the Phoenix
        algorithm module, but we can do better.

        Let's have an argument placeholder
        which is usable as if it was a STL container:

container_actor<expression::argument<1>::type> const con1;
// and so on ...

        The above example can be rewritten as:

std::vector<int> v;
v.push_back(0);
v.push_back(1);
v.push_back(2);
v.push_back(3);

(con1.size())(v);

        Wow, that was easy!

        Adding
        life to the actor

        This one will be even easier!

        First, we define a lazy function
        which evaluates the expression we want to implement. Following is the implementation
        of the size function:

struct size_impl
{
	// result_of protocol:
	template <typename Sig>
	struct result;

	template <typename This, typename Container>
	struct result<This(Container)>
	{
		// Note, remove reference here, because Container can be anything
		typedef typename boost::remove_reference<Container>::type container_type;

		// The result will be size_type
		typedef typename container_type::size_type type;
	};

	template <typename Container>
	typename result<size_impl(Container const&)>::type
	operator()(Container const& container) const
	{
		return container.size();
	}
};

        Good, this was the first part. The second part will be to implement the size
        member function of container_actor:

template <typename Expr>
struct container_actor
	: actor<Expr>
{
	typedef actor<Expr> base_type;
	typedef container_actor<Expr> that_type;

	container_actor( base_type const& base )
		: base_type( base ) {}

	typename expression::function<size_impl, that_type>::type const
	size() const
	{
		function<size_impl> const f = size_impl();
		return f(*this);
	}

	// the rest ...
};

        It is left as an exercise to the user to implement the missing parts by reusing
        functions from the Phoenix
        Algorithm Module (the impatient take a look here: container_actor.cpp).

Copyright © 2002-2005, 2010, 2014 Joel de Guzman, Dan Marsden, Thomas Heller, John
      Fletcher

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
if (typeof process !== "undefined") {
    require("amd-loader");
}

define(function(require, exports, module) {
"use strict";

var assert = require("../test/assertions");
var Worker = require("./json_worker").JsonWorker;

module.exports = {
    setUp : function() {
        this.sender = {
            on: function() {},
            callback: function(data, id) {
                this.data = data;
            },
            events: [],
            emit: function(type, e) {
                this.events.push([type, e]);
            }
        };
    },

    "test check valid json": function() {
        var worker = new Worker(this.sender);
        worker.setValue("{}");
        worker.deferredUpdate.call();

        assert.equal(this.sender.events[0][0], "ok");
    },

    "test check for syntax error": function() {
        var worker = new Worker(this.sender);
        worker.setValue([
            "{",
            "juhu: 12",
            "}"
        ].join("\n"));
        worker.deferredUpdate.call();

        var event = this.sender.events[0];
        assert.equal(event[0], "error");
        assert.equal(event[1].type, "error");
        assert.equal(event[1].text, "Bad string");
        assert.equal(event[1].row, 1);
        assert.equal(event[1].column, 0);

    },

    "test check for syntax error at first char": function() {
        var worker = new Worker(this.sender);
        worker.setValue("x");
        worker.deferredUpdate.call();

        var event = this.sender.events[0];
        assert.equal(event[0], "error");
        assert.equal(event[1].type, "error");
        assert.equal(event[1].text, "Unexpected 'x'");
        assert.equal(event[1].row, 0);
        assert.equal(event[1].column, 0);
    }

};

});

if (typeof module !== "undefined" && module === require.main) {
    require("asyncjs").test.testcase(module.exports).exec();
}


text:
package org.panthercode.arctic.core.resources;

import org.panthercode.arctic.core.arguments.ArgumentUtils;
import org.panthercode.arctic.core.helper.identity.IdentityInfo;
import org.panthercode.arctic.core.helper.priority.Priority;
import org.panthercode.arctic.core.helper.priority.Semaphore;
import org.panthercode.arctic.core.helper.version.VersionInfo;
import org.panthercode.arctic.core.reflect.ClassBuilder;
import org.panthercode.arctic.core.resources.impl.ResourceImpl;
import org.panthercode.arctic.core.settings.Configuration;

import java.lang.reflect.InvocationTargetException;

/**
 * TODO: documentation
 *
 * @author PantherCode
 */
public class ResourceFactory {

    public static String CAPACITY_KEY = "capacity";

    public static String PRIORITY_KEY = "priority";

    /**
     *
     */
    private ResourceFactory() {
    }

    public static <T extends AbstractResource> Resource create(Class<T> clazz)
            throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        return ResourceFactory.create(clazz, null);
    }

    public static <T extends AbstractResource> Resource create(Class<T> clazz, Configuration configuration)
            throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, ClassCastException {
        ArgumentUtils.assertNotNull(clazz, "class");

        if (!clazz.isAnnotationPresent(IdentityInfo.class)) {
            throw new IllegalArgumentException("The resource class has no IdentityInfo annotation");
        }

        if (!clazz.isAnnotationPresent(VersionInfo.class)) {
            throw new IllegalArgumentException("The resource class has no VersionInfo annotation");
        }

        configuration = configuration == null ? new Configuration() : configuration;

        Priority priority = configuration.containsKey(PRIORITY_KEY) ? (Priority) configuration.get(PRIORITY_KEY) : Priority.NORMAL;

        int capacity = configuration.containsKey(CAPACITY_KEY) ? (int) configuration.get(CAPACITY_KEY) : 1;

        AbstractResource abstractResource = ClassBuilder.create(AbstractResource.class).build();

        return new ResourceImpl(abstractResource, new Semaphore(capacity), priority, configuration);
    }
}


text: Remember names from address book


text:
#include "dag_config.h"
#include "../include/modules/generic_read_write.h"
#include "../include/util/utility.h"
#include "../include/modules/raw_smbus_module.h"
#include "../include/modules/latch.h"

#include "dagutil.h"
#include "dagreg.h"

/*Randomly choosen number*/
#define LATCH_MAGIC 0xFAC7D63D

struct LatchObject
{
   	/* Standard protection. */
	uint32_t mMagicNumber;
	uint32_t mChecksum;

    /* Every member from here onwards is checksummed */
    uint32_t mAddress;
    DagCardPtr mCard;
    uint32_t mMask;
    GenericReadWritePtr mGRW;
};

/* Implementation of internal routines. */
static uint32_t
compute_latch_checksum(LatchPtr latch)
{
	/* Don't check validity here with valid_attribute() because the attribute may not be fully constructed. */
    if (latch != NULL)
    {
	    return compute_checksum(&latch->mAddress, sizeof(*latch) - 2 * sizeof(uint32_t));
    }
    return 0;
}

static int
valid_latch(LatchPtr latch)
{
    uint32_t checksum;

	assert(latch);
	assert(LATCH_MAGIC == latch->mMagicNumber);

	checksum = compute_latch_checksum(latch);
	assert(checksum == latch->mChecksum);

	if ((NULL != latch) && (LATCH_MAGIC == latch->mMagicNumber) && (checksum == latch->mChecksum))
	{
		return 1;
	}

	return 0;
}

LatchPtr
latch_init(DagCardPtr card, uint32_t address, uint32_t mask)
{
    LatchPtr result = malloc(sizeof(*result));
    memset(result, 0, sizeof(*result));
    result->mMagicNumber = LATCH_MAGIC;
    result->mAddress = address;
    result->mCard = card;
    result->mMask = mask;
    result->mGRW = grw_init(card, address, grw_iom_read, grw_iom_write);
    result->mChecksum = compute_latch_checksum(result);
    (void)valid_latch(result);
    return result;
}

void
latch_dispose(LatchPtr latch)
{
    if (1 == valid_latch(latch))
    {
        grw_dispose(latch->mGRW);
    }
}

void
latch_set(LatchPtr latch)
{
    if (1 == valid_latch(latch))
    {
        uint32_t reg_val = grw_read(latch->mGRW);
        reg_val |= latch->mMask;
        grw_write(latch->mGRW, reg_val);
    }
}

void
latch_clear(LatchPtr latch)
{
    if (1 == valid_latch(latch))
    {
        uint32_t reg_val = grw_read(latch->mGRW);
        reg_val &= ~latch->mMask;
        grw_write(latch->mGRW, reg_val);
    }
}


text:
{% extends "base.html" %}

{% block title %} Register {% endblock %}

{% block content %}
    <form action="" method="post" class="form-default" style="text-align:left">{% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="註冊" class="btn btn-default">
    </form>
{% endblock %}


text:
> All the resources you could never imagine.

![](http://i3.kym-cdn.com/photos/images/original/000/187/320/6a1.png)

---

![](http://www.linickx.com/files/2011/08/octocat_darkwood_small.jpg)

## [Awesome](https://github.com/sindresorhus/awesome) and [Awesome Awesomeness](https://github.com/bayandin/awesome-awesomeness)

> A curated list of awesome lists.

---

![](https://www.bento.io/static/img/twitter_card_2.png)

## [Bento](https://www.bento.io/)

> There are so many ways to learn to code. Let Bento guide you through the best ones.

> You want to learn how to code, but it's hard to know where to start. There are so many resources on the web that it's difficult to cut through the noise. Bento picks the best free tutorials and tells what you need to learn in what order.

---

![](https://huacm.files.wordpress.com/2015/04/classcentral.png)

## [Class Central](https://www.class-central.com/)

> Class Central is a free online course aka MOOC aggregator from top universities like Stanford, MIT, Harvard, etc. offered via Coursera, Udacity, edX, NovoED, ...

---

![](http://cdn.geekwire.com/wp-content/uploads/codementor-logo-2.png)

## [Codementor's Learning Center](https://www.codementor.io/learn)

> Learn how to code, through Codementor's Learning Center. Whether you're trying to master new programming languages, learn web design, or just trying to become a better developer in general, you can find tutorials, help videos, training guides, and expert tips from experienced developers at Codementor's Learning Center.

---

![](https://huacm.files.wordpress.com/2015/03/freebie-supply.png)

## [Freebie Supply](http://freebie.supply/)

> Awesome free things for entrepreneurs and startups.

---

![](http://www.google.com/about/careers/files/home.jpg)

## [Guide for Technical Development](https://www.google.com/about/careers/students/guide-to-technical-development.html) from Google Careers

> This guide is a suggested path for University students to develop their technical skills academically and non-academically through self paced hands-on learning.

---

![](https://huacm.files.wordpress.com/2015/03/no-excuse-list.png)

## [No Excuse List](http://noexcuselist.com/)

> No Excuse List is the best place on the web to learn anything, free. We have curated the best resources on the web to teach you anything that you want.

---

![](http://airpair-blog.s3.amazonaws.com/wp-content/uploads/2014/04/The-Odin-Project-Open-Sourced-Free-Curriculum.png)

## [Odin Project](http://www.theodinproject.com/home)

> The Odin Project is one of those "What I wish I had when I was learning" resources. Not everyone has access to a computer science education or the funds to attend an intensive coding school and neither of those is right for everyone anyway.

> This project is designed to fill in the gap for people who are trying to hack it on their own but still want a high quality education.

---

![](https://huacm.files.wordpress.com/2015/04/oozled.png)

![](https://huacm.files.wordpress.com/2015/04/oozled-categories.png)

## [Oozled](http://oozled.com/)

> Curated resources for everything creative.

---

![](https://huacm.files.wordpress.com/2015/03/skilledup.png)

## [SkilledUp](http://www.skilledup.com/)

> SkilledUp was built to help you find online courses, gain and increase your skills and prove your worth to employers.

---

![](https://huacm.files.wordpress.com/2015/04/startup-stash.png)

## [Startup Stash](http://startupstash.com)

> A curated directory of resources & tools to help you build your Startup.

---

![](https://huacm.files.wordpress.com/2015/03/thinkful.png)

## [Thinkful Learn](http://www.thinkful.com/learn)

> Thinkful has provided many programming and design tutorials in topics such as, Javascript & jQuery, Ruby & Python, Data Science, HTML & CSS, GitHub, and Design.
>
> They're interactive and you can tell that time was really dedicated towards making each and every tutorial.

**Examples of tutorials offered**

- [Programming Fundamentals in Python](http://www.thinkful.com/learn/intro-to-python-tutorial/)
- [Getting Started with HTML5](http://www.thinkful.com/learn/getting-started-with-html5)
- [Javascript Best Practices Part 1](http://www.thinkful.com/learn/javascript-best-practices-1/)
- [AngularJS Tutorial](http://www.thinkful.com/learn/angularjs-tutorial-build-a-gmail-clone/)
- [Ruby on Rails Tutorial](http://www.thinkful.com/learn/ruby-on-rails-tutorial/)


text:
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.android.desugar.io;

import com.google.devtools.build.android.desugar.langmodel.ClassName;
import com.google.devtools.build.android.desugar.langmodel.TypeMapper;
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.Nullable;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.ClassRemapper;
import org.objectweb.asm.commons.Remapper;

/** Utility class to prefix or unprefix class names of core library classes */
public class CoreLibraryRewriter {

  private final String prefix;
  private final TypeMapper prefixer;

  public CoreLibraryRewriter(String prefix) {
    this.prefix = prefix;
    this.prefixer = new TypeMapper(this::prefix);
  }

  /**
   * Factory method that returns either a normal ClassReader if prefix is empty, or a ClassReader
   * with a ClassRemapper that prefixes class names of core library classes if prefix is not empty.
   */
  public ClassReader reader(InputStream content) throws IOException {
    if (prefix.isEmpty()) {
      return new ClassReader(content);
    } else {
      return new PrefixingClassReader(content, prefixer);
    }
  }

  /**
   * Factory method that returns a ClassVisitor that delegates to a ClassWriter, removing prefix
   * from core library class names if it is not empty.
   */
  public UnprefixingClassWriter writer(int flags) {
    return new UnprefixingClassWriter(flags);
  }

  static boolean shouldPrefix(String typeName) {
    return (typeName.startsWith("java/")
            || typeName.startsWith("sun/")
            || typeName.startsWith("javadesugar/") // Testing-only fake package prefix.
        )
        && !except(typeName);
  }

  private static boolean except(String typeName) {
    if (typeName.startsWith("java/lang/invoke/")) {
      return true;
    }

    switch (typeName) {
        // Autoboxed types
      case "java/lang/Boolean":
      case "java/lang/Byte":
      case "java/lang/Character":
      case "java/lang/Double":
      case "java/lang/Float":
      case "java/lang/Integer":
      case "java/lang/Long":
      case "java/lang/Number":
      case "java/lang/Short":

        // Special types
      case "java/lang/Class":
      case "java/lang/Object":
      case "java/lang/String":
      case "java/lang/Throwable":
        return true;

      default: // fall out
    }

    return false;
  }

  public String getPrefix() {
    return prefix;
  }

  public TypeMapper getPrefixer() {
    return prefixer;
  }

  private ClassName prefix(ClassName className) {
    if (shouldPrefix(className.binaryName())) {
      return className.withPackagePrefix(prefix);
    }
    return className;
  }

  /** Removes prefix from class names */
  public String unprefix(String typeName) {
    if (prefix.isEmpty() || !typeName.startsWith(prefix)) {
      return typeName;
    }
    return typeName.substring(prefix.length());
  }

  /** ClassReader that prefixes core library class names as they are read */
  private static class PrefixingClassReader extends ClassReader {

    private final TypeMapper prefixer;

    PrefixingClassReader(InputStream content, TypeMapper prefixer) throws IOException {
      super(content);
      this.prefixer = prefixer;
    }

    @Override
    public void accept(ClassVisitor cv, Attribute[] attrs, int flags) {
      cv = new ClassRemapper(cv, prefixer);
      super.accept(cv, attrs, flags);
    }

    @Override
    public String getClassName() {
      return prefixer.map(super.getClassName());
    }

    @Override
    public String getSuperName() {
      String result = super.getSuperName();
      return result != null ? prefixer.map(result) : null;
    }

    @Override
    public String[] getInterfaces() {
      String[] result = super.getInterfaces();
      for (int i = 0, len = result.length; i < len; ++i) {
        result[i] = prefixer.map(result[i]);
      }
      return result;
    }
  }

  /**
   * ClassVisitor that delegates to a ClassWriter, but removes a prefix as each class is written.
   * The unprefixing is optimized out if prefix is empty.
   */
  public class UnprefixingClassWriter extends ClassVisitor {
    private final ClassWriter writer;

    private String finalClassName;

    UnprefixingClassWriter(int flags) {
      super(Opcodes.ASM7);
      this.writer = new ClassWriter(flags);
      this.cv = this.writer;
      if (!prefix.isEmpty()) {
        this.cv =
            new ClassRemapper(
                this.writer,
                new Remapper() {
                  @Override
                  public String map(String typeName) {
                    return unprefix(typeName);
                  }
                });
      }
    }

    /** Returns the (unprefixed) name of the class once written. */
    @Nullable
    public String getClassName() {
      return finalClassName;
    }

    public byte[] toByteArray() {
      return writer.toByteArray();
    }

    @Override
    public void visit(
        int version,
        int access,
        String name,
        String signature,
        String superName,
        String[] interfaces) {
      finalClassName = unprefix(name);
      super.visit(version, access, name, signature, superName, interfaces);
    }
  }
}


text:
package com.example.helloworld;

import com.example.helloworld.core.Template;
import com.yammer.dropwizard.config.Configuration;
import com.yammer.dropwizard.db.DatabaseConfiguration;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

public class HelloWorldConfiguration extends Configuration {
    @NotEmpty
    private String template;

    @NotEmpty
    private String defaultName = "Stranger";

    @Valid
    @NotNull
    @JsonProperty("database")
    private DatabaseConfiguration databaseConfiguration = new DatabaseConfiguration();

    public String getTemplate() {
        return template;
    }

    public void setTemplate(String template) {
        this.template = template;
    }

    public String getDefaultName() {
        return defaultName;
    }

    public void setDefaultName(String defaultName) {
        this.defaultName = defaultName;
    }

    public Template buildTemplate() {
        return new Template(template, defaultName);
    }

    public DatabaseConfiguration getDatabaseConfiguration() {
        return databaseConfiguration;
    }

    public void setDatabaseConfiguration(DatabaseConfiguration databaseConfiguration) {
        this.databaseConfiguration = databaseConfiguration;
    }
}


text:
var fs = require('fs');
var querystring = require('querystring');

function App(addr, name, url, protocols) {
	this.addr = addr;
    this.config = {
    	name: name,
    	state: "stopped",
    	link: "",
    	connectionSvcURL: "",
    	protocols: ["ramp"],
    	app_url: "",
    	url: url
    }

	if(Array.isArray(protocols) ) {
		for(var i = 0; i < protocols.length; i++) {
			this.config.protocols.push(protocols[i]);
		}
	}

    this.receivers = [];
    this.remotes = [];
    this.messageQueue = [];
}

App.prototype.getName = function() {
	return this.config.name;
}

App.prototype.registerSession = function(connection) {
	var me = this;
	connection.on('message', function(message) {
		//if(message.utf8Data.indexOf('ping') != -1) {
		//	connection.send(message.utf8Data.replace('ping', 'pong'));
		//} else {
			if(me.receivers.length == 0) {
				console.log("buffering msg for receiver");
				me.messageQueue.push(message.utf8Data);
			} else {
				console.log("relaying msg to receiver");
				me.receivers[0].send(message.utf8Data);
			}

		if(message.utf8Data.indexOf('ping') == -1 && message.utf8Data.indexOf('pong') == -1) {
			console.log("-->to receiver: "+ message.utf8Data);
		}
		//}
	});

	connection.on('close', function(closeReason, description) {
		var i = me.remotes.indexOf(connection);
		me.remotes.splice(i,1);
		console.log("Closed SessionChannel");
	});

	console.log("Opened SessionChannel");
	this.remotes.push(connection);
}

App.prototype.registerReceiver = function(connection) {

	var me = this;
	connection.on('message', function(message) {
		//if(message.utf8Data.indexOf('ping') != -1) {
		//	connection.send(message.utf8Data.replace('ping', 'pong'));
		//} else {
			if(me.remotes.length > 0)
				me.remotes[0].send(message.utf8Data);
		//}

		if(message.utf8Data.indexOf('ping') == -1 && message.utf8Data.indexOf('pong') == -1) {
			console.log("-->to remote: "+ message.utf8Data);
		}
	});

	connection.on('close', function(closeReason, description) {
		var i = me.receivers.indexOf(connection);
		me.receivers.splice(i,1);
		console.log("Closed ReceiverChannel");
	});

	console.log("Opened ReceiverChannel");
	this.receivers.push(connection);

	while(me.messageQueue.length > 0) {
		connection.send(me.messageQueue.shift());
	}
}

App.prototype.getProtocols = function() {
	var p = "";

	if(this.config.state == "running") {
		for(var i = 0; i < this.config.protocols.length; i++) {
			p += "<protocol>"+this.config.protocols[i]+"</protocol>";
		}
	}

	return p;
}

App.prototype.registerApi = function(app) {
	var me = this;
	app.get("/apps/"+me.config.name, function(req, res) {
		fs.readFile('./app.xml', 'utf8', function (err,data) {
			data = data.replace("#name#", me.config.name)
				.replace("#connectionSvcURL#",me.config.connectionSvcURL)
				.replace('#protocols#',me.getProtocols())
				.replace('#state#', me.config.state)
				.replace('#link#', me.config.link);
			res.type('xml');
			res.setHeader("Access-Control-Allow-Method", "GET, POST, DELETE, OPTIONS");
			res.setHeader("Access-Control-Expose-Headers", "Location");
			res.setHeader("Cache-control", "no-cache, must-revalidate, no-store");
			res.send(data);
		});
	});

	app.delete("/apps/"+me.config.name+"/web-1", function(req, res) {
		me.config.state = "stopped";
		me.config.link = "";
		me.config.connectionSvcURL = "";

		fs.readFile('./app.xml', 'utf8', function (err,data) {

			if(global.stageConnection)
				global.stageConnection.send(JSON.stringify({
					cmd: "close",
					app: me.config.name
				}))

			data = data.replace("#name#", me.config.name)
				.replace("#connectionSvcURL#",me.config.connectionSvcURL)
				.replace('#protocols#',me.getProtocols())
				.replace('#state#', me.config.state)
				.replace('#link#', me.config.link);
			res.type('xml');
			res.setHeader("Access-Control-Allow-Method", "GET, POST, DELETE, OPTIONS");
			res.setHeader("Access-Control-Expose-Headers", "Location");
			res.setHeader("Cache-control", "no-cache, must-revalidate, no-store");
			res.send(data);
		});
	});

	app.post("/apps/"+me.config.name, function(req, res) {
		me.config.state = "running";
		me.config.link = "<link rel='run' href='web-1'/>";
		me.config.connectionSvcURL = "http://"+me.addr+":8008/connection/"+me.config.name

		if(global.stageConnection)
			global.stageConnection.send(JSON.stringify({
				cmd: "show",
				app: me.config.name,
				url:  me.config.url.replace('$query',req.rawBody)
			}))

		res.setHeader("Location", "http://"+me.addr+":8008/apps/"+me.config.name+"/web-1");
		res.send(201,"");
	});
}

module.exports = App;


text:
#pragma once
#include <aws/migrationhuborchestrator/MigrationHubOrchestrator_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/migrationhuborchestrator/model/StepGroupStatus.h>
#include <aws/core/utils/DateTime.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/migrationhuborchestrator/model/Tool.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace MigrationHubOrchestrator
{
namespace Model
{
  class AWS_MIGRATIONHUBORCHESTRATOR_API GetTemplateStepGroupResult
  {
  public:
    GetTemplateStepGroupResult();
    GetTemplateStepGroupResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    GetTemplateStepGroupResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
The ID of the template.

     */
    inline const Aws::String& GetTemplateId() const{ return m_templateId; }

    /**
     *
The ID of the template.

     */
    inline void SetTemplateId(const Aws::String& value) { m_templateId = value; }

    /**
     *
The ID of the template.

     */
    inline void SetTemplateId(Aws::String&& value) { m_templateId = std::move(value); }

    /**
     *
The ID of the template.

     */
    inline void SetTemplateId(const char* value) { m_templateId.assign(value); }

    /**
     *
The ID of the template.

     */
    inline GetTemplateStepGroupResult& WithTemplateId(const Aws::String& value) { SetTemplateId(value); return *this;}

    /**
     *
The ID of the template.

     */
    inline GetTemplateStepGroupResult& WithTemplateId(Aws::String&& value) { SetTemplateId(std::move(value)); return *this;}

    /**
     *
The ID of the template.

     */
    inline GetTemplateStepGroupResult& WithTemplateId(const char* value) { SetTemplateId(value); return *this;}

    /**
     *
The ID of the step group.

     */
    inline const Aws::String& GetId() const{ return m_id; }

    /**
     *
The ID of the step group.

     */
    inline void SetId(const Aws::String& value) { m_id = value; }

    /**
     *
The ID of the step group.

     */
    inline void SetId(Aws::String&& value) { m_id = std::move(value); }

    /**
     *
The ID of the step group.

     */
    inline void SetId(const char* value) { m_id.assign(value); }

    /**
     *
The ID of the step group.

     */
    inline GetTemplateStepGroupResult& WithId(const Aws::String& value) { SetId(value); return *this;}

    /**
     *
The ID of the step group.

     */
    inline GetTemplateStepGroupResult& WithId(Aws::String&& value) { SetId(std::move(value)); return *this;}

    /**
     *
The ID of the step group.

     */
    inline GetTemplateStepGroupResult& WithId(const char* value) { SetId(value); return *this;}

    /**
     *
The name of the step group.

     */
    inline const Aws::String& GetName() const{ return m_name; }

    /**
     *
The name of the step group.

     */
    inline void SetName(const Aws::String& value) { m_name = value; }

    /**
     *
The name of the step group.

     */
    inline void SetName(Aws::String&& value) { m_name = std::move(value); }

    /**
     *
The name of the step group.

     */
    inline void SetName(const char* value) { m_name.assign(value); }

    /**
     *
The name of the step group.

     */
    inline GetTemplateStepGroupResult& WithName(const Aws::String& value) { SetName(value); return *this;}

    /**
     *
The name of the step group.

     */
    inline GetTemplateStepGroupResult& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}

    /**
     *
The name of the step group.

     */
    inline GetTemplateStepGroupResult& WithName(const char* value) { SetName(value); return *this;}

    /**
     *
The description of the step group.

     */
    inline const Aws::String& GetDescription() const{ return m_description; }

    /**
     *
The description of the step group.

     */
    inline void SetDescription(const Aws::String& value) { m_description = value; }

    /**
     *
The description of the step group.

     */
    inline void SetDescription(Aws::String&& value) { m_description = std::move(value); }

    /**
     *
The description of the step group.

     */
    inline void SetDescription(const char* value) { m_description.assign(value); }

    /**
     *
The description of the step group.

     */
    inline GetTemplateStepGroupResult& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}

    /**
     *
The description of the step group.

     */
    inline GetTemplateStepGroupResult& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}

    /**
     *
The description of the step group.

     */
    inline GetTemplateStepGroupResult& WithDescription(const char* value) { SetDescription(value); return *this;}

    /**
     *
The status of the step group.

     */
    inline const StepGroupStatus& GetStatus() const{ return m_status; }

    /**
     *
The status of the step group.

     */
    inline void SetStatus(const StepGroupStatus& value) { m_status = value; }

    /**
     *
The status of the step group.

     */
    inline void SetStatus(StepGroupStatus&& value) { m_status = std::move(value); }

    /**
     *
The status of the step group.

     */
    inline GetTemplateStepGroupResult& WithStatus(const StepGroupStatus& value) { SetStatus(value); return *this;}

    /**
     *
The status of the step group.

     */
    inline GetTemplateStepGroupResult& WithStatus(StepGroupStatus&& value) { SetStatus(std::move(value)); return *this;}

    /**
     *
The time at which the step group was created.

     */
    inline const Aws::Utils::DateTime& GetCreationTime() const{ return m_creationTime; }

    /**
     *
The time at which the step group was created.

     */
    inline void SetCreationTime(const Aws::Utils::DateTime& value) { m_creationTime = value; }

    /**
     *
The time at which the step group was created.

     */
    inline void SetCreationTime(Aws::Utils::DateTime&& value) { m_creationTime = std::move(value); }

    /**
     *
The time at which the step group was created.

     */
    inline GetTemplateStepGroupResult& WithCreationTime(const Aws::Utils::DateTime& value) { SetCreationTime(value); return *this;}

    /**
     *
The time at which the step group was created.

     */
    inline GetTemplateStepGroupResult& WithCreationTime(Aws::Utils::DateTime&& value) { SetCreationTime(std::move(value)); return *this;}

    /**
     *
The time at which the step group was last modified.

     */
    inline const Aws::Utils::DateTime& GetLastModifiedTime() const{ return m_lastModifiedTime; }

    /**
     *
The time at which the step group was last modified.

     */
    inline void SetLastModifiedTime(const Aws::Utils::DateTime& value) { m_lastModifiedTime = value; }

    /**
     *
The time at which the step group was last modified.

     */
    inline void SetLastModifiedTime(Aws::Utils::DateTime&& value) { m_lastModifiedTime = std::move(value); }

    /**
     *
The time at which the step group was last modified.

     */
    inline GetTemplateStepGroupResult& WithLastModifiedTime(const Aws::Utils::DateTime& value) { SetLastModifiedTime(value); return *this;}

    /**
     *
The time at which the step group was last modified.

     */
    inline GetTemplateStepGroupResult& WithLastModifiedTime(Aws::Utils::DateTime&& value) { SetLastModifiedTime(std::move(value)); return *this;}

    /**
     *
List of AWS services utilized in a migration workflow.

     */
    inline const Aws::Vector<Tool>& GetTools() const{ return m_tools; }

    /**
     *
List of AWS services utilized in a migration workflow.

     */
    inline void SetTools(const Aws::Vector<Tool>& value) { m_tools = value; }

    /**
     *
List of AWS services utilized in a migration workflow.

     */
    inline void SetTools(Aws::Vector<Tool>&& value) { m_tools = std::move(value); }

    /**
     *
List of AWS services utilized in a migration workflow.

     */
    inline GetTemplateStepGroupResult& WithTools(const Aws::Vector<Tool>& value) { SetTools(value); return *this;}

    /**
     *
List of AWS services utilized in a migration workflow.

     */
    inline GetTemplateStepGroupResult& WithTools(Aws::Vector<Tool>&& value) { SetTools(std::move(value)); return *this;}

    /**
     *
List of AWS services utilized in a migration workflow.

     */
    inline GetTemplateStepGroupResult& AddTools(const Tool& value) { m_tools.push_back(value); return *this; }

    /**
     *
List of AWS services utilized in a migration workflow.

     */
    inline GetTemplateStepGroupResult& AddTools(Tool&& value) { m_tools.push_back(std::move(value)); return *this; }

    /**
     *
The previous step group.

     */
    inline const Aws::Vector<Aws::String>& GetPrevious() const{ return m_previous; }

    /**
     *
The previous step group.

     */
    inline void SetPrevious(const Aws::Vector<Aws::String>& value) { m_previous = value; }

    /**
     *
The previous step group.

     */
    inline void SetPrevious(Aws::Vector<Aws::String>&& value) { m_previous = std::move(value); }

    /**
     *
The previous step group.

     */
    inline GetTemplateStepGroupResult& WithPrevious(const Aws::Vector<Aws::String>& value) { SetPrevious(value); return *this;}

    /**
     *
The previous step group.

     */
    inline GetTemplateStepGroupResult& WithPrevious(Aws::Vector<Aws::String>&& value) { SetPrevious(std::move(value)); return *this;}

    /**
     *
The previous step group.

     */
    inline GetTemplateStepGroupResult& AddPrevious(const Aws::String& value) { m_previous.push_back(value); return *this; }

    /**
     *
The previous step group.

     */
    inline GetTemplateStepGroupResult& AddPrevious(Aws::String&& value) { m_previous.push_back(std::move(value)); return *this; }

    /**
     *
The previous step group.

     */
    inline GetTemplateStepGroupResult& AddPrevious(const char* value) { m_previous.push_back(value); return *this; }

    /**
     *
The next step group.

     */
    inline const Aws::Vector<Aws::String>& GetNext() const{ return m_next; }

    /**
     *
The next step group.

     */
    inline void SetNext(const Aws::Vector<Aws::String>& value) { m_next = value; }

    /**
     *
The next step group.

     */
    inline void SetNext(Aws::Vector<Aws::String>&& value) { m_next = std::move(value); }

    /**
     *
The next step group.

     */
    inline GetTemplateStepGroupResult& WithNext(const Aws::Vector<Aws::String>& value) { SetNext(value); return *this;}

    /**
     *
The next step group.

     */
    inline GetTemplateStepGroupResult& WithNext(Aws::Vector<Aws::String>&& value) { SetNext(std::move(value)); return *this;}

    /**
     *
The next step group.

     */
    inline GetTemplateStepGroupResult& AddNext(const Aws::String& value) { m_next.push_back(value); return *this; }

    /**
     *
The next step group.

     */
    inline GetTemplateStepGroupResult& AddNext(Aws::String&& value) { m_next.push_back(std::move(value)); return *this; }

    /**
     *
The next step group.

     */
    inline GetTemplateStepGroupResult& AddNext(const char* value) { m_next.push_back(value); return *this; }

  private:

    Aws::String m_templateId;

    Aws::String m_id;

    Aws::String m_name;

    Aws::String m_description;

    StepGroupStatus m_status;

    Aws::Utils::DateTime m_creationTime;

    Aws::Utils::DateTime m_lastModifiedTime;

    Aws::Vector<Tool> m_tools;

    Aws::Vector<Aws::String> m_previous;

    Aws::Vector<Aws::String> m_next;
  };

} // namespace Model
} // namespace MigrationHubOrchestrator
} // namespace Aws


text:
morpheus.DatasetSeriesView = function (dataset, seriesIndices) {
  morpheus.DatasetAdapter.call(this, dataset);
  this.seriesIndices = seriesIndices;
};
morpheus.DatasetSeriesView.prototype = {
  getValue: function (i, j, seriesIndex) {
    seriesIndex = seriesIndex || 0;
    return this.dataset.getValue(i, j, this.seriesIndices[seriesIndex]);
  },
  setValue: function (i, j, value, seriesIndex) {
    seriesIndex = seriesIndex || 0;
    this.dataset.setValue(i, j, value, this.seriesIndices[seriesIndex]);
  },
  getName: function (seriesIndex) {
    seriesIndex = seriesIndex || 0;
    return this.dataset.getName(this.seriesIndices[seriesIndex]);
  },
  setName: function (seriesIndex, name) {
    seriesIndex = seriesIndex || 0;
    this.dataset.setName(this.seriesIndices[seriesIndex], name);
  },
  addSeries: function (options) {
    var index = this.dataset.addSeries(options);
    this.seriesIndices.push(index);
    return index;
  },
  getSeriesCount: function () {
    return this.seriesIndices.length;
  },
  toString: function () {
    return this.getName();
  }
};
morpheus.Util.extend(morpheus.DatasetSeriesView, morpheus.DatasetAdapter);


text:
import java.util.Scanner;

public class ReverseCharacters {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        char firstChar = sc.nextLine().charAt(0);
        char secondChar = sc.nextLine().charAt(0);
        char thirdChar = sc.nextLine().charAt(0);

        System.out.printf("%c%c%c",thirdChar, secondChar, firstChar);
    }
}


text:
using System;
using System.Collections.Generic;

namespace CChessCore.Pieces
{
    public class Bishop : IPiece
    {
        private readonly Square[] _validDirections = new Square[] { new Square(1, 1), new Square(1, -1), new Square(-1, -1), new Square(-1, 1)};

        public PieceColor Color { get; private set; }
        public PieceType Type { get { return PieceType.Bishop; } }

        /// <summary>
        /// Abbreviation used in FEN notation.
        /// </summary>
        public string FenAbbreviation
        {
            get { return Color == PieceColor.White ? Type.PgnCode : Type.PgnCode.ToLower(); }
        }

        public Bishop(PieceColor color)
        {
            Color = color;
        }

        public bool CanMove(IGame game, IGameBoard board, Move move)
        {
            if (move.To.Equals(move.From))
                return false;

            int lengthX = move.To.X - move.From.X;
            int lengthY = move.To.Y - move.From.Y;
            if (Math.Abs(lengthX) != Math.Abs(lengthY))
            {
                return false;
            }

            Square direction = new Square(lengthX > 0 ? 1 : -1, lengthY > 0 ? 1 : -1);

            Square temp = move.From + direction;
            while (temp != null && !temp.Equals(move.To))
            {
                if (board[temp] != null)
                {
                    return false;
                }

                temp = temp + direction;
            }

            var captured = board[move.To];
            if (captured != null)
            {
                if (captured.Color == Color)
                {
                    return false;
                }
            }

            return true;
        }

        public IEnumerable<Move> GetValidMoves(IGame game, IGameBoard board, Square square)
        {
            var result = new List<Move>();
            if(board[square].Type != PieceType.Bishop)
            {
                return result;
            }

            foreach (var direction in _validDirections)
            {
                Square moveTo = square + direction;

                while (moveTo != null)
                {
                    Move move = new Move(square, moveTo);
                    if (CanMove(game, board, move))
                    {
                        result.Add(move);
                    }

                    if (board[moveTo] != null)
                    {
                        break;
                    }

                    moveTo = moveTo + direction;
                }
            }

            return result;
        }
    }
}


text:
# proyecto_juegos_en_red

## Nombre del juego:
	PANG

## Descripción del juego:
	El objetivo del juego es explotar unas bolas que se mueven por la pantalla.
	Los personajes cuentan con armas de fuego para ir rompiendo las bolas.
	Por cada impacto de un disparo en una de estas bolas, estas se dividen en dos bolas más pequeñas.
	Cuando las bolas adquieren un determinado tamaño, dejan de dividirse y desaparecen.
	El objetivo principal del juego es acabar con las bolas sin que estas toquen a los personajes.
	Si una bola toca un personaje, este perderá una vida.
	Nuestra idea es implementar el juego como un multijugador con puntuaciones, vidas, potenciadores y modificadores de armas.

	Video referencia: https://www.youtube.com/watch?v=rlsx9yrr2-w

 ## Demostración:
 https://youtu.be/RF21_ai4pIk

## Integrantes del grupo:
    - Alberto Blanco Barrios, a.blancoba@alumnos.urjc.es, github: alber0905
    - Jesús Téllez Serrano, j.tellezs@alumnos.urjc.es, github: jetese
    - Eva María Pérez Fernández, em.perezfe@alumnos.urjc.es, github: leeavemeal0ne

## Trello
    https://trello.com/b/yFTcqMEk/juegos-en-red

## Sprites
https://www.spriters-resource.com/arcade/superpang/

## Pantallas

### Menú principal

Es un menú en el que se puede seleccionar si jugar de forma local, buscar una sala o ver la tabla de puntuaciones.
Está implementada con una página HTML, ayudado con estilos de css y bootstrap.
![alt text](/pang_online/screenshots/menuprincipal.png)

### Pantalla buscar sala
Aquí es donde un jugador podrá crear una partida online, o unirse a la de otro (ahora mismo no hacen nada los botones).
![alt text](/pang_online/screenshots/seleccionsala.png)

### Pantalla de juego
Es la pantalla en la que transcurre el tiempo de juego. Está implementada mediante Phaser en el archivo pang.js.
El juego consiste en 3 elementos principales:
- Los personajes controlables, que pueden moverse por la pantalla y disparar.
- Las plataformas, contra las que colisionan las balas de los personajes y las bolas.
- Las bolas, que rebotan contra las plataformas y si colisionan con un jugador le quitan una vida.

Además de estos elementos, existen dos tipos de balas:
- El gancho, que es el arma principal, y la bala láser, que se activa al coger un potenciador de tipo estrella.

![alt text](/pang_online/screenshots/partida.png)

## Pantalla puntuaciones

Aquí aparece la leaderboard de puntuaciones, que se guardan al final de la partida. La tabla de puntuaciones se actualiza
teniendo en cuenta dichas puntuaciones, por medio de API REST.
![alt text](/pang_online/screenshots/puntuacion.png)

## Documentación del protocolo utilizado sobre websockets

El jugador establece una conexión al introducirse en alguna de las salas. Al elegir una sala, la partida comienza una vez los dos jugadores se encuentren dentro de la misma. El primer jugador que entra actúa como host de la sala, y una vez que entra,
se generan las plataformas, que serán las mismas para el segundo jugador que entre a la sala. Durante la partida,
mediante los websockets abiertos se envía información en tiempo real sobre posición de los jugadores, si se ha disparado o no, si alguno de los jugadores tiene powerups que cambie los disparos, la generación de bolas y las colisiones.

### Tipos de mensajes
En el juego hay tres tipos de mensajes que se gestionan mediante websockets:
- El primer tipo de mensaje es el que se envía cuando se conecta un jugador impar, que será host, y por tanto el servidor le manda un mensaje indicándole que es el host.
- El segundo tipo de mensaje se envía cuando dos jugadores se emparejan, y se les envía un json indicándoles que puede comenzar la partida. En este momento el servidor espera unos segundos para asegurarse de que los dos jugadores han cargado la página correctamente.
- El tercer tipo de mensaje es el que se manda durante el juego, y contiene datos como la posición del jugador, de las bolas, etc. El servidor recibe un mensaje de un jugador y se lo manda a su pareja de forma íntegra. Estos mensajes se llaman en varios sitios.
	- En el update: Mandando cada frame la posición de las bolas, de los jugadores y si un jugador ha disparado.
	- En eventos específicos, como cuando un jugador dispara, muere o coge un powerUp. En estos eventos solo se manda la posición del jugador y lo que ha sucedido en el evento particular.

### Interpretación de los mensajes en javascript
El cliente puede ser host o cliente. Dependiendo de si es uno u otro se ejecutará un Update distinto y se mandarán mensajes distintos. Por ejemplo: el jugador host manda la posición de las bolas en cada fotograma y el jugador cliente no lo hace. El jugador cliente interpreta estas posiciones cada vez que las recibe, y el jugador host no lo hace.

## Diagrama de Flujo
Para la última parte de la práctica, no se ha modificado el diagrama de flujo
![alt text](/pang_online/screenshots/Diagrama_de_flujo.png)

## Diagrama de clases del servidor

En verde está el @Controller, en azul el @service y en rojo el archivo js que utiliza la API REST.
Se ha añadido la clase que gestiona los sockets.

![alt text](/pang_online/screenshots/Diagrama_de_clases_server.PNG)

## Guia para la ejecucción del programa

Instalar Java Se

Ejecutar el servidor en Servidor/target/pang_online_server.jar

Para entrar en la página, escribir la url localhost:8090


text:
from typing import MutableMapping, MutableSequence

import proto  # type: ignore

from google.cloud.deploy_v1.types import log_enums

__protobuf__ = proto.module(
    package="google.cloud.deploy.v1",
    manifest={
        "ReleaseNotificationEvent",
    },
)

class ReleaseNotificationEvent(proto.Message):
    r"""Payload proto for "clouddeploy.googleapis.com/release_notification"
    Platform Log event that describes the failure to send release status
    change Pub/Sub notification.

    Attributes:
        message (str):
            Debug message for when a notification fails
            to send.
        release (str):
            The name of the ``Release``.
        type_ (google.cloud.deploy_v1.types.Type):
            Type of this notification, e.g. for a Pub/Sub
            failure.
    """

    message: str = proto.Field(
        proto.STRING,
        number=1,
    )
    release: str = proto.Field(
        proto.STRING,
        number=2,
    )
    type_: log_enums.Type = proto.Field(
        proto.ENUM,
        number=3,
        enum=log_enums.Type,
    )

__all__ = tuple(sorted(__protobuf__.manifest))


text:
year: 1
title: General
pinned: true
links:
  - name: handbook
    url: http://web.inf.ed.ac.uk/infweb/student-services/ito/students/year1
---
> _don't stress yourself out too much, first year doesn't count towards your degree_

- [LaundryView](http://www.laundryview.com/lvs.php?s=264)
- [Common Outside Course Options for Informatics Students](http://homepages.inf.ed.ac.uk/imurray2/pt/outside_courses.html)
- [Year 1 Google Drive](/drive?next=0B4SUSkTXjliXdkQxNGRYN0hfSGs)
- mailing list archives - [ug1-students](https://lists.inf.ed.ac.uk/mailman/private/ug1-students/)
- if you have a learning disability go to the [disability service](http://www.ed.ac.uk/student-disability-service/about)! make sure you go there long before the exams, it only takes few hours and can help you quite a bit.
- [Programming Club](http://progclub.inf.ed.ac.uk/)
- InfBase: a drop in helpdesk for you to get additional tutoring and support with your courses. See the [schedule](https://informaticsstudentsupport.wordpress.com/schedule-at-a-glance/) here - there's no need to sign up, just drop in


text:
/*jslint es5: true*/

var config = require('../config/config');
var ad = config.ad;
var ldapClient = require('./ldap-client');

var mongoose = require('mongoose');

var User = mongoose.model('User');
var Group = mongoose.model('Group');

function addUserFromAD(req, res, doc) {
  var name = req.body.name;
  var nameFilter = ad.nameFilter.replace('_name', name);
  var opts = {
    filter: nameFilter,
    attributes: ad.objAttributes,
    scope: 'sub',
  };

  ldapClient.search(ad.searchBase, opts, false, function(err, result) {
    if (err) {
      console.error(err.name + ' : ' + err.message);
      return res.status(500).json(err);
    }

    if (result.length === 0) {
      return res.status(400).send(name + ' is not found in AD!');
    }

    if (result.length > 1) {
      return res.status(400).send(name + ' is not unique!');
    }

    var id = result[0].uid.toLowerCase();
    var access = 0;
    if (req.body.access && req.body.access === 'write') {
      access = 1;
    }
    doc.sharedWith.addToSet({
      _id: id,
      username: name,
      access: access,
    });
    doc.save(function(docErr) {
      if (docErr) {
        console.error(docErr);
        return res.status(500).send(docErr.message);
      }
      var user = new User({
        _id: result[0].uid.toLowerCase(),
        name: result[0].displayName,
        email: result[0].mail,
        office: result[0].physicalDeliveryOfficeName,
        phone: result[0].telephoneNumber.toString(),
        mobile: result[0].mobile,
      });
      switch (doc.constructor.modelName) {
        case 'Form':
          user.forms = [doc._id];
          break;
        case 'Traveler':
          user.travelers = [doc._id];
          break;
        case 'Binder':
          user.binders = [doc._id];
          break;
        default:
          console.error(
            'Something is wrong with doc type ' + doc.constructor.modelName
          );
      }
      user.save(function(userErr) {
        if (userErr) {
          console.error(userErr);
        }
      });
      return res
        .status(201)
        .send('The user named ' + name + ' was added to the share list.');
    });
  });
}

function addGroupFromAD(req, res, doc) {
  if (!ad.groupSearchFilter) {
    return res.status(500).send('AD not set up for groups');
  }
  var id = req.body.id.toLowerCase();
  var filter = ad.groupSearchFilter.replace('_id', id);
  var opts = {
    filter: filter,
    attributes: ad.groupAttributes,
    scope: 'sub',
  };

  ldapClient.search(ad.groupSearchBase, opts, false, function(err, result) {
    if (err) {
      console.error(err);
      return res.status(500).send(err.message);
    }

    if (result.length === 0) {
      return res.status(400).send(id + ' is not found in AD!');
    }

    if (result.length > 1) {
      return res.status(400).send(id + ' is not unique!');
    }

    var name = result[0].displayName;
    var access = 0;
    if (req.body.access && req.body.access === 'write') {
      access = 1;
    }
    doc.sharedGroup.addToSet({
      _id: id,
      groupname: name,
      access: access,
    });
    doc.save(function(docErr) {
      if (docErr) {
        console.error(docErr);
        return res.status(500).send(docErr.message);
      }
      var group = new Group({
        _id: result[0].uid.toLowerCase(),
        name: result[0].displayName,
        email: result[0].mail,
      });
      switch (doc.constructor.modelName) {
        case 'Form':
          group.forms = [doc._id];
          break;
        case 'Traveler':
          group.travelers = [doc._id];
          break;
        case 'Binder':
          group.binders = [doc._id];
          break;
        default:
          console.error(
            'Something is wrong with doc type ' + doc.constructor.modelName
          );
      }
      group.save(function(groupErr) {
        if (groupErr) {
          console.error(groupErr);
        }
      });
      return res
        .status(201)
        .send('The group ' + id + ' was added to the share list.');
    });
  });
}

function addUser(req, res, doc) {
  var name = req.body.name;
  // check local db first then try ad
  User.findOne(
    {
      name: name,
    },
    function(err, user) {
      if (err) {
        console.error(err);
        return res.status(500).send(err.message);
      }
      if (user) {
        var access = 0;
        if (req.body.access && req.body.access === 'write') {
          access = 1;
        }
        doc.sharedWith.addToSet({
          _id: user._id,
          username: name,
          access: access,
        });
        doc.save(function(docErr) {
          if (docErr) {
            console.error(docErr);
            return res.status(500).send(docErr.message);
          }
          return res
            .status(201)
            .send('The user named ' + name + ' was added to the share list.');
        });
        var addToSet = {};
        switch (doc.constructor.modelName) {
          case 'Form':
            addToSet.forms = doc._id;
            break;
          case 'Traveler':
            addToSet.travelers = doc._id;
            break;
          case 'Binder':
            addToSet.binders = doc._id;
            break;
          default:
            console.error(
              'Something is wrong with doc type ' + doc.constructor.modelName
            );
        }
        user.update(
          {
            $addToSet: addToSet,
          },
          function(useErr) {
            if (useErr) {
              console.error(useErr);
            }
          }
        );
      } else {
        addUserFromAD(req, res, doc);
      }
    }
  );
}

function addGroup(req, res, doc) {
  var id = req.body.id.toLowerCase();
  // check local db first then try ad
  Group.findOne(
    {
      _id: id,
    },
    function(err, group) {
      if (err) {
        console.error(err);
        if (ad.groupSearchFilter) {
          return addGroupFromAD(req, res, doc);
        } else {
          return res.status(500).send(err.message);
        }
      }
      if (group) {
        var access = 0;
        if (req.body.access && req.body.access === 'write') {
          access = 1;
        }
        doc.sharedGroup.addToSet({
          _id: id,
          groupname: group.name,
          access: access,
        });
        doc.save(function(docErr) {
          if (docErr) {
            console.error(docErr);
            return res.status(500).send(docErr.message);
          }
          return res
            .status(201)
            .send('The group ' + id + ' was added to the share list.');
        });
        var addToSet = {};
        switch (doc.constructor.modelName) {
          case 'Form':
            addToSet.forms = doc._id;
            break;
          case 'Traveler':
            addToSet.travelers = doc._id;
            break;
          case 'Binder':
            addToSet.binders = doc._id;
            break;
          default:
            console.error(
              'Something is wrong with doc type ' + doc.constructor.modelName
            );
        }
        group.update(
          {
            $addToSet: addToSet,
          },
          function(groupErr) {
            if (groupErr) {
              console.error(groupErr);
            }
          }
        );
      } else if (ad.groupSearchFilter) {
        addGroupFromAD(req, res, doc);
      } else {
        console.error('Group not found: ' + id);
        return res.status(403).send('Group not found: ' + id);
      }
    }
  );
}

function removeFromList(req, res, doc) {
  // var form = req[req.params.id];
  var list;
  var ids = req.params.shareid.split(',');
  var removed = [];

  if (req.params.list === 'users') {
    list = doc.sharedWith;
  }
  if (req.params.list === 'groups') {
    list = doc.sharedGroup;
  }

  ids.forEach(function(id) {
    var share = list.id(id);
    if (share) {
      removed.push(id);
      share.remove();
    }
  });

  if (removed.length === 0) {
    return res
      .status(400)
      .send('cannot find ' + req.params.shareid + ' in list.');
  }

  doc.save(function(saveErr) {
    if (saveErr) {
      console.error(saveErr);
      return res.status(500).send(saveErr.message);
    }
    // keep the consistency of user's form list
    var Target;
    if (req.params.list === 'users') {
      Target = User;
    }
    if (req.params.list === 'groups') {
      Target = Group;
    }

    var pull = {};
    switch (doc.constructor.modelName) {
      case 'Form':
        pull.forms = doc._id;
        break;
      case 'Traveler':
        pull.travelers = doc._id;
        break;
      case 'Binder':
        pull.binders = doc._id;
        break;
      default:
        console.error(
          'Something is wrong with doc type ' + doc.constructor.modelName
        );
    }

    removed.forEach(function(id) {
      Target.findByIdAndUpdate(
        id,
        {
          $pull: pull,
        },
        function(updateErr, target) {
          if (updateErr) {
            console.error(updateErr);
          }
          if (!target) {
            console.error(
              'The ' + req.params.list + ' ' + id + ' is not in the db'
            );
          }
        }
      );
    });

    return res.status(200).json(removed);
  });
}

/**
 * add a user or a group into a document's share list
 * @param  {ClientRequest}   req http request object
 * @param  {ServerResponse}   res http response object
 * @param  {Documment}   doc the document to share
 * @return {undefined}
 */
function addShare(req, res, doc) {
  if (
    ['Form', 'Traveler', 'Binder'].indexOf(doc.constructor.modelName) === -1
  ) {
    return res
      .status(500)
      .send('cannot handle the document type ' + doc.constructor.modelName);
  }
  if (req.params.list === 'users') {
    addUser(req, res, doc);
  }

  if (req.params.list === 'groups') {
    addGroup(req, res, doc);
  }
}

/**
 * remove a list of users or groups from a document's share list
 * @param  {ClientRequest} req http request object
 * @param  {ServerResponse} res http response object
 * @param  {Documment} doc the document to share
 * @return {undefined}
 */
function removeShare(req, res, doc) {
  if (
    ['Form', 'Traveler', 'Binder'].indexOf(doc.constructor.modelName) === -1
  ) {
    return res
      .status(500)
      .send('cannot handle the document type ' + doc.constructor.modelName);
  }

  removeFromList(req, res, doc);
}

function changeOwner(req, res, doc) {
  // get user id from name here
  var name = req.body.name;
  var nameFilter = ad.nameFilter.replace('_name', name);
  var opts = {
    filter: nameFilter,
    attributes: ad.objAttributes,
    scope: 'sub',
  };

  ldapClient.search(ad.searchBase, opts, false, function(ldapErr, result) {
    if (ldapErr) {
      console.error(ldapErr.name + ' : ' + ldapErr.message);
      return res.status(500).send(ldapErr.message);
    }

    if (result.length === 0) {
      return res.status(400).send(name + ' is not found in AD!');
    }

    if (result.length > 1) {
      return res.status(400).send(name + ' is not unique!');
    }

    var id = result[0].uid.toLowerCase();

    if (doc.owner === id) {
      return res.status(204).send();
    }

    doc.owner = id;
    doc.transferredOn = Date.now();

    doc.save(function(saveErr) {
      if (saveErr) {
        console.error(saveErr);
        return res.status(500).send(saveErr.message);
      }
      return res.status(200).send('Owner is changed to ' + id);
    });
  });
}

module.exports = {
  addShare: addShare,
  removeShare: removeShare,
  changeOwner: changeOwner,
};


text:
<?php

namespace Lrt\SiteBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use JMS\DiExtraBundle\Annotation as DI;

/**
 * @DI\Service("form.site.partner.type")
 */
class PartnerType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
                ->add('name')
                ->add('description')
                ->add('website')
                ->add('picture', null, array('label' => 'Logo', 'required' => false));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Lrt\SiteBundle\Entity\Partner'
        ));
    }

    public function getName()
    {
        return 'lrt_sitebundle_partnertype';
    }

}


text:
package org.apache.easyant.tasks;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.apache.easyant.core.EasyAntConstants;
import org.apache.ivy.Ivy;
import org.apache.ivy.ant.IvyTask;
import org.apache.ivy.core.module.id.ModuleRevisionId;
import org.apache.ivy.core.resolve.ResolvedModuleRevision;
import org.apache.ivy.core.settings.IvySettings;
import org.apache.ivy.plugins.matcher.PatternMatcher;
import org.apache.ivy.plugins.resolver.DependencyResolver;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.input.InputHandler;
import org.apache.tools.ant.input.InputRequest;
import org.apache.tools.ant.input.MultipleChoiceInputRequest;

public class SearchModule extends IvyTask {

    private String organisation;

    private String module;

    private String branch = PatternMatcher.ANY_EXPRESSION;

    private String revision;

    private String matcher = PatternMatcher.EXACT_OR_REGEXP;

    private String propertyPrefix;
    private String resolver;

    public void doExecute() throws BuildException {
        if (getOrganisation() == null) {
            throw new BuildException("no organisation provided for SearchModule task");
        }
        if (getModule() == null) {
            throw new BuildException("no module name provided for SearchModule task");
        }
        if (getRevision() == null) {
            throw new BuildException("no revision provided for SearchModule task");
        }

        if (getPropertyPrefix() == null) {
            throw new BuildException("no property prefix provided provided for SearchModule task");
        }
        Ivy ivy = getIvyInstance();
        IvySettings settings = ivy.getSettings();

        // search all modules revision matching the requested criteria
        DependencyResolver resolverToCheck;
        if (getResolver() != null) {
            resolverToCheck = settings.getResolver(getResolver());
        } else {
            resolverToCheck = settings.getDefaultResolver();
        }
        ModuleRevisionId mridToSearch = ModuleRevisionId.newInstance(getOrganisation(), getModule(), getBranch(),
                getRevision());
        ModuleRevisionId[] mrids = ivy.getSearchEngine().listModules(resolverToCheck, mridToSearch,
                settings.getMatcher(matcher));

        // diplay the list
        List<String> choices = new ArrayList<String>();
        for (int i = 0; i < mrids.length; i++) {
            ResolvedModuleRevision rmr = ivy.findModule(mrids[i]);
            if (rmr == null) {
                log("Can't retrieve " + mrids[i].toString(), Project.MSG_WARN);
            } else {

                choices.add(String.valueOf(i));
                StringBuilder sb = new StringBuilder();
                sb.append(i).append(": ");
                sb.append(mrids[i].getName());
                sb.append(" v").append(mrids[i].getRevision());
                // hide organization if its the default one
                if (!EasyAntConstants.EASYANT_SKELETONS_ORGANISATION.equals(mrids[i].getOrganisation())) {
                    sb.append(" by ").append(mrids[i].getOrganisation());
                }
                // Get the description
                if (rmr.getDescriptor().getDescription() != null && !rmr.getDescriptor().getDescription().equals("")) {
                    sb.append(" (").append(rmr.getDescriptor().getDescription()).append(")");
                }
                log(sb.toString());
            }
        }
        if (choices.isEmpty()) {
            throw new BuildException("No matching module were found !");
        }

        // ask end user to select a module
        // TODO handle a default value
        Integer value = Integer.valueOf(getInput("Choose a number:", null, choices));
        ModuleRevisionId moduleToRetrieve = mrids[value];

        // set final properties
        getProject().setProperty(getPropertyPrefix() + ".org", moduleToRetrieve.getOrganisation());
        getProject().setProperty(getPropertyPrefix() + ".module", moduleToRetrieve.getName());
        getProject().setProperty(getPropertyPrefix() + ".rev", moduleToRetrieve.getRevision());

    }

    protected String getInput(String message, String defaultvalue, List<String> choices) {
        InputRequest request;
        request = new MultipleChoiceInputRequest(message, new Vector(choices));
        request.setDefaultValue(defaultvalue);

        InputHandler h = getProject().getInputHandler();

        h.handleInput(request);

        String value = request.getInput();
        if ((value == null || value.trim().isEmpty()) && defaultvalue != null) {
            value = defaultvalue;
        }
        return value;

    }

    public String getMatcher() {
        return matcher;
    }

    public void setMatcher(String matcher) {
        this.matcher = matcher;
    }

    public String getModule() {
        return module;
    }

    public void setModule(String module) {
        this.module = module;
    }

    public String getOrganisation() {
        return organisation;
    }

    public void setOrganisation(String organisation) {
        this.organisation = organisation;
    }

    public String getRevision() {
        return revision;
    }

    public void setRevision(String revision) {
        this.revision = revision;
    }

    public String getBranch() {
        return branch;
    }

    public void setBranch(String branch) {
        this.branch = branch;
    }

    public String getPropertyPrefix() {
        return propertyPrefix;
    }

    public void setPropertyPrefix(String propertyPrefix) {
        this.propertyPrefix = propertyPrefix;
    }

    public String getResolver() {
        return resolver;
    }

    public void setResolver(String resolver) {
        this.resolver = resolver;
    }

}


text:
layout: tagpage
title: "Tag: theory"
tag: theory
robots: noindex
---


text:
<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Form\Type\Configurator;

use Symfony\Component\Form\FormConfigInterface;

/**
 * This configurator is applied to any form field of type 'checkbox' and is used
 * to decide whether the field should be required or not.
 *
 * @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
 */
class CheckboxTypeConfigurator implements TypeConfiguratorInterface
{
    /**
     * {@inheritdoc}
     */
    public function configure($name, array $options, array $metadata, FormConfigInterface $parentConfig)
    {
        // If no value is provided explicitly for the "required" option, assume the checkbox is not required.
        // Otherwise, HTML5 validation will prevent the form from being submitted.
        if (!isset($options['required'])) {
            $options['required'] = false;
        }

        $options['label'] = $metadata['label'];

        return $options;
    }

    /**
     * {@inheritdoc}
     */
    public function supports($type, array $options, array $metadata)
    {
        return in_array($type, array('checkbox', 'Symfony\Component\Form\Extension\Core\Type\CheckboxType'), true);
    }
}

class_alias('EasyCorp\Bundle\EasyAdminBundle\Form\Type\Configurator\CheckboxTypeConfigurator', 'JavierEguiluz\Bundle\EasyAdminBundle\Form\Type\Configurator\CheckboxTypeConfigurator', false);


text:
package communitycommons;

import com.mendix.core.Core;
import com.mendix.logging.ILogNode;
import communitycommons.proxies.LogLevel;
import communitycommons.proxies.LogNodes;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Logging {

	private static Map<String, Long> timers = new HashMap<String, Long>();

	public static void trace(String lognode, String message) {
		log(lognode, LogLevel.Trace, message, null);
	}

	public static void info(String lognode, String message) {
		log(lognode, LogLevel.Info, message, null);
	}

	public static void debug(String lognode, String message) {
		log(lognode, LogLevel.Debug, message, null);
	}

	public static void warn(String lognode, String message, Throwable e) {
		log(lognode, LogLevel.Debug, message, e);
	}

	public static void warn(String lognode, String message) {
		warn(lognode, message, null);
	}

	public static void error(String lognode, String message, Throwable e) {
		log(lognode, LogLevel.Error, message, e);
	}

	public static void error(String lognode, String message) {
		error(lognode, message, null);
	}

	public static void critical(String lognode, String message, Throwable e) {
		log(lognode, LogLevel.Critical, message, e);
	}

	public static void log(String lognode, LogLevel loglevel, String message, Throwable e) {
		ILogNode logger = createLogNode(lognode);
		switch (loglevel) {
			case Critical:
				logger.critical(message, e);
				break;
			case Warning:
				logger.warn(message, e);
				break;
			case Debug:
				logger.debug(message);
				break;
			case Error:
				logger.error(message, e);
				break;
			case Info:
				logger.info(message);
				break;
			case Trace:
				logger.trace(message);
				break;
		}
	}

	public static Long measureEnd(String timerName, LogLevel loglevel,
		String message) {
		Long cur = new Date().getTime();
		if (!timers.containsKey(timerName)) {
			throw new IllegalArgumentException(String.format("Timer with key %s not found", timerName));
		}
		Long timeTaken = cur - timers.get(timerName);
		String time = String.format("%d", timeTaken);
		log(LogNodes.CommunityCommons.name(), loglevel, "Timer " + timerName + " finished in " + time + " ms. " + message, null);
		return timeTaken;
	}

	public static void measureStart(String timerName) {
		timers.put(timerName, new Date().getTime());
	}

	public static ILogNode createLogNode(String logNode) {
		return Core.getLogger(logNode);
	}
}


text:
Lizard.Views.MapLegend = L.Control.extend({
  options: {
    collapsed: true,
    position: 'bottomleft',
    autoZIndex: true
  },

  initialize: function (workspace, options) {
    L.setOptions(this, options);

    this._lastZIndex = 0;
    this._handlingClick = false;
    this.workspace = workspace;
    this._expanded = false;

  },

  onAdd: function (map) {
    this._initLayout();
    //this._update();
    return this._container;

  },

  onRemove: function (map) {
  },

  _initLayout: function () {
    var className = 'leaflet-control-legend',
      container = this._container = L.DomUtil.create('div', className);

    if (!L.Browser.touch) {
      L.DomEvent.disableClickPropagation(container);
      L.DomEvent.on(container, 'mousewheel', L.DomEvent.stopPropagation);
    } else {
      L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
    }

    if (this.options.collapsed) {
      L.DomEvent
        .on(container, 'click', this._toggle, this);
      var link = this._layersLink = L.DomUtil.create('i', "leaflet-control-legend-icon icon-list icon-white ", container);
      link.href = '#';
      link.title = 'Legenda';

      if (L.Browser.touch) {
        L.DomEvent
          .on(link, 'click', L.DomEvent.stopPropagation)
          .on(link, 'click', L.DomEvent.preventDefault)
          .on(link, 'click', this._toggle, this);
      } else {
        L.DomEvent.on(link, 'focus', this._toggle, this);
      }

      this._map.on('movestart', this._toggle, this);
      // TODO keyboard accessibility
    } else {
      this._toggle();
    }

  },
  _toggle: function () {
    if (this._expanded) {
      this._container.className = this._container.className.replace(' leaflet-control-legend-expanded', '');
      this._expanded = false;
    } else {
      L.DomUtil.addClass(this._container, 'leaflet-control-legend-expanded');
      this._expanded = true;
    }
  }
});


text:
#ifndef TextCompressor_H
# define TextCompressor_H

# include "CharCache.H"

class EncodeBuffer;
class DecodeBuffer;

class TextCompressor
{
  public:
    TextCompressor(CharCache * cache, unsigned int cacheSize):cache_(cache),
        cacheSize_(cacheSize), key_(0)
    {
    }

    void encodeChar(unsigned char ch, EncodeBuffer &);
    unsigned char decodeChar(DecodeBuffer &);
    void reset(unsigned int newKey = 0)
    {
        key_ = newKey;
    }

  private:
    CharCache * cache_;
    unsigned int cacheSize_;
    unsigned int key_;
};

#endif /* TextCompressor_H */