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

package com.azure.resourcemanager.network.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** Contains bgp community information offered in Service Community resources. */
@Fluent
public final class BgpCommunity {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(BgpCommunity.class);

    /*
     * The region which the service support. e.g. For O365, region is Global.
     */
    @JsonProperty(value = "serviceSupportedRegion")
    private String serviceSupportedRegion;

    /*
     * The name of the bgp community. e.g. Skype.
     */
    @JsonProperty(value = "communityName")
    private String communityName;

    /*
     * The value of the bgp community. For more information:
     * https://docs.microsoft.com/en-us/azure/expressroute/expressroute-routing.
     */
    @JsonProperty(value = "communityValue")
    private String communityValue;

    /*
     * The prefixes that the bgp community contains.
     */
    @JsonProperty(value = "communityPrefixes")
    private List<String> communityPrefixes;

    /*
     * Customer is authorized to use bgp community or not.
     */
    @JsonProperty(value = "isAuthorizedToUse")
    private Boolean isAuthorizedToUse;

    /*
     * The service group of the bgp community contains.
     */
    @JsonProperty(value = "serviceGroup")
    private String serviceGroup;

    /**
     * Get the serviceSupportedRegion property: The region which the service support. e.g. For O365, region is Global.
     *
     * @return the serviceSupportedRegion value.
     */
    public String serviceSupportedRegion() {
        return this.serviceSupportedRegion;
    }

    /**
     * Set the serviceSupportedRegion property: The region which the service support. e.g. For O365, region is Global.
     *
     * @param serviceSupportedRegion the serviceSupportedRegion value to set.
     * @return the BgpCommunity object itself.
     */
    public BgpCommunity withServiceSupportedRegion(String serviceSupportedRegion) {
        this.serviceSupportedRegion = serviceSupportedRegion;
        return this;
    }

    /**
     * Get the communityName property: The name of the bgp community. e.g. Skype.
     *
     * @return the communityName value.
     */
    public String communityName() {
        return this.communityName;
    }

    /**
     * Set the communityName property: The name of the bgp community. e.g. Skype.
     *
     * @param communityName the communityName value to set.
     * @return the BgpCommunity object itself.
     */
    public BgpCommunity withCommunityName(String communityName) {
        this.communityName = communityName;
        return this;
    }

    /**
     * Get the communityValue property: The value of the bgp community. For more information:
     * https://docs.microsoft.com/en-us/azure/expressroute/expressroute-routing.
     *
     * @return the communityValue value.
     */
    public String communityValue() {
        return this.communityValue;
    }

    /**
     * Set the communityValue property: The value of the bgp community. For more information:
     * https://docs.microsoft.com/en-us/azure/expressroute/expressroute-routing.
     *
     * @param communityValue the communityValue value to set.
     * @return the BgpCommunity object itself.
     */
    public BgpCommunity withCommunityValue(String communityValue) {
        this.communityValue = communityValue;
        return this;
    }

    /**
     * Get the communityPrefixes property: The prefixes that the bgp community contains.
     *
     * @return the communityPrefixes value.
     */
    public List<String> communityPrefixes() {
        return this.communityPrefixes;
    }

    /**
     * Set the communityPrefixes property: The prefixes that the bgp community contains.
     *
     * @param communityPrefixes the communityPrefixes value to set.
     * @return the BgpCommunity object itself.
     */
    public BgpCommunity withCommunityPrefixes(List<String> communityPrefixes) {
        this.communityPrefixes = communityPrefixes;
        return this;
    }

    /**
     * Get the isAuthorizedToUse property: Customer is authorized to use bgp community or not.
     *
     * @return the isAuthorizedToUse value.
     */
    public Boolean isAuthorizedToUse() {
        return this.isAuthorizedToUse;
    }

    /**
     * Set the isAuthorizedToUse property: Customer is authorized to use bgp community or not.
     *
     * @param isAuthorizedToUse the isAuthorizedToUse value to set.
     * @return the BgpCommunity object itself.
     */
    public BgpCommunity withIsAuthorizedToUse(Boolean isAuthorizedToUse) {
        this.isAuthorizedToUse = isAuthorizedToUse;
        return this;
    }

    /**
     * Get the serviceGroup property: The service group of the bgp community contains.
     *
     * @return the serviceGroup value.
     */
    public String serviceGroup() {
        return this.serviceGroup;
    }

    /**
     * Set the serviceGroup property: The service group of the bgp community contains.
     *
     * @param serviceGroup the serviceGroup value to set.
     * @return the BgpCommunity object itself.
     */
    public BgpCommunity withServiceGroup(String serviceGroup) {
        this.serviceGroup = serviceGroup;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
package serializedcall

import (
	"bytes"
	"encoding/json"
	"encoding/xml"
	"fmt"

	"github.com/k0kubun/pp"
)

// MarshalXMLArgs converts a list of arguments into XML
func MarshalXMLArgs(args ...interface{}) ([]byte, error) {

	argSlice := []interface{}{}

	for _, arg := range args {
		argSlice = append(argSlice, arg)
	}
	xmlBytes, err := json.Marshal(argSlice)
	if err != nil {
		return nil, err
	}

	fmt.Println(string(xmlBytes))
	return xmlBytes, nil
}

// UnmarshalXMLArgs converts XML into a slice of go data
func UnmarshalXMLArgs(xmlBytes []byte) ([]interface{}, error) {

	var args []interface{}

	dec := xml.NewDecoder(bytes.NewBuffer([]byte(xmlBytes)))
	err := dec.Decode(&args)
	if err != nil {
		return nil, err
	}

	// fmt.Printf("%#v\n", args)

	return args, nil
}

// CallWithXML Calls a function f with arguments from a XML byte stream
func CallWithXML(f interface{}, xmlBytes []byte) ([]byte, error) {
	args, err := UnmarshalXMLArgs(xmlBytes)
	if err != nil {
		return nil, err
	}

	pp.Println(args)

	vals, err := callFunction(args, f)
	if err != nil {
		return nil, err
	}

	// fmt.Printf("%#v\n", vals)

	results, err := buildResults(vals)
	if err != nil {
		return nil, err
	}

	// fmt.Printf("%#v\n", results)

	return json.Marshal(results)
}

redpajama_set_name: RedPajamaGithub


text:
package com.watook.model.response;

import java.io.Serializable;

/**
 * Created by Avinash on 22-07-2017.
 */

public class RegistrationResponse implements Serializable {

    public RegistrationResponse() {
    }

    /**
     * status : success
     * reasonCode : Authentication Success!
     * data : XlGAO6uf4cd7MP1qvUsDzs5R8bPTa4XKHl2/LI2o/Zk=
     */

    private String status;
    private String reasonCode;
    private String data;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getReasonCode() {
        return reasonCode;
    }

    public void setReasonCode(String reasonCode) {
        this.reasonCode = reasonCode;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}


text:
package com.jaouan.articledetailstransition.popfromitem.adapters;

import android.graphics.PointF;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jaouan.articledetailstransition.popfromitem.R;
import com.jaouan.articledetailstransition.popfromitem.models.Article;

import java.util.List;

/**
 * List adapter that handles {@link Article}.
 */
public class ArticleAdapter extends RecyclerView.Adapter<ArticleAdapter.ViewHolder> {

    private List<Article> mArticles;

    private OnArticleClickedListener mOnArticleClickedListener;

    /**
     * ArticleAdapter's constructor.
     *
     * @param articles Articles to display.
     */
    public ArticleAdapter(final List<Article> articles) {
        this.mArticles = articles;
    }

    @Override
    public ArticleAdapter.ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
        final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.article, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        final Article item = mArticles.get(position);
        holder.tvTitle.setText(item.getTitle());
        holder.tvDate.setText(item.getDate());
        holder.ivThumbnail.setImageResource(item.getHeader());
        holder.ivCoveringImage.setImageResource(item.getHeader());
        holder.rootView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View view, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP){
                    if (mOnArticleClickedListener != null) {
                        mOnArticleClickedListener.onArticleClicked(item, holder, new PointF(event.getX(), event.getY()));
                    }
                }
                return true;
            }
        });
    }

    @Override
    public int getItemCount() {
        return mArticles.size();
    }

    /**
     * Sets on article clicked listener.
     *
     * @param onArticleClickedListener Article clicked listener.
     */
    public void setOnArticleClickedListener(final OnArticleClickedListener onArticleClickedListener) {
        this.mOnArticleClickedListener = onArticleClickedListener;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public final View rootView;
        public final TextView tvTitle;
        public final TextView tvDate;
        public final ImageView ivThumbnail;
        public final ImageView ivCoveringImage;

        public ViewHolder(final View view) {
            super(view);
            this.rootView = view;
            this.tvTitle = (TextView) view.findViewById(R.id.title);
            this.tvDate = (TextView) view.findViewById(R.id.date);
            this.ivThumbnail = (ImageView) view.findViewById(R.id.thumbnail);
            this.ivCoveringImage = (ImageView) view.findViewById(R.id.covering_image);
        }
    }

    /**
     * On item clicked callback.
     */
    public interface OnArticleClickedListener {

        void onArticleClicked(Article article, ViewHolder articleViewHolder, PointF touchPoint);

    }

}


