text:
/*
  A MM1 queue object that, given lambda and mu, is capable
  of simulating a queue and evaluating results. This object
  can also be "plugged" in sequentially, creating queues
  that "feed" each other.
*/

#ifndef MM1_QUEUE_HPP
#define MM1_QUEUE_HPP

/* Header files needed for this program */
#include <iostream>
#include <vector>
#include <string>
#include "customer.h"
#include "random_number_generator.h"
#include <fstream>

/* Enable or disable the creation of the log file with detailed output */
#undef LOG_ENABLED

class MM1_Queue {
/*
  These variables are used to evaluate the performance of
  the queue during or at the end of the simulation
*/
  int arrivals_; // total number of arrivals
  int services_; // total number of served customers
  double no_waiting_arrivals_; // used for idle calculation
  double min_arrival_interval_;
  double max_arrival_interval_;
  double min_service_duration_;
  double max_service_duration_;
  double max_waiting_time_;
  double max_response_time_;
  double mean_queue_length_;
  double expected_queue_length_;
  double mean_number_customers_;
  double expected_number_customers_;
  double mean_waiting_time_;
  double expected_waiting_time_;
  double mean_response_time_;
  double expected_response_time_;
  double expected_idle_prob_;
  double expected_server_utilization_;

/*
  These variables are used for the simulation of the queue
*/
  double next_arrival_;
  double next_departure_;
  bool busy_;
  double mql_upd_time_; // last update time of the mean_queue_length_
  double mnc_upd_time_; // last update time of the mean_number_customers_
  vector<Customer> waiting_buffer_;
  Random_Number_Generator rnd_arrival;
  Random_Number_Generator rnd_service;
  double current_time_;
  bool generate_new_arrivals_;
  int has_external_arrivals_;
  double lambda_;
  double mu_;
  bool initialized_;
  Customer serving_;

/*
  Log files
*/
#ifdef LOG_ENABLED
  ofstream log_outFile;
#endif
  ofstream mwt_outFile;
  ofstream mst_outFile;

/*
  Private methods
*/
Customer create_new_customer();
void update_evaluation_values();

public:
	MM1_Queue() : min_arrival_interval_(100000), max_arrival_interval_(0),
                  arrivals_(-1), services_(-1), no_waiting_arrivals_(false),
                  min_service_duration_(100000), max_service_duration_(0),
                  mean_queue_length_(0), mean_number_customers_(0),
                  mean_waiting_time_(0), mean_response_time_(0),
                  max_waiting_time_(0), max_response_time_(0),
                  next_arrival_(0), next_departure_(0), busy_(false), mql_upd_time_(0),
                  mnc_upd_time_(0), current_time_(0), generate_new_arrivals_(true),
                  has_external_arrivals_(1), lambda_(0), mu_(0), initialized_(false),
                  expected_queue_length_(0), expected_number_customers_(0), expected_waiting_time_(0),
                  expected_response_time_(0), expected_idle_prob_(0), expected_server_utilization_(0) {};

    /* Getters and Setters */
	void set_lambda(double d) { lambda_ = d; };
	double get_lambda() const { return lambda_; };
	void set_mu(double d) { mu_ = d; };
	double get_mu() const { return mu_; };
	double get_current_time() const { return current_time_; };
    void autogenerate_new_arrivals(bool b) { generate_new_arrivals_ = b; };
    int get_current_queue_size() const { return waiting_buffer_.size(); };
    bool is_busy() const { return busy_; };
    int get_number_arrivals() const { return arrivals_; };
    int get_number_services() const { return services_; };

	/* mean values */
	double get_mean_waiting_time() const { return mean_waiting_time_/services_; };
	double get_mean_response_time() const { return mean_response_time_/services_; };
	double get_mean_queue_length() const { return mean_queue_length_/current_time_; };
	double get_mean_number_customers() const { return (mean_queue_length_ + mean_number_customers_)/current_time_; };
	double get_server_utilization() const { return mean_number_customers_/current_time_; };
	double get_idle_prob() const { return no_waiting_arrivals_/arrivals_; };

	/* expected values */
	double get_expected_server_utilization() const { return expected_server_utilization_; };
	double get_expected_idle_prob() const { return expected_idle_prob_; };
	double get_expected_queue_length() const { return expected_queue_length_; };
	double get_expected_number_customers() const { return expected_number_customers_; };
	double get_expected_waiting_time() const { return expected_waiting_time_; };
	double get_expected_response_time() const { return expected_response_time_; };

	/* this next method returns TRUE if the simulation is
	   within the desired confidence interval */
	bool is_within_confidence_interval() const {
         // 90%  confidence interval ->  z = 1.645
         // mean_var = { sum[ (xi)^2 - 2xixm + (xm)^2 ] } / n
         double var = ( pow(mean_response_time_, 2)
                      - (2 * mean_response_time_ * expected_response_time_)
                      + pow(expected_response_time_, 2) ) / services_;
         return get_mean_response_time() < expected_response_time_+(1.645*var)
                &&
                get_mean_response_time() > expected_response_time_-(1.645*var)
                &&
                services_ > 30;
    };

	/* this next method returns TRUE if the simulation is
	   within the desired error range */
	bool is_within_error_range(double err) const {
         return abs(get_mean_response_time() - expected_response_time_) < err;
    };

	/* definition of remaining public functions */
	void initialize();
    void set_file_names(string queue, string wait, string service);
	Customer process_next_event();
    Customer get_next_customer();
    void add_external_arrival();
    void set_seed(double arr, double serv);

    void output() const
    {
       cout << "Arrivals: " << arrivals_ << " Services: " << services_ << endl;
       cout << "Within 90\% CI? " << (is_within_confidence_interval()?"true":"false") << endl;
       cout << "Mean Response Time: " << get_mean_response_time() << " [" << get_expected_response_time() << "] " << endl;
       cout << "Mean Waiting Time: " << get_mean_waiting_time() << " [" << get_expected_waiting_time() << "] " << endl;
       cout << "Mean Queue Length: " << get_mean_queue_length() << " [" << get_expected_queue_length() << "] " << endl;
       cout << "Mean Number of Customers: " << get_mean_number_customers() << " [" << get_expected_number_customers() << "] " << endl;
       cout << "Server Utilization: " << get_server_utilization() << " [" << get_expected_server_utilization() << "] " << endl;
       cout << "Server Idle: " << get_idle_prob() << " [" << get_expected_idle_prob() << "] " << endl;
    }

    void plot_results_output() const
    {
       /* response time comparison */
       ofstream theory_rt;
       theory_rt.open("theory_rt.txt", ios::out|ios::app);
       theory_rt.precision(6);

       ofstream practice_rt;
       practice_rt.open("practice_rt.txt", ios::out|ios::app);
       practice_rt.precision(6);

       practice_rt << get_mean_response_time() << endl;
       theory_rt << get_expected_response_time() << endl;

       /* waiting time comparison */
       ofstream theory_wt;
       theory_wt.open("theory_wt.txt", ios::out|ios::app);
       theory_wt.precision(6);

       ofstream practice_wt;
       practice_wt.open("practice_wt.txt", ios::out|ios::app);
       practice_wt.precision(6);

       practice_wt << get_mean_waiting_time() << endl;
       theory_wt << get_expected_waiting_time() << endl;

       /* expected queue length comparison */
       ofstream theory_ql;
       theory_ql.open("theory_ql.txt", ios::out|ios::app);
       theory_ql.precision(6);

       ofstream practice_ql;
       practice_ql.open("practice_ql.txt", ios::out|ios::app);
       practice_ql.precision(6);

       practice_ql << get_mean_queue_length() << endl;
       theory_ql << get_expected_queue_length() << endl;

       /* mean number of customers comparison */
       ofstream theory_en;
       theory_en.open("theory_en.txt", ios::out|ios::app);
       theory_en.precision(6);

       ofstream practice_en;
       practice_en.open("practice_en.txt", ios::out|ios::app);
       practice_en.precision(6);

       practice_en << get_mean_number_customers() << endl;
       theory_en << get_expected_number_customers() << endl;

       /* utilization comparison */
       ofstream theory_u;
       theory_u.open("theory_u.txt", ios::out|ios::app);
       theory_u.precision(6);

       ofstream practice_u;
       practice_u.open("practice_u.txt", ios::out|ios::app);
       practice_u.precision(6);

       practice_u << get_server_utilization() << endl;
       theory_u << get_expected_server_utilization() << endl;

       /* idle comparison */
       ofstream theory_i;
       theory_i.open("theory_i.txt", ios::out|ios::app);
       theory_i.precision(6);

       ofstream practice_i;
       practice_i.open("practice_i.txt", ios::out|ios::app);
       practice_i.precision(6);

       practice_i << get_idle_prob() << endl;
       theory_i << get_expected_idle_prob() << endl;

    }

};

#endif


text:
extern "C" {
#endif

  namespace wrap_trackerrk4_py_external_effects{
    void initPyExternalEffects(PyObject* module);
  }

#ifdef __cplusplus
}
#endif

#endif

redpajama_set_name: RedPajamaGithub


text:
package gov.hhs.fha.nhinc.webserviceproxy;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import gov.hhs.fha.nhinc.properties.IPropertyAcessor;

import java.net.SocketTimeoutException;

import javax.xml.ws.WebServiceException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * This class tests the retry "Socketimeout" code of the WebServiceProxyHelper class.
 *
 * @author Greg Gurr
 */
public class WebServiceProxyHelperSocktimeoutTest {
	private final int RETRY_ATTEMPTS = 2;
	private final int RETRY_DELAY_MS = 1000;
	private final String RETRY_EXCEPTION_TEXT = "SocketTimeoutException";
	private final String UNSUPPORTED_ERROR_MESSAGE = "Unsupported error message";
	private final String SOCKET_TIMEOUT_ERROR_MESSAGE = "Supported socketTimeout error message";

	private WebServiceProxyHelper testSubject;
	private IPropertyAcessor mockPropertyAccessor;

	@Before
	public void setUp() throws Exception {
		mockPropertyAccessor = mock(IPropertyAcessor.class);

		testSubject = new WebServiceProxyHelper(mockPropertyAccessor) {

			@Override
			public int getRetryAttempts() {
				return RETRY_ATTEMPTS;
			}

			@Override
			public int getRetryDelay() {
				return RETRY_DELAY_MS;
			}

			@Override
			public String getExceptionText() {
				return RETRY_EXCEPTION_TEXT;
			}
		};
	}

	@After
	public void tearDown() throws Exception {
		testSubject = null;
	}

