text:
title: "Put Local Case Execution Variable"
weight: 160

menu:
  main:
    name: "Update"
    identifier: "rest-api-case-execution-put-local-variable"
    parent: "rest-api-case-execution-local-variables"
    pre: "PUT `/case-execution/{id}/localVariables/{varName}`"

---

Sets a variable in the context of a given case execution. Update does not propagate upwards in the case execution hierarchy.

# Method

PUT `/case-execution/{id}/localVariables/{varName}`

# Parameters

## Path Parameters

    Name
    Description

    id
    The id of the case execution to set the variable for.

    varName
    The name of the variable to set.

## Request Body

A JSON object with the following properties:

{{< rest-var-request >}}    x^

# Result

This method returns no content.

# Response Codes

    Code
    Media type
    Description

    204

    Request successful.

    400
    application/json
    The variable value or type is invalid, for example if the value could not be parsed to an Integer value or the passed variable type is not supported. See the <a href="{{< relref "reference/rest/overview/index.md#error-handling" >}}">Introduction for the error response format.

# Example 1

## Request

PUT `/case-execution/aCaseExecutionId/localVariables/aVarName`

    {"value" : "someValue", "type": "String"}

## Response

Status 204. No content.

# Example 2

## Request

PUT `/case-execution/aCaseExecutionId/localVariables/aVarName`

{{< rest-var-request-example >}}

## Response

Status 204. No content.


text:
"""
Example showing how to use the Rollbar API to list all occurrences since the last deploy
"""

from __future__ import print_function

import sys
import requests

# Occurrences are returned descending by ID, which is approximately but not exactly
# descending by timestamp. We'll keep searching through occurrences until we reach one that
# is this many seconds older than the last deploy.
SEARCH_BUFFER_SECONDS = 60

def fetch_last_deploy_timestamp(access_token, environment):
    """
    Return the timestamp of the last deploy in `environment`
    """
    # The /api/1/deploys endpoint returns all deploys in descending order by timestamp
    # We'll iterate through them until we find one that matches `environment`.

    page = 1
    while True:
        result = requests.get(
            "https://api.rollbar.com/api/1/deploys?page={}".format(page),
            headers={"X-Rollbar-Access-Token": access_token},
        )
        deploys = result.json()["result"]["deploys"]
        if not deploys:
            # we've reached the end of the list
            return None

        for deploy in deploys:
            if deploy["environment"] == environment:
                return deploy["start_time"]
        page += 1

def print_occurrences_since_timestamp(access_token, environment, min_timestamp):
    """
    Prints all occurrences (as json) since the specified timestamp
    """

    page = 1
    while True:
        result = requests.get(
            "https://api.rollbar.com/api/1/instances/?page={}".format(page),
            headers={"X-Rollbar-Access-Token": access_token},
        )
        occurrences = result.json()["result"]["instances"]
        if not occurrences:
            # reached the end of the list
            return

        for occurrence in occurrences:
            # filter by environment
            if occurrence["data"]["environment"] == environment:
                # now check timestamp
                if occurrence["timestamp"] >= min_timestamp:
                    print(occurrence["data"])
                elif occurrence["timestamp"] < min_timestamp - SEARCH_BUFFER_SECONDS:
                    # we've found an occurrence older than the min timestamp minus the buffer.
                    # done searching.
                    return

        page += 1

def main(access_token, environment):
    last_deploy_timestamp = fetch_last_deploy_timestamp(access_token, environment)
    print_occurrences_since_timestamp(access_token, environment, last_deploy_timestamp)

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print(
            "Usage: python list_occurrences_since_last_deploy.py <project read access token> <environment name>"
        )
        sys.exit(1)

    access_token = sys.argv[1]
    environment = sys.argv[2]

    main(access_token, environment)

redpajama_set_name: RedPajamaGithub


text:
app.controller('FlashMessage', function ($scope, $timeout) {
    $scope.alerts = [];

    function remove(alert) {
        var index = $scope.alerts.indexOf(alert);
        if (index > -1) {
            $scope.alerts.splice(index, 1);
        }
    }

    function add(type, message) {
        var icon;
        switch(type) {
            case 'success':
                icon = 'icon-ok-sign';
                break;
            case 'error':
                icon = 'icon-warning-sign';
                break;
            case 'info':
                icon = 'icon-info-sign';
                break;
            default:
                icon = '';
                break;
        }

        var alert = {
            type: type,
            icon: icon,
            message: message,
            close: function() {
                remove(this);
            }
        };

        $scope.alerts.push(alert);

        $timeout(function() {
            remove(alert);
        }, 1000 * 7);
    }

    $scope.$on('flash:success', function(e, args) {
        add('success', args.message);
    });

    $scope.$on('flash:error', function(e, args) {
        add('error', args.message);
    });

    $scope.$on('flash:info', function(e, args) {
        add('info', args.message);
    });
});


text:
package com.indignado.functional.test.levels.radialgravity.entities;

import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.indignado.logicbricks.components.IdentityComponent;
import com.indignado.logicbricks.components.RigidBodiesComponents;
import com.indignado.logicbricks.components.StateComponent;
import com.indignado.logicbricks.components.ViewsComponent;
import com.indignado.logicbricks.core.EntityFactory;
import com.indignado.logicbricks.core.actuators.MotionActuator;
import com.indignado.logicbricks.core.controllers.ConditionalController;
import com.indignado.logicbricks.core.data.TextureView;
import com.indignado.logicbricks.core.sensors.AlwaysSensor;
import com.indignado.logicbricks.core.sensors.Sensor;
import com.indignado.logicbricks.utils.builders.BodyBuilder;
import com.indignado.logicbricks.utils.builders.EntityBuilder;
import com.indignado.logicbricks.utils.builders.FixtureDefBuilder;
import com.indignado.logicbricks.utils.builders.LBBuilders;
import com.indignado.logicbricks.utils.builders.actuators.MotionActuatorBuilder;
import com.indignado.logicbricks.utils.builders.controllers.ConditionalControllerBuilder;
import com.indignado.logicbricks.utils.builders.sensors.AlwaysSensorBuilder;

/**
 * @author Rubentxu.
 */
public class Cohete extends EntityFactory {
    private String cohete = "assets/textures/cohete.png";

    public Cohete(LBBuilders builders, AssetManager assetManager) {
        super(builders, assetManager);

    }

    @Override
    public void loadAssets() {
        if (!assetManager.isLoaded(cohete)) assetManager.load(cohete, Texture.class);
    }

    @Override
    public Entity createEntity() {
        EntityBuilder entityBuilder = builders.getEntityBuilder();
        entityBuilder.initialize();
        BodyBuilder bodyBuilder = builders.getBodyBuilder();

        IdentityComponent identity = entityBuilder.getComponent(IdentityComponent.class);
        identity.tag = "Box";

        StateComponent state = entityBuilder.getComponent(StateComponent.class);
        state.createState("Default");

        Body bodyCohete = bodyBuilder.fixture(new FixtureDefBuilder()
                .boxShape(MathUtils.random(0.4f, 0.8f), MathUtils.random(0.4f, 0.8f))
                .friction(1f)
                .density(2f))
                .mass(2)
                .type(BodyDef.BodyType.DynamicBody)
                .build();

        AlwaysSensor alwaysSensor = builders.getBrickBuilder(AlwaysSensorBuilder.class)
                .setPulse(Sensor.Pulse.PM_TRUE)
                .setName("alwaysSensor")
                .getBrick();

        ConditionalController controller = builders.getBrickBuilder(ConditionalControllerBuilder.class)
                .setOp(ConditionalController.Op.OP_AND)
                .getBrick();

        MotionActuator motionActuator = builders.getBrickBuilder(MotionActuatorBuilder.class)
                .setTorque(5)
                .getBrick();

        RigidBodiesComponents bodiesComponents = entityBuilder.getComponent(RigidBodiesComponents.class);
        bodiesComponents.rigidBodies.add(bodyCohete);

        TextureView coheteView = new TextureView();
        coheteView.setName("Cohete");
        coheteView.setTextureRegion(new TextureRegion(assetManager.get(cohete, Texture.class)));
        coheteView.setHeight(2.5f);
        coheteView.setWidth(2.5f);
        coheteView.setAttachedTransform(bodyCohete.getTransform());
        coheteView.setLayer(0);

        ViewsComponent viewsComponent = entityBuilder.getComponent(ViewsComponent.class);
        viewsComponent.views.add(coheteView);

        Entity entity = entityBuilder.addController(controller, "Default")
                .connectToSensor(alwaysSensor)
                .connectToActuator(motionActuator)
                .getEntity();

        Gdx.app.log("Box", "instance" + entity);
        return entity;

    }

}


text:
/**
 * lazy creates a lazy value.
 *
 * @param fn value constructor.
 * @returns a function that returns a lazy value.
 */
export const lazy = <T>(fn: () => T, v?: T) => () => v === void 0 ? v = fn() : v!;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400,300">
    <link rel="stylesheet" href="{{ $assetURL }}css/bootstrap.min.css">
    <link rel="stylesheet" href="{{ $assetURL }}css/font-awesome.min.css">

               @yield('content')


text:
<?php
require '../_includes/handler-header.php';

if (!empty($_POST['wk11gm1']) && !empty($_POST['wk11gm2']) && !empty($_POST['wk11gm3']) &&
    !empty($_POST['wk11gm4']) && !empty($_POST['wk11gm5']) && !empty($_POST['wk11gm6']) &&
    !empty($_POST['wk11gm7']) && !empty($_POST['wk11gm8']) && !empty($_POST['wk11gm9']) &&
    !empty($_POST['wk11gm10']) && !empty($_POST['wk11gm11']) && !empty($_POST['wk11gm12']) &&
    !empty($_POST['wk11gm13']) && !empty($_POST['wk11-tiebreaker']) &&
    !empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username'])) {
    $username = $_SESSION['Username'];
    $wk11gm1 = mysql_real_escape_string($_POST['wk11gm1']);
    $wk11gm2 = mysql_real_escape_string($_POST['wk11gm2']);
    $wk11gm3 = mysql_real_escape_string($_POST['wk11gm3']);
    $wk11gm4 = mysql_real_escape_string($_POST['wk11gm4']);
    $wk11gm5 = mysql_real_escape_string($_POST['wk11gm5']);
    $wk11gm6 = mysql_real_escape_string($_POST['wk11gm6']);
    $wk11gm7 = mysql_real_escape_string($_POST['wk11gm7']);
    $wk11gm8 = mysql_real_escape_string($_POST['wk11gm8']);
    $wk11gm9 = mysql_real_escape_string($_POST['wk11gm9']);
    $wk11gm10 = mysql_real_escape_string($_POST['wk11gm10']);
    $wk11gm11 = mysql_real_escape_string($_POST['wk11gm11']);
    $wk11gm12 = mysql_real_escape_string($_POST['wk11gm12']);
    $wk11gm13 = mysql_real_escape_string($_POST['wk11gm13']);
    $tiebreaker = mysql_real_escape_string($_POST['wk11-tiebreaker']);
    $due_date = strtotime('2015-11-22T13:00:00-05:00');
    $submission_time = strtotime('now');
    $check_user_submission = mysql_query("SELECT wk11Complete FROM wk11 WHERE Username = '".$username."'");
    $submission_response_array = mysql_fetch_array($check_user_submission);

    if ($submission_response_array[0] == 1) {
        echo '
Error: You have already submitted your Week 11 picks. All submissions are final.
';
    } else if ($submission_time > $due_date) {
        echo '
Error: Your submission is too late. The first game of Week 11 has already started. Please try again next week.
';
    } else {
        $submit_wk11 = mysql_query("INSERT INTO wk11 (Username, wk11gm1, wk11gm2, wk11gm3, wk11gm4,
            wk11gm5, wk11gm6, wk11gm7, wk11gm8, wk11gm9, wk11gm10, wk11gm11, wk11gm12, wk11gm13,
            MondayTotalPoints, wk11Complete)
            VALUES('".$username."', '".$wk11gm1."', '".$wk11gm2."', '".$wk11gm3."', '".$wk11gm4."',
            '".$wk11gm5."', '".$wk11gm6."', '".$wk11gm7."', '".$wk11gm8."', '".$wk11gm9."',
            '".$wk11gm10."', '".$wk11gm11."', '".$wk11gm12."', '".$wk11gm13."',
            '".$tiebreaker."', true)");

        if ($submit_wk11) {
            echo '
Success! Your Week 11 picks have been recorded. Click here to view all picks.
';
        } else {
            echo '
Error: Your Week 11 submission has failed. Please go back and try again.
';
        }
    }

} else {
    echo '
Error: Your selections for Week 11 are incomplete. Please go back and try again.
';
}