text:
layout: post
title: CNN for VR A1:Numpy, Scipy, Matplotlib Tutorial
categories: [-07 Machine Learning]
tags: [Machine Learning]
number: [-11.1]
fullview: false
shortinfo: Numpy,Scipy,Matplotlib是Python data science用到的最主要的3个强大的库,这里做一个入门整理。

---
目录
{:.article_content_title}

* TOC
{:toc}

---
{:.hr-short-left}

## 1 Numpy ##

{: .img_middle_hg}
![NumPy Summary](/assets/images/posts/07_Machine Learning/Convolutional Neural Network/2015-06-15-CNN for Visual Recognition A1:Numpy, Scipy, Matplotlib Tutorial/NumPy Summary.png)

## 2 SciPy ##

{: .img_middle_hg}
![SciPy Summary](/assets/images/posts/07_Machine Learning/Convolutional Neural Network/2015-06-15-CNN for Visual Recognition A1:Numpy, Scipy, Matplotlib Tutorial/SciPy Summary.png)

## 3 Matplotlib ##

{: .img_middle_hg}
![Matplotlib Summary](/assets/images/posts/07_Machine Learning/Convolutional Neural Network/2015-06-15-CNN for Visual Recognition A1:Numpy, Scipy, Matplotlib Tutorial/Matplotlib Summary.png)

## 4 Summary ##

{: .img_middle_lg}
![NumPy,SciPy,Matplotlib,Python,MATLAB关系](/assets/images/posts/07_Machine Learning/Convolutional Neural Network/2015-06-15-CNN for Visual Recognition A1:Numpy, Scipy, Matplotlib Tutorial/NumPy,SciPy,Matplotlib,Python,MATLAB关系.png)

