text:
import cv2
import numpy as np
import time
import openface
import time
# import socket
import subprocess
import logging
logger = logging.getLogger(__name__)

class GestureRecognizer(object):

    def __init__(self, config):
        # Starting with 100's to prevent error while masking
        self.config = config
        self.threshold = 2.5
        self.high_threshold = 3.5
        self.font = cv2.FONT_HERSHEY_SIMPLEX
        self.start_videocapture()
        self.align = openface.AlignDlib('/home/verna/openface/models/dlib/shape_predictor_68_face_landmarks.dat')
        self.net = openface.TorchNeuralNet('/home/verna/openface/models/openface/nn4.small2.v1.t7', 96)
        self.pos = config["modules"]["modules.gesture_recognizer"]["pos"]
        print(self.pos)
        self.size = config["modules"]["modules.gesture_recognizer"]["size"]

    def start_videocapture(self):
        self.fingers = 0
        self.light = False

        # Open Camera object
        self.cap = cv2.VideoCapture(0)

        # Decrease frame size
        self.cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 700)
        self.cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 500)

    def light_on(self, config):
        if self.light is True:
            return (True, True, True)
        else:
            return (False, False, False)

    def recognize_continuously(self):
        done = False
        while(self.cap.isOpened() and not done):
            # time.sleep(0.5)
            finger_queue = []

            # Do 20 videocaptures before changing the light switch
            for i in range(10):
                self.recognize_once()
                finger_queue.append(self.fingers)
                # Close the output video by pressing 'ESC'
                k = cv2.waitKey(5) & 0xFF
                if k == 27:
                    done = True
                    break

            # Change light if average number of fingers is higher than
            # threshold
            if finger_queue and np.mean(finger_queue) > self.threshold:
            #     self.light = not self.light

            # if self.light:
                self.send_msg(self.pos, self.size, (True, False, False))
            else:
                self.send_msg(self.pos, self.size, (False, False, False))

        self.cap.release()
        cv2.destroyAllWindows()

    def send_msg(self, pos, size, light_values, timeout=10):
        args = list(pos) + list(size) + list(light_values)
        print(args)
        signal = self.encode(*args)
        # message = bytes(signal)
        # print(repr(self.config['testing']))
        if self.config['testing']:
            logger.debug("Sending: {:0>32b}".format(signal))
            return

        ip = self.config['server_ip']
        port = self.config['server_port']

        # AF_INET: IPv4
        # SOCK_STREAM: TCP
        # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # s.settimeout(timeout)
        # s.connect((ip, port))
        # # message = signal.to_bytes(4, byteorder='big')
        # s.send(message)

        # # Receive a message (as part of TCP?) (and discard it)
        # s.recv(1000)
        # s.close()
        subprocess.call(['python3', 'send.py', str(signal)])

    @staticmethod
    def encode_color(color, n_bits):
        """
        If color is given as boolean, interpret it as maximally on or totally off.
        Otherwise check whether it fits within the number of bits.
        """
        if isinstance(color, bool):
            return (2 ** n_bits - 1) * color
        elif 0 <= color < 2 ** n_bits:
            return color
        else:
            raise ValueError(
                "`color` should be a boolean or be between 0 and 2 ** n_bits - 1"
            )

    def encode(self, xpos, ypos, width, height, red=True, green=True, blue=True,
           color_bits=4):
        """
        Given the position and color of the leds, encodes this information in an
        int of 3 bytes, which can be decoded using decode

        0 <= xpos <= 31: 5 bits
        0 <= ypos <= 15: 4 bits
        """

        # input validation first
        if not 0 <= xpos <= 31:
            print(xpos)
            raise ValueError('The x-position has to be between 0 and 31 inclusive'
                             'to fit the size of the board')
        elif not 0 <= ypos <= 15:
            raise ValueError('The y-position has to be between 0 and 15 inclusive'
                             'to fit the size of the board')
        elif width < 1:
            raise ValueError('The width value has to be higher than 0')
        elif height < 1:
            raise ValueError('The height value has to be higher than 0')
        elif width + xpos > 32:
            raise ValueError('The width and the x-position combined should not'
                             'go over the edge of the board')
        elif height + ypos > 16:
            raise ValueError('The height and the y-position combined should not'
                             'go over the edge of the board')

        width -= 1
        height -= 1
        signal = 0
        signal += xpos
        signal <<= 4    # size of ypos
        signal += ypos
        signal <<= 5    # size of width
        signal += width
        signal <<= 4    # size of height
        signal += height

        signal <<= color_bits    # size of colour bits
        signal += self.encode_color(red, color_bits)
        signal <<= color_bits    # size of colour bits
        signal += self.encode_color(green, color_bits)
        signal <<= color_bits    # size of colour bits
        signal += self.encode_color(blue, color_bits)

        return signal

    def recognize(self):
        self.recognize_once()
        self.cap.release()
        cv2.destroyAllWindows()

    def recognize_once(self):
        # Capture frames from the camera
        self.fingers = 0
        ret, frame = self.cap.read()

        # cv2.imwrite('img.png',frame)

        # Blur the image
        blur = cv2.blur(frame, (3, 3))

        # Convert to HSV color space
        hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)
        mask2 = cv2.inRange(hsv, np.array([0, 50, 50]),
                np.array([15, 255, 255]))

        # Cr > 150 && Cr < 200 && Cb > 100 && Cb < 150.

        # Create a binary image with where white will be skin colors and rest
        # is black

        # Kernel matrices for morphological transformation
        kernel_square = np.ones((11, 11), np.uint8)
        kernel_ellipse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))

        # Perform morphological transformations to filter out the background
        # noise
        # Dilation increase skin color area
        # Erosion increase skin color area
        dilation = cv2.dilate(mask2, kernel_ellipse, iterations=1)
        erosion = cv2.erode(dilation, kernel_square, iterations=1)
        dilation2 = cv2.dilate(erosion, kernel_ellipse, iterations=1)
        filtered = cv2.medianBlur(dilation2, 5)
        kernel_ellipse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (8, 8))
        dilation2 = cv2.dilate(filtered, kernel_ellipse, iterations=1)
        kernel_ellipse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
        dilation3 = cv2.dilate(filtered, kernel_ellipse, iterations=1)
        median = cv2.medianBlur(dilation2, 5)
        ret, thresh = cv2.threshold(median, 127, 255, 0)

        # Find contours of the filtered frame
        contours, hierarchy = cv2.findContours(
            thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

        poly = []

        if len(contours) > 0:
            # Find Max contour area (Assume that hand is in the frame)
            max_area = 100
            ci = 0
            cnts = []

            for i in range(len(contours)):
                cnt = contours[i]
                area = cv2.contourArea(cnt)

                # Find largest hand candidate that does not contain a face
                if(area > max_area and not self.check_for_face(cnt, frame)):
                    max_area = area
                    cnts = cnt

            #cnts = self.find_hand_contours(contours,frame)

            if len(cnts) > 0:

                X = [coordinates[0] for item in cnts for coordinates in item]
                Y = [coordinates[1] for item in cnts for coordinates in item]
                minY = min(Y)
                maxY = max(Y)
                minX = min(X)
                maxX = max(X)
                # hand = median[minY:maxY,minX:maxX]
                # cv2.imwrite('boe.png',hand)
                # apply_thinning(hand)

                # Contour approximation with Douglas-Peucker algorithm
                poly = cv2.approxPolyDP(cnts, 0.1, True)

                # Find convex hull and defects
                hull = cv2.convexHull(cnts)
                hull2 = cv2.convexHull(cnts, returnPoints=False)
                defects = cv2.convexityDefects(cnts, hull2)

                fingers = 0
                FarDefect = []
                if not defects is None:
                    # Get defect points and draw them in the original image
                    for i in range(defects.shape[0]):
                        s, e, f, d = defects[i, 0]
                        start = tuple(cnts[s][0])
                        end = tuple(cnts[e][0])

                        x, y = end
                        far = tuple(cnts[f][0])
                        dist = d
                        FarDefect.append(far)
                        hordist = maxX - minX
                        if dist > 30 * hordist and y < (1.5 * hordist):
                            fingers += 1
                            cv2.line(frame, start, end, [0, 255, 0], 1)
                            cv2.circle(frame, far, 10, [100, 255, 255], 3)

                if fingers > 5:
                    fingers = 5
                self.fingers = fingers

                # Print bounding rectangle
                x, y, w, h = cv2.boundingRect(cnts)
                img = cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

            else:
                self.fingers = 0

            # # Find moments of the largest contour
            # moments = cv2.moments(cnts)

            # Central mass of first order moments
            # if moments['m00'] != 0:
            #     cx = int(moments['m10']/moments['m00'])  # cx = M10/M00
            #     cy = int(moments['m01']/moments['m00'])  # cy = M01/M00
            # centerMass = (cx, cy)

            # # Draw center mass
            # cv2.circle(frame, centerMass, 7, [100, 0, 255], 2)

            # cv2.putText(frame, 'Center', tuple(centerMass),
            #             self.font, 2, (255, 255, 255), 2)

            # Distance from each finger defect(finger webbing) to the center
            # mass
            # distanceBetweenDefectsToCenter = []
            # for i in range(0, len(FarDefect)):
            #     x = np.array(FarDefect[i])
            #     centerMass = np.array(centerMass)
            #     distance = np.sqrt(
            #         np.power(x[0]-centerMass[0], 2) +
            #         np.power(x[1]-centerMass[1], 2))
            #     distanceBetweenDefectsToCenter.append(distance)

            # # Get an average of three shortest distances from finger webbing
            # # to center mass
            # sortedDefectsDistances = sorted(distanceBetweenDefectsToCenter)
            # AverageDefectDistance = np.mean(sortedDefectsDistances[0:2])

            # # Get fingertip points from contour hull
            # # If points are in proximity of 80 pixels, consider as a single
            # # point in the group
            # finger = []
            # proximity = 1.6 * AverageDefectDistance
            # for i in range(0, len(hull)-1):
            #     if (np.absolute(hull[i][0][0] - hull[i+1][0][0]) > proximity) \
            #     or (np.absolute(hull[i][0][1] - hull[i+1][0][1]) > proximity):
            #         if hull[i][0][1] < 500:
            #             finger.append(hull[i][0])

            # # The fingertip points are 5 hull points with largest y coordinates
            # finger = sorted(finger, key=lambda x: x[1])
            # fingers = finger[0:5]

            # Calculate distance of each finger tip to the center mass
            # fingerDistance = []
            # for i in range(0, len(fingers)):
            #     distance = np.sqrt(
            #         np.power(fingers[i][0]-centerMass[0], 2) +
            #         np.power(fingers[i][1]-centerMass[0], 2))
            #     fingerDistance.append(distance)

            # # Finger is pointed/raised if the distance of between fingertip to
            # # the center mass is larger than the distance of average finger
            # # webbing to center mass by 130 pixels
            # result = 0
            # for i in range(0, len(fingers)):
            #     if fingerDistance[i] > AverageDefectDistance + 130:
            #         result = result + 1
            #         cv2.putText(
            #             frame, 'finger', tuple(finger[i]), self.font, 2,
            #             (255, 255, 255), 2)

            # self.fingers = result

            if len(poly) > 0:
                cv2.drawContours(frame, [poly], -1, (255, 255, 255), 2)

            # Print number of pointed fingers
            cv2.putText(frame, str(self.fingers)+" fingers", (100, 100),
                        self.font, 2, (255, 255, 255), 2)
            cv2.imshow('Dilation', frame)

    def check_for_face(self, contours, frame):
        faces = []
        bb = False

        # Extract the x and y coordinates from the contours of possible hand
        X = [coordinates[0] for item in contours for coordinates in item]
        Y = [coordinates[1] for item in contours for coordinates in item]
        img = frame[min(Y):max(Y),min(X):max(X)]
        cv2.imwrite('face.png',img)

        # Look for faces in nonempty image
        if not len(img) == 0:
            rgbImg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            bb = self.align.getLargestFaceBoundingBox(rgbImg)
            # cv2.imwrite('face.png',img)

        return (not bb is None)

    # def find_hand_contours(self, contours, frame):
    #     largest = []
    #     largest_index = 0
    #     max_area = 100
    #     for i, current in enumerate(contours):
    #         area = cv2.contourArea(current)

    #         # Find largest hand candidate that does not contain a face
    #         if(area > max_area):
    #             max_area = area
    #             largest = current
    #             largest_index = i

    #     isface = self.check_for_face(largest,frame)
    #     if isface:
    #         del contours[largest_index]
    #         return self.find_hand_contours(contours,frame)
    #     else:
    #         return largest

if __name__ == "__main__":
    import yaml
    with open('../config.yml') as f:
        config = yaml.load(f)
    recog = GestureRecognizer(config)
    recog.recognize_continuously()


text:
Edit Ingest

        <form data-ng-submit="update()" novalidate>
            <fieldset>

                    Name

                        <input type="text" data-ng-model="ingest.name" id="name" class="form-control" placeholder="Name" required>

                    Description

                        <input type="text" data-ng-model="ingest.description" id="description" class="form-control" placeholder="Description" required>

                    Supplier

                        <ui-select ng-model="ingest.supplier" id="supplier" theme="bootstrap">
                            <ui-select-match placeholder="Choose supplier...">{{$select.selected.name}}</ui-select-match>
                            <ui-select-choices repeat="supplier._id as supplier in suppliers | filter:$select.search">
                                {{supplier.name}}
                            </ui-select-choices>
                        </ui-select>

                    Download Url

                        <input type="text" data-ng-model="ingest.downloadUrl" id="downloadUrl" class="form-control" placeholder="http://my.download.url" required>

Security Settings

                            SecurityType

                                <ui-select ng-model="ingest.securityType" id="securityType" theme="bootstrap">
                                    <ui-select-match placeholder="Choose security...">{{$select.selected}}</ui-select-match>
                                    <ui-select-choices repeat="type in ['none', 'formPost'] | filter:$select.search">
                                        {{type}}
                                    </ui-select-choices>
                                </ui-select>

                            Form Post Url

                                <input type="text" data-ng-model="ingest.formPostUrl" id="formPostUrl" class="form-control" placeholder="http://form.post.url" required>

                            Form Post Payload

                                <textarea data-ng-model="ingest.formPostPayload" id="formPostPayload" class="form-control" placeholder="key: value" required></textarea>

Parsing Settings

                            Field Map

                                <textarea data-ng-model="ingest.fieldMap" id="fieldMap" class="form-control" rows="5" placeholder="key: field" required></textarea>

Search And Scrape Settings

                            Search Url Template

                                <input type="text" data-ng-model="ingest.searchUrlTemplate" id="searchUrlTemplate" class="form-control" placeholder="http://form.get.url" required>

                            Search Selectors

                                <textarea data-ng-model="ingest.searchSelectors" id="searchSelectors" class="form-control" rows="5" placeholder="key: field" required></textarea>

                            Product Selectors

                                <textarea data-ng-model="ingest.productSelectors" id="productSelectors" class="form-control" rows="5" placeholder="key: field" required></textarea>

                    <input type="submit" value="Update" class="btn btn-default">

            </fieldset>
        </form>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>

<resource xmlns:flora="urn:flora:options">
    <!-- primary data source is defined twice -->
    <flora:dataSource type="mysql" database="db" table="t"/>
    <flora:dataSource type="mysql" database="db" table="t"/>
</resource>


text:
@implementation DDString

- (NSString *)description
{
    return @"1";
}

@end


text:
package com.jmelzer.myttr.activities;

import android.app.Activity;
import android.provider.CalendarContract;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import java.util.List;

/**
 * Adapter for the tabs in liga result.
 */
public class EventsTabsPagerAdapter extends FragmentPagerAdapter {
    List<CalendarContract.Events> events;
    Activity parentActivity;

    public EventsTabsPagerAdapter(FragmentManager fm, Activity activity) {
        super(fm);
        parentActivity = activity;
    }

    @Override
    public Fragment getItem(int index) {
        if (index == 1) {
            return new EventsTTRChartFragment();
        } else {
            return new EventsFragment();
        }
    }

    @Override
    public int getCount() {
        return 2;
    }
    @Override
    public CharSequence getPageTitle(int position) {
        return "OBJECT " + (position + 1);
    }
}


text:
<?php
return [
    'creationOk' => 'Ваш коментарий принят',
    'editionOk' => 'Коментарий отредактирован',

    'rootCreated' => 'Корневая категория создана',
    'rootAlreadyExist' => 'Корневая категория уже существует',
];


text:
#include "system.h"

namespace simulation
{
	/********************************************//**
	*-----------------SYSTEM OUTPUT------------------
	************************************************/

	void system::writeSystemXYZ(std::string name)
	{
		//Check if XYZ output is enabled.
		if (outXYZ > 0)
		{
			//Create a stream to the desired file.
			std::ofstream myFile;
			myFile.open(name + ".xyz");

			//Write xyz header
			myFile << nParticles << "\n";
			myFile << "Current Time: " << std::to_string(int(std::round(currentTime))) << "\n";

			//Write the particle positions in XYZ format, spoofing all particles as Hydrogen.
			for (int i =0; i < nParticles; i++)
			{
				myFile << "H " << particles[i].getX() << " " << particles[i].getY() << " " << particles[i].getZ() << "\n";
			}
		}
	}

	void system::writeSystem(std::string name)
	{
		//Create a stream to the desired file.
		std::ofstream myFile;
		myFile.open(name + ".txt");
		//Write each point in the system as a line of csv formatted as: X,Y,Z
		for (int i = 0; i < nParticles; i++)
		{
			myFile << particles[i].getX() << "," << particles[i].getY() << "," << particles[i].getZ() << ",";
			myFile << particles[i].getX0() << "," << particles[i].getY0() << "," << particles[i].getZ0() << ",";
			myFile << particles[i].getFX() << "," << particles[i].getFY() << "," << particles[i].getFZ() << ",";
			myFile << particles[i].getFX0() << "," << particles[i].getFY0() << "," << particles[i].getFZ0();
			if (i < (nParticles-1))
			{
				myFile << "\n";
			}
		}
		//Close the stream.
		myFile.close();
	}

	void system::writeInitTemp()
	{
		float v2 = 0.0;
		//Get V^2 for each particle.
		for (int i = 0; i < nParticles; i++)
		{
			v2 += particles[i].getVX()*particles[i].getVX();
			v2 += particles[i].getVY()*particles[i].getVY();
			v2 += particles[i].getVZ()*particles[i].getVZ();
		}
		//Average v2.
		float vAvg = v2 / float(nParticles);
		float temp = (vAvg / 3.0);
		//
		std::cout << "---Temp: " << temp << " m/k" << "\n";
	}

	void system::writeSystemInit()
	{
		std::ofstream myFile;
		myFile.open(trialName + "/sysConfig.txt");

		//Writes the system configuration.
		myFile << "trialName: " << trialName << "\n";
		myFile << "nParticles: " << nParticles << "\n";
		myFile << "Concentration: " << concentration << "\n";
		myFile << "boxSize: " << boxSize << "\n";
		myFile << "cellSize: " << cellSize << "\n";
		myFile << "cellScale: " << cellScale << "\n";
		myFile << "temp: " << temp << "\n";
		myFile << "dTime: " << dTime;

		//Close the stream.
		myFile.close();
	}

	void system::writeSystemState(debugging::timer* tmr)
	{
		//Update the console.
		std::string outName = std::to_string(int(std::round(currentTime)));
		utilities::util::setTerminalColour(utilities::Colour::Cyan);
		std::cout << "\n\n" << "Writing: " << outName << ".txt";
		utilities::util::setTerminalColour(utilities::Colour::Normal);

		//Write the recovery image.
		std::string dirName = trialName + "/snapshots/time-" + outName;
		mkdir(dirName.c_str(),0777);
		writeSystem(dirName + "/recovery");

		//Write the XYZ image.
		std::string movName = trialName + "/movie/system-" + outName;
		writeSystemXYZ(movName);

		//Calculate the perfomance.
		tmr->stop();
		float timePerCycle = tmr->getElapsedSeconds() / float(outputFreq);
		std::setprecision(4);
		std::cout << "\n" << "Average Cycle Time: " << timePerCycle << " seconds.\n";
		float totalTime = (cycleHour*timePerCycle);
		float finishedTime = ((currentTime/dTime) / 3600) * timePerCycle;
		std::cout << "Time for completion: " << (totalTime-finishedTime) << " hours.\n";
		tmr->start();

		//Average coordination number and potential.
		int totCoor = 0;
		int totEAP = 0;
		for (int i=0; i<nParticles; i++)
		{
			totCoor+=particles[i].getCoorNumber();
			totEAP+=particles[i].getPotential();
		}

		float eap = (totEAP / float(nParticles));
		//float nClust = numClusters(outXYZ);
		float avgCoor = float(totCoor) / float(nParticles);

		//Output the current system statistics.
		std::cout <<"\n<R>: " << avgCoor << " - Rt: " << totCoor << "\n";
		std::cout <<"<EAP>: " << eap << "\n";
		//std::cout <<"<N>/Nc: " << nClust << "\n";
		std::cout <<"Temperature: " << getTemperature() << "\n";

		//Output the number of clusters with time.
		//std::ofstream myFileClust(trialName + "/clustGraph.txt", std::ios_base::app | std::ios_base::out);
		//myFileClust << currentTime << " " << nClust << "\n";
		//myFileClust.close();

		//Output the average potential with time.
		std::ofstream myFilePot(trialName + "/potGraph.txt", std::ios_base::app | std::ios_base::out);
		myFilePot << currentTime << " " << eap << "\n";
		myFilePot.close();

		//Output the coordination number with time
		std::ofstream myFileCoor(trialName + "/coorGraph.txt", std::ios_base::app | std::ios_base::out);
		myFileCoor << currentTime << " " << avgCoor << "\n";
		myFileCoor.clear();
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
   Copyright 2013 Oto Soares Coelho Junior

   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.
 -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.otojunior.archetype</groupId>
	<artifactId>jee-app-enterprise-archetype</artifactId>
	<version>1.6-SNAPSHOT</version>
	<packaging>jar</packaging>

	<prerequisites>
		<maven>3.0.5</maven>
	</prerequisites>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

		<plugin.version.buildnumber-maven-plugin>1.4</plugin.version.buildnumber-maven-plugin>
		<plugin.version.maven-compiler-plugin>3.7.0</plugin.version.maven-compiler-plugin>
		<plugin.version.maven-jar-plugin>3.0.2</plugin.version.maven-jar-plugin>
		<plugin.version.maven-release-plugin>2.5.3</plugin.version.maven-release-plugin>
		<plugin.version.maven-source-plugin>3.0.1</plugin.version.maven-source-plugin>
		<plugin.version.maven-javadoc-plugin>2.10.4</plugin.version.maven-javadoc-plugin>
		<plugin.version.maven-surefire-plugin>2.20.1</plugin.version.maven-surefire-plugin>
		<plugin.version.jacoco-maven-plugin>0.7.9</plugin.version.jacoco-maven-plugin>

		<config.version.java>1.8</config.version.java>
	</properties>

	<scm>
		<connection>scm:git:https://github.com/otojunior/jee-app-enterprise-archetype.git</connection>
		<developerConnection>scm:git:git@github.com:otojunior/jee-app-enterprise-archetype.git</developerConnection>
		<tag>HEAD</tag>
	</scm>

	<distributionManagement>
		<snapshotRepository>
			<id>mvnrepo-snapshot-${project.artifactId}</id>
			<url>file://${project.build.directory}/mvn-repo/snapshot</url>
		</snapshotRepository>
		<repository>
			<id>mvnrepo-release-${project.artifactId}</id>
			<url>file://${project.build.directory}/mvn-repo/release</url>
		</repository>
	</distributionManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>buildnumber-maven-plugin</artifactId>
				<version>${plugin.version.buildnumber-maven-plugin}</version>
				<executions>
					<execution>
						<phase>validate</phase>
						<goals>
							<goal>create</goal>
						</goals>
					</execution>
				</executions>
				<configuration>
					<revisionOnScmFailure>true</revisionOnScmFailure>
					<shortRevisionLength>8</shortRevisionLength>
					<timestampFormat>{0,date,dd/MM/yyyy HH:mm:ss}</timestampFormat>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${plugin.version.maven-compiler-plugin}</version>
				<configuration>
					<!-- http://maven.apache.org/plugins/maven-compiler-plugin/ -->
					<source>${config.version.java}</source>
					<target>${config.version.java}</target>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>${plugin.version.maven-jar-plugin}</version>
				<configuration>
					<archive>
						<manifest>
							<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
							<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
						</manifest>
						<manifestEntries>
							<Implementation-Build>${buildNumber}</Implementation-Build>
							<Implementation-Branch>${scmBranch}</Implementation-Branch>
							<Implementation-Date>${timestamp}</Implementation-Date>
						</manifestEntries>
					</archive>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-release-plugin</artifactId>
				<version>${plugin.version.maven-release-plugin}</version>
				<configuration>
					<tagNameFormat>v@{project.version}</tagNameFormat>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<version>${plugin.version.maven-source-plugin}</version>
				<executions>
					<execution>
						<id>attach-sources</id>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>${plugin.version.maven-javadoc-plugin}</version>
				<executions>
					<execution>
						<id>attach-javadocs</id>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>${plugin.version.maven-surefire-plugin}</version>
			</plugin>

			<plugin>
				<groupId>org.jacoco</groupId>
			    <artifactId>jacoco-maven-plugin</artifactId>
			    <version>${plugin.version.jacoco-maven-plugin}</version>
			    <executions>
			    	<execution>
			    		<id>id-jacoco-prepare-agent</id>
			    		<goals>
			    			<goal>prepare-agent</goal>
			    		</goals>
			    	</execution>
			    	<execution>
			    		<id>id-jacoco-report</id>
			    		<phase>package</phase>
			    		<goals>
			    			<goal>report</goal>
			    		</goals>
			    	</execution>
			    </executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
import React from 'react';
import PropTypes from 'prop-types';
import {GridLayer, withLeaflet} from 'react-leaflet';
import {bingLayer} from './leaflet.bing';

class BingLayer extends GridLayer {
  static propTypes = {
    bingkey: PropTypes.string.isRequired
  };

  createLeafletElement(props) {
    return L.bingLayer(props.bingkey, this.getOptions(props));
  }
}

export default withLeaflet(BingLayer);


text:
CHANGELOG
=========

5.4.0
-----

 * Deprecate `Comparator::setTarget()` and `Comparator::setOperator()`
 * Add a constructor to `Comparator` that allows setting target and operator
 * Finder's iterator has now `Symfony\Component\Finder\SplFileInfo` inner type specified
 * Add recursive .gitignore files support

5.0.0
-----

 * added `$useNaturalSort` argument to `Finder::sortByName()`

4.3.0
-----

 * added Finder::ignoreVCSIgnored() to ignore files based on rules listed in .gitignore

4.2.0
-----

 * added $useNaturalSort option to Finder::sortByName() method
 * the `Finder::sortByName()` method will have a new `$useNaturalSort`
   argument in version 5.0, not defining it is deprecated
 * added `Finder::reverseSorting()` to reverse the sorting

4.0.0
-----

 * removed `ExceptionInterface`
 * removed `Symfony\Component\Finder\Iterator\FilterIterator`

3.4.0
-----

 * deprecated `Symfony\Component\Finder\Iterator\FilterIterator`
 * added Finder::hasResults() method to check if any results were found

3.3.0
-----

 * added double-star matching to Glob::toRegex()

3.0.0
-----

 * removed deprecated classes

2.8.0
-----

 * deprecated adapters and related classes

2.5.0
-----
 * added support for GLOB_BRACE in the paths passed to Finder::in()

2.3.0
-----

 * added a way to ignore unreadable directories (via Finder::ignoreUnreadableDirs())
 * unified the way subfolders that are not executable are handled by always throwing an AccessDeniedException exception

2.2.0
-----

 * added Finder::path() and Finder::notPath() methods
 * added finder adapters to improve performance on specific platforms
 * added support for wildcard characters (glob patterns) in the paths passed
   to Finder::in()

2.1.0
-----

 * added Finder::sortByAccessedTime(), Finder::sortByChangedTime(), and
   Finder::sortByModifiedTime()
 * added Countable to Finder
 * added support for an array of directories as an argument to
   Finder::exclude()
 * added searching based on the file content via Finder::contains() and
   Finder::notContains()
 * added support for the != operator in the Comparator
 * [BC BREAK] filter expressions (used for file name and content) are no more
   considered as regexps but glob patterns when they are enclosed in '*' or '?'


text:
/**
 * Retrieves the value of the given key from an object.
 *
 * @function Phaser.Tweens.Builders.GetBoolean
 * @since 3.0.0
 *
 * @param {object} source - The object to retrieve the value from.
 * @param {string} key - The key to look for in the `source` object.
 * @param {*} defaultValue - The default value to return if the `key` doesn't exist or if no `source` object is provided.
 *
 * @return {*} The retrieved value.
 */
var GetBoolean = function (source, key, defaultValue)
{
    if (!source)
    {
        return defaultValue;
    }
    else if (source.hasOwnProperty(key))
    {
        return source[key];
    }
    else
    {
        return defaultValue;
    }
};

module.exports = GetBoolean;


text:
'use strict';

var assert = require('chai').assert;

var parse = require('./../../../src/parse');
var UserError = require('./../../../src/error/UserError');

describe('parse/unit', function () {

  it('should extract controller', function () {
    var source =
    "angular" +
    " .module('test', [])" +
    " .controller('TestController', function ($scope) {});";

    var units = parse(source);

    assert.deepEqual(units, [{
      type: 'controller',
      name: 'TestController',
      module: { name: 'test' },
      deps: [{ name: '$scope' }]
    }]);
  });

  it('should extract controller from IIFE', function () {
    var source =
    "(function () {" +
    " angular" +
    "   .module('test', [])" +
    "   .controller('TestController', function ($scope) {});" +
    "}())";

    var units = parse(source);

    assert.deepEqual(units, [{
      type: 'controller',
      name: 'TestController',
      module: { name: 'test' },
      deps: [{ name: '$scope' }]
    }]);
  });

  it('should extract multiple controllers for one module', function () {
    var source =
    "angular.module('test', [])" +
    ".controller('Test1Controller', function () {})" +
    ".controller('Test2Controller', function () {})" +
    ".controller('Test3Controller', function () {})";

    var units = parse(source);

    assert.deepEqual(units, [{
      type: 'controller',
      name: 'Test1Controller',
      module: { name: 'test' },
      deps: []
    }, {
      type: 'controller',
      name: 'Test2Controller',
      module: { name: 'test' },
      deps: []
    }, {
      type: 'controller',
      name: 'Test3Controller',
      module: { name: 'test' },
      deps: []
    }]);
  });

  it('should extract controller from a function declaration', function () {
    var source =
    "angular.module('test', []).controller('TestController', TestController);" +
    "function TestController($scope) {}";

    var units = parse(source);

    assert.deepEqual(units, [{
      type: 'controller',
      name: 'TestController',
      module: { name: 'test' },
      deps: [{ name: '$scope' }]
    }]);
  });

  it('should extract controller from a function expression', function () {
    var source =
    "angular.module('test', []).controller('TestController', TestController);" +
    "var TestController = function ($scope) {};"

    var units = parse(source);

    assert.deepEqual(units, [{
      type: 'controller',
      name: 'TestController',
      module: { name: 'test' },
      deps: [{ name: '$scope' }]
    }]);
  });

  it('should extract controller from a parent scope', function () {
    var source =
    "function TestController($scope) {}" +
    "(function () {" +
    "angular.module('test', []).controller('TestController', TestController);" +
    "}());";

    var units = parse(source);

    assert.deepEqual(units, [{
      type: 'controller',
      name: 'TestController',
      module: { name: 'test' },
      deps: [{ name: '$scope' }]
    }]);
  });

  it('should extract component', function () {
    var source =
    "angular" +
    " .module('test', [])" +
    " .component('TestComponent', {});";

    var units = parse(source);

    assert.deepEqual(units, [{
      type: 'component',
      name: 'TestComponent',
      module: { name: 'test' },
      deps: []
    }]);
  });

  it('should extract a service', function () {
    var source =
    "angular.module('test', [])" +
    ".service('TestService', function ($http) {});";

    var units = parse(source);

    assert.deepEqual(units, [{
      type: 'service',
      name: 'TestService',
      module: { name: 'test' },
      deps: [{ name: '$http' }]
    }]);
  });

  it('should extract directive', function () {
    var source =
    "angular.module('test', [])" +
    ".directive('TestDirective', function ($interval) {});";

    var units = parse(source);

    assert.deepEqual(units, [{
      type: 'directive',
      name: 'TestDirective',
      module: { name: 'test' },
      deps: [{ name: '$interval' }]
    }]);
  });

  it('should extract filter', function () {
    var source =
    "angular.module('test', [])" +
    ".filter('testFilter', function () {});";

    var units = parse(source);

    assert.deepEqual(units, [{
      type: 'filter',
      name: 'testFilter',
      module: { name: 'test' },
      deps: []
    }]);
  });

  it('should extract constant', function () {
    var source =
    "angular.module('test', [])" +
    ".constant('TEST', 'test');";

    var units = parse(source);

    assert.deepEqual(units, [{
      type: 'constant',
      name: 'TEST',
      module: { name: 'test' },
      deps: []
    }]);
  });

  it('should extract value', function () {
    var source =
    "angular.module('test', [])" +
    ".value('test', 'test');";

    var units = parse(source);

    assert.deepEqual(units, [{
      type: 'value',
      name: 'test',
      module: { name: 'test' },
      deps: []
    }]);
  });

  it('should not consider another function calls as units', function () {
    var source =
    "angular.module('test', [])" +
    ".controller('TestController', function () {" +
    " var a = [1,2,3].filter(function (n) {" +
    "   return n > 1;" +
    " });" +
    "})";

    var units = parse(source);

    assert.deepEqual(units, [{
      type: 'controller',
      name: 'TestController',
      module: { name: 'test' },
      deps: []
    }]);
  });

  it('should not include unit with unparsable name', function () {
    var source =
    "angular.module('test', [])" +
    ".controller(unknownVar, function () {});";

    var units = parse(source);

    assert.deepEqual(units, []);
  });

  it('should not include unit with unparsable module name', function () {
    var source =
    "angular.module(unknownVar, [])" +
    ".controller('TestController', function () {});";

    var units = parse(source);

    assert.deepEqual(units, []);
  });

  it('should not include unit with unparsable type', function () {
    var source =
    "angular.module('test', [])" +
    ".unknown('TestController', function () {});";

    var units = parse(source);

    assert.deepEqual(units, []);
  });

  it('should throw user error for invalid code', function () {
    var source = "angular.module('test' [])";

    var fn = function () { parse(source); };

    assert.throw(fn, UserError);
  });

  it('should throw user error for circular reference', function () {
    var source =
    "angular.module('test', [])" +
    ".service('TestService', function (TestService) {});";

    var fn = function () { parse(source); };

    assert.throw(fn, UserError);
  });

});


text:
var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');

gulp.task('build', function () {
    return browserify({
			entries: './source/js/main.js',
			extensions: ['.js', ''],
			debug: true
		})
    .transform(babelify.configure({
			presets: ['es2015']
		}))
		.bundle()
		.pipe(source('main.min.js'))
		.pipe(gulp.dest('dist/js'));
});

gulp.task('watch', function () {
  gulp.watch('source/js/**/*.js', ['build']);
  gulp.watch('source/js/**/*.es6', ['build']);
});

gulp.task('default', ['build', 'watch']);


text:
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
// import { RegisterComponent } from './login/register.component';
import { PaymentComponent } from './setting/payment.component';
import { ShippingComponent } from './setting/shipping.component';
import { LocalizationComponent } from './setting/localization.component';
import { SmtpComponent } from './setting/smtp.component';
import { CompanyComponent } from './setting/company.component';

import { AccountComponent } from './account/account.component';
import { MyInfoComponent } from './account/myinfo.component';
import { AttributesComponent } from './attribute/attributes.component';
import { TagComponent } from './tag/tag.component';
import { BrandComponent } from './brand/brand.component';
import { CategoryComponent } from './category/category.component';
import { CausalComponent } from './causal/causal.component';
import { RegistryComponent } from './registry/registry.component';
import { StoreComponent } from './store/store.component';
import { ProductsComponent } from './product/products.component';
import { ProductComponent } from './product/product.component';
import { ImportComponent } from './product/import.component';
import { StockComponent } from './product/stock.component';
import { MovementsComponent } from './movement/movements.component';
import { MovementComponent } from './movement/movement.component';
import { DocumentComponent } from './movement/document.component';
import { BarcodeComponent } from './movement/barcode.component';
import { InvoicesComponent } from './invoice/invoices.component';
import { InvoiceComponent } from './invoice/invoice.component';
import { InvoiceDocumentComponent } from './invoice/invoicedocument.component';
import { DeviceComponent } from './device/device.component';
import { ReportReceiptsComponent } from './report/receipts.component';
import { ReportSalesComponent } from './report/sales.component';
import { StatisticsComponent } from './report/statistics.component';
import { WhouseComponent } from './report/whouse.component';
import { AmazonComponent } from './setting/amazon.component';
import { RequestComponent } from './amazon/request.component';
import { CartComponent } from './cart/cart.component';

export const routes: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent, pathMatch: 'full' },
    { path: 'login', component: LoginComponent, pathMatch: 'full' },
    // { path: 'login/register', component: RegisterComponent, pathMatch: 'full' },
    { path: 'company', component: CompanyComponent, pathMatch: 'full' },
    { path: 'payment', component: PaymentComponent, pathMatch: 'full' },
    { path: 'shipping', component: ShippingComponent, pathMatch: 'full' },
    { path: 'smtp', component: SmtpComponent, pathMatch: 'full' },
    { path: 'localization', component: LocalizationComponent, pathMatch: 'full' },
    { path: 'account', component: AccountComponent, pathMatch: 'full' },
    { path: 'myinfo', component: MyInfoComponent, pathMatch: 'full' },
    { path: 'store', component: StoreComponent, pathMatch: 'full' },
    { path: 'brand', component: BrandComponent, pathMatch: 'full' },
    { path: 'category', component: CategoryComponent, pathMatch: 'full' },
    { path: 'attribute', component: AttributesComponent, pathMatch: 'full' },
    { path: 'tag', component: TagComponent, pathMatch: 'full' },
    { path: 'causal', component: CausalComponent, pathMatch: 'full' },
    { path: 'registry', component: RegistryComponent, pathMatch: 'full' },
    { path: 'product', component: ProductsComponent, pathMatch: 'full' },
    { path: 'product/:id', component: ProductComponent, pathMatch: 'full' },
    { path: 'product/:id/stock', component: StockComponent, pathMatch: 'full' },
    { path: 'movement', component: MovementsComponent, pathMatch: 'full' },
    { path: 'movement/:id', component: MovementComponent, pathMatch: 'full' },
    { path: 'movement/document/:id', component: DocumentComponent, pathMatch: 'full' },
    { path: 'movement/barcode/:id', component: BarcodeComponent, pathMatch: 'full' },
    { path: 'invoice', component: InvoicesComponent, pathMatch: 'full' },
    { path: 'invoice/:id', component: InvoiceComponent, pathMatch: 'full' },
    { path: 'invoice/document/:id', component: InvoiceDocumentComponent, pathMatch: 'full' },
    { path: 'device', component: DeviceComponent, pathMatch: 'full' },
    { path: 'report/receipts', component: ReportReceiptsComponent, pathMatch: 'full' },
    { path: 'report/sales', component: ReportSalesComponent, pathMatch: 'full' },
    { path: 'report/statistics', component: StatisticsComponent, pathMatch: 'full' },
    { path: 'report/whouse', component: WhouseComponent, pathMatch: 'full' },
    { path: 'import', component: ImportComponent, pathMatch: 'full' },
    { path: 'amazon', component: AmazonComponent, pathMatch: 'full' },
    { path: 'request', component: RequestComponent, pathMatch: 'full' },
    { path: 'cart', component: CartComponent, pathMatch: 'full' }
];

export const AppRoutes = RouterModule.forRoot(routes);


text:
"""
CIFAR-10 contains color images of 10 classes.
More info at: http://www.cs.toronto.edu/~kriz/cifar.html
"""

import logging
import numpy as np
import os
import tarfile

from neon.datasets.dataset import Dataset
from neon.util.compat import range
from neon.util.persist import deserialize

logger = logging.getLogger(__name__)

class CIFAR10(Dataset):

    """
    Sets up a CIFAR-10 dataset.

    Attributes:
        url (str): where to find the source data
        backend (neon.backends.Backend): backend used for this data
        inputs (dict): structure housing the loaded train/test/validation
                       input data
        targets (dict): structure housing the loaded train/test/validation
                        target data

    Keyword Args:
        repo_path (str, optional): where to locally host this dataset on disk
    """
    url = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'

    def __init__(self, **kwargs):
        self.macro_batched = False
        self.__dict__.update(kwargs)

    def initialize(self):
        pass

    def fetch_dataset(self, save_dir):
        save_dir = os.path.expandvars(os.path.expanduser(save_dir))
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)

        repo_gz_file = os.path.join(save_dir, os.path.basename(self.url))
        if not os.path.exists(repo_gz_file):
            self.download_to_repo(self.url, save_dir)

        data_file = os.path.join(save_dir, 'cifar-10-batches-py', 'test_batch')
        if not os.path.exists(data_file):
            logger.info('untarring: %s', repo_gz_file)
            infile = tarfile.open(repo_gz_file)
            infile.extractall(save_dir)
            infile.close()

    def load_file(self, filename, nclasses):
        logger.info('loading: %s', filename)
        dict = deserialize(filename)

        full_image = np.float32(dict['data'])
        full_image /= 255.

        labels = np.array(dict['labels'])
        onehot = np.zeros((len(labels), nclasses), dtype='float32')
        for col in range(nclasses):
            onehot[:, col] = (labels == col)
        return (full_image, onehot)

    def load(self, backend=None, experiment=None):
        if self.inputs['train'] is not None:
            return
        if 'repo_path' in self.__dict__:
            self.repo_path = os.path.expandvars(os.path.expanduser(
                self.repo_path))
            ncols = 32 * 32 * 3

            ntrain_total = 50000
            nclasses = 10
            save_dir = os.path.join(self.repo_path,
                                    self.__class__.__name__)
            self.fetch_dataset(save_dir)
            self.inputs['train'] = np.zeros((ntrain_total, ncols),
                                            dtype='float32')
            self.targets['train'] = np.zeros((ntrain_total, nclasses),
                                             dtype='float32')
            for i in range(5):
                filename = os.path.join(save_dir, 'cifar-10-batches-py',
                                        'data_batch_' + str(i + 1))
                data, labels = self.load_file(filename, nclasses)
                nrows = data.shape[0]
                start = i * nrows
                end = (i + 1) * nrows
                self.inputs['train'][start:end] = data
                self.targets['train'][start:end] = labels

            if 'sample_pct' in self.__dict__:
                self.sample_training_data()

            filename = os.path.join(save_dir, 'cifar-10-batches-py',
                                    'test_batch')
            data, labels = self.load_file(filename, nclasses)
            self.inputs['test'] = np.zeros((data.shape[0], ncols),
                                           dtype='float32')
            self.targets['test'] = np.zeros((data.shape[0], nclasses),
                                            dtype='float32')
            self.inputs['test'][:] = data
            self.targets['test'][:] = labels
            if hasattr(self, 'validation_pct'):
                self.split_set(
                    self.validation_pct, from_set='train', to_set='validation')
            self.format()
        else:
            raise AttributeError('repo_path not specified in config')