	/**
	 * Test the retry logic when we have a "SocketTimeoutException". This method will attempt to retry invoking the port for the
	 * specified retry attempts. After that an "InvocationTargetException" should be thrown.
	 */
	@SuppressWarnings("unused")
	@Test
	public void testInvokePort_RetrySocketTimeoutException() {
		try {
			Integer response = (Integer) testSubject.invokePort(this, this.getClass(), "supportedExceptionMethod", new Integer(100));
			fail("A Exception should have been thrown but was not.");
		} catch (Exception e) {
			assertTrue("Thrown exception should be InvocationTargetException but was not", e instanceof WebServiceException);
			assertEquals(SOCKET_TIMEOUT_ERROR_MESSAGE, e.getMessage());
		}
	}

	/**
	 * Test the retry logic when we have a "SocketTimeoutException". This method will attempt to retry invoking the port for the
	 * specified retry attempts. After that an "InvocationTargetException" should be thrown.
	 */
	@SuppressWarnings("unused")
	@Test
	public void testInvokePort_RetryUnSupportedException() {
		try {
			Integer response = (Integer) testSubject.invokePort(this, this.getClass(), "unSupportedExceptionMethod", new Integer(100));
			fail("A Exception should have been thrown but was not.");
		} catch (Exception e) {
			assertTrue("Thrown exception should be InvocationTargetException but was not", e instanceof WebServiceException);
			assertEquals(UNSUPPORTED_ERROR_MESSAGE, e.getMessage());
		}
	}

	/**
	 * Test the retry logic when we have no Exceptions. This method will invoke and return a valid value..
	 */
	@Test
	public void testInvokePort_RetryHappyPath() {
		try {
			Integer response = (Integer) testSubject.invokePort(this, this.getClass(), "helperMethod", new Integer(100));

			assertNotNull(response);
			assertEquals(100, response.intValue());
		} catch (Exception e) {
			fail("Should not have thrown an Exception but did");
		}
	}

    /**
     * This method is used to test out some of the dynamic invocation methods.
     *
     * @param x
	 *		Contains some Integer param.
	 *
	 * @return
	 * 		Returns the param that was passed in.
     */
    public Integer helperMethod(Integer x) {
        return x;
    }

    /**
     * This method is used to test out some of the dynamic invocation methods. It is used to test
     * when a "invokePort" call throws a non-SocketTimeoutException.
     *
     * @param x
	 *		Contains some Integer param.
	 *
	 * @return
	 * 		Returns the param that was passed in.
     * @throws Fault
	 * @exception
	 * 		Throws a Fault.
     */
    public Integer unSupportedExceptionMethod(Integer x) throws WebServiceException {
    	IllegalArgumentException illegalArgumentException = new IllegalArgumentException(UNSUPPORTED_ERROR_MESSAGE);

        throw new WebServiceException(UNSUPPORTED_ERROR_MESSAGE, illegalArgumentException);
    }

    /**
     * This method is used to test out some of the dynamic invocation methods. It is used to test
     * when a "invokePort" call throws a SocketTimeoutException.
     *
     * @param x
	 *		Contains some Integer param.
	 *
	 * @return
	 * 		Returns the param that was passed in.
     * @throws Fault
	 * @exception
	 * 		Throws a Fault.
     */
    public Integer supportedExceptionMethod(Integer x) throws WebServiceException {
    	SocketTimeoutException socketTimeoutException = new SocketTimeoutException(SOCKET_TIMEOUT_ERROR_MESSAGE);

        throw new WebServiceException(SOCKET_TIMEOUT_ERROR_MESSAGE, socketTimeoutException);
    }

}


text:
package com.lab.epam.entity;

import com.lab.epam.dao.Identified;
import com.lab.epam.transformer.Column;
import com.lab.epam.transformer.Table;

import java.util.Comparator;

/**
 * Created by Admin on 10.06.2015.
 */
@Table("place")
public class Place implements Identified<Integer> {
    @Column("id")
    private Integer id = null;
    @Column("latitude")
    private String latitude;
    @Column("longitude")
    private String longitude;
    @Column("visible")
    private Boolean visible = true;
    @Column("rating")
    private Integer rating;
    @Column("category_id")
    private Integer category_id;
    @Column("place_time")
    private Integer place_time;
    @Column("recomended")
    private Boolean recomended;
    @Column("recom_time")
    private Integer recom_time;
    @Column("custom")
    private Boolean custom;
    @Column("is_recommended")
    private Boolean is_recommended;
    @Column("deleted")
    private Boolean deleted = false;

    @Override
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Boolean getIs_recommended() {
        return is_recommended;
    }

    public void setIs_recommended(Boolean is_recommended) {
        this.is_recommended = is_recommended;
    }

    public Boolean getDeleted() {
        return deleted;
    }

    public void setDeleted(Boolean deleted) {
        this.deleted = deleted;
    }

    public Boolean getCustom() {
        return custom;
    }

    public void setCustom(Boolean custom) {
        this.custom = custom;
    }

    public Integer getRecom_time() {
        return recom_time;
    }

    public void setRecom_time(Integer recom_time) {
        this.recom_time = recom_time;
    }

    public Boolean getRecomended() {
        return recomended;
    }

    public void setRecomended(Boolean recomended) {
        this.recomended = recomended;
    }

    public Integer getPlace_time() {
        return place_time;
    }

    public void setPlace_time(Integer place_time) {
        this.place_time = place_time;
    }

    public Integer getCategory_id() {
        return category_id;
    }

    public void setCategory_id(Integer category_id) {
        this.category_id = category_id;
    }

    public Integer getRating() {
        return rating;
    }

    public void setRating(Integer rating) {
        this.rating = rating;
    }

    public Boolean getVisible() {
        return visible;
    }

    public void setVisible(Boolean visible) {
        this.visible = visible;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public String getLatitude() {
        return latitude;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }

    public Place() {

    }

    public Place(Integer id, String latitude, String longitude, Boolean visible, Integer category_id, Integer rating, Integer place_time, Boolean recomended, Boolean custom, Boolean deleted, Integer recom_time, Boolean is_recommended) {

        this.id = id;
        this.latitude = latitude;
        this.longitude = longitude;
        this.visible = visible;
        this.category_id = category_id;
        this.rating = rating;
        this.place_time = place_time;
        this.recomended = recomended;
        this.custom = custom;
        this.deleted = deleted;
        this.recom_time = recom_time;
        this.is_recommended = is_recommended;
    }

    public static class PlaceComparator implements Comparator<Object> {
        public int compare(Object cC1, Object cC2) {
            return ((Place)cC2).rating.compareTo(((Place)cC1).rating);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Place)) return false;

        Place place = (Place) o;

        return getId().equals(place.getId());

    }

    @Override
    public int hashCode() {
        return getId().hashCode();
    }

    @Override
    public String toString() {
        return "Place{" +
                "id=" + id +
                ", latitude='" + latitude + '\'' +
                ", longitude='" + longitude + '\'' +
                ", visible=" + visible +
                ", rating=" + rating +
                ", category_id=" + category_id +
                ", place_time=" + place_time +
                ", recomended=" + recomended +
                ", recom_time=" + recom_time +
                ", custom=" + custom +
                ", is_recommended=" + is_recommended +
                ", deleted=" + deleted +
                '}';
    }
}


text:
<?php

namespace Marein\ConnectFour\Domain\Game;

use Marein\ConnectFour\Domain\Game\Exception\PlayerHasInvalidStoneException;

final class Player
{
    /**
     * @var string
     */
    private $id;

    /**
     * @var Stone
     */
    private $stone;

    /**
     * Player constructor.
     *
     * @param string $id
     * @param Stone  $stone
     *
     * @throws PlayerHasInvalidStoneException
     */
    public function __construct(string $id, Stone $stone)
    {
        $this->id = $id;
        $this->stone = $stone;

        $this->guardPlayerHasCorrectStone($stone);
    }

    /*************************************************************
     *                          Guards
     *************************************************************/

    /**
     * Guard that the [Stone] is Stone::red() or Stone::yellow().
     *
     * @param Stone $stone
     *
     * @throws PlayerHasInvalidStoneException
     */
    private function guardPlayerHasCorrectStone(Stone $stone): void
    {
        if ($stone == Stone::none()) {
            throw new PlayerHasInvalidStoneException('Stone should be Stone::red() or Stone::yellow().');
        }
    }

    /*************************************************************
     *                          Getter
     *************************************************************/

    /**
     * @return string
     */
    public function id(): string
    {
        return $this->id;
    }

    /**
     * @return Stone
     */
    public function stone(): Stone
    {
        return $this->stone;
    }
}


text:
import getopt
import sys

from genologics.entities import Process
from genologics.lims import Lims

HOSTNAME = ""
VERSION = ""
BASE_URI = ""

api = None
args = None

def get_workflow_stage(lims, workflow_name, stage_name=None):
    workflows = [w for w in lims.get_workflows() if w.name == workflow_name]
    if len(workflows) != 1:
        return
    if not stage_name:
        return workflows[0].stages[0]
    stages = [s for s in workflows[0].stages if s.name == stage_name]
    if len(stages) != 1:
        return
    return stages[0]

def get_parent_process_id(art):
    return art.parent_process.id

def assignWorkflow():
    LIMSID = args["limsid"]
    usernameargs = args["username"]
    passwordargs = args["password"]
    stepURI = args["stepURI"]
    apiLocation = stepURI.find('/api')
    BASE_URI = stepURI[0:apiLocation]
    l = Lims(baseuri=BASE_URI, username=usernameargs, password=passwordargs)
    p = Process(l, id=LIMSID)
    artifacts = p.all_inputs()
    for art in artifacts:
        sample = art.samples[0]
        submitted_art = sample.artifact

        if art.samples[0].udf.get("Proceed To SeqLab") and not art.samples[0].udf.get("2D Barcode"): #checks to see if sample is in plate or fluidX tube
            stage = get_workflow_stage(l, "PreSeqLab EG 6.0", "Sequencing Plate Preparation EG 2.0")
            l.route_artifacts([submitted_art], stage_uri=stage.uri)

        elif art.samples[0].udf.get("Proceed To SeqLab") and art.samples[0].udf.get("2D Barcode"): #if is a fluidX tube will need to find the derived artifact created by the FluidX Transfer step
            fluidX_artifacts = l.get_artifacts(process_type="FluidX Transfer From Rack Into Plate EG 1.0 ST", sample_name=art.samples[0].name, type='Analyte')

            if len(fluidX_artifacts) >1: #its possible that the FluidX Transfer has occurred more than once so must find the most recent occurrence of that step
                fluidX_artifacts.sort(key=get_parent_process_id, reverse=True) #sorts the artifacts returned to place the most recent artifact at position 0 in list
                fluidX_artifact=fluidX_artifacts[0]
            else:
                fluidX_artifact=fluidX_artifacts[0]

            stage = get_workflow_stage(l, "PreSeqLab EG 6.0", "Sequencing Plate Preparation EG 2.0")
            l.route_artifacts([fluidX_artifact], stage_uri=stage.uri)