A complete IPython notes is [here](https://github.com/shunmian/CS231n/blob/master/A1_numpy%2Cscipy%2Cmatplotlib.ipynb).

## 5 参考资料 ##

- ["Numpy Quickstart Tutorial"](https://docs.scipy.org/doc/numpy-dev/user/quickstart.html);
- ["SciPy Documentation"](https://docs.scipy.org/doc/scipy/reference/index.html);
- ["matplotlib.pyplot"](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot);


text:
<?php

/**
 * Add a new user role to the site.
 */

$this->require_acl ('admin', 'user', 'user/roles');

$page->title = __ ('Add Role');
$page->layout = 'admin';

$form = new Form ('post', $this);

$resources = User::acl ()->resources ();
unset ($resources['default']);

$form->data = array (
	'_resources' => $resources,
	'_roles' => array_keys (User::acl ()->rules)
);

echo $form->handle (function ($form) use ($page) {
	$_POST['resources'] = isset ($_POST['resources'])
		? $_POST['resources']
		: array ();

	foreach ($_POST['resources'] as $key => $on) {
		$_POST['resources'][$key] = true;
	}

	// convert the resources for saving
	if (! isset ($_POST['resources']['default'])) {
		$_POST['resources']['default'] = false;
	} else {
		$resources = User::acl ()->resources ();
		foreach ($resources as $resource => $label) {
			if (isset ($_POST['resources'][$resource])) {
				unset ($resources[$resource]);
			} else {
				$resources[$resource] = false;
			}
		}
		$resources['default'] = true;
		$_POST['resources'] = $resources;
	}

	// save the file
	$acl = User::acl ();
	$acl->add_role ($_POST['name'], $_POST['resources']['default']);
	foreach ($_POST['resources'] as $resource => $allow) {
		if ($allow) {
			$acl->allow ($_POST['name'], $resource);
		} else {
			$acl->deny ($_POST['name'], $resource);
		}
	}

	if (! Ini::write ($acl->rules, conf ('Paths', 'access_control_list'))) {
		$form->controller->add_notification (__ ('Unable to save the file.'));
		return false;
	}
	$form->controller->add_notification (__ ('Role added.'));
	$form->controller->redirect ('/user/roles');
});


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
    Document   : service-config.xml
    Created on : May 19, 2009, 1:31 PM
    Author     :
    Copyright 2009 University of California at Berkeley
    Description:
        Service layer configuration
-->

<svc:service-config  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
                     xmlns:svc='http://collectionspace.org/services/config'
                     xmlns:types='http://collectionspace.org/services/config/types'
                     xsi:schemaLocation='http://collectionspace.org/services/config ../resources/common.xsd'>

	<cspace-instance-id>@CSPACE_INSTANCE_ID@</cspace-instance-id>
	<db-csadmin-name>@DB_CSADMIN_NAME@</db-csadmin-name>
	<db-nuxeo-name>@DB_NUXEO_NAME@</db-nuxeo-name>
	<db-cspace-name>@DB_CSPACE_NAME@</db-cspace-name>
	<use-app-generated-tenant-bindings>true</use-app-generated-tenant-bindings>

    <!-- name of the repository client is referred in each service binding -->
    <repository-client name="nuxeo-java" default="true">
        <!-- ip of network interface to which Nuxeo server is listening on -->
        <host>127.0.0.1</host>
        <port>62474</port> <!-- java -->
        <!--port>8080</port--> <!-- rest -->
        <user>Administrator</user>
        <password>Administrator</password>
        <client-type>java</client-type>
        <client-class>org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl</client-class>
        <properties>
            <types:item><types:key>pageSizeDefault</types:key><types:value>40</types:value></types:item> <!-- Use 'pgSz' query param to override this on a per request bassis. -->
            <types:item><types:key>pageSizeMax</types:key><types:value>2500</types:value></types:item> <!-- No list result page size can be greater than this amount -->
            <types:item><types:key>refreshAuthZOnStartup</types:key><types:value>true</types:value></types:item>
        </properties>
    </repository-client>

</svc:service-config>


text:
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
    <settings pass="windowsPE">
        <component name="Microsoft-Windows-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State">
            <RunSynchronous>
                <RunSynchronousCommand wcm:action="add">
                    <Description>Start DaRT</Description>
                    <Order>1</Order>
                    <Path>X:\Sources\recovery\tools\MSDartTools.exe</Path>
                </RunSynchronousCommand>
            </RunSynchronous>
        </component>
    </settings>
</unattend>


text:
package de.tudarmstadt.ukp.jwktl.parser.ru;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import junit.framework.TestCase;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryEntry;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryPage;
import de.tudarmstadt.ukp.jwktl.api.PartOfSpeech;
import de.tudarmstadt.ukp.jwktl.api.entry.WiktionaryPage;
import de.tudarmstadt.ukp.jwktl.parser.WiktionaryEntryParser;

/**
 * Test case for {@link RUWiktionaryEntryParser}.
 * @author Christian M. Meyer
 */
public class WikokitParserTest extends TestCase {

	/***/
	public void testLodka() throws Exception {
		IWiktionaryPage page = parse("lodka.txt", "лодка");
		IWiktionaryEntry entry;

		assertEquals(1, page.getEntryCount());
		entry = page.getEntry(0);
		assertEquals(PartOfSpeech.NOUN, entry.getPartOfSpeech());
		assertEquals(1, entry.getSenseCount());
		assertEquals("водное транспортное средство, небольшое судно, идущее на вёслах, под парусом или на моторной тяге", entry.getSense(1).getGloss().getPlainText());
	}

	/***/
	public void testLechu() throws Exception {
		IWiktionaryPage page = parse("lechu.txt", "лечу");
		IWiktionaryEntry entry;

		assertEquals(2, page.getEntryCount());
		entry = page.getEntry(0);
		//TODO: assertEquals(PartOfSpeech.VERB, entry.getPartOfSpeech());
		assertEquals(null, entry.getPartOfSpeech());
		//assertEquals(PartOfSpeech.WORD_FORM, entry.getPartsOfSpeech().get(1));
		assertEquals(0, entry.getSenseCount());
		entry = page.getEntry(1);
		//assertEquals(PartOfSpeech.VERB, entry.getPartOfSpeech());
		assertEquals(null, entry.getPartOfSpeech());
		//assertEquals(PartOfSpeech.WORD_FORM, entry.getPartsOfSpeech().get(1));
		assertEquals(0, entry.getSenseCount());
	}

	protected IWiktionaryPage parse(final String fileName, final String title) throws IOException {
		StringBuilder text = new StringBuilder();
		BufferedReader reader = new BufferedReader(
				new InputStreamReader(new FileInputStream(
						new File("src/test/resources/articles-ru/" + fileName)),
						"UTF-8"));
		String line;
		while ((line = reader.readLine()) != null)
			text.append(line).append("\n");
		reader.close();
		WiktionaryPage result = new WiktionaryPage();
		result.setTitle(title);
		WiktionaryEntryParser parser = new RUWiktionaryEntryParser();
		parser.parse(result, text.toString());
		return result;
	}

}


text:
// POC.Network.Sniffer
// TreeViewHelper.cs
//
// Copyright © 2007 - 2014 Ryan Wilson - All Rights Reserved
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  * Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of SyndicatedLife nor the names of its contributors may
//    be used to endorse or promote products derived from this software
//    without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

using System.Windows.Controls;
using POC.Network.Sniffer.Enums;
using POC.Network.Sniffer.Models;

namespace POC.Network.Sniffer.Helpers
{
    public static class TreeViewHelper
    {
        public static TreeViewItem MakeIPTreeViewItem(IPHeader ipHeader)
        {
            var ipTreeViewItem = new TreeViewItem();
            ipTreeViewItem.Header = "IP";
            ipTreeViewItem.Items.Add("Ver: " + ipHeader.Version);
            ipTreeViewItem.Items.Add("Header Length: " + ipHeader.HeaderLength);
            ipTreeViewItem.Items.Add("Differntiated Services: " + ipHeader.DifferentiatedServices);
            ipTreeViewItem.Items.Add("Total Length: " + ipHeader.TotalLength);
            ipTreeViewItem.Items.Add("Identification: " + ipHeader.Identification);
            ipTreeViewItem.Items.Add("Flags: " + ipHeader.Flags);
            ipTreeViewItem.Items.Add("Fragmentation Offset: " + ipHeader.FragmentationOffset);
            ipTreeViewItem.Items.Add("Time to live: " + ipHeader.TTL);
            switch (ipHeader.ProtocolType)
            {
                case Protocol.TCP:
                    ipTreeViewItem.Items.Add("Protocol: " + "TCP");
                    break;
                case Protocol.UDP:
                    ipTreeViewItem.Items.Add("Protocol: " + "UDP");
                    break;
                case Protocol.Unknown:
                    ipTreeViewItem.Items.Add("Protocol: " + "Unknown");
                    break;
            }
            ipTreeViewItem.Items.Add("Checksum: " + ipHeader.Checksum);
            ipTreeViewItem.Items.Add("Source: " + ipHeader.SourceAddress.ToString());
            ipTreeViewItem.Items.Add("Destination: " + ipHeader.DestinationAddress.ToString());
            return ipTreeViewItem;
        }

        public static TreeViewItem MakeTCPTreeViewItem(TCPHeader tcpHeader)
        {
            var tcpTreeViewItem = new TreeViewItem();
            tcpTreeViewItem.Header = "TCP";
            tcpTreeViewItem.Items.Add("Source Port: " + tcpHeader.SourcePort);
            tcpTreeViewItem.Items.Add("Destination Port: " + tcpHeader.DestinationPort);
            tcpTreeViewItem.Items.Add("Sequence Number: " + tcpHeader.SequenceNumber);
            if (tcpHeader.AcknowledgementNumber != "")
            {
                tcpTreeViewItem.Items.Add("Acknowledgement Number: " + tcpHeader.AcknowledgementNumber);
            }
            tcpTreeViewItem.Items.Add("Header Length: " + tcpHeader.HeaderLength);
            tcpTreeViewItem.Items.Add("Flags: " + tcpHeader.Flags);
            tcpTreeViewItem.Items.Add("Window Size: " + tcpHeader.WindowSize);
            tcpTreeViewItem.Items.Add("Checksum: " + tcpHeader.Checksum);
            if (tcpHeader.UrgentPointer != "")
            {
                tcpTreeViewItem.Items.Add("Urgent Pointer: " + tcpHeader.UrgentPointer);
            }
            return tcpTreeViewItem;
        }

        public static TreeViewItem MakeUDPTreeViewItem(UDPHeader udpHeader)
        {
            var udpTreeViewItem = new TreeViewItem();
            udpTreeViewItem.Header = "UDP";
            udpTreeViewItem.Items.Add("Source Port: " + udpHeader.SourcePort);
            udpTreeViewItem.Items.Add("Destination Port: " + udpHeader.DestinationPort);
            udpTreeViewItem.Items.Add("Length: " + udpHeader.Length);
            udpTreeViewItem.Items.Add("Checksum: " + udpHeader.Checksum);
            return udpTreeViewItem;
        }

        public static TreeViewItem MakeDNSTreeViewItem(byte[] byteData, int nLength)
        {
            var dnsHeader = new DNSHeader(byteData, nLength);
            var dnsTreeViewItem = new TreeViewItem();
            dnsTreeViewItem.Header = "DNS";
            dnsTreeViewItem.Items.Add("Identification: " + dnsHeader.Identification);
            dnsTreeViewItem.Items.Add("Flags: " + dnsHeader.Flags);
            dnsTreeViewItem.Items.Add("Questions: " + dnsHeader.TotalQuestions);
            dnsTreeViewItem.Items.Add("Answer RRs: " + dnsHeader.TotalAnswerRR);
            dnsTreeViewItem.Items.Add("Authority RRs: " + dnsHeader.TotalAuthorityRR);
            dnsTreeViewItem.Items.Add("Additional RRs: " + dnsHeader.TotalAdditionalRR);
            return dnsTreeViewItem;
        }

        public static void AddTreeViewItem(TreeViewItem node)
        {
            DispatcherHelper.Invoke(() => MainWindow.View.SnifferTV.Items.Add(node));
        }
    }
}


text:
// RBUserIOData.h: interface for the RBUserIOData class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_RBUSERIODATA_H__17FCA64D_AA0A_4179_8D16_B9085089E38B__INCLUDED_)
#define AFX_RBUSERIODATA_H__17FCA64D_AA0A_4179_8D16_B9085089E38B__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include <string>

using namespace std;

#define MAX_SIZE_X 1000
#define MAX_SIZE_Y 1000
#define MAX_NUMBER_OF_CONTROLS   1000

typedef struct
{
   int nPosX;
   int nPosY;
   int nWidth;
   int nHeight;
   int nMinValue;
   int nMaxValue;
   int nValue;
   string strLabel;
} structSliderSetup;

typedef struct
{
   int nPosX;
   int nPosY;
   bool bValue;
   string strLabel;
} structCheckBoxSetup;

typedef struct
{
   int nPosX;
   int nPosY;
   int nWidthInChars;
   bool bNewData;
   string strValue;
} structLabelSetup;

typedef struct
{
   int nPosX;
   int nPosY;
   int nWidth;
   int nHeight;
   bool bNewData;
	string strData;
   string strLabels;
} structOutputListSetup;

typedef struct
{
   int nPosX;
   int nPosY;
   int nWidth;
	string strData;
   string strLabel;
} structEditSetup;

typedef struct
{
   int nPosX;
   int nPosY;
	int nWidth;
	int nHeight;
   bool bClicked;
   string strLabel;
} structButtonSetup;

/*
typedef struct
{
   int nPosX;
   int nPosY;
   int nSideLength;
   string strLabel;
	bool bNewData;
	double dXValue;
	double dYValue;
} structChartSetup;*/

enum {
	NO_RBUSERIODATA_ERROR,
   ERROR_INVALID_POSX, // The position should be between 0 and MAX_SIZE_X
   ERROR_INVALID_POSY, // The position should be between 0 and MAX_SIZE_Y
   ERROR_INVALID_WIDTH, // The width should be between 0 and MAX_SIZE_X
   ERROR_INVALID_HEIGHT, // The height should be between 0 and MAX_SIZE_Y
   ERROR_INVALID_CONTROL_INDEX, // The specified index is not valid.  It must be 0 to the
      // number of controls specified
   ERROR_INVALID_NUMBER_OF_CONTROLS, // The number of controls (slider, chart, etc.)
      // must be 0 to MAX_NUMBER_OF_CONTROLS
	ERROR_NO_NEW_DATA, // New was attempted to be retrieved, but there is no
		// new data - consequently, the call is not necessary
   ERROR_SETUP_LOCKED // The setup was attempted to be changed after it was locked by
		// RobotBuilder

};

class RBUserIOData
{
public:
	int GetLastError () const;
	void CleanUp ();
/*	// Charts
   bool GetNewChartData (int nIndex, double &rdX, double &rdY);
	bool SetNewChartData (int nIndex, double dX, double dY);
	bool GetChartSetup (int nIndex, structChartSetup* pstrtChartSetup);
	int GetNumberOfCharts () const;
	bool SetupChart (int nIndex, int nPosX, int nPosY, int nSideLength, string strLabel);
	bool SetNumberOfCharts (int nNumber);
	bool IsThereNewChartData (int nIndex, bool &rbNewData); */

	// Sliders
   bool GetSliderValue (int nIndex, int &rnValue);
	bool SetSliderValue (int nIndex, int nValue);
	bool GetSliderSetup (int nIndex, structSliderSetup* pstrtSliderSetup);
	int GetNumberOfSliders () const;
	bool SetupSlider (int nIndex, int nPosX, int nPosY, int nWidth, int nHeight, int nMinValue, int nMaxValue, int nInitalValue, string strLabel);
	bool SetNumberOfSliders (int nNumber);

   // Check box
   bool GetCheckBoxValue (int nIndex, bool &rbValue);
	bool SetCheckBoxValue (int nIndex, bool bValue);
	bool GetCheckBoxSetup (int nIndex, structCheckBoxSetup* pstrtCheckBoxSetup);
	int GetNumberOfCheckBoxes () const;
	bool SetupCheckBox (int nIndex, int nPosX, int nPosY, bool bInitalValue, string strLabel);
	bool SetNumberOfCheckBoxes (int nNumber);

   // Edit box
   bool GetEditValue (int nIndex, string &rstrValue);
	bool SetEditValue (int nIndex, string strValue);
	bool GetEditSetup (int nIndex, structEditSetup* pstrtEditSetup);
	int GetNumberOfEdits () const;
	bool SetupEdit (int nIndex, int nPosX, int nPosY, int nWidth, string strInitialData, string strLabel);
	bool SetNumberOfEdits (int nNumber);

   // Button
   bool GetButtonClicked (int nIndex, bool &rbClicked);
	bool SetButtonClicked (int nIndex);
	bool GetButtonSetup (int nIndex, structButtonSetup* pstrtButtonSetup);
	int GetNumberOfButtons () const;
	bool SetupButton (int nIndex, int nPosX, int nPosY, int nWidth, int nHeight, string strLabel);
	bool SetNumberOfButtons (int nNumber);

	// Label
   bool GetLabelValue (int nIndex, string &rstrValue);
	bool SetLabelValue (int nIndex, string strValue);
	bool GetLabelSetup (int nIndex, structLabelSetup* pstrtLabelSetup);
	int GetNumberOfLabels () const;
	bool SetupLabel (int nIndex, int nPosX, int nPosY, int nWidthInChars, string strInitalValue);
	bool SetNumberOfLabels (int nNumber);
   bool IsThereNewLabelData (int nIndex, bool &rbNewData);

   // Output List
   bool GetOutputListData (int nIndex, string &rstrData);
	bool SetOutputListData (int nIndex, string strData);
	bool GetOutputListSetup (int nIndex, structOutputListSetup* pstrtOutputListSetup);
	int GetNumberOfOutputLists () const;
	bool SetupOutputList (int nIndex, int nPosX, int nPosY, int nWidth, int nHeight,
      string strLabels);
	bool SetNumberOfOutputLists (int nNumber);
   bool IsThereNewOutputListData (int nIndex, bool &rbNewData);

	// Project Directory
	string GetProjectDirectory () const;
	void SetProjectDirectory (string strDirectory);

	void LockSettingsData ();
//	int GetNumberOfOutputWindows () const;
//	void SetNumberOfOutputWindows (int nNumber);
	RBUserIOData();
	virtual ~RBUserIOData();

private:
//	structChartSetup* m_pstrtChartSetup;
//	int m_nNumberOfCharts;
   structButtonSetup* m_pstrtButtonSetup;
	int m_nNumberOfButtons;
   structEditSetup* m_pstrtEditSetup;
	int m_nNumberOfEdits;
   structOutputListSetup* m_pstrtOutputListSetup;
	int m_nNumberOfOutputLists;
   structLabelSetup* m_pstrtLabelSetup;
	int m_nNumberOfLabels;
   structCheckBoxSetup* m_pstrtCheckBoxSetup;
	int m_nNumberOfCheckBoxes;
	structSliderSetup* m_pstrtSliderSetup;
	int m_nNumberOfSliders;
	bool m_bLockSettingsData;
	int m_nNumberOfOutputWindows;
   int m_nLastError;

	string m_strProjectDirectory;
};

#endif // !defined(AFX_RBUSERIODATA_H__17FCA64D_AA0A_4179_8D16_B9085089E38B__INCLUDED_)


text:
import unittest
from test.tools.mock_descriptors import make_enum
from google.protobuf import descriptor_pb2

class EnumTest(unittest.TestCase):
    def test_basic_properties(self):
        enum = make_enum("Foo")
        self.assertEqual(enum.name, "Foo")
        self.assertEqual(enum.proto_file_name, "foo")
        self.assertEqual(enum.path, ())
        self.assertEqual(
            enum.source_code_line,
            -1,
        )
        self.assertEqual(enum.full_name, ".example.foo.enum")

    def test_enum_value_properties(self):
        enum_type = make_enum(
            name="Irrelevant",
            values=(
                ("RED", 1),
                ("GREEN", 2),
                ("BLUE", 3),
            ),
        )
        self.assertEqual(len(enum_type.values), 3)
        for ev, expected in zip(enum_type.values.values(), ("RED", "GREEN", "BLUE")):
            self.assertEqual(ev.name, expected)

    def test_source_code_properties(self):
        L = descriptor_pb2.SourceCodeInfo.Location
        # fmt: off
        locations = [L(path=(4, 0,), span=(1, 2, 3, 4))]
        enum = make_enum(
            name="Foo",
            proto_file_name="test.proto",
            locations=locations,
            path=(4, 0,),
        )

        # fmt: on
        self.assertEqual(enum.name, "Foo")
        self.assertEqual(enum.values, {})
        self.assertEqual(enum.proto_file_name, "test.proto")
        self.assertEqual(
            enum.source_code_line,
            2,
        )
        self.assertEqual(enum.path, (4, 0))

if __name__ == "__main__":
    unittest.main()


text:
std::ostream& operator<<(std::ostream& s, const vec3& p)
{
	return s << p.x << ' ' << p.y << ' ' << p.z;
}

String WavefrontObj::GetCommand() const
{
	return "wobj";
}

void WavefrontObj::PrintHelp() const
{
	std::cout << "Converts a Wavefront OBJ formatted geometry to Inanity geometry.\n";
	std::cout << "Optional with skin dronimal-formatted text file. Usage:\n";
	std::cout << "wobj <source .obj> <result .geo> [<skin text file>]\n";
}

void WavefrontObj::Run(const std::vector<String>& arguments)
{
	if(arguments.size() < 2)
		THROW("Must be at least 2 arguments for command");

	if(!freopen(arguments[0].c_str(), "r", stdin))
		THROW("Can't open source file");

	std::vector<int> positionNumbers;
	ptr<Graphics::EditableGeometry<Vertex, size_t> > geometry = WavefrontObj::Convert(positionNumbers);

	ptr<FileSystem> fileSystem = Platform::FileSystem::GetNativeFileSystem();

	if(arguments.size() >= 3)
	{
		std::vector<Vertex>& vertices = geometry->GetVertices();
		std::vector<SkinnedVertex> skinnedVertices(vertices.size());

		if(!freopen(arguments[2].c_str(), "r", stdin))
			THROW("Can't open skin file");

		// считать коэффициенты для кожи
		size_t skinVerticesCount;
		std::cin >> skinVerticesCount;

		struct SkinCoef
		{
			uint boneNumbers[4];
			float boneWeights[4];
			vec3 position;
		};
		std::vector<SkinCoef> skinCoefs(skinVerticesCount);

		std::vector<std::pair<float, int> > bones;
		for(size_t i = 0; i < skinVerticesCount; ++i)
		{
			// считать веса и номера костей
			size_t bonesCount;
			std::cin >> bonesCount;
			bones.resize(bonesCount);
			for(size_t j = 0; j < bonesCount; ++j)
				std::cin >> bones[j].second >> bones[j].first;
			std::sort(bones.begin(), bones.end());
			// если костей слишком много
			if(bones.size() > 4)
				// выбрать самые важные
				bones.erase(bones.begin(), bones.end() - 4);
			// если костей слишком мало, дополнить нулями
			while(bones.size() < 4)
				bones.push_back(std::make_pair(0.0f, 0));
			// нормализовать веса
			float weightsSum = 0;
			for(int j = 0; j < 4; ++j)
				weightsSum += bones[j].first;
			if(weightsSum <= 1e-8f)
				THROW("Bone with zero sum weight");
			float weightCoef = 1.0f / weightsSum;
			for(int j = 0; j < 4; ++j)
				bones[j].first *= weightCoef;

			// считать позицию для проверки
			vec3 position;
			std::cin >> position.x >> position.y >> position.z;

			// записать
			for(int j = 0; j < 4; ++j)
			{
				skinCoefs[i].boneNumbers[j] = bones[j].second;
				skinCoefs[i].boneWeights[j] = bones[j].first;
			}
			skinCoefs[i].position = position;
		}

		// сформировать вершины
		for(size_t i = 0; i < vertices.size(); ++i)
		{
			const Vertex& v = vertices[i];
			SkinnedVertex& sv = skinnedVertices[i];

			sv.position = v.position;
			sv.normal = v.normal;
			sv.texcoord = v.texcoord;

			int skinNumber = positionNumbers[i];
			const SkinCoef& skinCoef = skinCoefs[skinNumber];
			// проверить, что позиция совпадает
			if(fabs(length(sv.position - skinCoef.position)) > 1e-5f)
			{
				printf("Vertex %zu: position: %f %f %f, skin position: %f %f %f\n", i, sv.position.x, sv.position.y, sv.position.z,
					skinCoef.position.x, skinCoef.position.y, skinCoef.position.z);
			}
			for(int j = 0; j < 4; ++j)
			{
				sv.boneNumbers[j] = skinCoef.boneNumbers[j];
				sv.boneWeights[j] = skinCoef.boneWeights[j];
			}
		}

		ptr<Graphics::EditableGeometry<SkinnedVertex, size_t> > skinnedGeometry = NEW(Graphics::EditableGeometry<SkinnedVertex, size_t>(skinnedVertices, geometry->GetIndices()));

		ptr<Graphics::EditableGeometry<SkinnedVertex, uint16_t> > optimizedSkinnedGeometry = skinnedGeometry->Optimize()->CastIndices<uint16_t>();

		if(0)
		{
			const std::vector<SkinnedVertex>& vs = optimizedSkinnedGeometry->GetVertices();
			const std::vector<unsigned short>& is = optimizedSkinnedGeometry->GetIndices();
			for(size_t i = 0; i < vs.size(); ++i)
			{
				std::cout << vs[i].position;
				for(size_t j = 0; j < 4; ++j)
					std::cout << " (" << vs[i].boneNumbers[j] << ' ' << vs[i].boneWeights[j] << ")";
				std::cout << '\n';
			}
		}

		fileSystem->SaveFile(optimizedSkinnedGeometry->SerializeVertices(), arguments[1] + ".vertices");
		fileSystem->SaveFile(optimizedSkinnedGeometry->SerializeIndices(), arguments[1] + ".indices");
	}
	else
	{
		ptr<Graphics::EditableGeometry<Vertex, size_t> > optimizedGeometry = geometry->Optimize();
		if(optimizedGeometry->GetVertices().size() > 0x10000)
		{
			ptr<Graphics::EditableGeometry<Vertex, uint32_t> > typedGeometry = optimizedGeometry->CastIndices<uint32_t>();
			fileSystem->SaveFile(typedGeometry->SerializeVertices(), arguments[1] + ".vertices");
			fileSystem->SaveFile(typedGeometry->SerializeIndices(), arguments[1] + ".indices");
		}
		else
		{
			ptr<Graphics::EditableGeometry<Vertex, uint16_t> > typedGeometry = optimizedGeometry->CastIndices<uint16_t>();
			fileSystem->SaveFile(typedGeometry->SerializeVertices(), arguments[1] + ".vertices");
			fileSystem->SaveFile(typedGeometry->SerializeIndices(), arguments[1] + ".indices");
		}
	}
}

ptr<Graphics::EditableGeometry<Vertex, size_t> > WavefrontObj::Convert(std::vector<int>& positionNumbers)
{
	std::vector<vec3> points;
	std::vector<vec3> normals;
	std::vector<vec2> texPoints;
	std::string geometryName;
	std::vector<Vertex> vertices;

	//цикл по строкам файла
	char ss[1000];
	while(fgets(ss, sizeof(ss), stdin))
	{
		//если пустая, пропустить
		if(!ss[0]) continue;
		//если комментарий, пропустить
		if(isspace(ss[0]) || ss[0] == '#') continue;

		//считать первое слово (команду)
		std::stringstream s(ss);
		std::string command;
		s >> command;

		//вершина
		if(command == "v")
		{
			vec3 v;
			s >> v.x >> v.y >> v.z;
			points.push_back(v);
		}
		//нормаль к вершине
		else if(command == "vn")
		{
			vec3 v;
			s >> v.x >> v.y >> v.z;
			normals.push_back(v);
		}
		//текстурные координаты вершины
		else if(command == "vt")
		{
			vec3 v;
			s >> v.x >> v.y >> v.z;
			//развернуть ось Y, так как в максе начало координат текстуры внизу
			v.y = 1.0f - v.y;
			texPoints.push_back(vec2(v.x, v.y));
		}
		//название геометрии (хз зачем)
		else if(command == "g")
			s >> geometryName;
		//треугольник
		else if(command == "f")
		{
			char c;
			unsigned pointNumber, texPointNumber, normalNumber;
			unsigned i;
			for(i = 0; i < 3; ++i)
			{
				s >> pointNumber >> c >> texPointNumber >> c >> normalNumber;
				Vertex vertex;
				vertex.position = points[pointNumber - 1];
				vertex.normal = normals[normalNumber - 1];
				vertex.texcoord = texPoints[texPointNumber - 1];
				vertices.push_back(vertex);
				positionNumbers.push_back(pointNumber - 1);
			}
			//поменять порядок вершин (надо!)
			std::swap(vertices[vertices.size() - 1], vertices[vertices.size() - 3]);
			std::swap(positionNumbers[vertices.size() - 1], positionNumbers[vertices.size() - 3]);
		}
	}

	//создать модель, оптимизировать и вернуть
	return MakePointer(NEW(Graphics::EditableGeometry<Vertex, size_t>(vertices)));
}


text:
@class WYNewsChannelModel;

@interface WYChannelLabel : UILabel

@property (nonatomic, assign) CGFloat scale;

+ (instancetype)labelWithChannelModel:(WYNewsChannelModel*)channelModel;
@end


text:
package io.confluent.kafka.schemaregistry.rest.resources;

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

import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import io.confluent.kafka.schemaregistry.client.rest.Versions;

@Path("/")
@Produces(
    {Versions.SCHEMA_REGISTRY_V1_JSON_WEIGHTED, Versions.SCHEMA_REGISTRY_DEFAULT_JSON_WEIGHTED,
     Versions.JSON_WEIGHTED})
@Consumes({Versions.SCHEMA_REGISTRY_V1_JSON, Versions.SCHEMA_REGISTRY_DEFAULT_JSON,
           Versions.JSON, Versions.GENERIC_REQUEST})
public class RootResource {

  @GET
  public Map<String, String> get() {
    // Currently this just provides an endpoint that's a nop and can be used to check for
    // liveness and can be used for tests that need to test the server setup rather than the
    // functionality of a specific resource. Some APIs provide a listing of endpoints as their
    // root resource; it might be nice to provide that.
    return new HashMap<String, String>();
  }

  @POST
  public Map<String, String> post(@Valid Map<String, String> request) {
    // This version allows testing with posted entities
    return new HashMap<String, String>();
  }

}


text:
var cd = require('jquery-countdown');
var bc = require('./bootstrap-collection.js');

jQuery(document).ready(function($) {
	var el = $('[data-countdown-target]');
	if (!el.length) {
		return;
	}

	var d = el.data('countdown-target');
	el.countdown(d, function(e) {
	  $(this).html(
	  	'' + e.strftime('%w') + ' Hét' +
	  	'' + e.strftime('%d') + ' Nap' +
	  	'' + e.strftime('%H') + ' Óra' +
	  	'' + e.strftime('%M') + ' Perc' +
	  	'' + e.strftime('%S') + ' Mp.'
	  );
	});

	var mySwiper = new Swiper ('.swiper-container', {
	  // Optional parameters
	  autoplay: 3000,
	  loop: true,
    effect: 'fade',
	  // If we need pagination
	  pagination: '.swiper-pagination',

	  // Navigation arrows
	  nextButton: '.swiper-button-next',
	  prevButton: '.swiper-button-prev',

	})

});

var ESPCR = ESPCR || {};

function extend(destination, source) {
    var toString = Object.prototype.toString,
        objTest = toString.call({});
    for (var property in source) {
        if (source[property] && objTest == toString.call(source[property])) {
            destination[property] = destination[property] || {};
            extend(destination[property], source[property]);
        } else {
            destination[property] = source[property];
        }
    }
    return destination;
};

extend(ESPCR, {
  locationsMap:{
    init: function(){

      if(!$('.page-map').length) return false;

      this.createMap();

    },

    createMap: function(){
      var geocoder = new google.maps.Geocoder();
      var latlng = new google.maps.LatLng(47.8669915,19.978868,14);
      var mapOptions = {
        zoom: $("map-canvas").data('zoom'),
        center: latlng
      }
      map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

      var markers = [];

      var colors = ['e70000', 'dfe700', '5ce700', 'f99bcc', '0082e7', '2100e7', 'df00e7', ]
      var markerBounds = new google.maps.LatLngBounds();
      var infoWindows = [];

      $('.page-map .nav  li a').each(function(i){

        var address = $('small', this).text();
        var html = $(this).html();
        var $link = $(this)
        $(this).parent().css('border-left', '8px solid #' + colors[i])

        geocoder.geocode( { 'address': address}, function(results, status) {
// console.log(results[0].geometry.location.lng());
          var point = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng())

          if (status == google.maps.GeocoderStatus.OK) {

            var infoWindow = new google.maps.InfoWindow({
                content: html,
            });

            infoWindows.push(infoWindow);
             var marker = new google.maps.Marker({
               map: map,
              // icon: 'http://gmapsmarkergenerator.eu01.aws.af.cm/getmarker?scale=1&color=' + colors[i],
               position: point
             });

             markerBounds.extend(point);
             var infowindow = null;

             $link.mouseover(function(e){
              e.preventDefault();
              $('.page-map .nav  li').removeClass('active')
              $(this).parent().addClass('current')
              map.panTo(point);
              //map.setZoom(12);
              console.log(infoWindows)
              $.each(infoWindows,function(){
                this.close();
              })

              infoWindow.open(map, marker);

            })

             map.fitBounds(markerBounds);

              if(i==0 && $('.page-map .nav  li a').length == 1) {
               $link.click();
             };

          } else {
             alert('Geocode was not successful for the following reason: ' + status);
          }

        })

      });

    }
  }
});

extend(ESPCR, {

  customFormElements:{

    init: function(){
      $('input').iCheck({
        checkboxClass: 'icheckbox_minimal-grey',
        radioClass: 'iradio_minimal-grey',
      });

      $('input, select').removeAttr('required');
  //    $('select').selectpicker({

      // });

    }
  }
})

extend(ESPCR, {

  gmapsAutocomplete:{

    init: function(){
      if(!$('.gmaps-autocomplete').length) return false;

      var input = $('.gmaps-autocomplete').get(0);
      var autocomplete = new google.maps.places.Autocomplete(input);
      google.maps.event.addDomListener(input, 'keydown', function(e) {
        if (e.keyCode == 13) {
            e.preventDefault();
        }
      });

    }
  }
})

extend(ESPCR, {

  registrationForm:{

    init: function(){
      if(!$('form[name=eventRegistration]').length) return false;

      $('#mapModal').on('shown.bs.modal', this.onModalShown);
      $('form[name=eventRegistration] select').on('change', this.onPriceChanged);
      $('#eventRegistration_roomReservation_checkIn').on('changeDate', this.onPriceChanged);
      $('#eventRegistration_roomReservation_checkOut').on('changeDate', this.onPriceChanged);
      $('form[name=eventRegistration] input[type=checkbox]').on('ifChanged', this.onPriceChanged);
      $('form[name=eventRegistration] input[type=radio]').on('ifChecked', this.onPriceChanged);
      $('#eventRegistration_reservation_accomodation').on('ifChanged', this.onAccomodationSelected).change()
      $('input[name=selectedroom]').on('ifChanged', this.onRoomRadioChanged).trigger('ifChanged')
      $('table.room-table tr.room').click(this.onRoomTableRowClicked)
      $('.payment-method-tabs a[data-toggle="tab"]').on('shown.bs.tab', this.onPaymentTabShown)
      $('input[name="eventRegistration[paymentMethod]"]').on('ifChanged', this.onPaymentMethodRadioChanged)
      var selectedRoomId = $('#eventRegistration_roomReservation_room').val();
      if(selectedRoomId){
        $('table.room-table tr.room[data-id='+selectedRoomId+']').click()
      }else{
        $('table.room-table tr.room[data-id=""]').click()
      }

      $("form[name=eventRegistration] input").keypress(this.onEnterHit);

      this.onPriceChanged();

    },

    onModalShown: function(e){

      var accomodationName = $(e.relatedTarget).closest('tr').find('td.name b').text()
      var accomodationAddress = $(e.relatedTarget).closest('tr').find('td.name small').text()

      $('#mapModal .modal-title').text(accomodationName);

      ESPCR.registrationForm.showMap(accomodationAddress);

    },

    showMap: function(accomodationAddress){

      var map = new google.maps.Map($('#mapModal .modal-body').height(400).get(0), mapOptions);
      var geocoder = new google.maps.Geocoder();
      var mapOptions = {
        zoom: 12,
      }

      var baseLocation = new google.maps.Marker({
        position: {lng: 19.078370, lat: 47.481119},
        map: map,
        icon: 'http://gmapsmarkergenerator.eu01.aws.af.cm/getmarker?scale=2&color=cc5566'
      });

      geocoder.geocode( { 'address': accomodationAddress}, function(results, status) {

        var location = results[0].geometry.location;
        if (status == google.maps.GeocoderStatus.OK) {
           //  map.setCenter(results[0].geometry.location);
           var marker = new google.maps.Marker({
             map: map,
             position: results[0].geometry.location
           });

          map.panTo(location);
          // map.setCenter({lng: 19.071349599999962, lat: 47.482519});

           map.setZoom(16);

        } else {
           alert('Geocode was not successful for the following reason: ' + status);
        }

      })

    },

    onRoomTableRowClicked: function(){
      var v = $(this).data('id');

      v = !v ? null : v;

      $('#eventRegistration_roomReservation_room').val(v).change()
      $('tr', $(this).closest('table')).removeClass('selected')
      $(this).addClass('selected')
    },

    onAccomodationSelected:function() {

      if($(this).val())
        $('.accomodation-selected').show()
      else
        $('.accomodation-selected').hide()

    },

    onPaymentTabShown: function(){
      $('input[name="eventRegistration[paymentMethod]"][value='+$(this).data('value')+']').iCheck('check');
    },

    onPaymentMethodRadioChanged: function(){

      $('.payment-method-tabs a[data-value="'+$(this).val()+'"]').tab('show')
    },

    onEnterHit: function(event){
            if((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {

            $(".btn-success").click();

            return false;

            } else {

            return true;

            }

    },
    onPriceChanged: function(){

      var data = $('form[name=eventRegistration]').serializeArray();
      var url = $('form[name=eventRegistration]').data('calculate-url')

      jQuery.ajax({
        url: url,
        type: 'POST',
        dataType: 'html',
        data: data,

        complete: function(xhr, textStatus) {
          //called when complete
        },

        success: function(data, textStatus, xhr) {
                $('#calculation').html(data);
        },

        error: function(xhr, textStatus, errorThrown) {
          //called when there is an error
        }

      });

    }

  }

})

$(document).ready(function(){

  ESPCR.locationsMap.init();
  ESPCR.registrationForm.init();
  ESPCR.gmapsAutocomplete.init();
  ESPCR.customFormElements.init();

});


text:
use strict;
use warnings;

use Data::Dumper;
use File::Basename;

use lib File::Basename::dirname(__FILE__).'/../libs';
use Connect4::Game;
use Connect4::Board;
use Connect4::Player::Dumb;
use Connect4::Player::Human;
use Connect4::Player::Minimax;

my $board = Connect4::Board->new();

my $players = {
    'black' => 0,
    'red' => 0
};

foreach my $player ( keys %$players ) {

    print "Select Player $player type:\n".
          " 1) Human\n".
          " 2) Dumb\n".
          " 3) Minimax\n";
    my $type = <>;

    if ($type == 3) {
        $players->{$player} = Connect4::Player::Minimax->new();
    } elsif ($type == 2) {
        $players->{$player} = Connect4::Player::Dumb->new();
    } else {
        $players->{$player} = Connect4::Player::Human->new();
    }
}

my $game = Connect4::Game->new();
$game->setBoard($board);
$game->setPlayers($players->{'black'}, $players->{'red'});
$game->setBoardRendering(1);

$game->play();


text:
module BetfairApiNgRails
  module Api
    module Data
      class PlaceInstruction < Api::Data::Base
        include Api::Data::Concerns::Hashable

        PLACE_INSTRUCTION_ATTRS = [
          :order_type,
          :selection_id,
          :handicap,
          :side,
          { limit_order: { type: BetfairApiNgRails::LimitOrder } },
          { limit_on_close_order: { type: BetfairApiNgRails::LimitOnCloseOrder } },
          { market_on_close_order: { type: BetfairApiNgRails::MarketOnCloseOrder } }
        ]

        attributes PLACE_INSTRUCTION_ATTRS

        def self.to_hash_attrs
          PLACE_INSTRUCTION_ATTRS
        end
      end
    end
  end
end


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

namespace P02.Graphic_Editor
{
    public class Circle : IShape
    {
        public void Draw()
        {
            Console.WriteLine("I'm Circle");
        }
    }
}


text:
class CommandLine;

#include "base/string16.h"

string16 ReplaceLocalHostInName(const string16& user_name);
string16 GetCurrentUserName();
void CopyChromeSwitchesFromCurrentProcess(CommandLine* destination);

#endif  // CLOUD_PRINT_SERVICE_SERVICE_UTILS_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<doc>
  <assembly>
    <name>MbUnit35</name>
  </assembly>
  <members>
    <member name="T:MbUnit.Framework.AssertEx">
      <summary>Provides extended assertions for .Net 3.5. This class is <see langword="abstract" /> and so cannot be instantiated.</summary>
    </member>
    <member name="M:MbUnit.Framework.AssertEx.That(System.Linq.Expressions.Expression{System.Func{System.Boolean}})">
      <summary>
        <para> Verifies that a particular condition holds true. </para>
        <para> If the condition evaluates to false, the assertion failure message will describe in detail the intermediate value of relevant sub-expressions within the condition. Consequently the assertion failure will include more diagnostic information than if <see cref="M:MbUnit.Framework.Assert.IsTrue(System.Boolean)" /> were used instead. </para>
      </summary>
      <param name="condition">The conditional expression to evaluate</param>
      <exception cref="T:System.ArgumentNullException">Thrown if <paramref name="condition" /> is null</exception>
      <exception cref="T:Gallio.Framework.Assertions.AssertionException">Thrown if the verification failed unless the current <see cref="P:Gallio.Framework.Assertions.AssertionContext.AssertionFailureBehavior" /> indicates otherwise</exception>
    </member>
    <member name="M:MbUnit.Framework.AssertEx.That(System.Linq.Expressions.Expression{System.Func{System.Boolean}},System.String,System.Object[])">
      <summary>
        <para> Verifies that a particular condition holds true. </para>
        <para> If the condition evaluates to false, the assertion failure message will describe in detail the intermediate value of relevant sub-expressions within the condition. Consequently the assertion failure will include more diagnostic information than if <see cref="M:MbUnit.Framework.Assert.IsTrue(System.Boolean,System.String,System.Object[])" /> were used instead. </para>
      </summary>
      <param name="condition">The conditional expression to evaluate</param>
      <param name="messageFormat">The custom assertion message format, or null if none</param>
      <param name="messageArgs">The custom assertion message arguments, or null if none</param>
      <exception cref="T:System.ArgumentNullException">Thrown if <paramref name="condition" /> is null</exception>
      <exception cref="T:Gallio.Framework.Assertions.AssertionException">Thrown if the verification failed unless the current <see cref="P:Gallio.Framework.Assertions.AssertionContext.AssertionFailureBehavior" /> indicates otherwise</exception>
    </member>
  </members>
</doc>


text:
#include <pebble.h>

/* VARIABLES */
static Layer *s_battery_layer;

static int s_battery_level;
static bool s_battery_charging;

/* FUNCTIONS */
static void battery_update_proc(Layer *layer, GContext *ctx);
static void battery_callback(BatteryChargeState state);

void battery_init();
void battery_load(Layer*);
void battery_unload();


text:
require 'colored'

module Pod
  class TemplateConfigurator

    attr_reader :pod_name, :pods_for_podfile, :prefixes, :test_example_file, :username, :email

    def initialize(pod_name)
      @pod_name = pod_name
      @pods_for_podfile = []
      @prefixes = []
      @message_bank = MessageBank.new(self)
    end

    def ask(question)
      answer = ""
      loop do
        puts "\n#{question}?"

        @message_bank.show_prompt
        answer = gets.chomp

        break if answer.length > 0

        print "\nYou need to provide an answer."
      end
      answer
    end

    def ask_with_answers(question, possible_answers)

      print "\n#{question}? ["

      print_info = Proc.new {

        possible_answers_string = possible_answers.each_with_index do |answer, i|
           _answer = (i == 0) ? answer.underline : answer
           print " " + _answer
           print(" /") if i != possible_answers.length-1
        end
        print " ]\n"
      }
      print_info.call

      answer = ""

      loop do
        @message_bank.show_prompt
        answer = gets.downcase.chomp

        answer = "yes" if answer == "y"
        answer = "no" if answer == "n"

        # default to first answer
        if answer == ""
          answer = possible_answers[0].downcase
          print answer.yellow
        end

        break if possible_answers.map { |a| a.downcase }.include? answer

        print "\nPossible answers are ["
        print_info.call
      end

      answer
    end

    def run
      @message_bank.welcome_message

      ConfigureIOS.perform(configurator: self)

      replace_variables_in_files
      clean_template_files
      rename_template_files
      add_pods_to_podfile
      customise_prefix
      reinitialize_git_repo
      run_pod_install

      @message_bank.farewell_message
    end

    #----------------------------------------#

    def run_pod_install
      puts "\nRunning " + "pod install".magenta + " on your new library."
      puts ""

      Dir.chdir("Example") do
        system "pod install"
      end
    end

    def clean_template_files
      ["./**/.gitkeep", "configure", "_CONFIGURE.rb", "README.md", "LICENSE", "templates", "setup"].each do |asset|
        `rm -rf #{asset}`
      end
    end

    def replace_variables_in_files
      file_names = ['POD_LICENSE', 'POD_README.md', 'NAME.podspec', '.travis.yml', podfile_path]
      file_names.each do |file_name|
        text = File.read(file_name)
        text.gsub!("${POD_NAME}", @pod_name)
        text.gsub!("${REPO_NAME}", @pod_name.gsub('+', '-'))
        text.gsub!("${USER_NAME}", user_name)
        text.gsub!("${USER_EMAIL}", user_email)
        text.gsub!("${YEAR}", year)
        text.gsub!("${DATE}", date)
        File.open(file_name, "w") { |file| file.puts text }
      end
    end

    def add_pod_to_podfile podname
      @pods_for_podfile << podname
    end

    def add_pods_to_podfile
      podfile = File.read podfile_path
      podfile_content = @pods_for_podfile.map do |pod|
        "pod '" + pod + "'"
      end.join("\n  ")
      podfile.gsub!("${INCLUDED_PODS}", podfile_content)
      File.open(podfile_path, "w") { |file| file.puts podfile }
    end

    def add_line_to_pch line
      @prefixes << line
    end

    def customise_prefix
      prefix_path = "Example/Tests/Tests-Prefix.pch"
      pch = File.read prefix_path
      pch.gsub!("${INCLUDED_PREFIXES}", @prefixes.join("\n  ") )
      File.open(prefix_path, "w") { |file| file.puts pch }
    end

    def set_test_framework(test_type)
      content_path = "setup/test_examples/" + test_type + ".m"
      tests_path = "templates/ios/Example/Tests/Tests.m"
      tests = File.read tests_path
      tests.gsub!("${TEST_EXAMPLE}", File.read(content_path) )
      File.open(tests_path, "w") { |file| file.puts tests }
    end

    def rename_template_files
      `mv POD_README.md README.md`
      `mv POD_LICENSE LICENSE`
      `mv NAME.podspec #{pod_name}.podspec`
    end

    def reinitialize_git_repo
      `rm -rf .git`
      `git init`
      `git add -A`
      `git commit -m "Initial commit"`
    end

    def validate_user_details
        return (user_email.length > 0) && (user_name.length > 0)
    end

    #----------------------------------------#

    def user_name
      (ENV['GIT_COMMITTER_NAME'] || `git config user.name`).strip
    end

    def user_email
      (ENV['GIT_COMMITTER_EMAIL'] || `git config user.email`).strip
    end

    def year
      Time.now.year.to_s
    end

    def date
      Time.now.strftime "%m/%d/%Y"
    end

    def podfile_path
      'Example/Podfile'
    end

    #----------------------------------------#
  end
end


text:
/**
 *
 * This file is part of the AircraftSimulator Project, written as
 * part of the assessment for CAB302, semester 1, 2016.
 *
 */
package asgn2Simulators;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import asgn2Aircraft.A380;
import asgn2Aircraft.Aircraft;
import asgn2Aircraft.AircraftException;
import asgn2Aircraft.B747;
import asgn2Aircraft.Bookings;
import asgn2Passengers.Passenger;
import asgn2Passengers.PassengerException;

/**
 * Flights is a utility class to hold a collection of Aircraft for a single day. Most of the methods
 * rely on those of {@link asgn2Aircraft.Aircraft}, visiting each aircraft in the daily flight list.
 *
 * @author hogan
 */
public class Flights {

	private List<Aircraft> daily;
	private Bookings counts;

	/**
	 * Constructor creates a defined set of daily services.
	 *
	 * @throws AircraftException if problems with arguments to the {@link asgn2Aircraft.Aircraft} constructor.
	 */
	public Flights(int time) throws AircraftException {
		this.daily = createDailyServices(time);
		this.counts = null;
	}

	/**
	 * Adds a Passenger to one of the aircraft in the flight list.
	 * Precondition is a call to {@link #seatsAvailable(Passenger)}
	 *
	 * @param p Passenger to be added
	 * @param time int time operation performed
	 * @throws AircraftException See {@link asgn2Aircraft.Aircraft#confirmBooking(Passenger, int)}
	 * @throws PassengerException See {@link asgn2Aircraft.Aircraft#confirmBooking(Passenger, int)}
	 */
	public void addPassenger(Passenger p,int time) throws AircraftException, PassengerException {
		for (Aircraft a : this.daily) {
			if (a.seatsAvailable(p)) {
				a.confirmBooking(p, time);
				break;
			}
		}
	}

	/**
	 * Cancel bookings across the daily schedule based on cancellation probability
	 *
	 * @param rng Random - the active random number generator object
	 * @param cancelProb double Bernoulli trial cancellation probability
	 * @param cancelTime int cancellation time
	 * @return List<Passenger> of cancelled passengers
	 * @throws PassengerException See {@link asgn2Aircraft.Aircraft#cancelBooking(Passenger, int)}
	 * @throws AircraftException See {@link asgn2Aircraft.Aircraft#cancelBooking(Passenger, int)}
	 */
	public List<Passenger> cancelBookings(Random rng,double cancelProb,int cancelTime) throws PassengerException, AircraftException {
		List<Passenger> cancelled = new ArrayList<Passenger>();
		for (Aircraft a : this.daily) {
			List<Passenger> passengers =  a.getPassengers();
			for (Passenger p : passengers) {
				if (Simulator.randomSuccess(rng, cancelProb)) {
					a.cancelBooking(p, cancelTime);
					cancelled.add(p);
				}
			}
		}
		return cancelled;
	}

	/**
	 * Flies passengers across the daily schedule
	 *
	 * @param time int time operation performed
	 * @throws PassengerException See {@link asgn2Aircraft.Aircraft#flyPassengers(int)}
	 */
	public void flyPassengers(int time) throws PassengerException {
		for (Aircraft a : this.daily) {
			a.flyPassengers(time);
		}
	}

	/**
	 * Get the total passenger counts, for each fare class, in total, and seats remaining
	 *
	 * @return Bookings object containing the counts
	 */
	public Bookings getCurrentCounts() {
		this.totalFlightCounts();
		return counts;
	}

	/**
	 * Wrapper to return the status fields of all aircraft in the schedule.
	 * Used primarily for logging.
	 * Note that status field includes state transitions
	 *
	 * @param time int current time step
	 * @return String concatenating Aircraft status information
	 */
	public String getStatus(int time) {
		String str = "";
		for (Aircraft a : this.daily) {
			str += a.getStatus(time);
		}
		return str;
	}

	/**
	 * Wrapper to return initial state information for all aircraft in the schedule.
	 * Used primarily for logging.
	 *
	 * @return String concatenating Aircraft initial state information
	 */
	public String initialState() {
		String str = "";
		for (Aircraft a : this.daily) {
			str += a.initialState() + "\n";
		}
		return str;
	}

	/**
	 * Given a Passenger, method determines whether there are seats available in that
	 * fare class across the daily schedule
	 *
	 * @param p Passenger to be Confirmed
	 * @return boolean true if seats in Class(p); false otherwise
	 */
	public boolean seatsAvailable(Passenger p) {
		boolean status = false;
		for (Aircraft a : this.daily) {
			if (a.seatsAvailable(p)) {
				status = true;
				break;
			}
		}
		return status;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		String str = "";
		for (Aircraft a : this.daily) {
			str += a.toString() + "\n";
		}
		return str;
	}

	/**
	 *  Method to upgrade Passengers to try to fill the aircraft seating.
	 *  Passengers are upgraded solely within their original aircraft. We do
	 *  not move passengers between flights in the schedule.
	 */
	public void upgradePassengers() {
		for (Aircraft a : this.daily) {
			a.upgradeBookings();
		}

	}

	/**
	 * Helper to create schedule
	 *
	 * @param time int departureTime used as index
	 * @return list of created Aircraft
	 * @throws AircraftException if problems with arguments to the  {@link asgn2Aircraft.Aircraft} constructor.
	 */
	private List<Aircraft> createDailyServices(int time) throws AircraftException {
		List<Aircraft> al = new ArrayList<Aircraft>();
		al.add(new A380("QF11",time));
		al.add(new A380("QF93",time));
		al.add(new B747("QF15",time));
		return al;
	}

	/**
	 * Helper to total passenger counts across all aircraft in the schedule
	 */
	private void totalFlightCounts() {
		this.counts = new Bookings(0,0,0,0,0,0);
		for (Aircraft a : this.daily) {
			Bookings b = a.getBookings();
			int first = this.counts.getNumFirst();
			this.counts.setNumFirst(first + b.getNumFirst());
			int business = this.counts.getNumBusiness();
			this.counts.setNumBusiness(business + b.getNumBusiness());
			int premium = this.counts.getNumPremium();
			this.counts.setNumPremium(premium + b.getNumPremium());
			int economy = this.counts.getNumEconomy();
			this.counts.setNumEconomy(economy + b.getNumEconomy());
			int total = this.counts.getTotal();
			this.counts.setTotal(total + b.getTotal());
			int available = this.counts.getAvailable();
			this.counts.setAvailable(available + b.getAvailable());
		}
	}
}