text:
<?php
/*
 * Tikapot Views
 *
 */

include_once(home_dir . "framework/views/redirect.php");
require_once(home_dir . "framework/views/captcha.php");
require_once(home_dir . "framework/views/i18n.php");

?>


text:
package org.n52.sos.config;

/**
 * Holder for generic settings. Implementations are {@link SettingsManager}
 * specific.
 *

 *
 * @param <T>
 *            the value type
 *

 * @author Christian Autermann <c.autermann@52north.org>
 * @since 4.0.0
 */
public interface SettingValue<T> {

    /**
     * @return the key of this setting
     */
    String getKey();

    /**
     * @return the value
     */
    T getValue();

    /**
     * @param key
     *            the key of this setting
     *

     * @return this
     */
    SettingValue<T> setKey(String key);

    /**
     * @param value
     *            the value of this setting
     *

     * @return this
     */
    SettingValue<T> setValue(T value);

    /**
     * @return the {@code SettingType} of this value
     */
    SettingType getType();
}


text:
package org.apache.heron.scheduler.utils;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.bind.DatatypeConverter;

import org.apache.heron.api.generated.TopologyAPI;
import org.apache.heron.api.utils.TopologyUtils;
import org.apache.heron.common.basics.FileUtils;
import org.apache.heron.proto.scheduler.Scheduler;
import org.apache.heron.proto.system.Common;
import org.apache.heron.scheduler.ExecutorFlag;
import org.apache.heron.spi.common.Config;
import org.apache.heron.spi.common.Context;
import org.apache.heron.spi.packing.PackingPlan;
import org.apache.heron.spi.packing.PackingPlanProtoSerializer;
import org.apache.heron.spi.scheduler.IScheduler;
import org.apache.heron.spi.statemgr.SchedulerStateManagerAdaptor;
import org.apache.heron.spi.utils.ShellUtils;