def main():
    global api
    global args

    args = {}

    opts, extraparams = getopt.getopt(sys.argv[1:], "l:s:u:p:")

    for o, p in opts:
        if o == '-l':
            args["limsid"] = p
        elif o == '-s':
            args["stepURI"] = p
        elif o == '-u':
            args["username"] = p
        elif o == '-p':
            args["password"] = p

    ## at this point, we have the parameters the EPP plugin passed, and we have network plumbing
    ## so let's get this show on the road!
    assignWorkflow()

if __name__ == "__main__":
    main()


text:
$(document).ready(toggle_detail);
$(document).ready(get_resources_loading_indicator);

function toggle_detail() {
	$("#expand").click(function () {
		$("#action_detail").toggle();
		if ($(this).text() == "[+]") {
			$(this).text("[-]");
		} else {
			$(this).text("[+]");
		}
	});
}

function get_resources_loading_indicator() {
	$("#getresources > form").submit(function () {
		$("#getresources > form > input[type='submit']").attr('disabled', 'disabled');
		$("#loading_indicator").css('visibility', 'visible');
	});
}


text:
A Refinery CMS extension can be used as a standalone extension in your Rails application.

This guide will show you how to:

* Bootstrap a rails application with just the use of a Refinery CMS extension like `refinerycms-blog`

## Bootstrap a rails app with just the use of a Refinery CMS extension like `refinerycms-blog`

First, bootstrap a new rails application:

```shell
$ rails _4.2.6_ new blog_test_app
```

Put just the `refinerycms-blog` in your project's Gemfile:

```ruby
gem "refinerycms-blog", git: "https://github.com/refinery/refinerycms-blog"
```

This will merely pull in `refinerycms-core` and `refinerycms-settings` based on the current gemspec dependencies.

Then you can run:

```shell
$ bundle install
$ rails generate refinery:cms
```

And all the other normal set up tasks like migrations.

Now, you should have a Rails app with __only__ the Refinery CMS Blog.

Finally, start your application and enjoy the use of Refinery CMS Blog only:

```shell
$ rails server
```


text:
from django.shortcuts import render_to_response
from django.contrib.formtools.wizard.views import SessionWizardView
from django.template import RequestContext

from defs import definitions

def start(request):
    return render_to_response('base.html',
                              context_instance=RequestContext(request))

class QuestionnaireWizard(SessionWizardView):
    template_name= 'form_template.html'
    def done(self, form_list, **kwargs):
        return render_to_response('done.html', {
            'form_data': [form.cleaned_data for form in form_list],
        })

    def get_form_kwargs(self, step):
        return {'definition': definitions[int(step)]}


text:
var DataDisplayer = function(parent) {
    var self = this;
    self.parent = parent;
    //self.parent.dataLayer = new
    self.movingObjects = [];
    self.internalLoop = function() {
        //console.info(self.movingObjects.length + ' obj rimasti');
        var tmp = [];
        var obj = null;
        for (var i = 0; i < self.movingObjects.length; i++) {
            obj = self.movingObjects[i].update();
            if (obj===null){
                //self.movingObjects[i].mesh.visible = false;
                //self.parent.scene.remove(self.movingObjects[i].mesh);
            }else{
                tmp.push(obj);
            }
        };
        self.movingObjects = tmp;

        setTimeout(self.internalLoop, 1000 / 600);
    };
    setTimeout(function() {
        console.info('Starting dd.internalLoop ');
        self.internalLoop();
    }, 5 * 500);
    return self;
};
var MovingObject = function(mesh, start, end, speed) {
    var self = this;
    self.start = start;
    self.end = end;
    self.step = 0;
    self.steps = distance(start.lat, start.lng, end.lat, end.lng) / 5;
    self.position = start;
    self.mesh = mesh;
    self.dead = false;
    self.update = function() {
       // console.info('update called', self.step, self.steps);
        if (self.dead){
            self.mesh.material.color.r = 255;
            self.mesh.material.color.g = 0;
            self.mesh.material.color.b = 0;
            return null;
        }
        var newLat = easeInOutQuad(Number(self.step), Number(self.start.lat), Number(self.end.lat) - Number(self.start.lat), self.steps);
        var newLng = easeInOutQuad(Number(self.step), Number(self.start.lng), Number(self.end.lng) - Number(self.start.lng), self.steps);
        var position = coords(newLat, newLng, 0);
        self.mesh.position.x = position.x;
        self.mesh.position.y = position.y;
        self.mesh.position.z = position.z;
        //self.mesh.lookAt(start);
        self.step++;
        self.dead = self.step > self.steps;
        return self;
    }
    return self;
}
DataDisplayer.prototype.drawMovingObject = function(start, end, speed) {
    var self = this;
    var obj = new MovingObject(
        self.drawCube(start.lat, start.lng, 5) //mesh
        , start, end, speed);
    self.movingObjects.push(obj);
}
var materials = {};
materials.cubeMat = new THREE.MeshLambertMaterial({
    color: 0xffffff,
    opacity: 0.2,
    emissive: 0xffffff
});
materials.sphereMat = new THREE.MeshNormalMaterial({
    transparent: true,
    opacity: 0.2
});

DataDisplayer.prototype.drawCube = function(lat, lng, height) {
    var self = this;
    var value = parseFloat(height);
    var position = self.parent.coords(lat, lng, 0);
    var cube = new THREE.Mesh(new THREE.BoxGeometry(5, 5, value), materials.cubeMat);
    cube.position.x = position.x;
    cube.position.y = position.y;
    cube.position.z = position.z;
    cube.lookAt(new THREE.Vector3(0, 0, 0));
    self.parent.sp.add(cube);
    return cube;
};
DataDisplayer.prototype.drawSphere = function(lat, lng, radius) {
    var self = this;
    var value = parseFloat(radius);
    var position = self.parent.coords(lat, lng, value - radius);

    var cube = new THREE.Mesh(new THREE.SphereGeometry(radius, 32, 32), materials.sphereMat);
    cube.position.x = position.x;
    cube.position.y = position.y;
    cube.position.z = position.z;
    cube.lookAt(new THREE.Vector3(0, 0, 0));
    self.parent.sp.add(cube);
    return cube;
};

DataDisplayer.prototype.drawCity = function(id, name, lat, lng, data) {
    var self = this;
    var cube = self.drawSphere(lat, lng, 10 + data.relevance * 5);
    cube.name = data.name.common;
    //DRAW CITY NAME
    self.parent.scene.collision.push(cube);
    return cube;
}
var easeInOutQuad = function(t, b, c, d) {
    if (t < d / 2) return 2 * c * t * t / (d * d) + b;
    var ts = t - d / 2;
    return -2 * c * ts * ts / (d * d) + 2 * c * ts / d + c / 2 + b;
}

function distance(lat1, lon1, lat2, lon2) {
    var R = 6371; // Radius of the earth in km
    var dLat = deg2rad(lat2 - lat1); // deg2rad below
    var dLon = deg2rad(lon2 - lon1);
    var a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
        Math.sin(dLon / 2) * Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c; // Distance in km
    return d;
}

function deg2rad(deg) {
    return deg * (Math.PI / 180)
}

Newteam.prototype.coords = function(lat, lon, heigth) {
    var phi = (lat) * Math.PI / 180;
    var theta = (lon - 180) * Math.PI / 180;

    var x = -(EARTH_SIZE + heigth) * Math.cos(phi) * Math.cos(theta);
    var y = (EARTH_SIZE + heigth) * Math.sin(phi);
    var z = (EARTH_SIZE + heigth) * Math.cos(phi) * Math.sin(theta);

    return new THREE.Vector3(x, y, z);
};

var coords = function(lat, lon, heigth) {
    var phi = (lat) * Math.PI / 180;
    var theta = (lon - 180) * Math.PI / 180;

    var x = -(EARTH_SIZE + heigth) * Math.cos(phi) * Math.cos(theta);
    var y = (EARTH_SIZE + heigth) * Math.sin(phi);
    var z = (EARTH_SIZE + heigth) * Math.cos(phi) * Math.sin(theta);

    return new THREE.Vector3(x, y, z);
};

Newteam.prototype.initDataDisplayer = function(first_argument) {
    var self = this;
    self.dd = new DataDisplayer(self);
    self.op = new ObjectPicker(self);

    return self;
};

var ObjectPicker = function(_parent) {
    var self = this;
    self.parent = _parent;
    self.projector = new THREE.Projector();
    var getPointer = function() {
        var light = new THREE.DirectionalLight(0x333333, .3);
        light.position.set(POS_X_L, POS_Y_L, POS_Z_L);
        light.lookAt(POS_X, POS_Y, POS_Z);
        return light;
    };
    self.parent.pointer = getPointer();
    self.parent.scene.add(self.parent.pointer);
    self.pick = function(x, y, cb) {
        var objects = self.parent.scene.collision;
        var camera = self.parent.camera;
        var vector = new THREE.Vector3((x / window.innerWidth) * 2 - 1, -(y / window.innerHeight) * 2 + 1, 0.5);
        self.projector.unprojectVector(vector, camera);
        var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());

        var intersects = raycaster.intersectObjects(objects);

        if (intersects.length > 0) {
            cb(intersects[0], intersects);
        }

    };

    GLOBALS.pick = self.pick;

    return self;
}


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

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;