include '../_includes/handler-footer.php';


text:
package org.elasticsearch.action.search.type;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.ReduceSearchPhaseException;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.AtomicArray;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import org.elasticsearch.search.action.SearchServiceListener;
import org.elasticsearch.search.action.SearchServiceTransportAction;
import org.elasticsearch.search.controller.SearchPhaseController;
import org.elasticsearch.search.dfs.AggregatedDfs;
import org.elasticsearch.search.dfs.DfsSearchResult;
import org.elasticsearch.search.fetch.QueryFetchSearchResult;
import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.search.internal.ShardSearchTransportRequest;
import org.elasticsearch.search.query.QuerySearchRequest;
import org.elasticsearch.threadpool.ThreadPool;

import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 */
public class TransportSearchDfsQueryAndFetchAction extends TransportSearchTypeAction {

    @Inject
    public TransportSearchDfsQueryAndFetchAction(Settings settings, ThreadPool threadPool, ClusterService clusterService,
                                                 SearchServiceTransportAction searchService, SearchPhaseController searchPhaseController, ActionFilters actionFilters) {
        super(settings, threadPool, clusterService, searchService, searchPhaseController, actionFilters);
    }

    @Override
    protected void doExecute(SearchRequest searchRequest, ActionListener<SearchResponse> listener) {
        new AsyncAction(searchRequest, listener).start();
    }

    private class AsyncAction extends BaseAsyncAction<DfsSearchResult> {

        private final AtomicArray<QueryFetchSearchResult> queryFetchResults;

        private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listener) {
            super(request, listener);
            queryFetchResults = new AtomicArray<>(firstResults.length());
        }

        @Override
        protected String firstPhaseName() {
            return "dfs";
        }

        @Override
        protected void sendExecuteFirstPhase(DiscoveryNode node, ShardSearchTransportRequest request, SearchServiceListener<DfsSearchResult> listener) {
            searchService.sendExecuteDfs(node, request, listener);
        }

        @Override
        protected void moveToSecondPhase() {
            final AggregatedDfs dfs = searchPhaseController.aggregateDfs(firstResults);
            final AtomicInteger counter = new AtomicInteger(firstResults.asList().size());

            for (final AtomicArray.Entry<DfsSearchResult> entry : firstResults.asList()) {
                DfsSearchResult dfsResult = entry.value;
                DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId());
                QuerySearchRequest querySearchRequest = new QuerySearchRequest(request, dfsResult.id(), dfs);
                executeSecondPhase(entry.index, dfsResult, counter, node, querySearchRequest);
            }
        }

        void executeSecondPhase(final int shardIndex, final DfsSearchResult dfsResult, final AtomicInteger counter, DiscoveryNode node, final QuerySearchRequest querySearchRequest) {
            searchService.sendExecuteFetch(node, querySearchRequest, new SearchServiceListener<QueryFetchSearchResult>() {
                @Override
                public void onResult(QueryFetchSearchResult result) {
                    result.shardTarget(dfsResult.shardTarget());
                    queryFetchResults.set(shardIndex, result);
                    if (counter.decrementAndGet() == 0) {
                        finishHim();
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    onSecondPhaseFailure(t, querySearchRequest, shardIndex, dfsResult, counter);
                }
            });
        }

        void onSecondPhaseFailure(Throwable t, QuerySearchRequest querySearchRequest, int shardIndex, DfsSearchResult dfsResult, AtomicInteger counter) {
            if (logger.isDebugEnabled()) {
                logger.debug("[{}] Failed to execute query phase", t, querySearchRequest.id());
            }
            this.addShardFailure(shardIndex, dfsResult.shardTarget(), t);
            successfulOps.decrementAndGet();
            if (counter.decrementAndGet() == 0) {
                finishHim();
            }
        }

        private void finishHim() {
            try {
                threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            boolean useScroll = !useSlowScroll && request.scroll() != null;
                            sortedShardList = searchPhaseController.sortDocs(useScroll, queryFetchResults);
                            final InternalSearchResponse internalResponse = searchPhaseController.merge(sortedShardList, queryFetchResults, queryFetchResults);
                            String scrollId = null;
                            if (request.scroll() != null) {
                                scrollId = TransportSearchHelper.buildScrollId(request.searchType(), firstResults, null);
                            }
                            listener.onResponse(new SearchResponse(internalResponse, scrollId, expectedSuccessfulOps, successfulOps.get(), buildTookInMillis(), buildShardFailures()));
                        } catch (Throwable e) {
                            ReduceSearchPhaseException failure = new ReduceSearchPhaseException("query_fetch", "", e, buildShardFailures());
                            if (logger.isDebugEnabled()) {
                                logger.debug("failed to reduce search", failure);
                            }
                            listener.onFailure(failure);
                        }
                    }
                });
            } catch (EsRejectedExecutionException ex) {
                listener.onFailure(ex);
            }

        }
    }
}


text:
package com.useunix.soccermanager.services;

import android.os.CountDownTimer;

public abstract class StopWatch extends CountDownTimer {

    public StopWatch(long millisInFuture, long countDownInterval) {
    	super(millisInFuture, countDownInterval);
    }

    public void stop() {
        cancel();
    }

    public void reset() {

    }

}


text:
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>AngularJS Tutorials</title>
  	<link rel="stylesheet" href="css/foundation/foundation.css" />
</head>

<body>
  <div ng-app="superApp">
    <superhero speed fligth strength>Superman</superhero>
    <superhero speed >The Flash</superhero>
  </div>

  <script src="js/angularjs/angular.js" ></script>
  <script src="js/main3.js"></script>
</body>

</html>


text:
import HTMLParser
import json

import apiv2.search.fsearch.formula_extractor
import latex2mathml.converter as lml
import re

import apiv2.search.fsearch.formula_features_extractor
from apiv2.search.fsearch import formula_features_extractor as fe
from .models import *

INT_NOTATION = re.compile(r'\\int\^.+')
h = HTMLParser.HTMLParser()

def print_mml(latex_str): print(h.unescape(lml.convert(latex_str)))

def check_question_content():
    questions = Question.objects.all()
    broken = []

    for question in questions:
        formulastrs = apiv2.search.utils.formula_extractor.extract_formulas_from_text(question.content)

        try:
            for formulastr in formulastrs:
                try:
                    fe.generate_features(formulastr)
                except Exception as e:
                    err_obj = {"id": question.id, "formula": formulastr,
                               "error": str(e)}
                    broken.append(err_obj)
                    print(err_obj)
        except Exception as e:
            err_obj = {"id": question.id, "question_content": question.content,
                       "error": str(e)}
            broken.append(err_obj)
            print(err_obj)

    with open('question_errors.json', 'w') as fp:
        json.dump(broken, fp, indent=2)

    return broken

def check_keypoint_content():
    keypoints = KeyPoint.objects.all()
    broken = []

    for keypoint in keypoints:
        formulastrs = apiv2.search.utils.formula_extractor.extract_formulas_from_text(keypoint.content)

        try:
            for formulastr in formulastrs:
                try:
                    fe.generate_features(formulastr)
                except Exception as e:
                    err_obj = {"id": keypoint.id, "formula": formulastr,
                               "error": str(e)}
                    broken.append(err_obj)
                    print(err_obj)
        except Exception as e:
            err_obj = {"id": keypoint.id, "keypoint_content": keypoint.content,
                       "error": str(e)}
            broken.append(err_obj)
            print(err_obj)

    with open('keypoint_errors.json', 'w') as fp:
        json.dump(broken, fp, indent=2)

    return broken

def check_solution_content():
    solutions = Solution.objects.all()
    broken = []

    for solution in solutions:
        formulastrs = apiv2.search.utils.formula_extractor.extract_formulas_from_text(solution.content)

        try:
            for formulastr in formulastrs:
                try:
                    fe.generate_features(formulastr)
                except Exception as e:
                    err_obj = {"id": solution.id, "formula": formulastr,
                               "error": str(e)}
                    broken.append(err_obj)
                    print(err_obj)
        except Exception as  e:
            err_obj = {"id": solution.id, "solution_content": solution.content,
                       "error": str(e)}
            broken.append(err_obj)
            print(err_obj)

    with open('solution_errors.json', 'w') as  fp:
        json.dump(broken, fp, indent=2)

    return broken

def find_integral_sup():
    questions = Question.objects.filter(content__iregex=r'\\int\^.+')
    return questions

def find_sqrt():
    questions = Question.objects.filter(content__iregex=r'\\sqrt\[.+')
    return questions

pattern = r'(?<!.*(sqrt|array))['

def fix_integral_sup():
    questions = find_integral_sup()

    for question in questions:
        question.content = corrected.get(question.id)
        question.save()
        print("question %s is fixed" % question.id)

def fix_sqrt():
    questions = find_sqrt()
    for question in questions:
        fixed = corrected.get(question.id)
        if fixed:
            question.content = fixed
            question.save()
            print("Question %s is saved" % question.id)

def fix_integral_sup():
    questions = find_integral_sup()

    for question in questions:
        question.content = corrected.get(question.id)
        question.save()
        print("question %s is fixed" % question.id)

corrected = {'id': 'corrected_content'}

def fix_questions():
    for q_id in corrected:
        question = Question.objects.get(pk=q_id)
        question.content = corrected[q_id]
        question.save()
        print("question %s is fixed" % question.id)

# handle integral
# handle []:
# escape except exceptions
# fix exceptions: do not stop if error parsing is found


text:
Reports C-style block comments or end-of-line comments that belong to a class member (field, method, or class) which can be converted to a Javadoc.

New in 2021.2


text:
package com.roncoo.pay.account.enums;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 结算发起方式
 * 龙果学院:www.roncoo.com
 * @author:zenghao
 */
public enum SettModeTypeEnum {

	/**
	 * 手工结算
	 */
	SELFHELP_SETTLE("手工结算"),

	/**
	 * 自动(定期)结算
	 */
	REGULAR_SETTLE("自动结算");

	/** 描述 */
	private String desc;

	private SettModeTypeEnum(String desc) {
		this.desc = desc;
	}

	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	public static SettModeTypeEnum getEnum(String enumName) {
		SettModeTypeEnum resultEnum = null;
		SettModeTypeEnum[] enumAry = SettModeTypeEnum.values();
		for (int i = 0; i < enumAry.length; i++) {
			if (enumAry[i].name().equals(enumName)) {
				resultEnum = enumAry[i];
				break;
			}
		}
		return resultEnum;
	}