public final class SchedulerUtils {
  public static final int PORTS_REQUIRED_FOR_SCHEDULER = 1;
  public static final String SCHEDULER_COMMAND_LINE_PROPERTIES_OVERRIDE_OPTION = "P";

  private static final Logger LOG = Logger.getLogger(SchedulerUtils.class.getName());

  /**
   * Enum that defines the type of ports that an heron executor needs
   */

  public enum ExecutorPort {
    MASTER_PORT("master", true),
    TMASTER_CONTROLLER_PORT("tmaster-ctl", true),
    TMASTER_STATS_PORT("tmaster-stats", true),
    SHELL_PORT("shell-port", true),
    METRICS_MANAGER_PORT("metrics-mgr", true),
    SCHEDULER_PORT("scheduler", true),
    METRICS_CACHE_MASTER_PORT("metrics-cache-m", true),
    METRICS_CACHE_STATS_PORT("metrics-cache-s", true),
    CHECKPOINT_MANAGER_PORT("ckptmgr", true),
    JVM_REMOTE_DEBUGGER_PORTS("jvm-remote-debugger", false);

    private final String name;
    private final boolean required;

    ExecutorPort(String name, boolean required) {
      this.name = name;
      this.required = required;
    }

    public String getName() {
      return name;
    }

    public boolean isRequired() {
      return required;
    }