namespace NtApiDotNet
{
    /// <summary>
    /// Class to represent an Access Control List (ACL)
    /// </summary>
    public sealed class Acl : List<Ace>
    {
        #region Constructors
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="acl">Pointer to a raw ACL in memory</param>
        /// <param name="defaulted">True if the ACL was defaulted</param>
        public Acl(IntPtr acl, bool defaulted)
        {
            InitializeFromPointer(acl, defaulted);
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="acl">Buffer containing an ACL in memory</param>
        /// <param name="defaulted">True if the ACL was defaulted</param>
        public Acl(byte[] acl, bool defaulted)
        {
            using (var buffer = new SafeHGlobalBuffer(acl))
            {
                InitializeFromPointer(buffer.DangerousGetHandle(), defaulted);
            }
        }

        /// <summary>
        /// Constructor for a NULL ACL
        /// </summary>
        /// <param name="defaulted">True if the ACL was defaulted</param>
        public Acl(bool defaulted) : this(IntPtr.Zero, defaulted)
        {
            Defaulted = defaulted;
        }

        /// <summary>
        /// Constructor for an empty ACL
        /// </summary>
        public Acl() : this(new Ace[0], false)
        {
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="aces">List of ACEs to add to ACL</param>
        /// <param name="defaulted">True if the ACL was defaulted</param>
        public Acl(IEnumerable<Ace> aces, bool defaulted) : base(aces)
        {
            Defaulted = defaulted;
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="aces">List of ACEs to add to ACL</param>
        public Acl(IEnumerable<Ace> aces) : this(aces, false)
        {
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="sddl">An SDDL string to create the DACL from.</param>
        /// <remarks>The SDDL string should be of the form D:(...) or S:(...), if you specify
        /// both a DACL and a SACL then only the DACL will be used.</remarks>
        public Acl(string sddl)
        {
            SecurityDescriptor sd = new SecurityDescriptor(sddl);
            Acl acl = sd.Dacl ?? sd.Sacl
                ?? throw new ArgumentException("Must specify a DACL or a SACL", "sddl");
            Defaulted = acl.Defaulted;
            NullAcl = acl.NullAcl;
            Revision = acl.Revision;
            AddRange(acl);
        }
        #endregion

        #region Public Methods
        /// <summary>
        /// Convert the ACL to a byte array
        /// </summary>
        /// <returns>The ACL as a byte array</returns>
        public byte[] ToByteArray()
        {
            AclRevision revision;
            byte[] aces;
            using (var ace_stm = new MemoryStream())
            {
                using (var writer = new BinaryWriter(ace_stm))
                {
                    revision = Revision;
                    switch (revision)
                    {
                        case AclRevision.Revision:
                        case AclRevision.RevisionCompound:
                        case AclRevision.RevisionDS:
                            break;
                        default:
                            revision = AclRevision.Revision;
                            break;
                    }

                    foreach (Ace ace in this)
                    {
                        ace.Serialize(writer);
                        if (ace.IsObjectAce)
                        {
                            revision = AclRevision.RevisionDS;
                        }
                        else if (ace.Type == AceType.AllowedCompound
                            && revision < AclRevision.RevisionCompound)
                        {
                            revision = AclRevision.RevisionCompound;
                        }
                    }
                }
                aces = ace_stm.ToArray();
            }

            using (var buffer = new SafeHGlobalBuffer(Marshal.SizeOf(typeof(AclStructure)) + aces.Length))
            {
                NtRtl.RtlCreateAcl(buffer, buffer.Length, revision).ToNtException();
                NtRtl.RtlAddAce(buffer, revision, uint.MaxValue, aces, aces.Length).ToNtException();
                return buffer.ToArray();
            }
        }

        /// <summary>
        /// Convert the ACL to a safe buffer
        /// </summary>
        /// <returns>The safe buffer</returns>
        public SafeHGlobalBuffer ToSafeBuffer()
        {
            if (!NullAcl)
            {
                return new SafeHGlobalBuffer(ToByteArray());
            }
            else
            {
                return SafeHGlobalBuffer.Null;
            }
        }

        /// <summary>
        /// Add an ace to the ACL
        /// </summary>
        /// <param name="ace">The ACE to add</param>
        public new void Add(Ace ace)
        {
            base.Add(ace);
            NullAcl = false;
        }

        /// <summary>
        /// Add an access allowed ace to the ACL
        /// </summary>
        /// <param name="mask">The ACE access mask</param>
        /// <param name="flags">The ACE flags</param>
        /// <param name="sid">The ACE SID</param>
        public void AddAccessAllowedAce(AccessMask mask, AceFlags flags, string sid)
        {
            Add(new Ace(AceType.Allowed, flags, mask, new Sid(sid)));
        }

        /// <summary>
        /// Add an access allowed ace to the ACL
        /// </summary>
        /// <param name="mask">The ACE access mask</param>
        /// <param name="sid">The ACE SID</param>
        public void AddAccessAllowedAce(AccessMask mask, string sid)
        {
            AddAccessAllowedAce(mask, AceFlags.None, sid);
        }

        /// <summary>
        /// Add an access allowed ace to the ACL
        /// </summary>
        /// <param name="mask">The ACE access mask</param>
        /// <param name="flags">The ACE flags</param>
        /// <param name="sid">The ACE SID</param>
        public void AddAccessAllowedAce(AccessMask mask, AceFlags flags, Sid sid)
        {
            Add(new Ace(AceType.Allowed, flags, mask, sid));
        }

        /// <summary>
        /// Add an access allowed ace to the ACL
        /// </summary>
        /// <param name="mask">The ACE access mask</param>
        /// <param name="sid">The ACE SID</param>
        public void AddAccessAllowedAce(AccessMask mask, Sid sid)
        {
            AddAccessAllowedAce(mask, AceFlags.None, sid);
        }

        /// <summary>
        /// Add an access denied ace to the ACL
        /// </summary>
        /// <param name="mask">The ACE access mask</param>
        /// <param name="flags">The ACE flags</param>
        /// <param name="sid">The ACE SID</param>
        public void AddAccessDeniedAce(AccessMask mask, AceFlags flags, string sid)
        {
            Add(new Ace(AceType.Denied, flags, mask, new Sid(sid)));
        }

        /// <summary>
        /// Add an access denied ace to the ACL
        /// </summary>
        /// <param name="mask">The ACE access mask</param>
        /// <param name="sid">The ACE SID</param>
        public void AddAccessDeniedAce(AccessMask mask, string sid)
        {
            AddAccessDeniedAce(mask, AceFlags.None, sid);
        }

        /// <summary>
        /// Add an access denied ace to the ACL
        /// </summary>
        /// <param name="mask">The ACE access mask</param>
        /// <param name="flags">The ACE flags</param>
        /// <param name="sid">The ACE SID</param>
        public void AddAccessDeniedAce(AccessMask mask, AceFlags flags, Sid sid)
        {
            Add(new Ace(AceType.Denied, flags, mask, sid));
        }

        /// <summary>
        /// Add an access denied ace to the ACL
        /// </summary>
        /// <param name="mask">The ACE access mask</param>
        /// <param name="sid">The ACE SID</param>
        public void AddAccessDeniedAce(AccessMask mask, Sid sid)
        {
            AddAccessDeniedAce(mask, AceFlags.None, sid);
        }

        /// <summary>
        /// Add an audit ace to the ACL
        /// </summary>
        /// <param name="mask">The ACE access mask</param>
        /// <param name="flags">The ACE flags</param>
        /// <param name="sid">The ACE SID</param>
        public void AddAuditAce(AccessMask mask, AceFlags flags, string sid)
        {
            Add(new Ace(AceType.Audit, flags, mask, new Sid(sid)));
        }

        /// <summary>
        /// Add an audit ace to the ACL
        /// </summary>
        /// <param name="mask">The ACE access mask</param>
        /// <param name="flags">The ACE flags</param>
        /// <param name="sid">The ACE SID</param>
        public void AddAuditAce(AccessMask mask, AceFlags flags, Sid sid)
        {
            Add(new Ace(AceType.Audit, flags, mask, sid));
        }

        /// <summary>
        /// Add an audit success ace to the ACL
        /// </summary>
        /// <param name="mask">The ACE access mask</param>
        /// <param name="sid">The ACE SID</param>
        public void AddAuditSuccessAce(AccessMask mask, string sid)
        {
            AddAuditAce(mask, AceFlags.SuccessfulAccess, sid);
        }

        /// <summary>
        /// Add an audit success ace to the ACL
        /// </summary>
        /// <param name="mask">The ACE access mask</param>
        /// <param name="sid">The ACE SID</param>
        public void AddAuditSuccessAce(AccessMask mask, Sid sid)
        {
            AddAuditAce(mask, AceFlags.SuccessfulAccess, sid);
        }

        /// <summary>
        /// Add an audit fail ace to the ACL
        /// </summary>
        /// <param name="mask">The ACE access mask</param>
        /// <param name="sid">The ACE SID</param>
        public void AddAuditFailAce(AccessMask mask, string sid)
        {
            AddAuditAce(mask, AceFlags.FailedAccess, sid);
        }

        /// <summary>
        /// Add an audit fail ace to the ACL
        /// </summary>
        /// <param name="mask">The ACE access mask</param>
        /// <param name="sid">The ACE SID</param>
        public void AddAuditFailAce(AccessMask mask, Sid sid)
        {
            AddAuditAce(mask, AceFlags.FailedAccess, sid);
        }

        /// <summary>
        /// Gets an indication if this ACL is canonical.
        /// </summary>
        /// <remarks>Canonical means that deny ACEs are before allow ACEs.</remarks>
        /// <param name="dacl">True to canonicalize a DACL, otherwise a SACL.</param>
        /// <returns>True if the ACL is canonical.</returns>
        public bool IsCanonical(bool dacl)
        {
            Acl acl = Clone();
            var ace_order = acl.ToArray();
            acl.Canonicalize(dacl);
            if (acl.Count != ace_order.Length)
            {
                return false;
            }

            for (int i = 0; i < acl.Count; ++i)
            {
                if (!ReferenceEquals(ace_order[i], acl[i]))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// Gets an indication if this DACL is canonical.
        /// </summary>
        /// <remarks>Canonical basically means that deny ACEs are before allow ACEs.</remarks>
        /// <returns>True if the ACL is canonical.</returns>
        [Obsolete("Use IsCanonical with flag")]
        public bool IsCanonical()
        {
            return IsCanonical(true);
        }

        /// <summary>
        /// Canonicalize the ACL.
        /// </summary>
        /// <param name="dacl">True to canonicalize a DACL, otherwise a SACL.</param>
        public void Canonicalize(bool dacl)
        {
            var aces = dacl ? this.Select(GetDaclCanonicalLevel) : this.Select(GetSaclCanonicalLevel);
            Ace[] ace_array = aces.OrderBy(t => t.Item1).Select(t => t.Item2).ToArray();
            Clear();
            AddRange(ace_array);
        }

        /// <summary>
        /// Canonicalize the ACL (for use on DACLs only).
        /// </summary>
        /// <returns>The canonical ACL.</returns>
        [Obsolete("Use Canonicalize with flag")]
        public Acl Canonicalize()
        {
            Acl acl = Clone();
            acl.Canonicalize(true);
            return acl;
        }

        /// <summary>
        /// Find the first ACE with a specified type.
        /// </summary>
        /// <param name="type">The type to find.</param>
        /// <param name="include_inherit_only">True to include inherit only ACEs.</param>
        /// <returns>The found ace. Returns null if not found.</returns>
        public Ace FindAce(AceType type, bool include_inherit_only)
        {
            if (include_inherit_only)
                return Find(a => a.Type == type);
            return Find(a => a.Type == type && !a.IsInheritOnly);
        }

        /// <summary>
        /// Find the first ACE with a specified type. Includes InheritOnly ACEs.
        /// </summary>
        /// <param name="type">The type to find.</param>
        /// <returns>The found ace. Returns null if not found.</returns>
        public Ace FindAce(AceType type)
        {
            return FindAce(type, true);
        }

        /// <summary>
        /// Find the all ACE with a specified type.
        /// </summary>
        /// <param name="type">The type to find.</param>
        /// <param name="include_inherit_only">True to include inherit only ACEs.</param>
        /// <returns>The found aces.</returns>
        public IEnumerable<Ace> FindAllAce(AceType type, bool include_inherit_only)
        {
            if (include_inherit_only)
                return FindAll(a => a.Type == type);
            return FindAll(a => a.Type == type && !a.IsInheritOnly);
        }

        /// <summary>
        /// Find the all ACE with a specified type. Includes InheritOnly ACEs.
        /// </summary>
        /// <param name="type">The type to find.</param>
        /// <returns>The found aces.</returns>
        public IEnumerable<Ace> FindAllAce(AceType type)
        {
            return FindAllAce(type, true);
        }

        /// <summary>
        /// Find the last ACE with a specified type.
        /// </summary>
        /// <param name="type">The type to find.</param>
        /// <returns>The found ace. Returns null if not found.</returns>
        public Ace FindLastAce(AceType type)
        {
            return FindLast(a => a.Type == type);
        }

        /// <summary>
        /// Clone the ACL. Also clones all ACEs.
        /// </summary>
        /// <returns>The cloned ACL.</returns>
        public Acl Clone()
        {
            return new Acl(this.Select(a => a.Clone()))
            {
                Defaulted = Defaulted,
                NullAcl = NullAcl,
                Protected = Protected,
                AutoInherited = AutoInherited,
                AutoInheritReq = AutoInheritReq,
                Revision = Revision
            };
        }

        #endregion

        #region Public Properties
        /// <summary>
        /// Get or set whether the ACL was defaulted
        /// </summary>
        public bool Defaulted { get; set; }

        /// <summary>
        /// Get or set whether the ACL is NULL (no security)
        /// </summary>
        public bool NullAcl { get; set; }

        /// <summary>
        /// Get or set the protected flag.
        /// </summary>
        public bool Protected { get; set; }

        /// <summary>
        /// Get or set the auto-inherited flag.
        /// </summary>
        public bool AutoInherited { get; set; }

        /// <summary>
        /// Get or set the auto-inherited required flag.
        /// </summary>
        public bool AutoInheritReq { get; set; }

        /// <summary>
        /// Get or set the ACL revision
        /// </summary>
        public AclRevision Revision { get; set; }

        /// <summary>
        /// Indicates the ACL has at least one conditional ACE.
        /// </summary>
        public bool HasConditionalAce => this.Any(ace => ace.IsConditionalAce);

        /// <summary>
        /// Indicates the ACL has at least one object ACE.
        /// </summary>
        public bool HasObjectAce => this.Any(ace => ace.IsObjectAce);
        #endregion

        #region Private Members
        private static T GetAclInformation<T>(IntPtr acl, AclInformationClass info_class) where T : new()
        {
            using (var buffer = new SafeStructureInOutBuffer<T>())
            {
                NtRtl.RtlQueryInformationAcl(acl, buffer, buffer.Length, info_class).ToNtException();
                return buffer.Result;
            }
        }

        private void ParseAcl(IntPtr acl)
        {
            var size_info = GetAclInformation<AclSizeInformation>(acl, AclInformationClass.AclSizeInformation);
            using (var buffer = new SafeHGlobalBuffer(acl, size_info.AclBytesInUse, false))
            {
                using (var reader = new BinaryReader(new UnmanagedMemoryStream(buffer, 0, size_info.AclBytesInUse)))
                {
                    for (int i = 0; i < size_info.AceCount; ++i)
                    {
                        NtRtl.RtlGetAce(acl, i, out IntPtr ace).ToNtException();
                        reader.BaseStream.Position = ace.ToInt64() - acl.ToInt64();
                        Add(Ace.CreateAceFromReader(reader));
                    }
                }
            }
            Revision = GetAclInformation<AclRevisionInformation>(acl, AclInformationClass.AclRevisionInformation).AclRevision;
        }

        private void InitializeFromPointer(IntPtr acl, bool defaulted)
        {
            if (acl != IntPtr.Zero)
            {
                ParseAcl(acl);
            }
            else
            {
                NullAcl = true;
            }

            Defaulted = defaulted;
        }

        private const int ACE_LEVEL_0 = 0;
        private const int ACE_LEVEL_1 = 0x10000;
        private const int ACE_LEVEL_2 = 0x20000;
        private const int ACE_LEVEL_3 = 0x30000;
        private const int ACE_LEVEL_4 = 0x40000;
        private const int ACE_LEVEL_INHERITED = 0x50000;

        private Tuple<int, Ace> GetSaclCanonicalLevel(Ace ace, int index)
        {
            int level;
            if (ace.Flags.HasFlagSet(AceFlags.Inherited))
            {
                level = ACE_LEVEL_INHERITED;
            }
            else
            {
                switch (ace.Type)
                {
                    case AceType.Audit:
                    case AceType.AuditCallback:
                    case AceType.Alarm:
                    case AceType.AlarmCallback:
                        level = ACE_LEVEL_0;
                        break;
                    case AceType.AuditObject:
                    case AceType.AuditCallbackObject:
                    case AceType.AlarmObject:
                    case AceType.AlarmCallbackObject:
                        level = ACE_LEVEL_1;
                        break;
                    default:
                        level = ACE_LEVEL_2;
                        break;
                }
            }

            return Tuple.Create(level + index, ace);
        }

        private Tuple<int, Ace> GetDaclCanonicalLevel(Ace ace, int index)
        {
            int level;
            if (ace.Flags.HasFlagSet(AceFlags.Inherited))
            {
                level = ACE_LEVEL_INHERITED;
            }
            else
            {
                switch (ace.Type)
                {
                    case AceType.Allowed:
                    case AceType.AllowedCallback:
                    case AceType.AllowedCompound:
                        level = ACE_LEVEL_2;
                        break;
                    case AceType.AllowedObject:
                    case AceType.AllowedCallbackObject:
                        level = ACE_LEVEL_3;
                        break;
                    case AceType.Denied:
                    case AceType.DeniedCallback:
                        level = ACE_LEVEL_0;
                        break;
                    case AceType.DeniedObject:
                    case AceType.DeniedCallbackObject:
                        level = ACE_LEVEL_1;
                        break;
                    default:
                        level = ACE_LEVEL_4;
                        break;
                }
            }

            return Tuple.Create(level + index, ace);
        }

        #endregion
    }
}


text:
<?php

namespace Gedmo\Sortable\Mapping\Event\Adapter;

use Gedmo\Mapping\Event\Adapter\ODM as BaseAdapterODM;
use Gedmo\Sortable\Mapping\Event\SortableAdapter;
use Doctrine\Common\Util\ClassUtils;

/**
 * Doctrine event adapter for ODM adapted
 * for sortable behavior
 *
 * @author Lukas Botsch <lukas.botsch@gmail.com>
 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
final class ODM extends BaseAdapterODM implements SortableAdapter
{
    public function getMaxPosition(array $config, $meta, $groups)
    {
        $dm = $this->getObjectManager();

        $qb = $dm->createQueryBuilder($config['useObjectClass']);
        foreach ($groups as $group => $value) {
            if (is_object($value) && !$dm->getMetadataFactory()->isTransient(ClassUtils::getClass($value))) {
                $qb->field($group)->references($value);
            } else {
                $qb->field($group)->equals($value);
            }
        }
        $qb->sort($config['position'], 'desc');
        $document = $qb->getQuery()->getSingleResult();

        if ($document) {
            return $meta->getReflectionProperty($config['position'])->getValue($document);
        }

        return -1;
    }

    public function updatePositions($relocation, $delta, $config)
    {
        $dm = $this->getObjectManager();

        $delta = array_map('intval', $delta);

        $qb = $dm->createQueryBuilder($config['useObjectClass']);
        $qb->update();
        $qb->multiple(true);
        $qb->field($config['position'])->inc($delta['delta']);
        $qb->field($config['position'])->gte($delta['start']);
        if ($delta['stop'] > 0) {
            $qb->field($config['position'])->lt($delta['stop']);
        }
        foreach ($relocation['groups'] as $group => $value) {
            if (is_object($value) && !$dm->getMetadataFactory()->isTransient(ClassUtils::getClass($value))) {
                $qb->field($group)->references($value);
            } else {
                $qb->field($group)->equals($value);
            }
        }

        $qb->getQuery()->execute();
    }
}


text:
from lxml import etree
from lxml.etree import tostring
from itertools import chain

def stringify_children(node):
    parts = ([node.text] + list(chain(*([c.text, tostring(c), c.tail]
             for c in node.getchildren()))) + [node.tail])
    return ''.join(filter(None, parts))

def do(filepath, name):
    xml = etree.parse(filepath)
    root = xml.getroot()
    for page in root.findall("{http://www.mediawiki.org/xml/export-0.10/}page"):
        title = page.find("{http://www.mediawiki.org/xml/export-0.10/}title")
        text = page.find("{http://www.mediawiki.org/xml/export-0.10/}revision/"
                         "{http://www.mediawiki.org/xml/export-0.10/}text")
        u_title = stringify_children(title).strip().replace(u':', '_')\
            .replace(u'/', '_').replace(u'*', '_').replace(u'\"', '')\
            .replace(u'?', '_').replace(u'\\', '_')

        if len(u_title) > 30:
            u_title = u_title[:30]

        with open("./corpus/" + name + "/" + u_title + ".txt", 'wb') as f:
            u_text = stringify_children(text).encode('utf-8')
            f.write(u_text)

if __name__ == "__main__":
    filepath = "C:\\ruwiki-20151123-pages-articles1.xml"
    name = "ruwiki"

    print "Work..."
    do(filepath, name)
    print "Done!"


text:
package org.apache.ibatis.submitted.hashmaptypehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class HashMapTypeHandler extends BaseTypeHandler<HashMap<String, String>> {

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, HashMap<String, String> parameter, JdbcType jdbcType)
      throws SQLException {
    ps.setString(i, parameter.get("name"));
  }

  @Override
  public HashMap<String, String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
    return null;
  }

  @Override
  public HashMap<String, String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    return null;
  }

  @Override
  public HashMap<String, String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    return null;
  }
}


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2014-3-21 16:16:46 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="net.freecoder.restdemo.model.WlsMaterialAudio" table="wls_material_audio">
        <id name="id" type="string">
            <column name="id" length="8" />
            <generator class="assigned" />
        </id>
        <property name="fileName" type="string">
            <column name="file_name" length="128" not-null="true" />
        </property>
        <property name="url" type="string">
            <column name="url" length="1024" not-null="true" />
        </property>
        <property name="size" type="java.lang.Integer">
            <column name="size" />
        </property>
        <property name="length" type="java.lang.Short">
            <column name="length" />
        </property>
        <property name="memo" type="string">
            <column name="memo" length="100" />
        </property>
        <property name="appCreateTime" type="timestamp">
            <column name="app_create_time" length="19" />
        </property>
        <property name="appLastModifyTime" type="timestamp">
            <column name="app_last_modify_time" length="19" />
        </property>
        <property name="wlsWxAccountId" type="string">
            <column name="wls_wx_account_id" length="8" not-null="true" />
        </property>
    </class>
</hibernate-mapping>


text:
(function() {
  var $loaders, LOGGED, OVERLAY_BRAND_URL, UNKNOWN_SIL_URL, dataURItoBlob, facebookConnected, facebookStatusChangeCallback, initCanvas, onEverythingLoaded, swapToImage, twitterLoggedCallback;

  UNKNOWN_SIL_URL = "http://i.imgur.com/BsxSrpW.gif";

  OVERLAY_BRAND_URL = "/public/images/stopis_avatar_overlay.png";

  $loaders = $('.loading');

  LOGGED = false;

  dataURItoBlob = function(dataURI, mime) {
    var byteString, i, ia;
    byteString = window.atob(dataURI);
    ia = new Uint8Array(byteString.length);
    i = 0;
    while (i < byteString.length) {
      ia[i] = byteString.charCodeAt(i);
      i++;
    }
    return new Blob([ia], {
      type: mime
    });
  };

  onEverythingLoaded = function(canvas, avatarImage, overlayImage) {
    var $canvas, canvasHeight, canvasWidth, ctx;
    if (!canvas) {
      return;
    }
    ctx = canvas.getContext("2d");
    if (!ctx) {
      return;
    }
    $canvas = $(canvas);
    canvasWidth = $canvas.width();
    canvasHeight = $canvas.height();
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    ctx.save();
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    ctx.imageSmoothingEnabled = true;
    ctx.drawImage(avatarImage, 0, 0, avatarImage.width, avatarImage.height, 0, 0, canvasWidth, canvasHeight);
    ctx.fillStyle = "rgba(234, 6, 17, .75)";
    ctx.fillRect(0, 0, canvasWidth, canvasHeight);
    ctx.drawImage(overlayImage, 0, 0, overlayImage.width, overlayImage.height, 0, 0, canvasWidth, canvasHeight);
    ctx.restore();
    return console.log('Canvas rendering', this, ctx);
  };

  swapToImage = function(canvas) {
    var $canvas, image, imageData, mimeType;
    $canvas = $(canvas);
    mimeType = 'image/png';
    imageData = canvas.toDataURL(mimeType);
    image = new Image;
    image.src = imageData;
    return $('.fallback_img').removeClass('hidden').append(image);
  };

  initCanvas = function() {
    var avatarImage, imagesLoader, overlayImage;
    avatarImage = new Image();
    avatarImage.crossOrigin = "anonymous";
    avatarImage.src = UNKNOWN_SIL_URL;
    overlayImage = new Image();
    overlayImage.src = OVERLAY_BRAND_URL;
    imagesLoader = new imagesLoaded([avatarImage, overlayImage]);
    return imagesLoader.on('done', function(instance) {
      console.log('Canvas Image unkown loaded ok', instance);
      return onEverythingLoaded($('#profile_canvas')[0], avatarImage, overlayImage);
    });
  };

  facebookStatusChangeCallback = function(response) {
    console.log("statusChangeCallback", response);
    if (response.status === "connected") {
      if (LOGGED) {
        FB.logout();
        return;
      }
      LOGGED = 1;
      $loaders.removeClass('hidden');
      return facebookConnected();
    } else if (response.status === "not_authorized") {

    } else {

    }
  };

  twitterLoggedCallback = function(r) {
    console.log('Connected to twitter', r);
    return hello.api(r.network + ':/me', function(p) {
      var avatarPicURL, picAjax, picAjaxParams;
      console.log('Twitter profile is back!', p);
      if (!(p != null ? p.profile_image_url : void 0)) {
        return;
      }
      $loaders.removeClass('hidden');
      avatarPicURL = p.profile_image_url.replace('_normal', '');
      picAjaxParams = {
        url: avatarPicURL
      };
      picAjax = $.ajax({
        url: "https://sender.blockspring.com/api_v1/blocks/1422740194bcb80db36ebc0dabbc55d0?api_key=c7ec96c268e41780753eda8ea0410ce0",
        type: "POST",
        data: picAjaxParams,
        crossDomain: true
      });
      picAjax.fail(function(err) {
        console.log('Twitter ajax pic error', err);
        $loaders.addClass('hidden');
        return alert("We couldn't get your Twitter profile pic. Try facebook or contact us help@stopis.org. Error 194.");
      });
      return picAjax.done(function(res) {
        var avatarImage, imagesLoader, overlayImage;
        console.log('Twitter ajax response ok', res);
        if (!(res != null ? res.results : void 0)) {
          return;
        }
        avatarImage = new Image();
        avatarImage.crossOrigin = "anonymous";
        avatarImage.src = res.results;
        overlayImage = new Image();
        overlayImage.src = OVERLAY_BRAND_URL;
        imagesLoader = new imagesLoaded([avatarImage, overlayImage]);
        imagesLoader.on('always', function() {
          return $loaders.addClass('hidden');
        });
        imagesLoader.on('fail', function(error) {
          console.log('Twitter pics loading error', error);
          return alert("We couldn't get your Twitter profile pic. Try facebook or contact us help@stopis.org. Error 195.");
        });
        return imagesLoader.on('done', function(instance) {
          var $canvas, e;
          console.log('Twitter Images loaded ok', instance);
          $('.pic').removeClass('unknown').css('background-image', "url(" + avatarPicURL + ")");
          $canvas = $('#profile_canvas');
          $canvas.width(512);
          $canvas.height(512);
          onEverythingLoaded($canvas[0], avatarImage, overlayImage);
          $('.tmp-pics').addClass('hidden');
          $('.download').removeClass('hidden');
          swapToImage($canvas[0]);
          try {
            ga('send', 'event', 'app', 'picture_created', 'tw');
          } catch (_error) {
            e = _error;
            console.log('Analytics failed in tw picture creation', e);
          }
          return;
          $('.tmp-pics').addClass('hidden');
          $('.setpic').removeClass('hidden');
          return $('.setpic .btn').click(function(ev) {
            var helloParams, imageData, mimeType;
            console.log('Twitter set as profile picture clicked');
            ev.preventDefault();
            if (!$canvas || !$canvas[0]) {
              return;
            }
            mimeType = 'image/jpeg';
            imageData = $canvas[0].toDataURL(mimeType, 0.65);
            helloParams = {
              include_entities: "true",
              image: imageData.replace(/^data:image\/(png|jpg|jpeg);base64,/, '')
            };
            console.log('Twitter helloparams', {
              h: helloParams
            });
            return hello('twitter').api("me/avatar", "post", helloParams, function(res) {
              return console.log('Twitter pic posted response', res, helloParams);
            });
          });
        });
      });
    });
  };

  facebookConnected = function() {
    console.log("Welcome!  Fetching your information.... ");
    $loaders.removeClass('hidden');
    return FB.api("/me/picture?width=512&height=512", function(response) {
      var avatarImage, avatarPicURL, imagesLoader, overlayImage;
      if (response.data.is_silouette) {
        alert('No profile picture found.');
        return;
      }
      avatarPicURL = response.data.url;
      avatarImage = new Image();
      avatarImage.crossOrigin = "anonymous";
      avatarImage.src = avatarPicURL;
      overlayImage = new Image();
      overlayImage.src = OVERLAY_BRAND_URL;
      imagesLoader = new imagesLoaded([avatarImage, overlayImage]);
      imagesLoader.on('always', function() {
        return $loaders.addClass('hidden');
      });
      imagesLoader.on('error', function(error) {
        console.log('Facebook pics loading error', error);
        return alert("We couldn't get your Facebook profile pic. Try twitter or contact us help@stopis.org / @STOPISORG");
      });
      imagesLoader.on('done', function(instance) {
        var $canvas, e;
        console.log('Facebook Images loaded ok', instance);
        $('.pic').removeClass('unknown').css('background-image', "url(" + avatarPicURL + ")");
        $canvas = $('#profile_canvas');
        $canvas.width(512);
        $canvas.height(512);
        onEverythingLoaded($canvas[0], avatarImage, overlayImage);
        $('.tmp-pics').addClass('hidden');
        $('.download').removeClass('hidden');
        swapToImage($canvas[0]);
        try {
          ga('send', 'event', 'app', 'picture_created', 'fb');
        } catch (_error) {
          e = _error;
          console.log('Analytics failed in fb picture creation', e);
        }
        return;
        $('.tmp-pics').addClass('hidden');
        $('.setpic').removeClass('hidden');
        return $('.setpic .btn').click(function(ev) {
          var access_token, blob, form, imageData, mimeType, uploadParams, win;
          ev.preventDefault();
          if (!$canvas || !$canvas[0]) {
            return;
          }
          mimeType = 'image/png';
          imageData = $canvas[0].toDataURL(mimeType);
          imageData = imageData.replace(/^data:image\/(png|jpg);base64,/, '');
          try {
            blob = dataURItoBlob(imageData, mimeType);
          } catch (_error) {
            e = _error;
            console.log('blob failed', e);
          }
          access_token = FB.getAuthResponse()['accessToken'];
          console.log('binary ', imageData, blob);
          if (!blob) {
            return;
          }
          form = new FormData();
          form.append("access_token", access_token);
          form.append("source", blob);
          form.append("message", '#STOPIS http://STOPIS.org');
          win = open("about:blank", "_blank", "width=1, height= 1, left=" + screenLeft + ", top=" + screenTop);
          if (!win) {
            return;
          }
          win.document.write("Loading...");
          $.ajax({
            url: "https://graph.facebook.com/me/photos?access_token=" + access_token,
            type: "POST",
            data: form,
            processData: false,
            contentType: false,
            cache: false,
            success: function(data) {
              var h, left, makeProfileURL, picid, top, w;
              console.log("Facebook ajax success ", data);
              try {
                ga('send', 'event', 'app', 'picture_uploaded', 'fb');
              } catch (_error) {
                e = _error;
                console.log('Analytics failed in facebook picture posted', e);
              }
              if (!win) {
                return;
              }
              picid = data.id;
              makeProfileURL = "https://m.facebook.com/photo.php?fbid=" + picid + "&prof";
              w = 330;
              h = 600;
              left = (($(window).width()) / 2) + screenLeft - (w / 2);
              top = ($(document.body).height() / 2) + screenTop - (h / 2);
              win.resizeTo(w, h);
              win.moveTo(left, top);
              return win.location = makeProfileURL;
            },
            error: function(shr, status, data) {
              console.log("Facebook ajax error ", data + " Status ", shr.status);
              alert('We are sorry. Facebook returned an error. Please report it on github.com/stopis. #11');
              return win.close();
            }
          });
          uploadParams = {
            message: '#STOPIS stopis.org',
            source: imageData
          };
          return FB.api("/me/photos", 'post', uploadParams, function(response) {
            return console.log('Upload Response', response);
          });
        });
      });
      return console.log("Successful login ", avatarPicURL);
    });
  };

  window.fbAsyncInit = function() {
    FB.init({
      appId: "313186485472622",
      cookie: true,
      xfbml: true,
      version: "v2.0"
    });
    return FB.getLoginStatus(function(response) {
      return facebookStatusChangeCallback(response);
    });
  };

  (function(d, s, id) {
    var fjs, js;
    js = void 0;
    fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {
      return;
    }
    js = d.createElement(s);
    js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    return fjs.parentNode.insertBefore(js, fjs);
  })(document, "script", "facebook-jssdk");

  hello.on('auth.login', function(r) {
    if (LOGGED) {
      hello('twitter').logout();
      return;
    }
    LOGGED = 1;
    return twitterLoggedCallback(r);
  });

  hello.init({
    twitter: '9mc19rYyrkYD8arSeoDjX5QHi'
  }, {
    redirect_uri: '/',
    oauth_proxy: 'https://auth-server.herokuapp.com/proxy'
  });

  initCanvas();

  $('.tw').click(function(ev) {
    console.log('twitter clicked');
    return hello.login('twitter');
  });

  $('.fb').click(function(ev) {
    console.log('facebook clicked');
    FB.login(facebookStatusChangeCallback, {
      scope: 'public_profile,publish_actions'
    });
    return {
      auth_type: 'reauthenticate'
    };
  });

  $('.share_fb').click(function(ev) {
    ev.preventDefault();
    return FB.ui({
      method: 'feed',
      link: location.toString(),
      name: '#STOPIS',
      caption: 'Change your avatar. Stop the genocide. Save lives.',
      description: "In 2014 the Islamic State is expanding fast. Killing those who don't convert to Islam. This is not a political problem, it's a problem of everyone and this innocent people need your help. Change your profile picture now, stop the horrific genocide.",
      picture: "https://pbs.twimg.com/profile_images/499414418594070528/HZbwJbMj.png",
      message: ''
    });
  });

}).call(this);


text:
const Pad = require('./Pad');
const MergeDefault = require('./MergeDefault');
const GetBranchName = require('./Branch');

module.exports = { Pad, MergeDefault, GetBranchName };


text:
#ifndef SPATIAL_SOFTMAX_WITH_LOSS_OP_H_
#define SPATIAL_SOFTMAX_WITH_LOSS_OP_H_

#include "caffe2/core/context.h"
#include "caffe2/core/logging.h"
#include "caffe2/core/operator.h"
#include "caffe2/utils/math.h"

namespace caffe2 {

template <typename T, class Context>
class SpatialSoftmaxWithLossOp final : public Operator<Context> {
 public:
  SpatialSoftmaxWithLossOp(const OperatorDef& operator_def, Workspace* ws)
      : Operator<Context>(operator_def, ws),
        scale_(OperatorBase::GetSingleArgument<float>("scale", 1.)),
        order_(StringToStorageOrder(
            OperatorBase::GetSingleArgument<string>("order", "NCHW"))) {
    CAFFE_ENFORCE(scale_ >= 0);
    CAFFE_ENFORCE_EQ(
        order_, StorageOrder::NCHW, "Only NCHW order is supported right now.");
  }
  USE_OPERATOR_CONTEXT_FUNCTIONS;

  bool RunOnDevice() override;

 protected:
  float scale_;
  StorageOrder order_;

  Tensor<Context> losses_; // Per example loss
  Tensor<Context> rowmax_; // per example row max
  Tensor<Context> weights_; // unignored weights
  Tensor<Context> sum_multiplier_; // Vector of ones for summing via dot prod
  Tensor<Context> total_weight_ptr_;
  Tensor<Context> scratch_;
};

template <typename T, class Context>
class SpatialSoftmaxWithLossGradientOp final : public Operator<Context> {
 public:
  SpatialSoftmaxWithLossGradientOp(const OperatorDef& def, Workspace* ws)
      : Operator<Context>(def, ws),
        scale_(OperatorBase::GetSingleArgument<float>("scale", 1.)),
        order_(StringToStorageOrder(
            OperatorBase::GetSingleArgument<string>("order", "NCHW"))),
        only_loss_(OperatorBase::GetSingleArgument<bool>("only_loss", false)) {
    CAFFE_ENFORCE(scale_ >= 0);
    CAFFE_ENFORCE_EQ(
        order_, StorageOrder::NCHW, "Only NCHW order is supported right now.");
  }
  USE_OPERATOR_CONTEXT_FUNCTIONS;

  bool RunOnDevice() override;

 protected:
  float scale_;
  Tensor<Context> sum_multiplier_;
  Tensor<Context> weights_; // unignored weights
  Tensor<Context> total_weight_ptr_;
  StorageOrder order_;
  bool only_loss_;
  Tensor<Context> scratch_;
};

} // namespace caffe2

#endif // SOFTMAX_WITH_LOSS_OP_H_


text:
/*jslint indent: 4, node: true */
/*global require: false, process: false */

// findAllWords.js
//
// Given a word search puzzle in json format, create all
// combinations of horizontal, vertical and diagonal words
// and check them against a list of known English words
// reporting any found.
//
var http = require('http'),
    path = require('path'),
    fs = require('fs'),
    url = require('url'),
    wordlist = {},
    loadJSON = function (filename, callback) {
        "use strict";

        var result = {};

        fs.readFile(filename, { 'encoding': "utf8" }, function (err, data) {
            if (err) {
                console.log('failed to read operation chain');
                callback(err, null);
            } else {
                result = JSON.parse(data);

                callback(null, result);
            }
        });
    },
    findWords = function (line) {
        "use strict";

        var wordLength = 0,
            index = 0,
            word = '';

        for (wordLength = 4; wordLength <= line.length; wordLength += 1) {
            for (index = 0; index < line.length - wordLength + 1; index += 1) {
                word = line.substr(index, wordLength);
                if (wordlist.indexOf(word) !== -1) {
                    console.log(word);
                }
            }
        }
    },
    permuteBoard = function (board) {
        "use strict";

        var i = 0,
            line = '',
            mapColumn = function (index) {
                return function (row) {
                    return row[index];
                };
            },
            mapDiagonalDownLeft = function (index) {
                return function (row) {
                    var result = "";
                    if (index >= 0) {
                        result = row[index];
                        index -= 1;
                    }
                    return result;
                };
            },
            mapDiagonalDownRight = function (index) {
                return function (row) {

                    var result = "";
                    if (index < row.length) {
                        result = row[index];
                        index += 1;
                    }
                    return result;
                };
            };

        console.log('----------ROWS');
        for (i = 0; i < board.maxY; i += 1) {
            line = board.matrix[i].join("");
            findWords(line);
        }
        console.log('----------COLUMNS');
        for (i = 0; i < board.maxX; i += 1) {
            line = board.matrix.map(mapColumn(i)).join("");
            findWords(line);
        }
        console.log('----------DIAGONALS DOWN LEFT');
        for (i = 0; i < board.maxX; i += 1) {
            line = board.matrix.map(mapDiagonalDownLeft(i)).join("");
            findWords(line);
        }
        console.log('----------DIAGONALS DOWN RIGHT');
        for (i = 0; i < board.maxX; i += 1) {
            line = board.matrix.map(mapDiagonalDownRight(i)).join("");
            findWords(line);
        }
        console.log('----------DIAGONALS UP LEFT');
        for (i = 0; i < board.maxX; i += 1) {
            line = board.matrix.reverse().map(mapDiagonalDownLeft(i)).join("");
            findWords(line);
        }
        console.log('----------DIAGONALS UP RIGHT');
        for (i = 0; i < board.maxX; i += 1) {
            line = board.matrix.reverse().map(mapDiagonalDownRight(i)).join("");
            findWords(line);
        }
        console.log('----------ROWS REVERSED');
        for (i = 0; i < board.maxY; i += 1) {
            line = board.matrix[i].reverse().join("");
            findWords(line);
        }
        console.log('----------COLUMNS REVERSED');
        for (i = 0; i < board.maxX; i += 1) {
            line = board.matrix.map(mapColumn(i)).reverse().join("");
            findWords(line);
        }
        console.log('----------DIAGONALS DOWN LEFT REVERSED');
        for (i = 0; i < board.maxX; i += 1) {
            line = board.matrix.map(mapDiagonalDownLeft(i)).reverse().join("");
            findWords(line);
        }
        console.log('----------DIAGONALS DOWN RIGHT REVERSED');
        for (i = 0; i < board.maxX; i += 1) {
            line = board.matrix.map(mapDiagonalDownRight(i)).reverse().join("");
            findWords(line);
        }
        console.log('----------DIAGONALS UP LEFT REVERSED');
        for (i = 0; i < board.maxX; i += 1) {
            line = board.matrix.reverse().map(mapDiagonalDownLeft(i)).reverse().join("");
            findWords(line);
        }
        console.log('----------DIAGONALS UP RIGHT REVERSED');
        for (i = 0; i < board.maxX; i += 1) {
            line = board.matrix.reverse().map(mapDiagonalDownRight(i)).reverse().join("");
            findWords(line);
        }
    },
    getBoard = function (rows) {
        "use strict";

        var result = { 'matrix' : []},
            Y = 0,
            maxX = 0;

        result.maxY = rows.length;

        for (Y = 0; Y < result.maxY; Y += 1) {
            if (maxX !== 0 && rows[Y].length !== maxX) {
                return "row " + Y + "is " + rows[Y].length +
                    " characters. All the other rows are " + maxX + " characters.";
            }
            maxX = rows[Y].length;
            result.maxX = maxX;
            result.matrix[Y] = rows[Y].toUpperCase().split("");
        }

        return result;
    },
    validateBoard = function (rows) {
        "use strict";

        var board = getBoard(rows);

        if (typeof board !== "object") {
            console.log(board);
        } else {
            loadJSON(path.resolve('.', 'wordlist.json'), function (err, result) {
                if (err) {
                    console.log(err);
                } else {
                    wordlist = result;
                    permuteBoard(board);
                }
            });
        }
    },
    main = function (argc, argv) {
        "use strict";

        if (argc < 3) {
            console.log('usage: %s %s <board>', argv[0], argv[1]);
        } else {
            loadJSON(path.resolve('.', argv[2]), function (err, result) {
                if (err) {
                    console.log(err);
                } else {
                    validateBoard(result);
                }
            });
        }
    },
    argv = process.argv,
    argc = argv.length;

if (!String.prototype.format) {
    String.prototype.format = function () {
        "use strict";

        var args = arguments;

        // If we are passed an array then just use that.
        if (args.length === 1 && typeof args[0] === "object") {
            args = args[0] || [];
        }

        return this.replace(/\{(\d+)\}/g, function (match, number) {
            var result = args[number] || match;
            return result;
        });
    };
}

main(argc, argv);


text:
@implementation NSString (MIMEType)
- (NSString *)MIMEType
{
    if (![[NSFileManager defaultManager] fileExistsAtPath:self]) {
        return nil;
    }
    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge  CFStringRef)[self pathExtension], NULL);
    CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
    CFRelease(UTI);
    if (!MIMEType) {
        return @"application/octet-stream";
    }
    return (__bridge NSString *)MIMEType;
}

- (NSString *)MIMEType2
{
    NSURLResponse *response = nil;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:self]];
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    return response.MIMEType;
}
@end


text:
<?php

namespace Illuminate\Queue\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Arr;

class RetryCommand extends Command
{
    /**
     * The console command signature.
     *
     * @var string
     */
    protected $signature = 'queue:retry
                            {id?* : The ID of the failed job or "all" to retry all jobs}
                            {--range=* : Range of job IDs (numeric) to be retried}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Retry a failed queue job';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        foreach ($this->getJobIds() as $id) {
            $job = $this->laravel['queue.failer']->find($id);