	public static Map<String, Map<String, Object>> toMap() {
		SettModeTypeEnum[] ary = SettModeTypeEnum.values();
		Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>();
		for (int num = 0; num < ary.length; num++) {
			Map<String, Object> map = new HashMap<String, Object>();
			String key = ary[num].name();
			map.put("desc", ary[num].getDesc());
			enumMap.put(key, map);
		}
		return enumMap;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static List toList() {
		SettModeTypeEnum[] ary = SettModeTypeEnum.values();
		List list = new ArrayList();
		for (int i = 0; i < ary.length; i++) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("desc", ary[i].getDesc());
			list.add(map);
		}
		return list;
	}

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Gallio.UI.Properties;

namespace Gallio.UI.ControlPanel.Plugins
{
    internal partial class PluginControlPanelTab : ControlPanelTab
    {
        public PluginControlPanelTab()
        {
            InitializeComponent();
        }

        public void AddPlugin(string id, string name, Version version,
            Icon icon, string description, string disabledReason)
        {
            if (icon == null)
                icon = Resources.DefaultPluginIcon;

            Image smallIcon = new Icon(icon, new Size(16, 16)).ToBitmap();
            Image bigIcon = new Icon(icon, new Size(32, 32)).ToBitmap();

            var pluginInfo = new PluginInfo()
            {
                Id = id,
                Name = name,
                Version = version != null ? version.ToString() : "",
                SmallIcon = smallIcon,
                BigIcon = bigIcon,
                Description = description ?? name,
                DisabledReason = disabledReason
            };

            int rowIndex = pluginGrid.Rows.Add(pluginInfo.SmallIcon, pluginInfo.Name, pluginInfo.Version);
            DataGridViewRow row = pluginGrid.Rows[rowIndex];
            row.Tag = pluginInfo;

            if (disabledReason != null)
                row.DefaultCellStyle.ForeColor = Color.LightGray;
        }

        private void pluginGrid_SelectionChanged(object sender, EventArgs e)
        {
            if (pluginGrid.SelectedRows.Count != 0)
            {
                var row = pluginGrid.SelectedRows[0];
                var pluginInfo = (PluginInfo)row.Tag;

                pluginIconPictureBox.Image = pluginInfo.BigIcon;

                StringBuilder rtf = new StringBuilder();
                rtf.Append(@"{\rtf1 ");
                rtf.Append(RtfEscape(pluginInfo.Description));

                if (pluginInfo.DisabledReason != null)
                {
                    rtf.Append(@"\par\b Disabled:\b0  ");
                    rtf.Append(RtfEscape(pluginInfo.DisabledReason));
                }

                rtf.Append(@"}");

                pluginDescriptionRichTextBox.Rtf = rtf.ToString();
            }
            else
            {
                pluginIconPictureBox.Image = null;
                pluginDescriptionRichTextBox.Clear();
            }
        }

        private static string RtfEscape(string text)
        {
            return text.Replace(@"\", @"\\").Replace("{", @"\{").Replace("}", @"\}");
        }

        private sealed class PluginInfo
        {
            public string Id { get; set; }
            public string Name { get; set; }
            public string Version { get; set; }
            public Image SmallIcon { get; set; }
            public Image BigIcon { get; set; }
            public string Description { get; set; }
            public string DisabledReason { get; set; }
        }

        private void PluginControlPanelTab_Load(object sender, EventArgs e)
        {
            pluginGrid.Sort(pluginNameColumn, ListSortDirection.Ascending);
        }
    }
}


text:
package kieker.tools.slastic.plugins.cloud.amazon.service.configuration;

import java.util.Collection;
import java.util.Map;

import kieker.tools.slastic.plugins.cloud.amazon.model.AmazonApplicationInstance;
import kieker.tools.slastic.plugins.cloud.loadBalancerServlet.LoadBalancerServlet;

public interface IAmazonApplicationCloudingServiceConfiguration {

	/**
	 * Returns the debug configuration value.
	 *
	 * @return
	 */
	public boolean isDebugEnabled();

	/**
	 * In the dummy mode, the operation only claim to call the Amazon tools
	 * and return dummy values.
	 *
	 * @return
	 */
	public boolean isDummyModeEnabled();

	/**
	 * Returns whether the load balancer is enabled or not.
	 *
	 * @return
	 */
	public boolean isLoadBalancerEnabled();

	/**
	 * Returns the URL of a deployed {@link LoadBalancerServlet}.
	 *
	 * @return
	 */
	public String getLoadBalancerServletURL();

	/**
	 * Returns the file system location of this Amazon tools (e.g.
	 * {@code /usr/local/bin/}).
	 *
	 * @return
	 */
	public String getEC2toolsPath();

	/**
	 * Returns a map of image names x EMI.
	 *
	 * @return
	 */
	public Map<String, String> getAMIs();

	/**
	 * Returns a list of node instances to create initially. Each element of the
	 * returned collection is a String array with 4 elements: node name, ip,
	 * instance id, image name
	 *
	 * @return
	 * @see IAmazonApplicationCloudingServiceConfiguration#getAMIs()
	 */
	public Collection<String[]> getInitialNodeInstances();

	/**
	 * Returns a list of application to create initially.
	 *
	 * @return
	 */
	public Collection<String> getInitialApplications();

	/**
	 * Returns a list of application instances to create initially. Each element
	 * of the returned collection is a String array with 2 elements: application
	 * name, node instance
	 *
	 * @return
	 */
	public Collection<String[]> getInitialApplicationInstances();

	/**
	 * Returns the number of seconds to wait after a node de-allocation
	 * request before an instance is actually released. This property can be
	 * used to avoid the termination of active requests on instances.
	 *
	 * @return
	 */
	public int getNodeShutDownDelaySeconds();

	/**
	 * Returns the maximum time to wait for an allocated node to be available.
	 *
	 * @return
	 */
	public int getNodeAllocationMaxWaitTimeSeconds();

	/**
	 * Returns the poll period with which to check if an allocated node is available.
	 */
	public int getNodeAllocationPollPeriodSeconds();

	/**
	 * Returns the maximum time to wait for an application to be available.
	 *
	 * @return
	 */
	public int getApplicationInstanceDeployMaxWaitTimeSeconds();

	/**
	 * Returns the poll period with which to check if an application instance is
	 * available.
	 *
	 * @return
	 */
	public int getApplicationInstanceDeployPollPeriodSeconds();

	/**
	 * Returns the default port to send an HTTP request to (in order to check
	 * whether a newly deployed application instance became available).
	 *
	 * @return
	 * @see #getDefaultApplicationInstanceQueryPath()
	 */
	public int getDefaultApplicationInstanceQueryPort();

	/**
	 * Returns the path to send an HTTP request to (in order to check whether a
	 * newly deployed application instance became available).
	 *
	 * @return
	 * @see #getDefaultApplicationInstanceQueryPort()
	 */
	public String getDefaultApplicationInstanceQueryPath();

	/**
	 * Returns the file system location of the default artifact to copy to the
	 * directory specified by the property {@link #getTomcatHome()}.
	 *
	 * @return
	 */
	public String getDefaultApplicationDeploymentArtifact();

	/**
	 * Returns the name of the public key used for authentication with
	 * Amazon.
	 *
	 * @return
	 */
	public String getAmazonKeyName();

	/**
	 * Returns the name of the Amazon group to use (e.g., default)
	 *
	 * @return
	 */
	public String getAmazonGroup();

	/**
	 * Returns the file system locations of the private SSH key used to deploy
	 * {@link AmazonApplicationInstance}s via scp.
	 *
	 * @return
	 */
	public String getSSHPrivateKeyFile();

	/**
	 * Returns the user name used to deploy
	 * {@link AmazonApplicationInstance}s via scp.
	 *
	 * @return
	 */
	public String getSSHUserName();