    public static String getPort(ExecutorPort executorPort,
                                 Map<ExecutorPort, String> portMap) {
      if (!portMap.containsKey(executorPort) && executorPort.isRequired()) {
        throw new RuntimeException("Required port " + executorPort.getName() + " not provided");
      }

      return portMap.get(executorPort);
    }

    public static Set<ExecutorPort> getRequiredPorts() {
      Set<ExecutorPort> executorPorts = new HashSet<>();
      for (ExecutorPort executorPort : ExecutorPort.values()) {
        if (executorPort.isRequired()) {
          executorPorts.add(executorPort);
        }
      }
      return executorPorts;
    }
  }

  private SchedulerUtils() {
  }

  /**
   * Utils method to construct the command to start heron-scheduler
   *
   * @param config The static Config
   * @param runtime The runtime Config
   * @param freePorts list of free ports
   * @return String[] representing the command to start heron-scheduler
   */
  public static String[] schedulerCommand(
      Config config,
      Config runtime,
      List<Integer> freePorts) {
    List<String> commands = new ArrayList<>();

    // The java executable should be "{JAVA_HOME}/bin/java"
    String javaExecutable = String.format("%s/%s", Context.clusterJavaHome(config), "bin/java");
    commands.add(javaExecutable);
    commands.add("-cp");

    // Construct the complete classpath to start scheduler
    String completeSchedulerProcessClassPath = String.format("%s:%s:%s",
        Context.schedulerClassPath(config),
        Context.packingClassPath(config),
        Context.stateManagerClassPath(config));
    commands.add(completeSchedulerProcessClassPath);
    commands.add("org.apache.heron.scheduler.SchedulerMain");

    String[] commandArgs = schedulerCommandArgs(config, runtime, freePorts);
    commands.addAll(Arrays.asList(commandArgs));

    return commands.toArray(new String[0]);
  }