            if (is_null($job)) {
                $this->error("Unable to find failed job with ID [{$id}].");
            } else {
                $this->retryJob($job);

                $this->info("The failed job [{$id}] has been pushed back onto the queue!");

                $this->laravel['queue.failer']->forget($id);
            }
        }
    }

    /**
     * Get the job IDs to be retried.
     *
     * @return array
     */
    protected function getJobIds()
    {
        $ids = (array) $this->argument('id');

        if (count($ids) === 1 && $ids[0] === 'all') {
            return Arr::pluck($this->laravel['queue.failer']->all(), 'id');
        }

        if ($ranges = (array) $this->option('range')) {
            $ids = array_merge($ids, $this->getJobIdsByRanges($ranges));
        }

        return array_values(array_filter(array_unique($ids)));
    }

    /**
     * Get the job IDs ranges, if applicable.
     *
     * @param  array  $ranges
     * @return array
     */
    protected function getJobIdsByRanges(array $ranges)
    {
        $ids = [];

        foreach ($ranges as $range) {
            if (preg_match('/^[0-9]+\-[0-9]+$/', $range)) {
                $ids = array_merge($ids, range(...explode('-', $range)));
            }
        }

        return $ids;
    }

    /**
     * Retry the queue job.
     *
     * @param  \stdClass  $job
     * @return void
     */
    protected function retryJob($job)
    {
        $this->laravel['queue']->connection($job->connection)->pushRaw(
            $this->resetAttempts($job->payload), $job->queue
        );
    }