	/**
	 * Returns the file system location of the tomcat (e.g.,
	 * {@code /opt/tomcat/})
	 *
	 * @return
	 */
	public String getTomcatHome();
}


text:
PySpark Loglikelihood Examples.

Inspired by [Mahout](http://mahout.apache.org/):
* [LogLikelihood](https://github.com/apache/mahout/blob/master/math/src/main/java/org/apache/mahout/math/stats/LogLikelihood.java)
* [User / Item Similarity](https://github.com/apache/mahout/blob/master/mr/src/main/java/org/apache/mahout/cf/taste/impl/similarity/LogLikelihoodSimilarity.java)
* [Nearest N-Neighborhood](https://github.com/apache/mahout/blob/master/mr/src/main/java/org/apache/mahout/cf/taste/impl/neighborhood/NearestNUserNeighborhood.java)

### Installation

```sh
$ pip install https://github.com/talmago/pyspark-loglikelihood/archive/master.zip
```

> **NOTICE:** PySpark Loglikelihood is adapted to [python2.7](https://www.python.org/download/releases/2.7/) to run. [pyenv](https://github.com/yyuu/pyenv) and [virtualenv](https://virtualenv.pypa.io/en/stable/) are recommended for setting an independent python environment.

### Usage

After the installation you can use `spark-submit` command line to execute the item-similarity and user-similarity jobs with your dataset respectively.

#### Item-Item Similarity (LogLikelihood)

```sh
$ spark-submit item_similarity.py \
               input.csv \
               output \
               --maxPrefs=10000 \
               --maxSimilaritiesPerItem 100
```
> **NOTICE:** Input file lines are expected to be comma seperated vectors of `USER_ID`,`ITEM_ID`. Output format will be consisted of `ITEM_ID1`,`ITEM_ID2`,`SCORE`.

#### User-User Similarity (N-neighborhood + Loglikelihood)

```sh

$ spark-submit user_similarity.py \
               input.csv \
               output \
               --numOfNeighbors=40 \
               --numOfRecommendations 1000
```
> **NOTICE:** Input file lines are expected to be comma seperated vectors of `USER_ID`,`ITEM_ID`. Output format will be consisted of `USER_ID`,`ITEM_ID`,`SCORE`.

### Example

##### Run [exmple](https://github.com/talmago/pyspark-loglikelihood/blob/master/examples/item-similarity-ml-100k-dataset) from command line

```sh
wget -O - https://raw.githubusercontent.com/talmago/pyspark-loglikelihood/master/examples/item-sim-ml-100l-dataset | bash -x
```

##### Step by Step

Step 1: Download and re-format the [movielens 100k](https://grouplens.org/datasets/movielens/100k/) dataset.

```sh
$ wget -O - http://files.grouplens.org/datasets/movielens/ml-100k/u.data | cut -f1 -f2 | tr '\t' ',' > input.csv
```

Step 2: Upload data set to local hfds

```sh
$ hadoop fs -rm -r /item-sim
$ hadoop fs -mkdir -p /item-sim
$ hadoop fs -moveFromLocal input.csv /item-sim/input.csv
```

Step 3: Run item-silmilarity job on our hadoop data set

```sh
$ spark-submit item_similarity.py \
               /item-sim/input.csv \
               /item-sim/output \
               --maxPrefs=10000 \
               --maxSimilaritiesPerItem 100
```

Step 4: Merge parquet files into a single csv file

```sh
$ hadoop fs -getmerge /item-sim/output result.csv
```

Step 5: Analyze / process / visualize the result set

```sh
$ head result.csv
26,381,0.9889748
26,732,0.9876871
26,70,0.98738647
26,715,0.98685825
26,238,0.98625606
26,58,0.98580784
26,1,0.985786
26,83,0.9857064
26,88,0.9856318
26,367,0.9854448
```


text:
@interface PodsDummy_Pods_Wattpad_Life_Parse : NSObject
@end
@implementation PodsDummy_Pods_Wattpad_Life_Parse
@end


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>{site_name}</title>
    <link href='http://fonts.googleapis.com/css?family=Roboto+Condensed|Oswald:400,700' rel='stylesheet' type='text/css'>
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="{assets}/css/foundation.min.css" />
    <link rel="stylesheet" href="{assets}/css/main.css" />

About

Podcasts

Blog

Contact


text:
<?php

/**
 * UI class for Stylizer.
 */
class stylizer_ui extends ctools_export_ui {

  function access($op, $item) {
    $access = parent::access($op, $item);
    if ($op == 'add' && $access && empty($this->base_types)) {
     // Make sure there are base styles defined.
     $access = FALSE;
    }
    return $access;
  }

  function list_form(&$form, &$form_state) {
    ctools_include('stylizer');
    parent::list_form($form, $form_state);

    $all = array('all' => t('- All -'));

    if (empty($this->base_types)) {
      // Give a warning about the missing base styles.
      drupal_set_message($this->plugin['strings']['message']['missing base type'], 'warning');
    }

    $types = $all;
    foreach ($this->base_types as $module => $info) {
      foreach ($info as $key => $base_type) {
        $types[$module . '-' . $key] = $base_type['title'];
      }
    }

    $form['top row']['type'] = array(
      '#type' => 'select',
      '#title' => t('Type'),
      '#options' => $types,
      '#default_value' => 'all',
      '#weight' => -10,
      '#attributes' => array('class' => 'ctools-auto-submit'),
    );

    $plugins = ctools_get_style_bases();
    $form_state['style_plugins'] = $plugins;

    $options = $all;
    // @todo base should use $module . '-' . $name
    foreach ($plugins as $name => $plugin) {
      $options[$name] = $plugin['title'];
    }

    $form['top row']['base'] = array(
      '#type' => 'select',
      '#title' => t('Base'),
      '#options' => $all + $options,
      '#default_value' => 'all',
      '#weight' => -9,
      '#attributes' => array('class' => 'ctools-auto-submit'),
    );
  }

  function list_sort_options() {
    return array(
      'disabled' => t('Enabled, title'),
      'title' => t('Title'),
      'name' => t('Name'),
      'base' => t('Base'),
      'type' => t('Type'),
      'storage' => t('Storage'),
    );
  }

  function list_filter($form_state, $item) {
    if (empty($form_state['style_plugins'][$item->settings['style_base']])) {
      $this->style_plugin = array(
        'name' => 'broken',
        'title' => t('Missing plugin'),
        'type' => t('Unknown'),
        'module' => '',
      );
    }
    else {
      $this->style_plugin = $form_state['style_plugins'][$item->settings['style_base']];
    }

    // This isn't really a field, but by setting this we can list it in the
    // filter fields and have the search box pick it up.
    $item->plugin_title = $this->style_plugin['title'];

    if ($form_state['values']['type'] != 'all') {
      list($module, $type) = explode('-', $form_state['values']['type']);
      if ($module != $this->style_plugin['module'] || $type != $this->style_plugin['type']) {
        return TRUE;
      }
    }

    if ($form_state['values']['base'] != 'all' && $form_state['values']['base'] != $this->style_plugin['name']) {
      return TRUE;
    }

    return parent::list_filter($form_state, $item);
  }

  function list_search_fields() {
    $fields = parent::list_search_fields();
    $fields[] = 'plugin_title';
    return $fields;
  }

  function list_build_row($item, &$form_state, $operations) {
    // Set up sorting
    switch ($form_state['values']['order']) {
      case 'disabled':
        $this->sorts[$item->name] = empty($item->disabled) . $item->admin_title;
        break;
      case 'title':
        $this->sorts[$item->name] = $item->admin_title;
        break;
      case 'name':
        $this->sorts[$item->name] = $item->name;
        break;
      case 'type':
        $this->sorts[$item->name] = $this->style_plugin['type'] . $item->admin_title;
        break;
      case 'base':
        $this->sorts[$item->name] = $this->style_plugin['title'] . $item->admin_title;
        break;
      case 'storage':
        $this->sorts[$item->name] = $item->type . $item->admin_title;
        break;
    }

    if (!empty($this->base_types[$this->style_plugin['module']][$this->style_plugin['type']])) {
      $type = $this->base_types[$this->style_plugin['module']][$this->style_plugin['type']]['title'];
    }
    else {
      $type = t('Unknown');
    }

    $this->rows[$item->name] = array(
      'data' => array(
        array('data' => $type, 'class' => 'ctools-export-ui-type'),
        array('data' => check_plain($item->name), 'class' => 'ctools-export-ui-name'),
        array('data' => check_plain($item->admin_title), 'class' => 'ctools-export-ui-title'),
        array('data' => check_plain($this->style_plugin['title']), 'class' => 'ctools-export-ui-base'),
        array('data' => check_plain($item->type), 'class' => 'ctools-export-ui-storage'),
        array('data' => theme('links', $operations), 'class' => 'ctools-export-ui-operations'),
      ),
      'title' => check_plain($item->admin_description),
      'class' => !empty($item->disabled) ? 'ctools-export-ui-disabled' : 'ctools-export-ui-enabled',
    );
  }

  function list_table_header() {
    return array(
      array('data' => t('Type'), 'class' => 'ctools-export-ui-type'),
      array('data' => t('Name'), 'class' => 'ctools-export-ui-name'),
      array('data' => t('Title'), 'class' => 'ctools-export-ui-title'),
      array('data' => t('Base'), 'class' => 'ctools-export-ui-base'),
      array('data' => t('Storage'), 'class' => 'ctools-export-ui-storage'),
      array('data' => t('Operations'), 'class' => 'ctools-export-ui-operations'),
    );
  }

  function init($plugin) {
    ctools_include('stylizer');
    $this->base_types = ctools_get_style_base_types();

    parent::init($plugin);
  }

  function get_wizard_info(&$form_state) {
    $form_info = parent::get_wizard_info($form_state);
    ctools_include('stylizer');

    // For add forms, we have temporarily set the 'form type' to include
    // the style type so the default wizard_info can find the path. If
    // we did that, we have to put it back.
    if (!empty($form_state['type'])) {
      $form_state['form type'] = 'add';
      $form_info['show back'] = TRUE;
    }

    // Ensure these do not get out of sync.
    $form_state['item']->settings['name'] = $form_state['item']->name;
    $form_state['settings'] = $form_state['item']->settings;

    // Figure out the base style plugin in use and make sure that is available.
    $plugin = NULL;
    if (!empty($form_state['item']->settings['style_base'])) {
      $plugin = ctools_get_style_base($form_state['item']->settings['style_base']);
      ctools_stylizer_add_plugin_forms($form_info, $plugin, $form_state['op']);
    }
    else {
      // This is here so the 'finish' button does not show up, and because
      // we don't have the selected style we don't know what the next form(s)
      // will be.
      $form_info['order']['next'] = t('Configure style');

    }

    // If available, make sure these are available for the 'choose' form.
    if (!empty($form_state['item']->style_module)) {
      $form_state['module'] = $form_state['item']->style_module;
      $form_state['type'] = $form_state['item']->style_type;
    }

    $form_state['plugin'] = $plugin;
    $form_state['settings'] = $form_state['item']->settings;
    return $form_info;
  }

  /**
   * Store the stylizer info in our settings.
   *
   * The stylizer wizard stores its stuff in slightly different places, so
   * we have to find it and move it to the right place.
   */
  function store_stylizer_info(&$form_state) {
    /*
    foreach (array('name', 'admin_title', 'admin_description') as $key) {
      if (!empty($form_state['values'][$key])) {
        $form_state['item']->{$key} = $form_state['values'][$key];
      }
    }
    */

    if ($form_state['step'] != 'import') {
      $form_state['item']->settings = $form_state['settings'];
    }
    // Do not let the 'name' accidentally get out of sync under any circumstances.
    $form_state['item']->settings['name'] = $form_state['item']->name;
  }

  function edit_wizard_next(&$form_state) {
    $this->store_stylizer_info($form_state);
    parent::edit_wizard_next($form_state);
  }

  function edit_wizard_finish(&$form_state) {
    // These might be stored by the stylizer wizard, so we should clear them.
    if (isset($form_state['settings']['old_settings'])) {
      unset($form_state['settings']['old_settings']);
    }
    $this->store_stylizer_info($form_state);
    parent::edit_wizard_finish($form_state);
  }

  function edit_form_type(&$form, &$form_state) {
    foreach ($this->base_types as $module => $info) {
      foreach ($info as $key => $base_type) {
        $types[$module . '-' . $key] = $base_type['title'];
      }
    }

    $form['type'] = array(
      '#type' => 'select',
      '#title' => t('Type'),
      '#options' => $types,
      '#default_value' => 'all',
      '#weight' => -10,
      '#attributes' => array('class' => 'ctools-auto-submit'),
    );
  }

  function edit_form_type_submit(&$form, &$form_state) {
    list($form_state['item']->style_module, $form_state['item']->style_type) = explode('-', $form_state['values']['type']);
  }
}


text:
<?php

namespace Magefan\Blog\Model;

/**
 * Blog url model
 */
class Url
{
    /**
     * Permalink Types
     */
    const PERMALINK_TYPE_DEFAULT = 'default';
    const PERMALINK_TYPE_SHORT = 'short';

    /**
     * Objects Types
     */
    const CONTROLLER_POST = 'post';
    const CONTROLLER_CATEGORY = 'category';
    const CONTROLLER_ARCHIVE = 'archive';
    const CONTROLLER_AUTHOR = 'author';
    const CONTROLLER_SEARCH = 'search';
    const CONTROLLER_RSS = 'rss';
    const CONTROLLER_TAG = 'tag';

    /**
     * @var \Magento\Framework\Registry
     */
    protected $_registry;

    /**
     * @var \Magento\Framework\UrlInterface
     */
    protected $_url;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;

    /**
     * Core store config
     *
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $_scopeConfig;

    /**
     * Initialize dependencies.
     *
     * @param \Magento\Framework\Registry $registry
     * @param \Magento\Framework\UrlInterface $url
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     */
    public function __construct(
        \Magento\Framework\Registry $registry,
        \Magento\Framework\UrlInterface $url,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    ) {
        $this->_registry = $registry;
        $this->_url = $url;
        $this->_storeManager = $storeManager;
        $this->_scopeConfig = $scopeConfig;
    }

    /**
     * Retrieve permalink type
     * @return string
     */
    public function getPermalinkType()
    {
        return $this->_getConfig('type');
    }

    /**
     * Retrieve route name by controller
     * @param  string  $controllerName
     * @param  boolean $skip
     * @return string || null
     */
    public function getRoute($controllerName = null, $skip = true)
    {
        if ($controllerName) {
            $controllerName .= '_';
        }

        if ($route = $this->_getConfig($controllerName.'route')) {
            return $route;
        } else {
            return $skip ? $controllerName : null;
        }
    }

    /**
     * Retrieve controller name by route
     * @param  string  $route
     * @param  boolean $skip
     * @return string || null
     */
    public function getControllerName($route, $skip = true)
    {
        foreach([
            self::CONTROLLER_POST,
            self::CONTROLLER_CATEGORY,
            self::CONTROLLER_ARCHIVE,
            self::CONTROLLER_AUTHOR,
            self::CONTROLLER_TAG,
            self::CONTROLLER_SEARCH
        ] as $controllerName) {
            if ($this->getRoute($controllerName) == $route) {
                return $controllerName;
            }
        }

        return $skip ? $route : null;
    }

    /**
     * Retrieve blog base url
     * @return string
     */
    public function getBaseUrl()
    {
        return $this->_url->getUrl($this->getRoute());
    }

    /**
     * Retrieve blog page url
     * @param  string $identifier
     * @param  string $controllerName
     * @return string
     */
    public function getUrl($identifier, $controllerName)
    {
        return $this->_url->getUrl(
            $this->getUrlPath($identifier, $controllerName)
        );
    }

    /**
     * Retrieve blog url path
     * @param  string $identifier
     * @param  string $controllerName
     * @return string
     */
    public function getUrlPath($identifier, $controllerName)
    {
        if (is_object($identifier)) {
            $identifier = $identifier->getIdentifier();
        }

        switch ($this->getPermalinkType()) {
            case self::PERMALINK_TYPE_DEFAULT :
                return $this->getRoute() . '/' . $this->getRoute($controllerName) . '/' . $identifier;
            case self::PERMALINK_TYPE_SHORT :
                if ($controllerName == self::CONTROLLER_SEARCH
                    || $controllerName == self::CONTROLLER_AUTHOR
                    || $controllerName == self::CONTROLLER_TAG
                ) {
                    return $this->getRoute() . '/' . $this->getRoute($controllerName) . '/' . $identifier;
                } else {
                    return $this->getRoute() . '/' . $identifier;
                }
        }
    }

    /**
     * Retrieve media url
     * @param string $file
     * @return string
     */
    public function getMediaUrl($file)
    {
        return $this->_storeManager->getStore()
            ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . $file;
    }

    /**
     * Retrieve blog permalink config value
     * @param  string $key
     * @return string || null || int
     */
    protected function _getConfig($key)
    {
        return $this->_scopeConfig->getValue(
            'mfblog/permalink/'.$key,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

}


text:
"""XML reporting for coverage.py"""

import os, sys, time
import xml.dom.minidom

from coverage import __url__, __version__
from coverage.backward import sorted, rpartition    # pylint: disable=W0622
from coverage.report import Reporter

def rate(hit, num):
    """Return the fraction of `hit`/`num`, as a string."""
    return "%.4g" % (float(hit) / (num or 1.0))

class XmlReporter(Reporter):
    """A reporter for writing Cobertura-style XML coverage results."""

    def __init__(self, coverage, config):
        super(XmlReporter, self).__init__(coverage, config)

        self.packages = None
        self.xml_out = None
        self.arcs = coverage.data.has_arcs()

    def report(self, morfs, outfile=None):
        """Generate a Cobertura-compatible XML report for `morfs`.

        `morfs` is a list of modules or filenames.

        `outfile` is a file object to write the XML to.

        """
        # Initial setup.
        outfile = outfile or sys.stdout

        # Create the DOM that will store the data.
        impl = xml.dom.minidom.getDOMImplementation()
        docType = impl.createDocumentType(
            "coverage", None,
            "http://cobertura.sourceforge.net/xml/coverage-03.dtd"
            )
        self.xml_out = impl.createDocument(None, "coverage", docType)

        # Write header stuff.
        xcoverage = self.xml_out.documentElement
        xcoverage.setAttribute("version", __version__)
        xcoverage.setAttribute("timestamp", str(int(time.time()*1000)))
        xcoverage.appendChild(self.xml_out.createComment(
            " Generated by coverage.py: %s " % __url__
            ))
        xpackages = self.xml_out.createElement("packages")
        xcoverage.appendChild(xpackages)

        # Call xml_file for each file in the data.
        self.packages = {}
        self.report_files(self.xml_file, morfs)

        lnum_tot, lhits_tot = 0, 0
        bnum_tot, bhits_tot = 0, 0

        # Populate the XML DOM with the package info.
        for pkg_name in sorted(self.packages.keys()):
            pkg_data = self.packages[pkg_name]
            class_elts, lhits, lnum, bhits, bnum = pkg_data
            xpackage = self.xml_out.createElement("package")
            xpackages.appendChild(xpackage)
            xclasses = self.xml_out.createElement("classes")
            xpackage.appendChild(xclasses)
            for class_name in sorted(class_elts.keys()):
                xclasses.appendChild(class_elts[class_name])
            xpackage.setAttribute("name", pkg_name.replace(os.sep, '.'))
            xpackage.setAttribute("line-rate", rate(lhits, lnum))
            xpackage.setAttribute("branch-rate", rate(bhits, bnum))
            xpackage.setAttribute("complexity", "0")

            lnum_tot += lnum
            lhits_tot += lhits
            bnum_tot += bnum
            bhits_tot += bhits

        xcoverage.setAttribute("line-rate", rate(lhits_tot, lnum_tot))
        xcoverage.setAttribute("branch-rate", rate(bhits_tot, bnum_tot))

        # Use the DOM to write the output file.
        outfile.write(self.xml_out.toprettyxml())

        # Return the total percentage.
        denom = lnum_tot + bnum_tot
        if denom == 0:
            pct = 0.0
        else:
            pct = 100.0 * (lhits_tot + bhits_tot) / denom
        return pct

    def xml_file(self, cu, analysis):
        """Add to the XML report for a single file."""

        # Create the 'lines' and 'package' XML elements, which
        # are populated later.  Note that a package == a directory.
        package_name = rpartition(cu.name, ".")[0]
        className = cu.name

        package = self.packages.setdefault(package_name, [{}, 0, 0, 0, 0])

        xclass = self.xml_out.createElement("class")

        xclass.appendChild(self.xml_out.createElement("methods"))

        xlines = self.xml_out.createElement("lines")
        xclass.appendChild(xlines)

        xclass.setAttribute("name", className)
        filename = cu.file_locator.relative_filename(cu.filename)
        xclass.setAttribute("filename", filename.replace("\\", "/"))
        xclass.setAttribute("complexity", "0")

        branch_stats = analysis.branch_stats()

        # For each statement, create an XML 'line' element.
        for line in sorted(analysis.statements):
            xline = self.xml_out.createElement("line")
            xline.setAttribute("number", str(line))

            # Q: can we get info about the number of times a statement is
            # executed?  If so, that should be recorded here.
            xline.setAttribute("hits", str(int(line not in analysis.missing)))

            if self.arcs:
                if line in branch_stats:
                    total, taken = branch_stats[line]
                    xline.setAttribute("branch", "true")
                    xline.setAttribute("condition-coverage",
                        "%d%% (%d/%d)" % (100*taken/total, taken, total)
                        )
            xlines.appendChild(xline)

        class_lines = len(analysis.statements)
        class_hits = class_lines - len(analysis.missing)

        if self.arcs:
            class_branches = sum([t for t,k in branch_stats.values()])
            missing_branches = sum([t-k for t,k in branch_stats.values()])
            class_br_hits = class_branches - missing_branches
        else:
            class_branches = 0.0
            class_br_hits = 0.0

        # Finalize the statistics that are collected in the XML DOM.
        xclass.setAttribute("line-rate", rate(class_hits, class_lines))
        xclass.setAttribute("branch-rate", rate(class_br_hits, class_branches))
        package[0][className] = xclass
        package[1] += class_hits
        package[2] += class_lines
        package[3] += class_br_hits
        package[4] += class_branches


text:
"""
Tests for :mod:`ranger-ims-server.model.json._incident`
"""

from hypothesis import given

from ims.ext.trial import TestCase

from ..._incident import Incident
from ...strategies import incidents
from .._json import jsonDeserialize, jsonSerialize
from .json import jsonFromIncident

__all__ = ()

class IncidentSerializationTests(TestCase):
    """
    Tests for serialization of :class:`Incident`
    """

    @given(incidents())
    def test_serialize(self, incident: Incident) -> None:
        """
        :func:`jsonSerialize` serializes the given incident.
        """
        self.assertEqual(jsonSerialize(incident), jsonFromIncident(incident))

class IncidentDeserializationTests(TestCase):
    """
    Tests for deserialization of :class:`Incident`
    """

    @given(incidents())
    def test_deserialize(self, incident: Incident) -> None:
        """
        :func:`jsonDeserialize` returns an incident with the correct data.
        """
        self.assertEqual(
            jsonDeserialize(jsonFromIncident(incident), Incident), incident
        )


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Reverb.Data.Contracts;
using Reverb.Data.SaveChanges;

namespace Reverb.Data.UnitTests.SaveContextTests
{
    [TestClass]
    public class SaveChanges_Should
    {
        [TestMethod]
        public void CallContextSaveChangesOnce_WhenInvoked()
        {
            // Arrange
            var context = new Mock<IReverbDbContext>();

            context.Setup(x => x.SaveChanges());

            var sut = new SaveContext(context.Object);

            // Act
            sut.SaveChanges();

            // Assert
            context.Verify(x => x.SaveChanges(), Times.Once);
        }
    }
}


text:
using System;

namespace Microsoft.Media.ISO.Boxes
{
    /// <summary>
    /// Placeholder for unknown boxes that can be ignored.
    /// </summary>
    public class InitialObjectDescriptorBox : Box
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="UnknownBox"/> class.
        /// </summary>
        /// <param name="offset">The offset in the stream where this box begins.</param>
        /// <param name="size">The size of this box.</param>
        /// <param name="boxType">Type of the box.</param>
        public InitialObjectDescriptorBox(long offset, long size)
            : base(offset, size, BoxType.Iods)
        {
        }

        protected override void ReadBoxPropertiesFromStream(BoxBinaryReader reader)
        {
            reader.GotoEndOfBox(this.Offset, this.Size);
        }
    }
}


text:
#ifndef _VECTOR4_H_
#define _VECTOR4_H_

#if _MSC_VER == 1200
#pragma warning(disable:4786)
#endif

#include <iostream>

/// Definition of a vector in 4 dimensions.
class CVector4
{
public:

	/// Default constructor: sets the vector to zero.
	CVector4() { x = y = z = 0.0f; w = 1.0f; }

	/// Initialize the vector with the specified components.
	CVector4( float x_, float y_, float z_, float w_ = 1.0f ) { x = x_; y = y_; z = z_; w = w_; }

	/// Addition operator.
	CVector4	operator + ( const CVector4 &v ) const;

	/// Subtraction operator.
	CVector4	operator - ( const CVector4 &v ) const;

	/// Dot product operator.
	float		operator * ( const CVector4 &v ) const;

	/// Vector-scalar multiplication.
	CVector4	operator * ( const float &a ) const;

	/// Vector-scalar division.
	CVector4	operator / ( const float &a ) const;

	/// Vector-scalar multiplication and assign operator.
	CVector4&	operator *= ( const float &a );

	/// Vector-scalar division and assign operator.
	CVector4&	operator /= ( const float &a );

	/// Add and assign operator.
	CVector4&	operator += ( const CVector4 &v );

	/// Subtract and assign operator.
	CVector4&	operator -= ( const CVector4 &v );

	/// Inversion.
	CVector4	operator - () const;

	/// Returns a reference to a vector component.
	float&		operator [] ( const int i )			{ return *(&x + i);	}

	/// Returns a vector component.
	float		operator [] ( const int i )	const	{ return *(&x + i);	}

	/// Equality boolean operator
	bool		operator == ( const CVector4& v ) const;

	/// Inequality boolean operator
	bool		operator != ( const CVector4& v ) const;

	/// Scalar-vector multiplication operator.
	friend		CVector4 operator * ( const float &a, const CVector4 &v );

	/// Scalar-vector division operator.
	friend		CVector4 operator / ( const float &a, const CVector4 &v );

	/// Stream output operator.
	friend		std::ostream& operator << (std::ostream& os, const CVector4& v );

	/// Returns the vector's norm.
	float		Norm() const;

	/// Normalize the vector.
	CVector4	Normalize();

	/// Returns the smallest vector component.
	float		Max() const;

	/// Returns the greatest vector component.
	float		Min() const;

	/// A zero vector.
	static const CVector4	ZERO;

	float
	/// The x component.
	x,
	/// The y component.
	y,
	/// The z component.
	z,
	/// The w component.
	w;
};

#endif


text:
In case user is connecting to JIRA system and gets the error like
"Impossible interact with external system.<name of current user's project>", there
are some reasons could cause the issue.

**First**, verify that the link to JIRA system is correct. There are some variants
are possible, for instance:
https://jira.company.com/jira
https://jiraeu.company.com

**Second**, verify the project name is correct. Please fill in Project name field with
project key value, e.g. project ABC-DEF has key ABCDEF.

**Third**, verify username and password data. Make sure, that login name and not email
is in the username field. In case all the data above is correct, but the error
appears again, check whether user's credentials to JIRA are not expired.
As far as JIRA sends the request in html format, we are not able to display the real
reason of error.
To check and/or resolve the issue, please do the next steps:
1. Open JIRA page
2. Login JIRA with domain credentials using basic authorization (i.e., fill in user's
login name and password into the fields)
3. Submit the login form
Screen with CAPTCHA should appears
4. Enter the symbols
5. Submit the credentials again
6. Now try to establish the connection to JIRA on ReportPortal project.

**Fourth**, maybe the connection to the jira instance requires a certificate, in this
case you need to import the certificate inside the jira container:

1. docker exec -it reportportal_jira_1 ash # go inside shell
2. cd /usr/lib/jvm/java-1.8-openjdk/jre/lib/security/
3. wget url://to/your/foo.cert
4. keytool -importcert -noprompt -file foo.crt -alias "JIRA CERT" -keystore cacerts -storepass abc123 (default password for keystore: changeit)
5. exit and restart the docker jira
6. Now try to establish the connection to JIRA on ReportPortal project.

or

1. docker cp cert.der reportportal_jira_1:/cert.der
2. docker exec -t -i reportportal_jira_1 ./usr/lib/jvm/java-1.8-openjdk/jre/bin/keytool -import -alias rootcert -keystore /usr/lib/jvm/java-1.8-openjdk/jre/lib/security/cacerts -file /cert.der
3. exit and restart the docker jira
4. Now try to establish the connection to JIRA on ReportPortal project.

**Note:**
SSL instance of JIRA (even cloud version) can be accessed by JIRA API token, used instead of password.

If these didn't resolve your issues, please contact us.


text:
package org.apache.cassandra.gms;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.*;

import org.apache.cassandra.io.ICompactSerializer;
import java.net.InetAddress;

/**
 * This message gets sent out as a result of the receipt of a GossipDigestSynMessage by an
 * endpoint. This is the 2 stage of the 3 way messaging in the Gossip protocol.
 */

class GossipDigestAckMessage
{
    private static ICompactSerializer<GossipDigestAckMessage> serializer_;
    static
    {
        serializer_ = new GossipDigestAckMessageSerializer();
    }

    List<GossipDigest> gDigestList_ = new ArrayList<GossipDigest>();
    Map<InetAddress, EndPointState> epStateMap_ = new HashMap<InetAddress, EndPointState>();

    static ICompactSerializer<GossipDigestAckMessage> serializer()
    {
        return serializer_;
    }

    GossipDigestAckMessage(List<GossipDigest> gDigestList, Map<InetAddress, EndPointState> epStateMap)
    {
        gDigestList_ = gDigestList;
        epStateMap_ = epStateMap;
    }

    List<GossipDigest> getGossipDigestList()
    {
        return gDigestList_;
    }

    Map<InetAddress, EndPointState> getEndPointStateMap()
    {
        return epStateMap_;
    }
}

class GossipDigestAckMessageSerializer implements ICompactSerializer<GossipDigestAckMessage>
{
    public void serialize(GossipDigestAckMessage gDigestAckMessage, DataOutputStream dos) throws IOException
    {
        /* Use the helper to serialize the GossipDigestList */
        boolean bContinue = GossipDigestSerializationHelper.serialize(gDigestAckMessage.gDigestList_, dos);
        dos.writeBoolean(bContinue);
        /* Use the EndPointState */
        if ( bContinue )
        {
            EndPointStatesSerializationHelper.serialize(gDigestAckMessage.epStateMap_, dos);
        }
    }

    public GossipDigestAckMessage deserialize(DataInputStream dis) throws IOException
    {
        Map<InetAddress, EndPointState> epStateMap = new HashMap<InetAddress, EndPointState>();
        List<GossipDigest> gDigestList = GossipDigestSerializationHelper.deserialize(dis);
        boolean bContinue = dis.readBoolean();

        if ( bContinue )
        {
            epStateMap = EndPointStatesSerializationHelper.deserialize(dis);
        }
        return new GossipDigestAckMessage(gDigestList, epStateMap);
    }
}


text:
/**
 * Validates that a value is a valid email address. The underlying value is cast to a string before being validated.
 *
 * @author Alexey Bob <alexey.bob@gmail.com>
 * @todo: strict, checkMX, checkHost
 */
'use strict';

//import Validator from './AbstractValidator';
var Validator = require('./AbstractValidator');

class EmailValidator extends Validator {
    constructor() {
        super(arguments);

        var strict = arguments[0]['strict'];
        var checkMX = arguments[0]['checkMX'];
        var checkHost = arguments[0]['checkHost'];
        var message = arguments[0]['message'];

        this.configuring();

        this.setMessage('message', message);

        this.setParameter('strict', strict);
        this.setParameter('checkMX', checkMX);
        this.setParameter('checkHost', checkHost);
    }

    configuring() {
        this.setDefaultMessages({
            'message': 'This value is not a valid email address.',
        });

        this.setDefaultParameters({
            'strict': false,
            'checkMX': false,
            'checkHost': false,
        });
    }

    validate(data, errorType) {
        errorType = (errorType == null) ? 'array' : errorType;
        this.setErrorType(errorType);
        this.resetErrors();

        //if(/^.+\@\S+\.\S+$/.test(data) == false){
        if(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(data) == false){
            this.addError(this.getMessage('message'));
        }
    }
}

module.exports = EmailValidator;


text:
<?php

namespace Ikodota\Yeoman\Controllers\Admin\System;

use Ikodota\Yeoman\Models\Role;
use Ikodota\Yeoman\Models\Permission;
use Illuminate\Http\Request;
use Ikodota\Yeoman\Requests\Admin\PermissionForm;
use Ikodota\Yeoman\Controllers\Admin\Controller;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\URL;

class PermissionController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if (Gate::foruser($this->loggedUser())->denies('admin.permission.read')) {
            abort(403);
        }
        $keyword=$request->get('keyword');
        $permissions = Permission::where('display_name', 'like', '%'.$keyword.'%')
            ->orWhere('name', 'like', '%'.$keyword.'%')
            ->paginate(10);
        return view('yeoman::backend.permission.index', compact('permissions'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $referer_url = URL::previous();
        if (Gate::foruser($this->loggedUser())->denies('admin.permission.read')) {
            abort(403);
        }
        return view('yeoman::backend.permission.create',compact('referer_url'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if (Gate::foruser($this->loggedUser())->denies('admin.permission.create')) {
            abort(403);
        }
        $data = $request->all();
        $referer_url=$data['_referer'];
        unset($data['_token']);
        unset($data['_method']);
        unset($data['_referer']);
        try {
            if (Permission::create($data)) {
                return redirect()->to($referer_url)->with('success','新增权限成功');
            }
        }
        catch (\Exception $e)
        {
            return redirect()->to($referer_url)->withErrors(array('error' => $e->getMessage()))->withInput();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //选择的权限
        $permission = Permission::find($id);
        $roles = Role::where('name','<>','super_admin')->get();
        //获取角色拥有的权限
        $permission_roles = Permission::find($id)->roles()->orderBy('name')->get();
        $permission_roles_names = [];
        foreach ($permission_roles as $role){
            $permission_roles_names[]= $role->name;
        }

        return view('yeoman::backend.permission.roles', compact('permission','roles','permission_roles_names'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $referer_url = URL::previous();
        if (Gate::foruser($this->loggedUser())->denies('admin.permission.read')) {
            abort(403);
        }
        $permission = Permission::find($id);

        $roles = Role::where('name','<>','super_admin')->get();
        //获取角色拥有的权限
        $permission_roles = Permission::find($id)->roles()->orderBy('name')->get();
        $permission_roles_names = [];
        foreach ($permission_roles as $role){
            $role_permission_names[]= $role->name;
        }
        return view('yeoman::backend.permission.edit',  compact('permission','roles','permission_roles_names','referer_url'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(PermissionForm $request, $id)
    {
        if (Gate::foruser($this->loggedUser())->denies('admin.permission.update')) {
            abort(403);
        }
        $data = $request->all();
        $referer_url=$data['_referer'];

        unset($data['_token']);
        unset($data['_method']);
        unset($data['_referer']);
        try {
            if (Permission::where('id', $id)->update($data)) {
                return redirect()->to($referer_url)->withSuccess('编辑权限成功');
            }
        }
        catch (\Exception $e)
        {
            return redirect()->to($referer_url)->withErrors(array('error' => $e->getMessage()))->withInput();
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (Gate::foruser($this->loggedUser())->denies('admin.permission.delete')) {
            abort(403);
        }
        try {
            if (Permission::destroy($id)) {
                return redirect()->back()->with('success','删除权限成功');
            }
        }
        catch (\Exception $e)
        {
            return redirect()->back()->withErrors(array('error' => $e->getMessage()));
        }
    }

    /**
     * @param Request $request
     * @param $id
     * @return $this
     */
    public function attach(Request $request,$id)
    {
        if (Gate::foruser($this->loggedUser())->denies('admin.permission.attach')) {
            abort(403);
        }
        $data = $request->all();
        unset($data['_token']);
        unset($data['_method']);
        try {
            $Permission=Permission::find($id);
            if(!empty($data['roles'])){
                $Permission->Roles()->sync($data['roles']);
            }
            return redirect()->back()->with('success',trans('system.success.attach_permission_to_roles'));
        }
        catch (\Exception $e)
        {
            return redirect()->back()->withErrors(array('error' => $e->getMessage()))->withInput();
        }
    }
}


text:
*Format stolen from [urllib3/CONTRIBUTORS.txt](https://github.com/shazow/urllib3/blob/master/CONTRIBUTORS.txt)*

# Contributors to `piazza-api`

## Creator & Maintainer

* Hamza Faran [@hfaran](https://github.com/hfaran)

## Contributors

* Ben Cook [@blx](https://github.com/blx)
    * Get users
    * `PiazzaRPC.request`
    * [`Piazza.get_user_classes`](https://github.com/hfaran/piazza-api/pull/22)

* Waleed Khan [@arxanas](https://github.com/arxanas)
    * [`Network.create_followup`](https://github.com/hfaran/piazza-api/pull/25)

* Jérémie Lumbroso [@jlumbroso](https://github.com/jlumbroso)
    * Support for nonces (`aid`)
    * Added ``get_user_status`` and fixed retrieval of user classes (``get_user_classes``).

* Philip Mallory [@pmallory](https://github.com/pmallory)
    * Enroll users
    * Get all users
    * Remove users

* David Snider [@DavidSnider](https://github.com/DavidSnider)
    * [feat(user): Add answer-creating functionality](https://github.com/hfaran/piazza-api/pull/31)


text:
var w = window.innerWidth;
var h = window.innerHeight;

var canvas = document.getElementById('c');
var context = canvas.getContext('2d');

canvas.width = w;
canvas.height = h;

var pi2x = Math.PI * 2;

window.requestAnimFrame = (function(callback) {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
        function(callback) {
            window.setTimeout(callback, 1000 / 60);
        };
})();

function drawText(text,font,xx,yy){
    context.font = font;
    context.fillStyle = "rgb(255,255,255)";
    context.fillText(text, xx, yy);

    var px = [];

    var imgData=context.getImageData(0,0,canvas.width,canvas.height);

    for(x=0; x<imgData.width; x++)
    {
        for(y=0 ; y<imgData.height; y++)
        {
            if(getPixel(imgData,x,y)[3] > 0)
            {
                px.push( [x,y] );
            }
        }
    }

    return px;
}

function getPixel(imgData, x, y) {
    var offset = (x + y * imgData.width) * 4;
    var r = imgData.data[offset+0];
    var g = imgData.data[offset+1];
    var b = imgData.data[offset+2];
    var a = imgData.data[offset+3];

    return [r,g,b,a];
}

function draw(pixels,space,z,moveBy){

    context.lineJoin="bevel";
    context.lineWidth = 1;

    for(var i=0;i<pixels.length;i+=space){

        var x = pixels[i][0];
        var y = pixels[i][1];

        var r = Math.ceil(Math.random()*254);
        var g = Math.ceil(Math.random()*254);
        var b = Math.ceil(Math.random()*254);
        var a = Math.random();

        var style = "rgba("+r+","+g+","+b+","+a+")";

        context.beginPath();
        context.moveTo(x+moveBy,y+moveBy);
        context.lineTo(x+z, y+z);
        context.strokeStyle = style;
        context.closePath();
        context.stroke();

    }

}

function roundedRectangle(x, y, w, h, radius,color,lineSize,fill)
{
    var r = x + w;
    var b = y + h;
    context.beginPath();
    context.strokeStyle=color;
    context.lineWidth=lineSize;
    context.moveTo(x+radius, y);
    context.lineTo(r-radius, y);
    context.quadraticCurveTo(r, y, r, y+radius);
    context.lineTo(r, y+h-radius);
    context.quadraticCurveTo(r, b, r-radius, b);
    context.lineTo(x+radius, b);
    context.quadraticCurveTo(x, b, x, b-radius);
    context.lineTo(x, y+radius);
    context.quadraticCurveTo(x, y, x+radius, y);
    if(fill){
        context.fillStyle=color;
        context.fill();
    }
    context.stroke();
}

function animate(pixels) {
    context.clearRect(0, 0, canvas.width, canvas.height);

    roundedRectangle(20,20,w-60,h-60,5,"black",2,true);

    roundedRectangle(40,40,w-100,h-100,5,"green",2);

    roundedRectangle(w/4,h-50,w/2,25,5,"black",2,true);

    draw(pixels,Math.ceil((Math.random()*5)+5),10,Math.random()*20);

    requestAnimFrame(function() {
        animate(pixels);
    });

}

var size = 120;
var pixels = drawText("JS1K TV :D","bold "+size+"pt Arial",w/2-(size*4),h/2);
animate(pixels);


text:
#region License

#endregion

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using Beholder;
using Beholder.Libraries.SharpDX11.Platform;
using Beholder.Math;
using Beholder.Platform;
using Ravc.Utility.DataStructures;
using Win32;

namespace Ravc.Host.WinLib
{
    public class MainLoop : IPipelinedProvider<GpuRawFrame>, IDisposable
    {
        private static readonly int[] DetailSequence = { 1, 1, 1, 1, 1, 1, 1, 0 };
        //private static readonly int[] DetailSequence = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 };
        //private static readonly int[] DetailSequence = { 2, 1, 2, 1, 2, 1, 2, 0 };
        //private static readonly int[] DetailSequence = { 1 };
        //private static readonly int[] DetailSequence = { 0 };
        //private static readonly int[] DetailSequence = new[] { 0, 1, 0, 0, 0, 0, 0, 0 };

        private static readonly int[] DiffThresholdSequence = { 5, 2, 5, 0 };

        private readonly IHostStatistics statistics;
        private readonly IDevice device;
        private readonly IScreenCaptor screenCaptor;
        private readonly Stopwatch stopwatch;
        private readonly bool isD3d11;
        private double previousTimestamp;
        private int frameIndex;
        private int processedFrameIndex;
        private IPipelinedConsumer<GpuRawFrame> nextStage;
        private IntSize oldSize;
        private volatile bool makeAbsoluteFrame;

        public IPipelinedConsumer<GpuRawFrame> NextStage { set { nextStage = value; } }

        public MainLoop(IHostStatistics statistics, IHostGlobalEvents globalEvents, IDevice device, IScreenCaptor screenCaptor)
        {
            this.statistics = statistics;
            this.device = device;
            this.screenCaptor = screenCaptor;
            stopwatch = new Stopwatch();
            isD3d11 = device.Adapter is CAdapter;
            globalEvents.NewClientConnected += () => { makeAbsoluteFrame = true; };
        }

        public void Dispose()
        {
            screenCaptor.Dispose();
        }

        public void OnNewFrame(IRealTime realTime)
        {
            var context = device.ImmediateContext;
            var swapChain = device.PrimarySwapChain;
            if (swapChain.BeginScene())
            {
                context.ClearRenderTargetView(swapChain.GetCurrentColorBuffer(), Color4.Black);

                var newTimestamp = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency;
                if (newTimestamp - previousTimestamp > 0.001)
                {
                    previousTimestamp = newTimestamp;

                    var focusedWindowHwnd = GetFocusedWindowHwnd();
                    RECT clientRect;
                    var clientPoint = new POINT(0, 0);
                    Functions.GetClientRect(focusedWindowHwnd, out clientRect);
                    Functions.ClientToScreen(focusedWindowHwnd, ref clientPoint);
                    var beholderRect = new IntRectangle(
                        Math.Max(clientPoint.X, 0),
                        Math.Max(clientPoint.Y, 0),
                        Math.Max(clientRect.right - clientRect.left, 1),
                        Math.Max(clientRect.bottom - clientRect.top, 1));
                    var size = new IntSize(beholderRect.Width, beholderRect.Height);
                    if (!size.Equals(oldSize) && size.Width > 0 && size.Height > 0)
                    {
                        oldSize = size;
                        statistics.OnResize(size.Width, size.Height);
                    }

                    if (!isD3d11)
                        context.ClearRenderTargetView(swapChain.GetCurrentColorBuffer(), Color4.CornflowerBlue);

                    var frameType = makeAbsoluteFrame ? FrameType.Absolute : FrameType.Relative;
                    makeAbsoluteFrame = false;

                    GpuRawFrame capturedFrame;
                    if (screenCaptor.TryGetCaptured(context, beholderRect, frameType,
                        DiffThresholdSequence[processedFrameIndex % DiffThresholdSequence.Length],
                        DetailSequence[processedFrameIndex % DetailSequence.Length], out capturedFrame))
                    {
                        if (frameIndex % 2 == 0 || frameType == FrameType.Absolute)
                        {
                            stopwatch.Restart();
                            nextStage.Consume(capturedFrame);
                            stopwatch.Stop();
                            statistics.OnGpuCalls(stopwatch.Elapsed.TotalMilliseconds);
                            processedFrameIndex++;
                        }
                        else
                        {
                            capturedFrame.TexturePooled.Release();
                        }
                    }
                }
                else
                {
                    Thread.Sleep(1);
                }

                swapChain.EndScene();

                stopwatch.Restart();
                swapChain.Present();
                stopwatch.Stop();
                statistics.OnPresent(realTime.ElapsedRealTime, stopwatch.Elapsed.TotalMilliseconds);

                frameIndex++;
            }
        }

        static readonly int sizeOfGUITHREADINFO = Marshal.SizeOf(typeof(GUITHREADINFO));

        static IntPtr GetFocusedWindowHwnd()
        {
            var gui = new GUITHREADINFO
            {
                cbSize = sizeOfGUITHREADINFO
            };
            Functions.GetGUIThreadInfo(0, out gui);
            return gui.hwndFocus;
        }
    }
}


text:
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Drawing;
using System.Windows.Forms;

namespace Sce.Atf.Applications
{
    ///
    /// Editor that presents an IPrototypingContext using a TreeControl
    [Export(typeof(PrototypeLister))]
    [Export(typeof(IInitializable))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class PrototypeLister : TreeControlEditor, IControlHostClient, IInitializable
    {
        ///
        /// Constructor
        /// <param name="commandService">Command service for the underlying TreeControlEditor,
        /// which can be used to open context menus on a right-click</param>
        [ImportingConstructor]
        public PrototypeLister(ICommandService commandService)
            : base(commandService)
        {
            Configure(out m_controlInfo);
        }

        ///
        /// Configures the PrototypeLister
        /// <param name="controlInfo">Information about the Control for the hosting service</param>
        protected virtual void Configure(
            out ControlInfo controlInfo)
        {
            controlInfo = new ControlInfo(
                "Prototypes".Localize(),
                "Creates new instances from prototypes".Localize(),
                StandardControlGroup.Right,
                s_factoryImage);

            TreeControl.ShowRoot = false;
            TreeControl.AllowDrop = true;
            TreeControl.SelectionMode = SelectionMode.One;
        }

        ///
        /// Gets the ControlInfo instance, which determines the appearance and
        /// initial location of the Control in the application
        public ControlInfo ControlInfo
        {
            get { return m_controlInfo; }
        }

        ///
        /// Gets or sets the prototyping context to be viewed and edited by the user
        public IPrototypingContext PrototypeContext
        {
            get { return m_prototypingContext; }
            set
            {
                if (m_prototypingContext != value)
                {
                    m_prototypingContext = value;
                    TreeView = m_prototypingContext;
                }
            }
        }

        [Import]
        private IControlHostService m_controlHostService;

        [Import]
        private IContextRegistry m_contextRegistry;

        #region IInitializable Members

        void IInitializable.Initialize()
        {
            m_contextRegistry.ActiveContextChanged += contextRegistry_ActiveContextChanged;

            m_controlHostService.RegisterControl(TreeControl, m_controlInfo, this);
        }

        #endregion

        #region IControlHostClient Members

        ///
        /// Notifies the client that its Control has been activated. Activation occurs when
        /// the Control gets focus, or a parent "host" Control gets focus.
        /// <param name="control">Client Control that was activated</param>
        void IControlHostClient.Activate(Control control)
        {
            if (m_prototypingContext != null)
                m_contextRegistry.ActiveContext = m_prototypingContext;
        }

        ///
        /// Notifies the client that its Control has been deactivated. Deactivation occurs when
        /// another Control or "host" Control gets focus.
        /// <param name="control">Client Control that was deactivated</param>
        void IControlHostClient.Deactivate(Control control)
        {
        }

        ///
        /// Requests permission to close the client's Control.
        /// <param name="control">Client Control to be closed</param>
        /// <returns>True if the Control can close, or false to cancel</returns>
        bool IControlHostClient.Close(Control control)
        {
            return true;
        }

        #endregion

        ///
        /// Called for every mouse move event in which drag-and-drop objects are being dragged.
        /// Begins a drag-and-drop operation on the underlying tree Control.
        /// <param name="items">Enumeration of items being dragged</param>
        protected override void OnStartDrag(IEnumerable<object> items)
        {
            IDataObject dataObject = m_prototypingContext.GetInstances(items);
            TreeControl.DoDragDrop(dataObject, DragDropEffects.All | DragDropEffects.Link);
        }

        ///
        /// Performs custom actions after the LastHitChanged event
        /// <param name="e">Event args</param>
        protected override void OnLastHitChanged(EventArgs e)
        {
            if (m_prototypingContext != null)
                m_prototypingContext.SetActiveItem(LastHit);

            base.OnLastHitChanged(e);
        }

        private void contextRegistry_ActiveContextChanged(object sender, EventArgs e)
        {
            PrototypeContext = m_contextRegistry.GetMostRecentContext<IPrototypingContext>();
            TreeControl.Text = (PrototypeContext != null) ?
                "Copy items from the document and paste them here to create prototypes that can be dragged and dropped onto a canvas.".Localize()
                : null;
        }

        private IPrototypingContext m_prototypingContext;
        private readonly ControlInfo m_controlInfo;

        private static readonly Image s_factoryImage = ResourceUtil.GetImage16(Resources.FactoryImage);
    }
}


text:
@interface JSCustomBadge()

- (id)initWithString:(NSString *)badgeString withScale:(CGFloat)scale withShining:(BOOL)shining;

- (id)initWithString:(NSString *)badgeString
     withStringColor:(UIColor *)stringColor
      withInsetColor:(UIColor *)insetColor
      withBadgeFrame:(BOOL)badgeFrameYesNo
 withBadgeFrameColor:(UIColor *)frameColor
           withScale:(CGFloat)scale
         withShining:(BOOL)shining
          withShadow:(BOOL)shadow;

- (void)drawRoundedRectWithContext:(CGContextRef)context inRect:(CGRect)rect;
- (void)drawShineWithContext:(CGContextRef)context inRect:(CGRect)rect;
- (void)drawFrameWithContext:(CGContextRef)context inRect:(CGRect)rect;

@end

@implementation JSCustomBadge

#pragma mark - Initialization

- (id)initWithString:(NSString *)badgeString withScale:(CGFloat)scale withShining:(BOOL)shining
{
	self = [super initWithFrame:CGRectMake(0.0f, 0.0f, 25.0f, 25.0f)];

	if(self) {
		self.contentScaleFactor = [[UIScreen mainScreen] scale];
		self.backgroundColor = [UIColor clearColor];
		_badgeText = badgeString;
		_badgeTextColor = [UIColor whiteColor];
		_badgeFrame = NO;
		_badgeFrameColor = nil;
		_badgeInsetColor =  [UIColor colorWithRed:1.0f green:0.22f blue:0.22f alpha:1.0f]; // iOS 7 red
		_badgeCornerRoundness = 0.4f;
		_badgeScaleFactor = scale;
		_badgeShining = shining;
        _badgeShadow = NO;
		[self autoBadgeSizeWithString:badgeString];
	}

	return self;
}

- (id)initWithString:(NSString *)badgeString
     withStringColor:(UIColor *)stringColor
      withInsetColor:(UIColor *)insetColor
      withBadgeFrame:(BOOL)badgeFrameYesNo
 withBadgeFrameColor:(UIColor *)frameColor
           withScale:(CGFloat)scale
         withShining:(BOOL)shining
          withShadow:(BOOL)shadow
{
	self = [super initWithFrame:CGRectMake(0.0f, 0.0f, 25.0f, 25.0f)];

	if(self) {
		self.contentScaleFactor = [[UIScreen mainScreen] scale];
		self.backgroundColor = [UIColor clearColor];
		_badgeText = badgeString;
		_badgeTextColor = stringColor;
		_badgeFrame = badgeFrameYesNo;
		_badgeFrameColor = frameColor;
		_badgeInsetColor = insetColor;
		_badgeCornerRoundness = 0.4f;
		_badgeScaleFactor = scale;
		_badgeShining = shining;
        _badgeShadow = shadow;
		[self autoBadgeSizeWithString:badgeString];
	}

	return self;
}

- (void)dealloc
{
    _badgeText = nil;
    _badgeTextColor = nil;
    _badgeInsetColor = nil;
    _badgeFrameColor = nil;
}

#pragma mark - Class initializers

+ (JSCustomBadge *) customBadgeWithString:(NSString *)badgeString
{
	return [[JSCustomBadge alloc] initWithString:badgeString withScale:1.0f withShining:NO];
}

+ (JSCustomBadge *) customBadgeWithString:(NSString *)badgeString
                          withStringColor:(UIColor *)stringColor
                           withInsetColor:(UIColor *)insetColor
                           withBadgeFrame:(BOOL)badgeFrameYesNo
                      withBadgeFrameColor:(UIColor *)frameColor
                                withScale:(CGFloat)scale
                              withShining:(BOOL)shining
                               withShadow:(BOOL)shadow
{
	return [[JSCustomBadge alloc] initWithString:badgeString
                                 withStringColor:stringColor
                                  withInsetColor:insetColor
                                  withBadgeFrame:badgeFrameYesNo
                             withBadgeFrameColor:frameColor
                                       withScale:scale
                                     withShining:shining
                                      withShadow:shadow];
}

#pragma mark - Utilities

- (void)autoBadgeSizeWithString:(NSString *)badgeString
{
	CGSize retValue;
	CGFloat rectWidth, rectHeight;
	CGSize stringSize = [badgeString sizeWithFont:[UIFont boldSystemFontOfSize:12.0f]];
	CGFloat flexSpace;

    if([badgeString length] >= 3.0f) {
		flexSpace = [badgeString length];
		rectWidth = 25.0f + (stringSize.width + flexSpace); rectHeight = 25.0f;
		retValue = CGSizeMake(rectWidth * _badgeScaleFactor, rectHeight * _badgeScaleFactor);
	}
    else {
		retValue = CGSizeMake(25.0f * _badgeScaleFactor, 25.0f * _badgeScaleFactor);
	}

    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, retValue.width, retValue.height);
	_badgeText = badgeString;

    [self setNeedsDisplay];
}

#pragma mark - Drawing

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

	[self drawRoundedRectWithContext:context inRect:rect];

	if(self.badgeShining)
		[self drawShineWithContext:context inRect:rect];

	if(self.badgeFrame)
		[self drawFrameWithContext:context inRect:rect];

	if([self.badgeText length] > 0.0f) {

		[self.badgeTextColor set];
		CGFloat sizeOfFont = 13.5f * self.badgeScaleFactor;

        if([self.badgeText length] < 2.0f) {
			sizeOfFont += sizeOfFont * 0.2f;
		}

		UIFont *textFont = [UIFont boldSystemFontOfSize:sizeOfFont];
		CGSize textSize = [self.badgeText sizeWithFont:textFont];

        [self.badgeText drawAtPoint:CGPointMake((rect.size.width/2.0f - textSize.width/2.0f),
                                                (rect.size.height/2.0f - textSize.height/2.0f))
                           withFont:textFont];
	}
}

- (void)drawRoundedRectWithContext:(CGContextRef)context inRect:(CGRect)rect
{
	CGContextSaveGState(context);

	CGFloat radius = CGRectGetMaxY(rect) * self.badgeCornerRoundness;
	CGFloat puffer = CGRectGetMaxY(rect) * 0.1f;
	CGFloat maxX = CGRectGetMaxX(rect) - puffer;
	CGFloat maxY = CGRectGetMaxY(rect) - puffer;
	CGFloat minX = CGRectGetMinX(rect) + puffer;
	CGFloat minY = CGRectGetMinY(rect) + puffer;

    CGContextBeginPath(context);
	CGContextSetFillColorWithColor(context, [self.badgeInsetColor CGColor]);
	CGContextAddArc(context, maxX-radius, minY+radius, radius, M_PI+(M_PI/2.0f), 0.0f, 0.0f);
	CGContextAddArc(context, maxX-radius, maxY-radius, radius, 0.0f, M_PI/2.0f, 0.0f);
	CGContextAddArc(context, minX+radius, maxY-radius, radius, M_PI/2.0f, M_PI, 0.0f);
	CGContextAddArc(context, minX+radius, minY+radius, radius, M_PI, M_PI+M_PI/2.0f, 0.0f);

    if(self.badgeShadow) {
        CGContextSetShadowWithColor(context,
                                    CGSizeMake(0.0f, 1.0f),
                                    2.0f,
                                    [UIColor colorWithWhite:0.0f alpha:0.75f].CGColor);
    }

    CGContextFillPath(context);

	CGContextRestoreGState(context);
}

- (void)drawShineWithContext:(CGContextRef)context inRect:(CGRect)rect
{
	CGContextSaveGState(context);

	CGFloat radius = CGRectGetMaxY(rect) * self.badgeCornerRoundness;
	CGFloat puffer = CGRectGetMaxY(rect) * 0.1f;
	CGFloat maxX = CGRectGetMaxX(rect) - puffer;
	CGFloat maxY = CGRectGetMaxY(rect) - puffer;
	CGFloat minX = CGRectGetMinX(rect) + puffer;
	CGFloat minY = CGRectGetMinY(rect) + puffer;

	CGContextBeginPath(context);
	CGContextAddArc(context, maxX-radius, minY+radius, radius, M_PI+(M_PI/2.0f), 0.0f, 0.0f);
	CGContextAddArc(context, maxX-radius, maxY-radius, radius, 0.0f, M_PI/2.0f, 0.0f);
	CGContextAddArc(context, minX+radius, maxY-radius, radius, M_PI/2.0f, M_PI, 0.0f);
	CGContextAddArc(context, minX+radius, minY+radius, radius, M_PI, M_PI+M_PI/2.0f, 0.0f);
	CGContextClip(context);

	size_t num_locations = 2.0f;
	CGFloat locations[2] = { 0.0f, 0.4f };
	CGFloat components[8] = { 0.92f, 0.92f, 0.92f, 1.0f, 0.82f, 0.82f, 0.82f, 0.4f };

	CGColorSpaceRef cspace;
	CGGradientRef gradient;
	cspace = CGColorSpaceCreateDeviceRGB();
	gradient = CGGradientCreateWithColorComponents(cspace, components, locations, num_locations);

	CGPoint sPoint, ePoint;
	sPoint.x = 0.0f;
	sPoint.y = 0.0f;
	ePoint.x = 0.0f;
	ePoint.y = maxY;
	CGContextDrawLinearGradient (context, gradient, sPoint, ePoint, 0.0f);

	CGColorSpaceRelease(cspace);
	CGGradientRelease(gradient);

	CGContextRestoreGState(context);
}

- (void)drawFrameWithContext:(CGContextRef)context inRect:(CGRect)rect
{
	CGFloat radius = CGRectGetMaxY(rect) * self.badgeCornerRoundness;
	CGFloat puffer = CGRectGetMaxY(rect) * 0.1f;

	CGFloat maxX = CGRectGetMaxX(rect) - puffer;
	CGFloat maxY = CGRectGetMaxY(rect) - puffer;
	CGFloat minX = CGRectGetMinX(rect) + puffer;
	CGFloat minY = CGRectGetMinY(rect) + puffer;

    CGContextBeginPath(context);
	CGFloat lineSize = 2.0f;

	if(self.badgeScaleFactor > 1.0f) {
		lineSize += self.badgeScaleFactor * 0.25f;
	}

	CGContextSetLineWidth(context, lineSize);
	CGContextSetStrokeColorWithColor(context, [self.badgeFrameColor CGColor]);
	CGContextAddArc(context, maxX-radius, minY+radius, radius, M_PI + (M_PI/2.0f), 0.0f, 0.0f);
	CGContextAddArc(context, maxX-radius, maxY-radius, radius, 0.0f, M_PI/2.0f, 0.0f);
	CGContextAddArc(context, minX+radius, maxY-radius, radius, M_PI/2.0f, M_PI, 0.0f);
	CGContextAddArc(context, minX+radius, minY+radius, radius, M_PI, M_PI+M_PI/2.0f, 0.0f);

    CGContextClosePath(context);
	CGContextStrokePath(context);
}

@end