  /**
   * Util method to get the arguments to the heron scheduler.
   *
   * @param config The static Config
   * @param runtime The runtime Config
   * @param freePorts list of free ports
   * @return String[] representing the arguments to start heron-scheduler
   */
  public static String[] schedulerCommandArgs(
      Config config, Config runtime, List<Integer> freePorts) {
    // First let us have some safe checks
    if (freePorts.size() < PORTS_REQUIRED_FOR_SCHEDULER) {
      throw new RuntimeException("Failed to find enough ports for executor");
    }
    for (int port : freePorts) {
      if (port == -1) {
        throw new RuntimeException("Failed to find available ports for executor");
      }
    }

    int httpPort = freePorts.get(0);

    List<String> commands = new ArrayList<>();

    commands.add("--cluster");
    commands.add(Context.cluster(config));
    commands.add("--role");
    commands.add(Context.role(config));
    commands.add("--environment");
    commands.add(Context.environ(config));
    commands.add("--topology_name");
    commands.add(Context.topologyName(config));
    commands.add("--topology_bin");
    commands.add(Context.topologyBinaryFile(config));
    commands.add("--http_port");
    commands.add(Integer.toString(httpPort));

    return commands.toArray(new String[0]);
  }

  /**
   * Utils method to construct the command to start heron-executor
   *
   * @param config The static config
   * @param runtime The runtime config
   * @param shardId the executor/container index
   * @param ports a map of ports to use where the key indicate the port type and the
   * value is the port
   * @return String[] representing the command to start heron-executor
   */
  public static String[] getExecutorCommand(
      Config config,
      Config runtime,
      int shardId,
      Map<ExecutorPort, String> ports) {
    return getExecutorCommand(config, runtime, Integer.toString(shardId), ports);
  }