    /**
     * Reset the payload attempts.
     *
     * Applicable to Redis jobs which store attempts in their payload.
     *
     * @param  string  $payload
     * @return string
     */
    protected function resetAttempts($payload)
    {
        $payload = json_decode($payload, true);

        if (isset($payload['attempts'])) {
            $payload['attempts'] = 0;
        }

        return json_encode($payload);
    }
}


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class FaFilePowerpointO extends React.Component<IconBaseProps, any> { }


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.eurekaclinical</groupId>
    <artifactId>javautil</artifactId>
    <packaging>jar</packaging>
    <version>4.3-SNAPSHOT</version>
    <name>JavaUtil</name>
    <url>https://github.com/eurekaclinical/javautil.git</url>
    <description>JavaUtil is a utility library to speed the development of
        Java software. We developed it over multiple years during
        our internal development efforts, and it has reached a
        point of stability where we have decided to make it
        available to the outside world. The JavaUtil package aims
        to fill in the gaps of the Apache Commons and similar
        utility libraries out there.  Features include convenience
        classes for string, collections, arrays, dates, iterators,
        colors, logging, unit testing, a little bit of basic
        statistics, database queries, caching and more.
    </description>
    <parent>
        <groupId>org.eurekaclinical</groupId>
        <artifactId>eurekaclinical-parent-standard-deps</artifactId>
        <version>3</version>
    </parent>
    <inceptionYear>2012</inceptionYear>

    <scm>
        <connection>scm:git:https://github.com/eurekaclinical/javautil.git</connection>
        <developerConnection>scm:git:https://github.com/eurekaclinical/javautil.git</developerConnection>
        <url>https://github.com/eurekaclinical/javautil.git</url>
        <tag>HEAD</tag>
    </scm>

    <issueManagement>
        <system>GitHub</system>
        <url>https://github.com/eurekaclinical/javautil/issues</url>
    </issueManagement>

    <dependencies>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.mockrunner</groupId>
            <artifactId>mockrunner-jdbc</artifactId>
            <version>1.1.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.jasig.maven</groupId>
                <artifactId>maven-notice-plugin</artifactId>
                <configuration>
                    <noticeTemplate>etc/NOTICE.template</noticeTemplate>
                    <licenseMapping>
                        <param>etc/license-mappings.xml</param>
                    </licenseMapping>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>license-maven-plugin</artifactId>
                <configuration>
                    <licenseName>apache_v2</licenseName>
                    <roots>
                        <root>src/main</root>
                        <root>src/test/java/</root>
                    </roots>
                    <extraExtensions>
                        <!-- .xsd files are not supported by default -->
                        <!-- but should be commented in XML style -->
                        <xsd>xml</xsd>
                    </extraExtensions>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <configuration>
                    <additionalparam>-Xdoclint:none</additionalparam>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('heatherr', '0003_auto_20160211_1357'),
    ]

    operations = [
        migrations.CreateModel(
            name='Acronym',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('acronym', models.CharField(blank=True, max_length=100)),
                ('definition', models.TextField(blank=True)),
                ('slackaccount', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='heatherr.SlackAccount')),
            ],
        ),
    ]


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=Edge"/>

        <title>await Wisdom() - St. Louis Days of .NET 2013</title>
        <meta name="description" content="await Wisdom()" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link type="application/rss+xml" rel="alternate" title="await Wisdom()" href="/feed.rss" />
                <link type="application/atom+xml" rel="alternate" title="await Wisdom()" href="/feed.atom" />
        <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
        <link rel="icon" href="/favicon.ico" type="image/x-icon">

        <link href="/assets/css/bootstrap.min.css" rel="stylesheet" />
        <link href="/assets/css/highlight.css" rel="stylesheet">
        <link href="/assets/css/clean-blog.css" rel="stylesheet" />
        <link href="/assets/css/master.css" rel="stylesheet" />
        <link href="/assets/css/font-awesome.min.css" rel="stylesheet" type="text/css">
        <link href='//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
        <link href='//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
        <link href="/assets/css/override.css" rel="stylesheet" />

        <meta name="application-name" content="await Wisdom()" />
        <meta name="msapplication-tooltip" content="await Wisdom()" />
        <meta name="msapplication-starturl" content="/" />

        <meta property="og:title" content="await Wisdom() - St. Louis Days of .NET 2013" />
        <meta property="og:type" content="website" />
        <meta property="og:url" content="https://blog.awaitwisdom.com/posts/stldodn-2013" />

        <link type="application/rss+xml" rel="alternate" title="await Wisdom() Tech" href="/techfeed.rss" />
        <link type="application/atom+xml" rel="alternate" title="await Wisdom() Tech" href="/techfeed.atom" />

                                        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
                                        Toggle navigation

                                        </button>
                                        await Wisdom()

About Josh

About Polaris Solutions

About this blog

All Tags

Archive

St. Louis Days of .NET 2013

Published on Sunday, October 27, 2013

                    Migrated
                    Speaking
                    Tech

St. Louis Days of .NET (STLDODN) 2013 is fast approaching. Polaris Solutions is a sponsor this year and I'll be presenting there with two of my colleagues.

Angela Dugan is presenting Agile Testing in a Waterfall World.

Clint Edmonson will present an Application Architecture Jumpstart and Advanced OOP - Laws, Principles, Idioms.

I'm going to be walking through A Pragmatic Intro to Unit Testing. Then I'll have some fun talking about code smells and refactoring patterns with  Dude, I Just Stepped into your Code.

So check out check out STLDODN to get signed up and be sure to check us out. The detailed agenda isn't posted yet, but should be available soon.

                        Copyright © 2017

                             RSS Feed
                        |
                             Atom Feed

                        Generated by Wyam


text:
[![Latest Version on Packagist][ico-version]][link-packagist]
[![Total Downloads][ico-downloads]][link-downloads]
[![Software License][ico-license]][link-license]

Yet another user groups management system.

It includes some additional features like:
- Group Leaders: each group can have one or more leaders
- Group Prefixes and Suffixes: group members may have formatted names depending on their group belonging
- Group Limit: a group can have a limit of members