  /**
   * Utils method to construct the command to start heron-executor
   *
   * @param config The static config
   * @param runtime The runtime config
   * @param shardId the executor/container index
   * @param ports a map of ports to use where the key indicate the port type and the
   * value is the port
   * @return String[] representing the command to start heron-executor
   */
  public static String[] getExecutorCommand(
      Config config,
      Config runtime,
      String shardId,
      Map<ExecutorPort, String> ports) {
    List<String> commands = new ArrayList<>();
    commands.add(Context.executorBinary(config));

    String[] commandArgs = executorCommandArgs(config, runtime, ports, shardId);
    commands.addAll(Arrays.asList(commandArgs));

    return commands.toArray(new String[0]);
  }

  /**
   * Util method to get the arguments to the heron executor. This method creates the arguments
   * without the container index, which is the first argument to the executor
   *
   * @param config The static Config
   * @param runtime The runtime Config
   * @param ports a map of ports to use where the key indicate the port type and the
   * value is the port
   * @param containerIndex The index of the current container
   * @return String[] representing the arguments to start heron-executor
   */
  public static String[] executorCommandArgs(
      Config config, Config runtime, Map<ExecutorPort, String> ports, String containerIndex) {
    List<String> args = new ArrayList<>();
    addExecutorTopologyArgs(args, config, runtime);
    addExecutorContainerArgs(args, ports, containerIndex);

    return args.toArray(new String[args.size()]);
  }

  /**
   * Util method to parse configs and translate them into topology configs to be used by executor
   *
   * @param args The list to accept new topology arguments
   * @param config The static Config
   * @param runtime The runtime Config
   */
  public static void addExecutorTopologyArgs(List<String> args, Config config, Config runtime) {
    TopologyAPI.Topology topology = Runtime.topology(runtime);
    args.add(createCommandArg(ExecutorFlag.TopologyName, topology.getName()));
    args.add(createCommandArg(ExecutorFlag.TopologyId, topology.getId()));
    args.add(createCommandArg(ExecutorFlag.TopologyDefinitionFile,
        FileUtils.getBaseName(Context.topologyDefinitionFile(config))));
    args.add(createCommandArg(ExecutorFlag.StateManagerConnection,
        Context.stateManagerConnectionString(config)));
    args.add(createCommandArg(ExecutorFlag.StateManagerRoot,
        Context.stateManagerRootPath(config)));
    args.add(createCommandArg(ExecutorFlag.StateManagerConfigFile,
        Context.stateManagerFile(config)));
    args.add(createCommandArg(ExecutorFlag.TMasterBinary, Context.tmasterBinary(config)));
    args.add(createCommandArg(ExecutorFlag.StmgrBinary, Context.stmgrBinary(config)));
    args.add(createCommandArg(ExecutorFlag.MetricsManagerClasspath,
        Context.metricsManagerClassPath(config)));
    args.add(createCommandArg(ExecutorFlag.InstanceJvmOpts,
        SchedulerUtils.encodeJavaOpts(TopologyUtils.getInstanceJvmOptions(topology))));
    args.add(createCommandArg(ExecutorFlag.Classpath,
        TopologyUtils.makeClassPath(topology, Context.topologyBinaryFile(config))));
    args.add(createCommandArg(ExecutorFlag.HeronInternalsConfigFile,
        Context.systemConfigFile(config)));
    args.add(createCommandArg(ExecutorFlag.OverrideConfigFile, Context.overrideFile(config)));
    args.add(createCommandArg(ExecutorFlag.ComponentRamMap, Runtime.componentRamMap(runtime)));
    args.add(createCommandArg(ExecutorFlag.ComponentJvmOpts,
        SchedulerUtils.encodeJavaOpts(TopologyUtils.getComponentJvmOptions(topology))));
    args.add(createCommandArg(ExecutorFlag.PkgType,
        Context.topologyPackageType(config).name().toLowerCase()));
    args.add(createCommandArg(ExecutorFlag.TopologyBinaryFile,
        Context.topologyBinaryFile(config)));
    args.add(createCommandArg(ExecutorFlag.HeronJavaHome, Context.clusterJavaHome(config)));
    args.add(createCommandArg(ExecutorFlag.HeronShellBinary, Context.shellBinary(config)));
    args.add(createCommandArg(ExecutorFlag.Cluster, Context.cluster(config)));
    args.add(createCommandArg(ExecutorFlag.Role, Context.role(config)));
    args.add(createCommandArg(ExecutorFlag.Environment, Context.environ(config)));
    args.add(createCommandArg(ExecutorFlag.InstanceClasspath, Context.instanceClassPath(config)));
    args.add(createCommandArg(ExecutorFlag.MetricsSinksConfigFile,
        Context.metricsSinksFile(config)));

    String completeSchedulerProcessClassPath = String.format("%s:%s:%s",
        Context.schedulerClassPath(config),
        Context.packingClassPath(config), Context.stateManagerClassPath(config));

    args.add(createCommandArg(ExecutorFlag.SchedulerClasspath, completeSchedulerProcessClassPath));
    args.add(createCommandArg(ExecutorFlag.PythonInstanceBinary,
        Context.pythonInstanceBinary(config)));
    args.add(createCommandArg(ExecutorFlag.CppInstanceBinary, Context.cppInstanceBinary(config)));

    args.add(createCommandArg(ExecutorFlag.MetricsCacheManagerClasspath,
        Context.metricsCacheManagerClassPath(config)));
    String metricscacheMgrMode = Context.metricscacheMgrMode(config)
        == null ? "disabled" : Context.metricscacheMgrMode(config);
    args.add(createCommandArg(ExecutorFlag.MetricsCacheManagerMode, metricscacheMgrMode));

    Boolean ckptMgrEnabled = TopologyUtils.shouldStartCkptMgr(topology);
    args.add(createCommandArg(ExecutorFlag.IsStateful, Boolean.toString(ckptMgrEnabled)));
    String completeCkptmgrProcessClassPath = String.format("%s:%s:%s",
        Context.ckptmgrClassPath(config),
        Context.statefulStoragesClassPath(config),
        Context.statefulStorageCustomClassPath(config));
    args.add(createCommandArg(ExecutorFlag.CheckpointManagerClasspath,
        completeCkptmgrProcessClassPath));
    args.add(createCommandArg(ExecutorFlag.StatefulConfigFile, Context.statefulConfigFile(config)));
    args.add(createCommandArg(
        ExecutorFlag.CheckpointManagerRam,
        Long.toString(TopologyUtils.getCheckpointManagerRam(topology).asBytes())));

    String healthMgrMode = Context.healthMgrMode(config)
        == null ? "disabled" : Context.healthMgrMode(config);
    args.add(createCommandArg(ExecutorFlag.HealthManagerMode, healthMgrMode));
    args.add(createCommandArg(ExecutorFlag.HealthManagerClasspath,
        Context.healthMgrClassPath(config)));
  }

  /**
   * Util method to parse port map and container id and translate them into arguments to be used
   * by executor
   *
   * @param args The list to accept new topology arguments
   * @param ports a map of ports to use where the key indicate the port type and the
   * value is the port
   * @param containerIndex The index of the current container
   */
  public static void addExecutorContainerArgs(
      List<String> args,
      Map<ExecutorPort, String> ports,
      String containerIndex) {
    String masterPort = ExecutorPort.getPort(ExecutorPort.MASTER_PORT, ports);
    String tmasterControllerPort = ExecutorPort.getPort(
        ExecutorPort.TMASTER_CONTROLLER_PORT, ports);
    String tmasterStatsPort = ExecutorPort.getPort(ExecutorPort.TMASTER_STATS_PORT, ports);
    String shellPort = ExecutorPort.getPort(ExecutorPort.SHELL_PORT, ports);
    String metricsmgrPort = ExecutorPort.getPort(ExecutorPort.METRICS_MANAGER_PORT, ports);
    String schedulerPort = ExecutorPort.getPort(ExecutorPort.SCHEDULER_PORT, ports);
    String metricsCacheMasterPort = ExecutorPort.getPort(
        ExecutorPort.METRICS_CACHE_MASTER_PORT, ports);
    String metricsCacheStatsPort = ExecutorPort.getPort(
        ExecutorPort.METRICS_CACHE_STATS_PORT, ports);
    String ckptmgrPort = ExecutorPort.getPort(ExecutorPort.CHECKPOINT_MANAGER_PORT, ports);
    String remoteDebuggerPorts = ExecutorPort.getPort(
        ExecutorPort.JVM_REMOTE_DEBUGGER_PORTS, ports);

    if (containerIndex != null) {
      args.add(createCommandArg(ExecutorFlag.Shard, containerIndex));
    }
    args.add(createCommandArg(ExecutorFlag.MasterPort, masterPort));
    args.add(createCommandArg(ExecutorFlag.TMasterControllerPort, tmasterControllerPort));
    args.add(createCommandArg(ExecutorFlag.TMasterStatsPort, tmasterStatsPort));
    args.add(createCommandArg(ExecutorFlag.ShellPort, shellPort));
    args.add(createCommandArg(ExecutorFlag.MetricsManagerPort, metricsmgrPort));
    args.add(createCommandArg(ExecutorFlag.SchedulerPort, schedulerPort));
    args.add(createCommandArg(ExecutorFlag.MetricsCacheManagerMasterPort, metricsCacheMasterPort));
    args.add(createCommandArg(ExecutorFlag.MetricsCacheManagerStatsPort, metricsCacheStatsPort));
    args.add(createCommandArg(ExecutorFlag.CheckpointManagerPort, ckptmgrPort));
    if (remoteDebuggerPorts != null) {
      args.add(createCommandArg(ExecutorFlag.JvmRemoteDebuggerPorts, remoteDebuggerPorts));
    }
  }

  public static String createCommandArg(ExecutorFlag flag, String value) {
    return String.format("%s=%s", flag.getFlag(), value);
  }

  public static String[] splitCommandArg(String command) {
    return command.split("=");
  }

  /**
   * Set the location of scheduler for other processes to discover,
   * when invoke IScheduler as a library on client side
   *
   * @param runtime the runtime configuration
   * @param scheduler the IScheduler to provide more info
   * @param isService true if the scheduler is a service; false otherwise
   */
  public static boolean setLibSchedulerLocation(
      Config runtime,
      IScheduler scheduler,
      boolean isService) {
    // Dummy value since there is no scheduler running as service
    final String endpoint = "scheduler_as_lib_no_endpoint";
    return setSchedulerLocation(runtime, endpoint, scheduler);
  }