## Documentation

Read the [Wiki](https://github.com/atorscho/membership/wiki).

## Change log

Please see [CHANGELOG][link-changelog] for more information what has changed recently.

## Contributing

Please see [CONTRIBUTING][link-contributing] for details.

## Security

If you discover any security related issues, please email `contact@alextorscho.com` instead of using the issue tracker.

## Credits

- [Alex Torscho][link-author]
- [All Contributors][link-contributors]

## License

The MIT License (MIT). Please see [License File][link-license] for more information.

[ico-version]: https://poser.pugx.org/atorscho/membership/version
[ico-license]: https://poser.pugx.org/atorscho/membership/license
[ico-downloads]: https://poser.pugx.org/atorscho/membership/downloads

[link-packagist]: https://packagist.org/packages/atorscho/membership
[link-downloads]: https://packagist.org/packages/atorscho/membership
[link-author]: https://github.com/atorscho
[link-contributors]: https://github.com/atorscho/membership/graphs/contributors
[link-contributing]: https://github.com/atorscho/membership/blob/master/CONTRIBUTING.md
[link-changelog]: https://github.com/atorscho/membership/blob/master/CHANGELOG.md
[link-license]: https://github.com/atorscho/membership/blob/master/LICENSE.md


text:
@implementation BookForm (Configure)

- (void)configureWithBook:(Book *)book
{
    self.customImageItem.customImage = [UIImage imageWithContentsOfFile:book.imageFileURL];
    self.titleItem.value = book.title;
    self.publisherItem.value = book.publisher;
    self.publishedDateItem.value = book.publishedDate;
    self.pageCountItem.value = [book.pageCount stringValue];
    self.ratingItem.value = @[[book.rating stringValue]];
    self.summaryItem.value = book.summary;
    self.notesItem.value = book.notes;

    [self.authorsSection removeAllItems];
    [self.authors removeAllObjects];
    for (Author *author in book.authors) {
        [self addAuthorTextItem:author.name toSection:self.authorsSection];
    }
    [self.authorsSection addItem:self.addAuthorButton];

    [self.tagsSection removeAllItems];
    [self.tags removeAllObjects];
    for (ReadingCollectionItemTag *tag in book.tags) {
        [self addTagTextItem:tag.name toSection:self.tagsSection];
    }
    [self.tagsSection addItem:self.addTagButton];
}

@end