  /**
   * Set the location of scheduler for other processes to discover
   *
   * @param runtime the runtime configuration
   * @param schedulerEndpoint the endpoint that scheduler listens for receives requests
   * @param scheduler the IScheduler to provide more info
   */
  public static boolean setSchedulerLocation(
      Config runtime,
      String schedulerEndpoint,
      IScheduler scheduler) {

    // Set scheduler location to host:port by default. Overwrite scheduler location if behind DNS.
    Scheduler.SchedulerLocation.Builder builder = Scheduler.SchedulerLocation.newBuilder()
        .setTopologyName(Runtime.topologyName(runtime))
        .setHttpEndpoint(schedulerEndpoint);

    // Set the job link in SchedulerLocation if any
    List<String> jobLinks = scheduler.getJobLinks();
    // Check whether IScheduler provides valid job link
    if (jobLinks != null) {
      builder.addAllJobPageLink(jobLinks);
    }

    Scheduler.SchedulerLocation location = builder.build();

    LOG.log(Level.INFO, "Setting Scheduler locations: {0}", location);
    SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime);
    Boolean result =
        statemgr.setSchedulerLocation(location, Runtime.topologyName(runtime));

    if (result == null || !result) {
      LOG.severe("Failed to set Scheduler location");
      return false;
    }

    return true;
  }

  /**
   * construct heron scheduler response basing on the given result
   *
   * @param isOK whether the request successful
   */
  public static Scheduler.SchedulerResponse constructSchedulerResponse(boolean isOK) {
    Common.Status.Builder status = Common.Status.newBuilder();
    if (isOK) {
      status.setStatus(Common.StatusCode.OK);
    } else {
      status.setStatus(Common.StatusCode.NOTOK);
    }

    return Scheduler.SchedulerResponse.newBuilder().
        setStatus(status).
        build();
  }

  /**
   * Encode the JVM options
   *
 1. Convert it into Base64 format
   *
 2. Add \" at the start and at the end
   *
 3. replace "=" with "(61)" and "&equals;"
   * '=' can be parsed in a wrong way by some schedulers (aurora) hence it needs to be escaped.
   *
   * @return encoded string
   */
  public static String encodeJavaOpts(String javaOpts) {
    String javaOptsBase64 = DatatypeConverter.printBase64Binary(
        javaOpts.getBytes(StandardCharsets.UTF_8));
    return String.format("\"%s\"", javaOptsBase64.replace("=", "(61)"));
  }

  /**
   * Decode the JVM options
   *
 1. strip \" at the start and at the end
   *
 2. replace "(61)" and "&equals;" with "="
   *
 3. Revert from Base64 format
   * Note that '=' is escaped in two different ways. '(61)' is the new escaping.
   * '&equals;' was the original replacement but it is not friendly to bash and
   * was causing issues. The original escaping is still left there for reference
   * and backward compatibility purposes (to be removed after no topology needs
   * it)
   *
   * @return decoded string
   */
  public static String decodeJavaOpts(String encodedJavaOpts) {
    String javaOptsBase64 =
        encodedJavaOpts.
            replaceAll("^\"+", "").
            replaceAll("\\s+$", "").
            replace("(61)", "=").
            replace("=", "=");

    return new String(
        DatatypeConverter.parseBase64Binary(javaOptsBase64), StandardCharsets.UTF_8);
  }

  /**
   * Create the directory if it does not exist otherwise clean the directory.
   *
   * @param directory the working directory to setup
   * @return true if successful
   */
  public static boolean createOrCleanDirectory(String directory) {
    // if the directory does not exist, create it.
    if (!FileUtils.isDirectoryExists(directory)) {
      LOG.fine("The directory does not exist; creating it.");
      if (!FileUtils.createDirectory(directory)) {
        LOG.severe("Failed to create directory: " + directory);
        return false;
      }
    }

    // Cleanup the directory
    if (!FileUtils.cleanDir(directory)) {
      LOG.severe("Failed to clean directory: " + directory);
      return false;
    }

    return true;
  }

  public static boolean extractPackage(String workingDirectory, String packageURI,
      String packageDestination, boolean deletePackage, boolean verbose) {
    return curlAndExtractPackage(workingDirectory, packageURI, packageDestination,
        deletePackage, verbose);
  }

  /**
   * Curl a package, extract it to working directory
   *
   * @param workingDirectory the working directory to setup
   * @param packageURI the URL of core release package
   * @param packageDestination the destination of the core release package fetched
   * @param isDeletePackage delete the package curled or not
   * @param isVerbose display verbose output or not
   * @return true if successful
   */
  public static boolean curlAndExtractPackage(
      String workingDirectory,
      String packageURI,
      String packageDestination,
      boolean isDeletePackage,
      boolean isVerbose) {
    // curl the package to the working directory and extract it
    LOG.log(Level.FINE, "Fetching package {0}", packageURI);
    LOG.fine("Fetched package can overwrite old one.");
    if (!ShellUtils.curlPackage(
        packageURI, packageDestination, isVerbose, false)) {
      LOG.severe("Failed to fetch package.");
      return false;
    }

    // untar the heron core release package in the working directory
    LOG.log(Level.FINE, "Extracting the package {0}", packageURI);
    if (!ShellUtils.extractPackage(
        packageDestination, workingDirectory, isVerbose, false)) {
      LOG.severe("Failed to extract package.");
      return false;
    }

    // remove the core release package
    if (isDeletePackage && !FileUtils.deleteFile(packageDestination)) {
      LOG.warning("Failed to delete the package: " + packageDestination);
    }

    return true;
  }

  /**
   * Replaces persisted packing plan in state manager.
   */
  public static void persistUpdatedPackingPlan(String topologyName,
                                               PackingPlan updatedPackingPlan,
                                               SchedulerStateManagerAdaptor stateManager) {
    LOG.log(Level.INFO, "Updating scheduled-resource in packing plan: {0}", topologyName);
    PackingPlanProtoSerializer serializer = new PackingPlanProtoSerializer();

    if (!stateManager.updatePackingPlan(serializer.toProto(updatedPackingPlan), topologyName)) {
      throw new RuntimeException(String.format(
          "Failed to update packing plan for topology %s", topologyName));
    }
  }
}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'service_status'
require 'webmock/rspec'
WebMock.disable_net_connect!(allow_localhost: false)


text:
class Pokerstars < Cask
  url 'http://www.pokerstars.com/PokerStars.app.zip'
  homepage 'http://www.pokerstars.com/'
  version 'latest'
  no_checksum
  link 'PokerStars.app'
end


text:
from __future__ import unicode_literals

MESSAGES = {
    "%d min remaining to read": "%d min gjenstår å lese",
    "(active)": "(aktiv)",
    "Also available in:": "Også tilgjengelig på:",
    "Archive": "Arkiv",
    "Categories": "Kategorier",
    "Comments": "Kommentarer",
    "LANGUAGE": "norsk",
    "Languages:": "Språk:",
    "More posts about %s": "Flere innlegg om %s",
    "Newer posts": "Nyere innlegg",
    "Next post": "Neste innlegg",
    "No posts found.": "Fant ingen innlegg.",
    "Nothing found.": "Fant ingenting.",
    "Older posts": "Eldre innlegg",
    "Original site": "Opprinnelig side",
    "Posted:": "Publisert:",
    "Posts about %s": "Innlegg om %s",
    "Posts for year %s": "Innlegg fra %s",
    "Posts for {month} {day}, {year}": "Innlegg fra {day}. {month} {year}",
    "Posts for {month} {year}": "Innlegg fra {month} {year}",
    "Previous post": "Forrige innlegg",
    "Publication date": "Publiseringsdato",
    "RSS feed": "RSS-nyhetskanal",
    "Read in English": "Les på norsk",
    "Read more": "Les mer",
    "Skip to main content": "Hopp til hovedinnholdet",
    "Source": "Kilde",
    "Subcategories:": "Underkategorier:",
    "Tags and Categories": "Merker og kategorier",
    "Tags": "Merker",
    "Write your page here.": "Skriv siden din her.",
    "Write your post here.": "Skriv innlegget din her.",
    "old posts, page %d": "eldre innlegg, side %d",
    "page %d": "side %d",
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using MoonSharp.Interpreter.Diagnostics;
using MoonSharp.Interpreter.Interop.BasicDescriptors;

namespace MoonSharp.Interpreter.Interop
{
    /// <summary>
    ///     Class providing easier marshalling of CLR functions
    /// </summary>
    public class MethodMemberDescriptor : FunctionMemberDescriptorBase, IOptimizableDescriptor
    {
        private readonly bool m_IsAction;
        private Action<object, object[]> m_OptimizedAction;
        private Func<object, object[], object> m_OptimizedFunc;

        /// <summary>
        ///     Initializes a new instance of the <see cref="MethodMemberDescriptor" /> class.
        /// </summary>
        /// <param name="methodBase">The MethodBase (MethodInfo or ConstructorInfo) got through reflection.</param>
        /// <param name="accessMode">The interop access mode.</param>
        /// <exception cref="System.ArgumentException">Invalid accessMode</exception>
        public MethodMemberDescriptor(MethodBase methodBase, InteropAccessMode accessMode = InteropAccessMode.Default)
        {
            CheckMethodIsCompatible(methodBase, true);

            IsConstructor = (methodBase is ConstructorInfo);
            MethodInfo = methodBase;

            var isStatic = methodBase.IsStatic || IsConstructor;

            if (IsConstructor)
                m_IsAction = false;
            else
                m_IsAction = ((MethodInfo) methodBase).ReturnType == typeof (void);

            var reflectionParams = methodBase.GetParameters();
            var parameters = reflectionParams.Select(pi => new ParameterDescriptor(pi)).ToArray();

            var isExtensionMethod = (methodBase.IsStatic && parameters.Length > 0 &&
                                     methodBase.GetCustomAttributes(typeof (ExtensionAttribute), false).Any());

            Initialize(methodBase.Name, isStatic, parameters, isExtensionMethod);

            // adjust access mode
            if (Script.GlobalOptions.Platform.IsRunningOnAOT())
                accessMode = InteropAccessMode.Reflection;

            if (accessMode == InteropAccessMode.Default)
                accessMode = UserData.DefaultAccessMode;

            if (accessMode == InteropAccessMode.HideMembers)
                throw new ArgumentException("Invalid accessMode");

            if (parameters.Any(p => p.Type.IsByRef))
                accessMode = InteropAccessMode.Reflection;

            AccessMode = accessMode;

            if (AccessMode == InteropAccessMode.Preoptimized)
                ((IOptimizableDescriptor) this).Optimize();
        }

        /// <summary>
        ///     Gets the method information (can be a MethodInfo or ConstructorInfo)
        /// </summary>
        public MethodBase MethodInfo { get; }

        /// <summary>
        ///     Gets the access mode used for interop
        /// </summary>
        public InteropAccessMode AccessMode { get; }

        /// <summary>
        ///     Gets a value indicating whether the described method is a constructor
        /// </summary>
        public bool IsConstructor { get; }

        /// <summary>
        ///     Called by standard descriptors when background optimization or preoptimization needs to be performed.
        /// </summary>
        /// <exception cref="InternalErrorException">Out/Ref params cannot be precompiled.</exception>
        void IOptimizableDescriptor.Optimize()
        {
            var parameters = Parameters;

            if (AccessMode == InteropAccessMode.Reflection)
                return;

            var methodInfo = MethodInfo as MethodInfo;

            if (methodInfo == null)
                return;

            using (PerformanceStatistics.StartGlobalStopwatch(PerformanceCounter.AdaptersCompilation))
            {
                var ep = Expression.Parameter(typeof (object[]), "pars");
                var objinst = Expression.Parameter(typeof (object), "instance");
                var inst = Expression.Convert(objinst, MethodInfo.DeclaringType);

                var args = new Expression[parameters.Length];

                for (var i = 0; i < parameters.Length; i++)
                {
                    if (parameters[i].OriginalType.IsByRef)
                    {
                        throw new InternalErrorException("Out/Ref params cannot be precompiled.");
                    }
                    var x = Expression.ArrayIndex(ep, Expression.Constant(i));
                    args[i] = Expression.Convert(x, parameters[i].OriginalType);
                }

                Expression fn;

                if (IsStatic)
                {
                    fn = Expression.Call(methodInfo, args);
                }
                else
                {
                    fn = Expression.Call(inst, methodInfo, args);
                }

                if (m_IsAction)
                {
                    var lambda = Expression.Lambda<Action<object, object[]>>(fn, objinst, ep);
                    Interlocked.Exchange(ref m_OptimizedAction, lambda.Compile());
                }
                else
                {
                    var fnc = Expression.Convert(fn, typeof (object));
                    var lambda = Expression.Lambda<Func<object, object[], object>>(fnc, objinst, ep);
                    Interlocked.Exchange(ref m_OptimizedFunc, lambda.Compile());
                }
            }
        }

        /// <summary>
        ///     Tries to create a new MethodMemberDescriptor, returning
        ///     <c>null</c> in case the method is not
        ///     visible to script code.
        /// </summary>
        /// <param name="methodBase">The MethodBase.</param>
        /// <param name="accessMode">The <see cref="InteropAccessMode" /></param>
        /// <param name="forceVisibility">if set to <c>true</c> forces visibility.</param>
        /// <returns>
        ///     A new MethodMemberDescriptor or null.
        /// </returns>
        public static MethodMemberDescriptor TryCreateIfVisible(MethodBase methodBase, InteropAccessMode accessMode,
            bool forceVisibility = false)
        {
            if (!CheckMethodIsCompatible(methodBase, false))
                return null;

            if (forceVisibility || (methodBase.GetVisibilityFromAttributes() ?? methodBase.IsPublic))
                return new MethodMemberDescriptor(methodBase, accessMode);

            return null;
        }

        /// <summary>
        ///     Checks if the method is compatible with a standard descriptor
        /// </summary>
        /// <param name="methodBase">The MethodBase.</param>
        /// <param name="throwException">
        ///     if set to <c>true</c> an exception with the proper error message is thrown if not
        ///     compatible.
        /// </param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">
        ///     Thrown if throwException is <c>true</c> and one of this applies:
        ///     The method contains unresolved generic parameters, or has an unresolved generic return type
        ///     or
        ///     The method contains pointer parameters, or has a pointer return type
        /// </exception>
        public static bool CheckMethodIsCompatible(MethodBase methodBase, bool throwException)
        {
            if (methodBase.ContainsGenericParameters)
            {
                if (throwException) throw new ArgumentException("Method cannot contain unresolved generic parameters");
                return false;
            }

            if (methodBase.GetParameters().Any(p => p.ParameterType.IsPointer))
            {
                if (throwException) throw new ArgumentException("Method cannot contain pointer parameters");
                return false;
            }

            var mi = methodBase as MethodInfo;

            if (mi != null)
            {
                if (mi.ReturnType.IsPointer)
                {
                    if (throwException) throw new ArgumentException("Method cannot have a pointer return type");
                    return false;
                }

                if (mi.ReturnType.IsGenericTypeDefinition)
                {
                    if (throwException)
                        throw new ArgumentException("Method cannot have an unresolved generic return type");
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        ///     The internal callback which actually executes the method
        /// </summary>
        /// <param name="script">The script.</param>
        /// <param name="obj">The object.</param>
        /// <param name="context">The context.</param>
        /// <param name="args">The arguments.</param>
        /// <returns></returns>
        public override DynValue Execute(Script script, object obj, ScriptExecutionContext context,
            CallbackArguments args)
        {
            this.CheckAccess(MemberDescriptorAccess.CanExecute, obj);

            if (AccessMode == InteropAccessMode.LazyOptimized &&
                m_OptimizedFunc == null && m_OptimizedAction == null)
                ((IOptimizableDescriptor) this).Optimize();

            List<int> outParams = null;
            var pars = BuildArgumentList(script, obj, context, args, out outParams);
            object retv = null;

            if (m_OptimizedFunc != null)
            {
                retv = m_OptimizedFunc(obj, pars);
            }
            else if (m_OptimizedAction != null)
            {
                m_OptimizedAction(obj, pars);
                retv = DynValue.Void;
            }
            else if (m_IsAction)
            {
                MethodInfo.Invoke(obj, pars);
                retv = DynValue.Void;
            }
            else
            {
                if (IsConstructor)
                    retv = ((ConstructorInfo) MethodInfo).Invoke(pars);
                else
                    retv = MethodInfo.Invoke(obj, pars);
            }

            return BuildReturnValue(script, outParams, pars, retv);
        }
    }
}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <title>Citizen Science: Community</title>

Experiments

 Not sure what experiment you want to try? Here are some easy starters for beginners. Otherwise, try our search and tag features to locate experiments that interest you.


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Z.Core.Test
{
    [TestClass]
    public class System_String_ExtractUInt16
    {
        [TestMethod]
        public void ExtractUInt16()
        {
            // Type

            // Exemples
            ushort result1 = "Fizz 123 Buzz".ExtractUInt16(); // return 123;
            ushort result2 = "Fizz -123 Buzz".ExtractUInt16(); // return 123;
            ushort result3 = "-Fizz 123 Buzz".ExtractUInt16(); // return 123;
            ushort result4 = "Fizz 123.4 Buzz".ExtractUInt16(); // return 1234;
            ushort result5 = "Fizz -123Fizz.Buzz4 Buzz".ExtractUInt16(); // return 1234;

            // Unit Test
            Assert.AreEqual((UInt16) 123, result1);
            Assert.AreEqual((UInt16) 123, result2);
            Assert.AreEqual((UInt16) 123, result3);
            Assert.AreEqual((UInt16) 1234, result4);
            Assert.AreEqual((UInt16) 1234, result5);
        }
    }
}


text:
<?php
mb_http_output("EUC-JP");
header("Content-Type: application/octet-stream");
ob_start();
ob_start('mb_output_handler');
echo "テスト";
ob_end_flush();
var_dump(bin2hex(ob_get_clean()));
?>


text:
package anthonyostrich;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.*;
import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef;

/**
 * Created by anthony on 12/27/14.
 */
public class BeeMan extends CompoundActor{

    static TextureRegion[] beeTextures = {Assets.getTexture("torso"),
                                    Assets.getTexture("leftArm"),
                                    Assets.getTexture("rightArm")};

    Actor leftArm;

    public BeeMan(World world, float x, float y, float width)
    {
        super(beeTextures[0], world, x, y, width);
        leftArm = new Actor(beeTextures[1], null, world, x - (getWidth()*2f/3), y + getHeight()/8, 1);
        this.actors.add(leftArm);
        RevoluteJointDef leftArmJointDef = new RevoluteJointDef();
        leftArmJointDef.collideConnected = false;
        leftArmJointDef.initialize(this.body, leftArm.body, new Vector2(x - (getWidth() / 6), y + getHeight() / 8));
        world.createJoint(leftArmJointDef);

        Actor rightArm = new Actor(beeTextures[2], null, world, x + (getWidth()*2f/3), y + getHeight()/8, 1);
        this.actors.add(rightArm);
        RevoluteJointDef rightArmJointDef = new RevoluteJointDef();
        rightArmJointDef.collideConnected = false;
        rightArmJointDef.initialize(this.body, rightArm.body, new Vector2(x + (getWidth() / 6), y + getHeight() / 8));
        world.createJoint(rightArmJointDef);

    }

}


text:
<?php

namespace PhpWorkshop\PhpWorkshop\Exercise;

use PhpWorkshop\PhpWorkshop\ExerciseCheck\StdOutExerciseCheck;

/**
 * Class BabySteps
 * @package PhpWorkshop\PhpWorkshop\Exercise
 * @author Aydin Hassan <aydin@hotmail.co.uk>
 */
class BabySteps implements ExerciseInterface, StdOutExerciseCheck
{

    /**
     * @return string
     */
    public function getName()
    {
        return 'Baby Steps';
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        return 'Simple Addition';
    }

    /**
     * @return string
     */
    public function getSolution()
    {
        return __DIR__ . '/../../res/solutions/baby-steps/solution.php';
    }

    /**
     * @return string
     */
    public function getProblem()
    {
        return __DIR__ . '/../../res/problems/baby-steps/problem.md';
    }

    /**
     * @return array
     */
    public function getArgs()
    {
        $numArgs = rand(0, 10);

        $args = [];
        for ($i = 0; $i < $numArgs; $i ++) {
            $args[] = rand(0, 100);
        }

        return $args;
    }

    /**
     * @return void
     */
    public function tearDown()
    {
    }
}