text:
shared :file_directory do |cmd, klass, name|
  describe "#{name || "#{klass}.#{cmd}"}" do
    before :each do
      platform_is :windows do
        @dir  = "C:\\"
        @file = "C:\\winnt\\notepad.exe"
      end

      platform_is_not :windows do
        @dir  = "/"
        @file = "/bin/ls"
      end
    end

    after :each do
      @dir = nil
    end

    it "return true if dir is a directory, otherwise return false" do
      klass.send(cmd, @dir).should == true
      klass.send(cmd, @file).should == false
    end

    it "raises an ArgumentError if not passed one argument" do
      lambda { klass.send(cmd)              }.should raise_error(ArgumentError)
      lambda { klass.send(cmd, @dir, @file) }.should raise_error(ArgumentError)
    end

    it "raises a TypeError if not passed a String type" do
      lambda { klass.send(cmd, nil) }.should raise_error(TypeError)
    end
  end
end


text:
@interface FeedPostOneImageTableViewCell ()
{
    UILabel *_titleLabel;
    UILabel *_dateLabel;
    UILabel *_authorLabel;

    UIImageView *_imageView;
}

@end

@implementation FeedPostOneImageTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self){
        self.selectionStyle = UITableViewCellSelectionStyleNone;

        [self _setupView];
    }
    return self;
}

- (void)_setupView{
    UIView *root = self.contentView;
    _titleLabel = [UILabel new];
    _titleLabel.font = [UIFont systemFontOfSize:18];
    _titleLabel.textColor = [UIColor blackColor];
    _titleLabel.numberOfLines = 2;
    [root addSubview:_titleLabel];

    _dateLabel = [UILabel new];
    _dateLabel.font = [UIFont systemFontOfSize:14];
    _dateLabel.textColor = UIColorGraySubTitle;
    [root addSubview:_dateLabel];

    _authorLabel = [UILabel new];
    _authorLabel.font = [UIFont systemFontOfSize:14];
    _authorLabel.textColor = UIColorGraySubTitle;
    [root addSubview:_authorLabel];

    _imageView = [UIImageView new];
    _imageView.layer.borderWidth = 0.5;
    _imageView.layer.borderColor = UIColorFromRGBA(0xd7dae2, 1.0).CGColor;
    [root addSubview:_imageView];

    [_imageView mas_makeConstraints:^(MASConstraintMaker *make){
        make.width.equalTo(@60);
        make.height.equalTo(@60);
        make.right.equalTo(root).offset(-20);
        make.centerY.equalTo(root);
    }];

    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.equalTo(root).offset(38/2);
        make.top.equalTo(root).offset(34/2);
        make.right.equalTo(_imageView.mas_left).offset(-38/2);
    }];

    [_dateLabel mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.equalTo(_titleLabel);
        make.top.equalTo(_titleLabel.mas_bottom).offset(8);
    }];

    [_authorLabel mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.equalTo(_dateLabel.mas_right).offset(8);
        make.right.lessThanOrEqualTo(_imageView.mas_left).offset(-38/2);
        make.centerY.equalTo(_dateLabel.mas_centerY);
    }];
}

- (void)prepareForReuse{
    [super prepareForReuse];
    _imageView.image = nil;
}

- (void)setTitle:(NSString *)title{
    _titleLabel.text = title?title:@"";
}

- (void)setDate:(NSDate *)date{
    _dateLabel.text = [[AppUtil util] formatDate:date];
}

- (void)setAuthor:(NSString *)author{
    _authorLabel.text = author;
}
- (void)setImageURL:(NSString *)imageURL{
    if(!imageURL)return;
    [_imageView yy_setImageWithURL:[NSURL URLWithString:imageURL] placeholder:nil options:kNilOptions completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
    }];
}

@end

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 * Support classes for document generation,
 * providing View implementations for PDF and Excel.
 *
 */
package org.springframework.web.servlet.view.document;


text:
package edu.wustl.cab2b.admin.bizlogic;

import java.util.Collection;
import java.util.List;

import edu.wustl.cab2b.common.queryengine.Cab2bQuery;
import edu.wustl.cab2b.common.queryengine.ICab2bQuery;
import edu.wustl.cab2b.common.queryengine.ServiceGroup;
import edu.wustl.cab2b.server.queryengine.QueryOperations;

public class QueryBizLogic {

	public Collection<ICab2bQuery> findMultiModelQueries() {
		 QueryOperations queryOperations = new QueryOperations();
		 List<ICab2bQuery> queries = queryOperations.getAllMultiModelQueries();
		 return queries;
	}

	public ICab2bQuery loadQuery(Long id) {
		 QueryOperations queryOperations = new QueryOperations();
		 ICab2bQuery query = queryOperations.getQueryById(id);
		 query.getServiceGroups();
		 return query;
	}

	public Cab2bQuery addServiceGroups(Long id, Collection<ServiceGroup> groups) {
		QueryOperations queryOperations = new QueryOperations();
		queryOperations.deleteAllServiceGroups(id);
		return queryOperations.addServiceGroupsToQuery(id, groups);
	}
}


text:
## Overview

Better interaction, Better learning with __flip learning__

## Contact

* Blog: https://flassofficial.tistory.com
* Facebook: https://www.facebook.com/flassofficial


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CC.MT.Public.Sheriff.Controllers
{
  /// <summary>
  /// HomeController
  /// </summary>
  public class HomeController : Controller
  {
    /// <summary>
    /// Index Action
    /// </summary>
    /// <returns>A Page or null and a Redirect</returns>
    public ActionResult Index()
    {
#if DEBUG
      string path = String.Empty;

      path = "/CurrentArrest";
      //path = "/CurrentArrestString";
      //path = "/JailList";
      //path = "/JailRosterByLetter/B";
      //path = "/JailRosterByLetter/-ALL";
      //path = "/JailRosterByName/Smith";
      //path = "/DMVWaitTime";
      //path = "/DMVWaitTimeQueue";

      Response.Redirect(Request.AppRelativeCurrentExecutionFilePath + path);
      return null;
#else
      return View();
#endif
    }
  }
}


text:
<?xml version="1.0"?>
<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>

  <artifactId>stratuslab-cli-user-rpm</artifactId>
  <name>StratusLab User CLI (RPM)</name>
  <packaging>rpm</packaging>

  <parent>
    <groupId>eu.stratuslab.client</groupId>
    <artifactId>stratuslab-cli-user</artifactId>
    <version>14.06.1-SNAPSHOT</version>
  </parent>

  <profiles>
    <profile>
      <id>rpm</id>
      <activation>
	<file>
	  <exists>/bin/rpm</exists>
	</file>
      </activation>
      <build>

	<plugins>

	  <plugin>
	    <groupId>org.apache.maven.plugins</groupId>
	    <artifactId>maven-dependency-plugin</artifactId>

	    <executions>
	      <execution>
		<id>unpack-sources</id>
		<phase>generate-sources</phase>
		<goals>
		  <goal>copy</goal>
		</goals>
		<configuration>
		  <outputDirectory>${project.build.directory}/zip-sources</outputDirectory>
		  <artifactItems>
		    <artifactItem>
		      <groupId>eu.stratuslab.client</groupId>
		      <artifactId>stratuslab-client-pypi</artifactId>
                      <type>tar.gz</type>
		    </artifactItem>
		  </artifactItems>
		</configuration>
	      </execution>
	    </executions>

	  </plugin>

	  <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <executions>
              <execution>
		<phase>process-sources</phase>
		<goals>
		  <goal>exec</goal>
		</goals>
              </execution>
            </executions>
            <configuration>
              <executable>${basedir}/src/main/scripts/install-client.sh</executable>
              <workingDirectory>${project.build.directory}</workingDirectory>
              <arguments>
		<argument>${project.build.directory}</argument>
		<argument>${project.build.directory}/zip-sources/stratuslab-client-pypi-${project.version}.tar.gz</argument>
              </arguments>
            </configuration>
	  </plugin>

	  <plugin>
	    <groupId>org.codehaus.mojo</groupId>
	    <artifactId>rpm-maven-plugin</artifactId>
	    <extensions>true</extensions>
	    <executions>
	      <execution>
		<goals>
		  <goal>rpm</goal>
		</goals>
	      </execution>
	    </executions>
	  </plugin>
	</plugins>
      </build>
    </profile>

  </profiles>

  <dependencies>
    <dependency>
      <groupId>eu.stratuslab.client</groupId>
      <artifactId>stratuslab-client-pypi</artifactId>
      <version>14.06.1-SNAPSHOT</version>
      <type>tar.gz</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>

  <build>

    <plugins>

      <plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-deploy-plugin</artifactId>
      </plugin>

      <plugin>
	<groupId>org.codehaus.mojo</groupId>
	<artifactId>rpm-maven-plugin</artifactId>
	<configuration>
	  <release>${RELEASE}</release>
	  <summary>${project.name}</summary>
	  <name>stratuslab-cli-user</name>
	  <vendor>SixSq Sarl</vendor>
	  <copyright>Apache 2.0</copyright>
	  <url>http://stratuslab.eu/</url>

	  <distribution>StratusLab</distribution>
	  <group>StratusLab</group>
	  <packager>StratusLab</packager>

	  <buildarch>noarch</buildarch>

	  <requires>
	    <require>stratuslab-api</require>
	    <require>python-ldap</require>
	  </requires>

	  <mappings>
	    <mapping>
	      <directory>/usr/bin/</directory>
	      <directoryIncluded>false</directoryIncluded>
	      <filemode>755</filemode>
	      <username>root</username>
	      <groupname>root</groupname>
	      <sources>
		<source>
		  <location>${project.build.directory}/venv/bin</location>
		  <includes>
		    <include>stratus-*</include>
		  </includes>
		</source>
	      </sources>
	    </mapping>
	    <mapping>
	      <directory>/var/share/stratuslab/</directory>
	      <directoryIncluded>false</directoryIncluded>
	      <username>root</username>
	      <groupname>root</groupname>
	      <sources>
		<source>
		  <location>${project.build.directory}/venv/share</location>
		</source>
	      </sources>
	    </mapping>
	    <mapping>
	      <directory>/etc/stratuslab/</directory>
	      <directoryIncluded>false</directoryIncluded>
	      <configuration>noreplace</configuration>
	      <username>root</username>
	      <groupname>root</groupname>
	      <sources>
		<source>
		  <location>${project.build.directory}/venv/conf</location>
		  <includes>
		    <include>stratuslab-user.cfg.ref</include>
		  </includes>
		</source>
	      </sources>
	    </mapping>
	    <mapping>
	      <directory>/var/lib/stratuslab/java/</directory>
	      <directoryIncluded>false</directoryIncluded>
	      <username>root</username>
	      <groupname>root</groupname>
	      <sources>
		<source>
		  <location>${project.build.directory}/venv/java</location>
		  <includes>
		    <include>**/*.jar</include>
		  </includes>
		</source>
	      </sources>
	    </mapping>
	  </mappings>
	</configuration>
      </plugin>

    </plugins>

  </build>

  <licenses>
    <license>
      <name>Apache 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0</url>
      <distribution>repo</distribution>
      <comments>Copyright (c) 2013, SixSq Sarl</comments>
    </license>
  </licenses>

</project>


text:
layout: post
title: Cup Pouring Problem
subtitle: "Getting a volume of water using some cups with computer science"
category: eng

excerpt: "A classical computer science problem, exhibiting the strength of a simple graph searching technique"

---

Given two cups , with known volumes and an infinite supply of water. Is it possible to get a stated third volume by pouring, filling and emptying operations? If so , how?

It sounds simple and difficult at the same time. Simple as you can simply evaluate a possibilities, difficult as you might reevaluate a condition again with brute force (trying all conditions) techniques.

To clarify, there are six operations available (there are two ways to do the operations below)

* Empty a cup
* Fill a cup
* Pour water from a cup to another

An example - we have two cups with volumes 9 units and 4 units respectively and we are trying to obtain a volume of 2 units.

In case you are not clear , you can try some operations:

* If you fill up the first cup, you will have (9 , 0)
* Then fill up the second cup, you will have (9 , 4)
* Then empty the second cup, you now have (9 , 0)
* Pour waterr from the first cup to the second cup, it becomes (5 , 4)

Read the above paragraph until you understand what is going on.

Now, let's try solving this problem by hand.

* (0 , 0) - We start with two empty cups
* (9 , 0) - We fill up the first cup with water
* (5 , 4) - We pour water from the first cup into the second cup
* (5 , 0) - We empty the second cup
* (1 , 4) - We pour water from the first cup into the second cup
* (1 , 0) - We empty the second cup
* (0 , 1) - We pour water from the first cup into the second cup
* (9 , 1) - We fill up the first cup with water
* (6 , 4) - We pour water from the first cup into the second cup
* (6 , 0) - We empty the second cup
* (4 , 2) - We pour water from the first cup into the second cup

Eureka! (Literally, as this was what archimedes discovered when he was dealng with waters too). We managed to get 2 units of water in 10 steps. For small volumes like this, it is always easy to calculate the solution. But what if I were to give you really odd values like 101ml and 79ml to form 2ml? You probably can't and won't do it by hand. (In case you are curious, it is feasible, 162 steps)

Here are the problems with attempting this problem by hand:

* Too many possibilities - by doing one of the operations, and doing another one subsequently , some simple multiplication shows that there are a lot of possiblities
* Hard (if not unable) to identify revisited conditions - by using a computer, you can easily trace a condition with O(log N) (O(1) if you are using arrays ) using the heap data structure. By hand? good luck.
* Mindfuck - You would probably go mad before getting a solution. In the example above, we were lucky to get the correct answer on the first try. (My brother who doesn't do computer science used something like 10 minutes, my computer took less than 0.01 seconds)

Exactly why a computer can solve the problem is inverse to those above

* Too many possibilities don't exist in computer science (unless you are speaking something like a googol)
* Data structures to easily and quickly check visited conditions
* Computer don't have emotions (hence, won't get mind-fuck)

To solve this problem, if you are familiar with computer science and graphs, all needed is a simple Breadth First Search technique and terminate search if we reach a familiar condition. Why? Try thinking about it :)

If you are not, try thinking this way:

You start with two empty cups

Is the current state the (one of the volume of the cups fulfills the target volume) intended state? If positive, go to step 6. If not, move to next step

Have you visited the state before? If positive , do not try to evaluate the state and try the next state in the list

Try every of the six operations. Check if the state was visited before. If positive, don't evaluate the state. Else , make a memo that you will evaluate the state in the future

Go to step 2

Wohoo you are done!

If you are not convivned it will work, try drawing diagrams. My friends and I (for the sake of fun) have assembled a project to solve this problems in several programming languages, including a simulation in the web browswer.

The project is open source in github, started by a friend of mine. I contributed some of the implementations and writen the simulation for a web browser (in case you are curious, in jquery)

As said, the simulation is here


text:
import time
from datetime import timedelta

class Timer():
    def __init__(self, percision=3):
        self.percision = percision

    def __enter__(self):
        self.start = time.monotonic()
        self._delta = None
        return self

    def __exit__(self, *args):
        self._delta = timedelta(seconds=time.monotonic()-self.start)
        self._delta = round(self._delta.microseconds / 1000, self.percision)

    @property
    def delta(self):
        if not self._delta:
            self._delta = timedelta(seconds=time.monotonic()-self.start)
            self._delta = round(self._delta.microseconds / 1000, self.percision)

        return self._delta


text:
//To check if cordova is loaded: if(window.cordova)
//To check if DeviceReady has been fired once: if(isDeviceReady)
var isDeviceReady = false;

var SUCCESS = "Success";
var FAILURE = "Failure";
var EXCEPTION = "Exception";

var app = {
    // Application Constructor
    initialize: function ()
    {
        app.bindEvents();
        app.uiinit();
        app.applyKO();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function ()
    {
        document.addEventListener('deviceready', app.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function ()
    {
        isDeviceReady = true;

        appViewModel.username(window.localStorage.getItem("username"));
    },
    uiinit: function ()
    {
        $(function ()
        {
            //$("[data-role='footer']").html("
XYZ
Test");
            //$.mobile.changePage("#page_allsongs", { transition: "slidefade", changeHash: false });

            $("[data-role='footer']").html("
© " + new Date().getFullYear() + "
");
            $("body>[data-role='panel']").panel().enhanceWithin();
        });
    },
    applyKO: function ()
    {
        ko.applyBindings(appViewModel);
    },
    test: function ()
    {
        appViewModel.username("SSsdsdS");
    },
    openPanel: function ()
    {
        if (appViewModel.username() == null)
        {
            $("#leftpanel1").panel("open");
        }
        else
        {
            $("#leftpanel2").panel("open");
        }
    },
    ratingsRadioButtonOnClick: function (event)
    {
        app.ratingAddUpdate(event.target.dataset.songfilename, event.target.value);
    },
    ratingAddUpdate: function (songfilename, rating)
    {
        $.mobile.loading("show");
        services.SingItCompleteService("AddUpdateSongRating", JSON.stringify({ songrater: appViewModel.username(), songfilename: songfilename, rating: rating }), app.ratingAddUpdateSuccess, app.ratingAddUpdateError);
    },
    ratingAddUpdateSuccess: function (x)
    {
        $.mobile.loading("hide");
    },
    ratingAddUpdateError: function (x)
    {
        $.mobile.loading("hide");
        navigator.notification.alert("Please check your network connection and try again later!", null, "Service Failure");
    },
    gotoMySongs: function ()
    {
        $.mobile.changePage("#page_mysongs", { transition: "slidefade", changeHash: false });
    },
    gotoAllSongs: function ()
    {
        $.mobile.changePage("#page_allsongs", { transition: "slidefade", changeHash: false });

        $.mobile.loading("show");
        $("#page_allsongs_listview").empty().listview("refresh").enhanceWithin();

        services.SingItCompleteService("GetAllSongsGroupedBySongTitle", JSON.stringify({ username: appViewModel.username() }), app.gotoAllSongsSuccess, app.gotoAllSongsError);
    },
    gotoAllSongsSuccess: function (x)
    {
        $("#page_allsongs_listview").append(x.Output).listview("refresh").enhanceWithin();
        $.mobile.loading("hide");
    },
    gotoAllSongsError: function (x)
    {
        $.mobile.loading("hide");
        navigator.notification.alert("Please check your network connection and try again later!", null, "Service Failure");
    },
    gotoNewSong: function ()
    {
        $.mobile.changePage("#page_newsong", { transition: "slidefade", changeHash: false });
    },
    gotoRecommendedSong: function ()
    {
        $.mobile.changePage("#page_recommendedsong", { transition: "slidefade", changeHash: false });
        $.mobile.loading("show");
        services.SingItCompleteService("GetRecommendedSongForUser", JSON.stringify({ username: appViewModel.username() }), app.gotoRecommendedSongSuccess, app.gotoRecommendedSongError);
    },
    gotoRecommendedSongSuccess: function (x)
    {
        $.mobile.loading("hide");
        if (x.Output == FAILURE || x.Output == EXCEPTION)
        {
            navigator.notification.alert("Sorry, we couldn't find you a recommended song!", null, "Recommendation Failure");
        }
        else
        {
            $("#page_newsong_songtitle").val(x.Output);
            appViewModel.songtitle($("#page_newsong_songtitle").val());
            navigator.notification.confirm("Hurray!!! We found you the following recommendation:\n" + x.Output + "\nWould you like to record this song?", app.gotoRecommendedSongOnConfirm, "Recommendation Found!", ["Yes", "No"]);
        }
    },
    gotoRecommendedSongError: function (x)
    {
        $.mobile.loading("hide");
        navigator.notification.alert("Please check your network connection and try again later!", null, "Service Failure");
    },
    gotoRecommendedSongOnConfirm: function (x)
    {
        if (x == 1)
        {
            $.mobile.changePage("#page_newsong", { transition: "slidefade", changeHash: false });
        }
    },
    recordNewSong: function ()
    {
        appViewModel.songtitle($("#page_newsong_songtitle").val());
        appViewModel.songgenre($("#page_newsong_selectgenre").val());
        audioCaptureAndUpload.capture();
    },
    login: function ()
    {
        services.SingItCompleteService("Validate", JSON.stringify({ username: $("#page_login_username").val(), password: $("#page_login_password").val() }), app.loginSuccess, app.loginError);
    },
    loginSuccess: function (x)
    {
        if (x.Output == FAILURE || x.Output == EXCEPTION)
        {
            navigator.notification.alert("Please enter valid credentials!", null, "Login Failure");
        }
        else
        {
            appViewModel.username(JSON.parse(x.Output).username);
            window.localStorage.setItem("username", appViewModel.username());
            app.gotoAllSongs();
        }
    },
    loginError: function (x)
    {
        navigator.notification.alert("Please enter valid credentials!", null, "Login Failure");
    },
    logout: function ()
    {
        appViewModel.username(null);
        window.localStorage.setItem("username", null);
        $.mobile.changePage("#page_login", { transition: "slideup", changeHash: false });
    }
};

var appViewModel = {
    username: ko.observable(null),
    songtitle: ko.observable(null),
    songgenre: ko.observable(null)
};

var ServiceURLLocalhost = "http://localhost:81";
var ServiceURLLocalhostIP = "http://192.168.1.250:81";
var ServiceURLRemote = "http://singit.azurewebsites.net";

var services = {
    SingItCompleteService: function (methodName, InputData, successCB, errorCB)
    {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: ServiceURLLocalhostIP + "/SingItCompleteService.svc/" + methodName,
            data: InputData,
            dataType: "json",
            success: successCB,
            error: errorCB
        });
    },
    serviceTest: function ()
    {
        services.SingItCompleteService("TestValidate", JSON.stringify({ username: "anuj", password: "anuj" }), services.successTest, services.errorTest);
    },
    successTest: function (x)
    {
        alert(JSON.stringify(x));
    },
    errorTest: function (x)
    {
        alert(JSON.stringify(x));
    }
};

var audioCaptureAndUpload = {

    capture: function ()
    {
        navigator.device.capture.captureAudio(audioCaptureAndUpload.captureSuccess, audioCaptureAndUpload.captureError, { limit: 1 });
    },
    captureSuccess: function (files)
    {
        var i, path, length;
        for (i = 0, length = files.length; i < length; i++)
        {
            var options = new FileUploadOptions();
            options.fileKey = "file";
            options.fileName = files[i].name;
            options.mimeType = files[i].type;
            options.headers = { Connection: "close" };
            options.chunkedMode = false;

            var params = {};
            params.username = appViewModel.username();
            params.songtitle = appViewModel.songtitle();
            params.songgenre = appViewModel.songgenre();
            options.params = params;

            var ft = new FileTransfer();
            ft.upload(files[i].fullPath, encodeURI(ServiceURLLocalhostIP + "/FileTransferService.svc/UploadSong"), audioCaptureAndUpload.win, audioCaptureAndUpload.fail, options, true);
        }
    },
    captureError: function (error)
    {
        navigator.notification.alert("An error has occurred: Code = " + error.code, null, "Capture Error");
    },
    win: function (r)
    {
        console.log("Code = " + r.responseCode);
        console.log("Response = " + r.response);
        console.log("Sent = " + r.bytesSent);
    },
    fail: function (error)
    {
        navigator.notification.alert("An error has occurred: Code = " + error.code, null, "Upload Error");
        console.log("upload error source " + error.source);
        console.log("upload error target " + error.target);
    }
};


text:
from sodapy import Socrata
import requests
import requests_mock

import os.path
import inspect
import json

PREFIX = "mock"
DOMAIN = "fakedomain.com"
PATH = "/songs.json"
APPTOKEN = "FakeAppToken"
USERNAME = "fakeuser"
PASSWORD = "fakepassword"
TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(
        inspect.currentframe()))), "test_data")

def test_client():
    client = Socrata(DOMAIN, APPTOKEN)
    assert isinstance(client, Socrata)
    client.close()

def test_get():
    mock_adapter = {}
    mock_adapter["prefix"] = PREFIX
    adapter = requests_mock.Adapter()
    mock_adapter["adapter"] = adapter
    client = Socrata(DOMAIN, APPTOKEN, session_adapter=mock_adapter)

    response_data = "get_songs.txt"
    set_up_mock(adapter, "GET", response_data, 200)
    response = client.get(PATH)

    assert isinstance(response, list)
    assert len(response) == 10

    client.close()

def test_upsert_exception():
    mock_adapter = {}
    mock_adapter["prefix"] = PREFIX
    adapter = requests_mock.Adapter()
    mock_adapter["adapter"] = adapter
    client = Socrata(DOMAIN, APPTOKEN, session_adapter=mock_adapter)

    path = "/songs.json"
    response_data = "403_response_json.txt"
    set_up_mock(adapter, "POST", response_data, 403, reason="Forbidden")

    data = [{"theme": "Surfing", "artist": "Wavves",
             "title": "King of the Beach", "year": "2010"}]
    try:
        response = client.upsert(PATH, data)
    except Exception, e:
        assert isinstance(e, requests.exceptions.HTTPError)
    else:
        raise AssertionError("No exception raised for bad request.")
    finally:
        client.close()

def test_upsert():
    mock_adapter = {}
    mock_adapter["prefix"] = PREFIX
    adapter = requests_mock.Adapter()
    mock_adapter["adapter"] = adapter
    client = Socrata(DOMAIN, APPTOKEN, username=USERNAME, password=PASSWORD,
                     session_adapter=mock_adapter)

    response_data = "upsert_songs.txt"
    data = [{"theme": "Surfing", "artist": "Wavves",
             "title": "King of the Beach", "year": "2010"}]
    set_up_mock(adapter, "POST", response_data, 200)
    response = client.upsert(PATH, data)

    assert isinstance(response, dict)
    assert response.get("Rows Created") == 1
    client.close()

def test_replace():
    mock_adapter = {}
    mock_adapter["prefix"] = PREFIX
    adapter = requests_mock.Adapter()
    mock_adapter["adapter"] = adapter
    client = Socrata(DOMAIN, APPTOKEN, username=USERNAME, password=PASSWORD,
                     session_adapter=mock_adapter)

    response_data = "replace_songs.txt"
    data = [
        {"theme": "Surfing", "artist": "Wavves", "title": "King of the Beach",
         "year": "2010"},
        {"theme": "History", "artist": "Best Friends Forever",
         "title": "Abe Lincoln", "year": "2008"},
    ]
    set_up_mock(adapter, "PUT", response_data, 200)
    response = client.replace(PATH, data)

    assert isinstance(response, dict)
    assert response.get("Rows Created") == 2
    client.close()

def test_delete():
    mock_adapter = {}
    mock_adapter["prefix"] = PREFIX
    adapter = requests_mock.Adapter()
    mock_adapter["adapter"] = adapter
    client = Socrata(DOMAIN, APPTOKEN, username=USERNAME, password=PASSWORD,
                     session_adapter=mock_adapter)

    uri = "{0}://{1}{2}".format(PREFIX, DOMAIN, PATH)
    adapter.register_uri("DELETE", uri, status_code=200)
    response = client.delete(PATH)
    assert response.status_code == 200

    try:
        client.delete("/foobar.json")
    except Exception, e:
        assert isinstance(e, requests_mock.exceptions.NoMockAddress)
    finally:
        client.close()

def set_up_mock(adapter, method, response, response_code,
                reason="OK", auth=None):
    path = os.path.join(TEST_DATA_PATH, response)
    with open(path, "rb") as f:
        body = json.load(f)
    uri = "{0}://{1}{2}".format(PREFIX, DOMAIN, PATH)
    headers = {
        "content-type": "application/json; charset=utf-8"
    }
    adapter.register_uri(method, uri, status_code=response_code,
                         json=body, reason=reason, headers=headers)


text:
.. _network_virtual:

Virtual Networks
****************

A Virtual Network represents a model of network configuration, which allows *Danube Cloud* to define virtual network interfaces, IP addresses and domains for virtual machines.

Virtual networks are defined by the following attributes:

- IP address range
- default gateway
- VLAN ID (0 for untagged VLAN)
- NIC tag
- DNS resolvers
- reverse domain

Virtual networks are mapped onto physical network interfaces through :ref:`NIC tags <network_nictag>`. NIC tags map the virtual network and compute node's physical network interfaces. Virtual network interfaces are created on top of NIC tags.

*Danube Cloud* comes with the following preconfigured virtual networks:

- **admin** - Required for internal use of *Danube Cloud* and data center management.
- **lan** - Dummy network example for virtual machines.

.. warning:: The malfunctioning of the **admin** network can cause operational problems of certain *Danube Cloud* parts and seriously affect **the correct functioning** of your data center. Therefore, any work or configuration regarding this network should be approached with great care! This network should be exclusively used for *Danube Cloud* internal purposes and not for use with virtual or physical servers outside of *Danube Cloud*.

.. seealso:: Detailed explanation on how to work with virtual networks, can be found in the :ref:`Virtual data center -> Networks <networks>` section.


text:
<?php
if ($this->session->userdata('email') != ' ') {
    ?>

                <?php echo $this->session->userdata('user_nickname') . ' is chatting with ' . $this->session->userdata('mem_nickname') ;?>

                    <input id='pchat_message' name='pchat_message' type='text' value='' tabindex="1" />

                    <?php echo anchor('#', 'Post', array('title' => 'Send Chat Message', 'id' => 'submit_message', 'class' => 'actbut')); ?>

<?php $this->view('ad2'); ?>

<?php $this->view('adbot_1'); ?>

    <?php
} else {
    redirect('../user/jumpin', refresh);
}
?>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;

namespace SmoothGL.Graphics
{
    /// <summary>
    /// Represents a handle to a storage object which can be attached to a custom frame buffer
    /// such that depth and stencil testing is performed on it.
    /// </summary>
    public interface IDepthStencilAttachment
    {
        /// <summary>
        /// Attaches the underlying storage object to the currently bound frame buffer.
        /// This method is not required to be called by client code.
        /// </summary>
        void Attach();
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<meta name="generator" content="HTML Tidy, see www.w3.org">
<title></title>
</head>
<body bgcolor="#FFFFFF">
</body>
</html>


text:
module Parsers::Xml::Cv
  class EnrollmentParser
    include HappyMapper

    register_namespace "cv", "http://openhbx.org/api/terms/1.0"
    tag 'enrollment'
    namespace 'cv'

    element :premium_amount_total, String, tag: "premium_amount_total"
    element :total_responsible_amount, String, tag: "total_responsible_amount"
    has_one :plan, Parsers::Xml::Cv::PlanParser, tag:'plan'
    has_one :shop_market, Parsers::Xml::Cv::ShopMarketParser, tag:'shop_market'

    def to_hash
      {
          premium_total_amount:premium_amount_total,
          total_responsible_amount:total_responsible_amount,
          plan: plan.to_hash,
          shop_market:shop_market.to_hash
      }
    end
  end
end


text:
<?php
header("Content-Type: text/html; charset=utf-8");

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

include 'db_connect.php';

$placeId = $_GET['id'];
$name = urldecode($_GET['name']);
$street = urldecode($_GET['street']);
$rating = $_GET['rating'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];

if(!isset($_COOKIE['travelcounsellorid'])){
  $randomstring = generateRandomString(10);
  setcookie("travelcounsellorid",$randomstring, time()+36000, '/');
  $cookieId = $randomstring;
} else {
    $cookieId = $_COOKIE['travelcounsellorid'];
}

mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $conn);

$sql = "INSERT INTO my_route (cookie_id, places_id, name, street, rating, lat, lng)
VALUES ('$cookieId', '$placeId', '$name', '$street', '$rating', '$lat', '$lng')";
//echo $sql;
//echo $placeId . " ! ! " . $name . " ! ! " . $street . " ! ! " . $rating . " ! ! " . $lat . " ! ! " . $lng . " ! ! " . $cookieId;

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

?>


text:
#include <stdafx.h>
#include <core/renderer.h>
#include <kernels/kernels.h>

#include <maya/MFnCamera.h>

using namespace Aurora;

void Renderer::generateRays(const MDagPath& camera, const Dim& size, const Rect& region,
	const unsigned short sampleID, Ray* rays, HitPoint* hit)
{
	MFnCamera dagCamera(camera);
	MPoint camEyePoint   = dagCamera.eyePoint(MSpace::kWorld);
	MVector camDirection = dagCamera.viewDirection(MSpace::kWorld);
	double camAspect     = dagCamera.aspectRatio();

	double camFovX, camFovY;
	dagCamera.getPortFieldOfView(size.width, size.height, camFovX, camFovY);

	Camera rayCamera(
		make_float3((float)camEyePoint.x, (float)camEyePoint.y, (float)camEyePoint.z),
		make_float3((float)camDirection.x, (float)camDirection.y, (float)camDirection.z),
		make_float2((float)camFovX, (float)camFovY), (float)camAspect);

	cudaGenerateRays(region, sampleID, size.depth, rayCamera, rays, hit);
}

void Renderer::clearPixels(const Dim& size, void* pixels)
{
	gpu::cudaMemset(pixels, 0, size.width * size.height * sizeof(float4));
}

void Renderer::drawPixels(const Dim& size, const Rect& region, const HitPoint* hit, const float weight, void* pixels)
{
	cudaDrawPixels(size, region, weight, hit, pixels);
}

void Renderer::filterPixels(const Dim& size, const Rect& region, void** pixels)
{
	cudaFilterPixels(size, region, pixels);
}

bool Renderer::setupRNG(RNG** rng, const size_t count, const unsigned int seed)
{
	if(gpu::cudaMalloc(rng, count * sizeof(RNG)) != gpu::cudaSuccess)
		return false;

	cudaSetupRNG(*rng, count, seed);
	return true;
}


text:
package org.apache.olingo.odata2.api.uri.info;

import java.util.List;
import java.util.Map;

import org.apache.olingo.odata2.api.edm.EdmEntityContainer;
import org.apache.olingo.odata2.api.edm.EdmEntitySet;
import org.apache.olingo.odata2.api.edm.EdmFunctionImport;
import org.apache.olingo.odata2.api.edm.EdmLiteral;
import org.apache.olingo.odata2.api.edm.EdmProperty;
import org.apache.olingo.odata2.api.edm.EdmType;
import org.apache.olingo.odata2.api.uri.KeyPredicate;
import org.apache.olingo.odata2.api.uri.NavigationSegment;

/**
 * Access to the parts of the request URI that are relevant for DELETE requests.
 * @org.apache.olingo.odata2.DoNotImplement
 *
 */
public interface DeleteUriInfo {
  /**
   * Gets the target entity container.
   * @return {@link EdmEntityContainer} the target entity container
   */
  public EdmEntityContainer getEntityContainer();

  /**
   * Gets the start entity set - identical to the target entity set if no navigation
   * has been used.
   * @return {@link EdmEntitySet}
   */
  public EdmEntitySet getStartEntitySet();

  /**
   * Gets the target entity set after navigation.
   * @return {@link EdmEntitySet} target entity set
   */
  public EdmEntitySet getTargetEntitySet();

  /**
   * Gets the function import.
   * @return {@link EdmFunctionImport} the function import
   */
  public EdmFunctionImport getFunctionImport();

  /**
   * Gets the target type of the request: an entity type, a simple type, or a complex type.
   * @return {@link EdmType} the target type
   */
  public EdmType getTargetType();

  /**
   * Gets the key predicates used to select a single entity out of the start entity set,
   * or an empty list if not used.
   * @return List of {@link KeyPredicate}
   * @see #getStartEntitySet()
   */
  public List<KeyPredicate> getKeyPredicates();

  /**
   * Gets the key predicates used to select a single entity out of the target entity set,
   * or an empty list if not used - identical to the key predicates from the last entry
   * retrieved from {@link #getNavigationSegments()} or, if no navigation has been used,
   * to the result of {@link #getKeyPredicates()}.
   * @return List of {@link KeyPredicate}
   * @see #getTargetEntitySet()
   */
  public List<KeyPredicate> getTargetKeyPredicates();

  /**
   * Gets the navigation segments, or an empty list if no navigation has been used.
   * @return List of {@link NavigationSegment}
   */
  public List<NavigationSegment> getNavigationSegments();

  /**
   * Gets the path used to select a (simple or complex) property of an entity,
   * or an empty list if no property is accessed.
   * @return List of {@link EdmProperty}
   */
  public List<EdmProperty> getPropertyPath();

  /**
   * Gets the parameters of a function import as Map from parameter names to
   * their corresponding typed values, or an empty list if no function import
   * is used or no parameters are given in the URI.
   * @return Map of {@literal <String,} {@link EdmLiteral}{@literal >} function import parameters
   */
  public Map<String, EdmLiteral> getFunctionImportParameters();

  /**
   * Gets the custom query options as Map from option names to their
   * corresponding String values, or an empty list if no custom query options
   * are given in the URI.
   * @return Map of {@literal <String, String>} custom query options
   */
  public Map<String, String> getCustomQueryOptions();
}


text:
(function() {
	function Sprite(url, pos, size, speed, frames, dir, once) {
		this.url = url; // The path to the image for this sprite
		this.pos = pos; // The x,y coordinate in the image for this sprite
		this.size = size; // Size of the sprite (the keyframe)
		this.speed = typeof speed === 'number' ? speed : 0; // Speed in frames per second for animating
		this.frames = frames; // An array of frame indexes for animating
		this.dir = dir || 'horizontal'; // Which direction to move in the sprite map when animating
		this.once = once; // True to run the animation once, defaults to false
		this._index = 0;
		this.width = this.size[0];
		this.height = this.size[1];
	};

	Sprite.prototype = {
		update: function(dt) {
			this._index += this.speed*dt;
		},

		render: function(ctx) {
			var frame;

			if(this.speed > 0) {
				var max = this.frames.length;
				var idx = Math.floor(this._index);
				frame = this.frames[idx % max];

				if(this.once && idx >= max) {
					this.done = true;
					return;
				}
			}
			else {
				frame = 0;
			}

			var x = this.pos[0];
			var y = this.pos[1];

			if(this.dir == 'vertical') {
				y += frame * this.size[1];
			}
			else {
				x += frame * this.size[0];
			}

			ctx.drawImage(resources.get(this.url),
						x, y,
						this.size[0], this.size[1],
						0, 0,
						this.size[0], this.size[1]);
		}
	};

	window.Sprite = Sprite;
})();


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using YALV.Core.Domain;

namespace YALV.Core.Providers
{
    class XmlEntriesProvider : AbstractEntriesProvider
    {
        public override IEnumerable<LogItem> GetEntries(string dataSource, FilterParams filter)
        {
            var settings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };
            var nt = new NameTable();
            var mgr = new XmlNamespaceManager(nt);
            mgr.AddNamespace("log4j", Constants.LAYOUT_LOG4J);
            var pc = new XmlParserContext(nt, mgr, string.Empty, XmlSpace.Default);
            var date = new DateTime(1970, 1, 1, 0, 0, 0, 0);

            using (var stream = new FileStream(dataSource, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite))
            {
                using (var reader = new StreamReader(stream, System.Text.Encoding.Default, true))
                {
                    using (var xmlTextReader = XmlReader.Create(reader, settings, pc))
                    {
                        var entryId = 1;
                        DateTime? prevTimeStamp = null;
                        while (xmlTextReader.Read())
                        {
                            if ((xmlTextReader.NodeType != XmlNodeType.Element) || (xmlTextReader.Name != "log4j:event"))
                                continue;

                            var entry = new LogItem { Id = entryId, Path = dataSource };

                            entry.Logger = xmlTextReader.GetAttribute("logger");

                            entry.TimeStamp = date.AddMilliseconds(Convert.ToDouble(xmlTextReader.GetAttribute("timestamp"))).ToLocalTime();
                            if (prevTimeStamp.HasValue)
                                entry.Delta = (entry.TimeStamp - prevTimeStamp.Value).TotalSeconds;
                            prevTimeStamp = entry.TimeStamp;

                            entry.Level = xmlTextReader.GetAttribute("level");
                            entry.Thread = xmlTextReader.GetAttribute("thread");

                            while (xmlTextReader.Read())
                            {
                                var breakLoop = false;
                                switch (xmlTextReader.Name)
                                {
                                    case "log4j:event":
                                        breakLoop = true;
                                        break;
                                    default:
                                        switch (xmlTextReader.Name)
                                        {
                                            case ("log4j:message"):
                                                entry.Message = xmlTextReader.ReadString();
                                                break;
                                            case ("log4j:data"):
                                                switch (xmlTextReader.GetAttribute("name"))
                                                {
                                                    case ("log4net:UserName"):
                                                        entry.UserName = xmlTextReader.GetAttribute("value");
                                                        break;
                                                    case ("log4japp"):
                                                        entry.App = xmlTextReader.GetAttribute("value");
                                                        break;
                                                    case ("log4jmachinename"):
                                                        entry.MachineName = xmlTextReader.GetAttribute("value");
                                                        break;
                                                    case ("log4net:HostName"):
                                                        entry.HostName = xmlTextReader.GetAttribute("value");
                                                        break;
                                                }
                                                break;
                                            case ("log4j:throwable"):
                                                entry.Throwable = xmlTextReader.ReadString();
                                                break;
                                            case ("log4j:locationInfo"):
                                                entry.Class = xmlTextReader.GetAttribute("class");
                                                entry.Method = xmlTextReader.GetAttribute("method");
                                                entry.File = xmlTextReader.GetAttribute("file");
                                                entry.Line = xmlTextReader.GetAttribute("line");
                                                break;
                                        }
                                        break;
                                }
                                if (breakLoop) break;
                            }

                            if (filterByParameters(entry, filter))
                            {
                                yield return entry;
                                entryId++;
                            }
                        }
                    }
                }
            }
        }

        private static bool filterByParameters(LogItem entry, FilterParams parameters)
        {
            if (entry == null)
                throw new ArgumentNullException("entry");
            if (parameters == null)
                throw new ArgumentNullException("parameters");

            bool accept = false;
            switch (parameters.Level)
            {
                case 1:
                    if (String.Equals(entry.Level, "ERROR",
                        StringComparison.InvariantCultureIgnoreCase))
                        accept = true;
                    break;

                case 2:
                    if (String.Equals(entry.Level, "INFO",
                        StringComparison.InvariantCultureIgnoreCase))
                        accept = true;
                    break;

                case 3:
                    if (String.Equals(entry.Level, "DEBUG",
                        StringComparison.InvariantCultureIgnoreCase))
                        accept = true;
                    break;

                case 4:
                    if (String.Equals(entry.Level, "WARN",
                        StringComparison.InvariantCultureIgnoreCase))
                        accept = true;
                    break;

                case 5:
                    if (String.Equals(entry.Level, "FATAL",
                        StringComparison.InvariantCultureIgnoreCase))
                        accept = true;
                    break;

                default:
                    accept = true;
                    break;
            }

            if (parameters.Date.HasValue)
                if (entry.TimeStamp < parameters.Date)
                    accept = false;

            if (!String.IsNullOrEmpty(parameters.Thread))
                if (!String.Equals(entry.Thread, parameters.Thread, StringComparison.InvariantCultureIgnoreCase))
                    accept = false;

            if (!String.IsNullOrEmpty(parameters.Message))
                if (!entry.Message.ToUpper().Contains(parameters.Message.ToUpper()))
                    accept = false;

            if (!String.IsNullOrEmpty(parameters.Logger))
                if (!entry.Logger.ToUpper().Contains(parameters.Logger.ToUpper()))
                    accept = false;

            return accept;
        }
    }
}


text:
"""Generic MIME writer.

Classes:

MimeWriter - the only thing here.

"""

import mimetools

__all__ = ["MimeWriter"]

class MimeWriter:

    """Generic MIME writer.

    Methods:

    __init__()
    addheader()
    flushheaders()
    startbody()
    startmultipartbody()
    nextpart()
    lastpart()

    A MIME writer is much more primitive than a MIME parser.  It
    doesn't seek around on the output file, and it doesn't use large
    amounts of buffer space, so you have to write the parts in the
    order they should occur on the output file.  It does buffer the
    headers you add, allowing you to rearrange their order.

    General usage is:

    f = <open the output file>
    w = MimeWriter(f)
    ...call w.addheader(key, value) 0 or more times...

    followed by either:

    f = w.startbody(content_type)
    ...call f.write(data) for body data...

    or:

    w.startmultipartbody(subtype)
    for each part:
        subwriter = w.nextpart()
        ...use the subwriter's methods to create the subpart...
    w.lastpart()

    The subwriter is another MimeWriter instance, and should be
    treated in the same way as the toplevel MimeWriter.  This way,
    writing recursive body parts is easy.

    Warning: don't forget to call lastpart()!

    XXX There should be more state so calls made in the wrong order
    are detected.

    Some special cases:

    - startbody() just returns the file passed to the constructor;
      but don't use this knowledge, as it may be changed.

    - startmultipartbody() actually returns a file as well;
      this can be used to write the initial 'if you can read this your
      mailer is not MIME-aware' message.

    - If you call flushheaders(), the headers accumulated so far are
      written out (and forgotten); this is useful if you don't need a
      body part at all, e.g. for a subpart of type message/rfc822
      that's (mis)used to store some header-like information.

    - Passing a keyword argument 'prefix=<flag>' to addheader(),
      start*body() affects where the header is inserted; 0 means
      append at the end, 1 means insert at the start; default is
      append for addheader(), but insert for start*body(), which use
      it to determine where the Content-Type header goes.

    """

    def __init__(self, fp):
        self._fp = fp
        self._headers = []

    def addheader(self, key, value, prefix=0):
        lines = value.split("\n")
        while lines and not lines[-1]: del lines[-1]
        while lines and not lines[0]: del lines[0]
        for i in range(1, len(lines)):
            lines[i] = "    " + lines[i].strip()
        value = "\n".join(lines) + "\n"
        line = key + ": " + value
        if prefix:
            self._headers.insert(0, line)
        else:
            self._headers.append(line)

    def flushheaders(self):
        self._fp.writelines(self._headers)
        self._headers = []

    def startbody(self, ctype, plist=[], prefix=1):
        for name, value in plist:
            ctype = ctype + ';\n %s=\"%s\"' % (name, value)
        self.addheader("Content-Type", ctype, prefix=prefix)
        self.flushheaders()
        self._fp.write("\n")
        return self._fp

    def startmultipartbody(self, subtype, boundary=None, plist=[], prefix=1):
        self._boundary = boundary or mimetools.choose_boundary()
        return self.startbody("multipart/" + subtype,
                              [("boundary", self._boundary)] + plist,
                              prefix=prefix)

    def nextpart(self):
        self._fp.write("\n--" + self._boundary + "\n")
        return self.__class__(self._fp)

    def lastpart(self):
        self._fp.write("\n--" + self._boundary + "--\n")

if __name__ == '__main__':
    import test.test_MimeWriter


text:
namespace crave {

void Generator::enable_multithreading() {
  delete var_gen_;
  var_gen_ = new VariableGeneratorMT(*var_ctn_);
  reset();
  rebuild(true);
}

bool Generator::enableConstraint(std::string const& name) { return constr_mng_.enableConstraint(name); }

bool Generator::disableConstraint(std::string const& name) { return constr_mng_.disableConstraint(name); }

bool Generator::isConstraintEnabled(std::string const& name) { return constr_mng_.isConstraintEnabled(name); }

bool Generator::isChanged() { return constr_mng_.isChanged(); }

Generator& Generator::operator()() {
  if (!next()) {
    throw std::runtime_error("Generator constraint unsatisfiable.");
  }
  return *this;
}

void Generator::merge(const Generator& other) { constr_pttn_.mergeConstraints(other.constr_mng_); }

void Generator::reset() {
  constr_mng_.resetChanged();
  constr_pttn_.reset();
  resetCoverage();
}

void Generator::rebuild(bool selfInclude) {
  if (selfInclude) merge(*this);
  constr_pttn_.partition();
  // currently, every hard/soft/cover constraint is considered for
  // partitioning, this is suboptimal.
  var_gen_->reset(constr_pttn_.getPartitions());
  vec_gen_.reset(constr_pttn_.getVectorConstraints());
  var_cov_gen_.reset(constr_pttn_.getPartitions());
}

bool Generator::next() {
  if (constr_mng_.isChanged()) {
    reset();
    rebuild(true);
  }
  return var_gen_->solve() && vec_gen_.solve(*var_gen_);
}

bool Generator::nextCov() {
  if (constr_mng_.isChanged()) {
    reset();
    rebuild(true);
  }
  if (!covered_) {
    if (var_cov_gen_.solve() && vec_gen_.solve(var_cov_gen_))
      return true;
    else
      covered_ = true;
  }
  return next();
}

bool Generator::isCovered() { return covered_; }

void Generator::resetCoverage() {
  covered_ = false;
  var_cov_gen_.reset(constr_pttn_.getPartitions());
}

std::ostream& Generator::printDotGraph(std::ostream& os, bool root) {
  if (root) os << "digraph AST {" << std::endl;
  constr_mng_.printDotGraph(os);
  if (root) os << "}" << std::endl;
  return os;
}

std::vector<std::vector<std::string> > Generator::analyseContradiction() { return var_gen_->analyseContradiction(); }

std::vector<std::string> Generator::getInactiveSofts() { return var_gen_->getInactiveSofts(); }
}


text:
from enum import Enum

class Activity(Enum):
    '''
    As defined here:
    https://developers.google.com/fit/rest/v1/reference/activity-types
    Only storing the ones I actually handle for now
    '''
    in_vehicle = 0
    biking = 1
    on_foot = 2
    still_not_moving = 3
    unknown_unable_to_detect_activity = 4
    tilting_sudden_device_gravity_change = 5
    walking = 7
    running = 8
    aerobics = 9
    zumba = 10
    badminton = 10
    baseball = 11
    basketball = 12
    biathlon = 13
    handbiking = 14
    mountain_biking = 15
    road_biking = 16
    spinning = 17
    stationary_biking = 18
    utility_biking = 19
    boxing = 20
    calisthenics = 21
    circuit_training = 22
    cricket = 23
    dancing = 24
    elliptical = 25
    fencing = 26
    football_american = 27
    football_australian = 28
    football_soccer = 29
    frisbee = 30
    gardening = 31
    golf = 32
    gymnastics = 33
    handball = 34
    hiking = 35
    hockey = 36
    horseback_riding = 37
    housework = 38
    jumping_rope = 39
    kayaking = 40
    kettlebell_training = 41
    kickboxing = 42
    kitesurfing = 43
    martial_arts = 44
    meditation = 45
    mixed_martial_arts = 46
    p90x_exercises = 47
    paragliding = 48
    pilates = 49
    polo = 50
    racquetball = 51
    rock_climbing = 52
    rowing = 53
    rowing_machine = 54
    rugby = 55
    jogging = 56
    running_on_sand = 57
    running_treadmill = 58
    sailing = 59
    scuba_diving = 60
    skateboarding = 61
    skating = 62
    cross_skating = 63
    inline_skating_rollerblading = 64
    skiing = 65
    back_country_skiing = 66
    cross_country_skiing = 67
    downhill_skiing = 68
    kite_skiing = 69
    roller_skiing = 70
    sledding = 71
    sleeping = 72
    snowboarding = 73
    snowmobile = 74
    snowshoeing = 75
    squash = 76
    stair_climbing = 77
    stair_climbing_machine = 78
    stand_up_paddleboarding = 79
    strength_training = 80
    surfing = 81
    swimming = 82
    swimming_swimming_pool = 83
    swimming_open_water = 84
    table_tennis_ping_pong = 85
    team_sports = 86
    tennis = 87
    treadmill_walking_or_running = 88
    volleyball = 89
    volleyball_beach = 90
    volleyball_indoor = 91
    wakeboarding = 92
    walking_fitness = 93
    nording_walking = 94
    walking_treadmill = 95
    waterpolo = 96
    weightlifting = 97
    wheelchair = 98
    windsurfing = 99
    yoga = 100
    diving = 102
    ergometer = 103
    ice_skating = 104
    indoor_skating = 105
    curling = 106
    other_unclassified_fitness_activity = 108
    light_sleep = 109
    deep_sleep = 110
    rem_sleep = 111
    awake_during_sleep_cycle = 112

    def valid(self):
        '''
        Returns true if the current value is in the following list of supported vals
        '''
        return self in (
            Activity.biking,
            Activity.walking,
            Activity.running,
        )

    @property
    def mfp_id(self):
        if self == Activity.biking:
            return 19
        elif self == Activity.walking:
            # Walking, 12.5 mins per km, mod. pace
            return 26688321
        elif self == Activity.running:
            # Running (jogging), 10.7 kph (5.6 min per km)
            return 127
        else:
            raise NotImplementedError('We do not know the myfitnesspal ID for {0}'.format(self))


text:
<?php

namespace Reeser\Controller;

use Reeser\Form\MonotributistaForm;

use Zend\View\Model\ViewModel;

use Zend\Mvc\Controller\AbstractActionController;

/**
 * Controlador de Efectores (Monotributistas)
 *
 * @author totote
 * @package \Reeser\Controller
 */
class EfectorController extends AbstractActionController
{

	/**
	 * Muestra el formulario de alta de monotributísta
	 *
	 * @return \Zend\View\Model\ViewModel
	 */
	public function altaAction()
	{
		$this->getServiceLocator()->get( 'Reeser\Util\System' );

        $form = new MonotributistaForm();
        // $form->get('submit')->setAttribute('value', 'Add');

        $error = false;
        $cuiterror = "";// ##CUIT##

        $request = $this->getRequest();

        if ($request->isPost()) {
        	$params = $request->getPost();

            $form->setData($params);

            $cuitvalidator = new \Reeser\Util\Validator\CuitValidator; // ##CUIT##
            $cuit = $params['efector']['cuit']['a'] . $params['efector']['cuit']['b']. $params['efector']['cuit']['c']; // ##CUIT##

            if ($form->isValid() && $cuitvalidator->isValid($cuit)) // ##CUIT##
            {
				// $params = $form->getData();

				$this->getServiceLocator()->get( 'Reeser\Util\System' );
				$em = \Reeser\Util\System::getInstance()->getEntityManager();

				try
				{
					$em->getConnection()->beginTransaction();

					// Filtramos los datos de la persona
					$personaData = $this->getPersonaData( $params );
					// Guardamos los datos de la persona
					$persona = new \Reeser\Model\Persona( $personaData );
					$persona->save();
					$personaData = $persona->getArray();

					// Filtramos los datos del efector
					$efectorData = $this->getEfectorData( $params );
					// Guardamos los datos del efector
					$efector = new \Reeser\Model\Efector( $efectorData );
					$efector->save();
					$efectorData = $efector->getArray();

					// Activamos el Efector
					$estadoEfector = new \Reeser\Model\HistorialEstadoEfector( $efectorData['idefector'] );
					$estadoEfector->setNuevo( \Reeser\Model\EstadoEfector::PENDIENTE_DE_CONFIRMACION, 'Efector Registrado' );

					// Generamos los datos del monotributista
					$monotributistaData = $this->getMonotributistaData();
					$monotributistaData['idpersona'] = $personaData['idpersona'];
					$monotributistaData['idefector'] = $efectorData['idefector'];
					// Guardamos los datos del monotributista
					$monotributista = new \Reeser\Model\Monotributista( $monotributistaData );
					$monotributista->save();
					$monotributistaData = $monotributista->getArray();

					// Filtramos los datos de domicilio de la persona
					$domicilioData = $this->getDomicilioPersonaData( $params );
					// Guardamos los datos de domicilio de la persona
					$domicilioData['idpersona'] = $personaData['idpersona'];
					$domicilio = new \Reeser\Model\DomicilioPersona( $domicilioData );
					$domicilio->save();
					$domicilioData = $domicilio->getArray();

					// Filtramos los datos de contacto de la persona
					$contactosData = $this->getContactosPersonaData( $params );
					// Guardamos los datos de contacto de la persona
					foreach ( $contactosData as $contactoData )
					{
						$contactoData['idpersona'] = $personaData['idpersona'];
						$contacto = new \Reeser\Model\ContactoPersona($contactoData);
						$contacto->save();
					}

					$em->flush();
					$em->getConnection()->commit();

				}
				catch ( \Exception $e )
				{
					$em->getConnection()->rollBack();
					throw $e;
				}

				// Si todo sale bien, con esto finaliza el registro de una cooperativa,
                // ahora mostramos el mensaje de registro exitoso y el nº de registro
                // otrogado al emprendimiento
                $return_data = array(
                    'nom_emp' => $personaData['apellido'] . ', ' . $personaData['nombre'],
                    'num_reg' => \Reeser\Model\TipoEfector::MONOTRIBUTISTA . '-' . $efectorData['numerotramite'],
                );

                $viewModel = new ViewModel($return_data);
                return $viewModel->setTemplate('reeser/efector/registrado.phtml');
            }
            else
            {
            	$error = true;
            	$cuitvalidator->isValid($cuit); // ##CUIT##
            	$cuiterror = $cuitvalidator->getMessages(); // ##CUIT##
            }
        }

        return array(
        	'form' => $form,
        	'error' => $error,
        	'cuiterror'=>$cuiterror // ##CUIT##
        	);
	}

	/**
	 * Obtiene los datos de una persona que vienen de un formulario
	 *
	 * @param array $params
	 * @return array
	 */
	public function getPersonaData($params)
	{
		$fecha = $params['efector']['fenac']['dia'] . '-' . $params['efector']['fenac']['mes'] . '-' . $params['efector']['fenac']['anio'];
		$cuit = $params['efector']['cuit']['a'] . $params['efector']['cuit']['b']. $params['efector']['cuit']['c'];

		$personaData = array(
			'idpersona' => null,
			'cuit' => $cuit,
			'apellido' => $params['efector']['apellido'],
			'nombre' => $params['efector']['nombre'],
			'fechanacimiento' => $fecha,
			'sexo' => $params['efector']['gender'],
			'activo' => true
		);

		return $personaData;
	}

	/**
	 * Obtiene los datos de contacto de una persona recibidos por un formulario
	 *
	 * @param array $params
	 * @return array
	 */
	public function getContactosPersonaData($params)
	{
		$tipoContactoModel = new \Reeser\Model\TipoContacto();
		$contactos = array();

		if ( isset( $params['domicilio']['tel_area'], $params['domicilio']['tel_num'] ) == true && $params['domicilio']['tel_area'] != '' && $params['domicilio']['tel_num'] != '' )
		{
			$tipoContactoModel->findByCodigo( $tipoContactoModel::TELEFONO );
			$tipoContacto = $tipoContactoModel->getArray();

			$contacto = array();
			$contacto['idcontactopersona'] = ( isset( $params['tel_id'] ) == true && $params['tel_id'] ) ? $params['tel_id'] : null;
			$contacto['descripcion'] = '(' . $params['domicilio']['tel_area'] . ') 4' . $params['domicilio']['tel_num'];
			$contacto['observacion'] = null;
			$contacto['activo'] = true;
			$contacto['idtipocontacto'] = $tipoContacto['idtipocontacto'];
			$contacto['idpersona'] = null;

			$contactos[] = $contacto;
		}

		if ( isset( $params['domicilio']['cel_area'], $params['domicilio']['cel_num'] ) == true && $params['domicilio']['cel_area'] != '' && $params['domicilio']['cel_num'] != '' )
		{
			$tipoContactoModel->findByCodigo( $tipoContactoModel::CELULAR );
			$tipoContacto = $tipoContactoModel->getArray();

			$contacto = array();
			$contacto['idcontactopersona'] = ( isset( $params['domicilio']['cel_id'] ) == true && $params['domicilio']['cel_id'] ) ? $params['domicilio']['cel_id'] : null;
			$contacto['descripcion'] = '(' . $params['domicilio']['cel_area'] . ') 15' . $params['domicilio']['cel_num'];
			$contacto['observacion'] = null;
			$contacto['activo'] = true;
			$contacto['idtipocontacto'] = $tipoContacto['idtipocontacto'];
			$contacto['idpersona'] = null;

			$contactos[] = $contacto;
		}

		if ( isset( $params['domicilio']['email'] ) && $params['domicilio']['email'] != '' )
		{
			$tipoContactoModel->findByCodigo( $tipoContactoModel::MAIL );
			$tipoContacto = $tipoContactoModel->getArray();

			$contacto = array();
			$contacto['idcontactopersona'] = ( isset( $params['domicilio']['mail_id'] ) == true && $params['domicilio']['mail_id'] ) ? $params['domicilio']['mail_id'] : null;
			$contacto['descripcion'] = $params['domicilio']['email'];
			$contacto['observacion'] = null;
			$contacto['activo'] = true;
			$contacto['idtipocontacto'] = $tipoContacto['idtipocontacto'];
			$contacto['idpersona'] = null;

			$contactos[] = $contacto;
		}

		return $contactos;
	}

	/**
	 * Obtiene los datos de domicilio para una persona por un formulario
	 *
	 * @param array $params
	 * @return array
	 */
	public function getDomicilioPersonaData($params)
	{

		$domicilioData = array(
			'iddomicilio' => ( $params['domicilio_id'] ) ? $params['domicilio_id'] : null,
			'calle' => $params['domicilio']['calle'],
			'numero' => $params['domicilio']['n_calle'],
			'piso' => $params['domicilio']['piso'],
			'dpto' => $params['domicilio']['dpto'],
			'manzana' => $params['domicilio']['manzana'],
			'casa' => $params['domicilio']['casa'],
			'torre' => $params['domicilio']['torre'],
			'escalera' => $params['domicilio']['escalera'],
			'barrio' => $params['domicilio']['barrio'],
			'observacion' => null,
			'activo' => true,
			'idlocalidad' => $params['domicilio']['localidad'],
			'idpersona' => null,
		);

		return $domicilioData;
	}

	/**
	 * Obtiene los datos del efector por un formulario
	 *
	 * @param array $params
	 * @return array
	 */
	public function getEfectorData($params)
	{
		$tipoEfectorModel = new \Reeser\Model\TipoEfector();
		$tipoEfectorModel->findByCodigo( \Reeser\Model\TipoEfector::MONOTRIBUTISTA );
		$tipoEfector = $tipoEfectorModel->getArray();

		$efectorData = array(
			'idefector' => ( $params['efector_id'] ) ? $params['efector_id'] : null,
			'numerotramite' => $params['efector']['n_form'],
			'numeroefector' => null,

			// TODO: que el monto disponible esté en la base de datos o algún archivo de configuración
			'montodisponible' => 48000,
			'activo' => true,
			'idtipoefector' => $tipoEfector['idtipoefector'],
			'idactividad' => $params['actividad']['actividad'],
			'idsubrubro' => $params['actividad']['subrubro'],
			'observacion' => $params['actividad']['desc_act'],
		);

		return $efectorData;
	}

	/**
	 * Genera el array con los datos del monotributista
	 *
	 * @return array
	 */
	public function getMonotributistaData()
	{
		$monotributistaData = array(
			'idmonotributista' => null,
			'idpersona' => null,
			'idefector' => null,
			'activo' => true,
		);

		return $monotributistaData;
	}
}


text:
import sys
import numpy as np
import scipy.io
import argparse
import os
import re
import os.path
from operator import itemgetter

'''
    Sets up command line info
'''
def parse_args(argv):
    parser = argparse.ArgumentParser(prog="doCollection",
                                     description=('Collection over all graphs'))
    parser.add_argument('directory',help='directory for the mat files')
    parser.add_argument('output',help='output for the new mat file')

    args= parser.parse_args(argv[1:])
    return args.directory, args.output

'''
    This will go through a directory and get the Phase lag and Pop Correl
    of each file. I am assuming the directory you are looking through
    will only contain postproccesed data and the values will be in the file
'''
def collect_plpc(dir_path):
    data = []
    for f in os.listdir(dir_path):
        ##Only care about mat files
        if f.endswith('.mat'):
            file_loc = os.path.join(dir_path,f)
            values = scipy.io.loadmat(file_loc)
            mean_phi = values['mean_phi']
            std_phi = values['variance_angle']
	    chi_1 = values['chi1']
	    chi_2 = values['chi2']

            ##This gets the degree so we can arrange data since f is not in order
            string_pieces = re.split(r'[_]+|intra+|inter+|rep',f)
            intra = string_pieces[3]
            inter = string_pieces[5]
            rep=string_pieces[9]
            ##Sends data as tuple for easier graphing
            data.append((intra,inter,mean_phi,std_phi,chi_1,chi_2,rep))

    ##Now we sort the data according to the degree to make it ordered
    ordered_data =  sorted(data,key=itemgetter(0))

    ##Change list to np.array so that it can be saved as .mat
    data = np.asarray(ordered_data,dtype=object)
    return data

def main(argv=None):
    if argv is None:
        argv = sys.argv
    (directory, out_fn) = parse_args(argv)

    phase_lag_pop_corr = collect_plpc(directory)

    scipy.io.savemat(out_fn,
                     mdict = {'phi_avrg_std':phase_lag_pop_corr}, oned_as = 'column')
if __name__ == '__main__':
    status = main()
    sys.exit(status)


text:
<?php

declare(strict_types=1);

use Auth0\SDK\API\Authentication;
use Auth0\SDK\API\Management;
use Auth0\SDK\Auth0;
use Auth0\SDK\Configuration\SdkConfiguration;
use Auth0\SDK\Utility\HttpRequest;
use Auth0\Tests\Utilities\HttpResponseGenerator;
use Auth0\Tests\Utilities\MockDomain;
use Auth0\Tests\Utilities\TokenGenerator;
use Symfony\Component\Cache\Adapter\ArrayAdapter;

uses()->group('management');

beforeEach(function(): void {
    $this->configuration = new SdkConfiguration([
        'domain' => MockDomain::valid(),
        'cookieSecret' => uniqid(),
        'clientId' => '__test_client_id__',
        'redirectUri' => 'https://some-app.auth0.com',
        'audience' => ['aud1', 'aud2', 'aud3'],
        'scope' => ['scope1', 'scope2', 'scope3'],
        'organization' => ['org1', 'org2', 'org3'],
        'managementToken' => uniqid()
    ]);

    $this->sdk = new Auth0($this->configuration);
});

test('__construct() fails without a configuration', function(): void {
    new Management(null);
})->throws(\Auth0\SDK\Exception\ConfigurationException::class, \Auth0\SDK\Exception\ConfigurationException::MSG_CONFIGURATION_REQUIRED);

test('getHttpClient() fails without a managementToken, if client id and secret are not configured', function(): void {
    $this->configuration->setManagementToken(null);
    $this->sdk->management()->blacklists();
})->throws(\Auth0\SDK\Exception\ConfigurationException::class, \Auth0\SDK\Exception\ConfigurationException::MSG_REQUIRES_MANAGEMENT_KEY);

test('getHttpClient() fails if tenant is not configured with required scope(s)', function(): void {
    $this->configuration->setClientSecret(uniqid());
    $this->configuration->setManagementToken(null);

    $authentication = new Authentication($this->configuration);
    $authentication->getHttpClient()->mockResponse(
        HttpResponseGenerator::create('{"error":"access_denied","error_description":"Client is not authorized to access"}', 403),
    );

    $this->sdk->management()->getHttpClient($authentication);
})->throws(\Auth0\SDK\Exception\NetworkException::class, sprintf(\Auth0\SDK\Exception\NetworkException::MSG_NETWORK_REQUEST_REJECTED, ''));

test('blacklists() returns an instance of Auth0\SDK\API\Management\Blacklists', function(): void {
    $class = $this->sdk->management()->blacklists();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Blacklists::class);
});

test('clients() returns an instance of Auth0\SDK\API\Management\Clients', function(): void {
    $class = $this->sdk->management()->clients();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Clients::class);
});

test('clientGrants() returns an instance of Auth0\SDK\API\Management\ClientGrants', function(): void {
    $class = $this->sdk->management()->clientGrants();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\ClientGrants::class);
});

test('connections() returns an instance of Auth0\SDK\API\Management\Connections', function(): void {
    $class = $this->sdk->management()->connections();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Connections::class);
});

test('deviceCredentials() returns an instance of Auth0\SDK\API\Management\DeviceCredentials', function(): void {
    $class = $this->sdk->management()->deviceCredentials();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\DeviceCredentials::class);
});

test('emails() returns an instance of Auth0\SDK\API\Management\Emails', function(): void {
    $class = $this->sdk->management()->emails();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Emails::class);
});

test('emailTemplates() returns an instance of Auth0\SDK\API\Management\EmailTemplates', function(): void {
    $class = $this->sdk->management()->emailTemplates();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\EmailTemplates::class);
});

test('grants() returns an instance of Auth0\SDK\API\Management\Grants', function(): void {
    $class = $this->sdk->management()->grants();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Grants::class);
});

test('guardian() returns an instance of Auth0\SDK\API\Management\Guardian', function(): void {
    $class = $this->sdk->management()->guardian();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Guardian::class);
});

test('jobs() returns an instance of Auth0\SDK\API\Management\Jobs', function(): void {
    $class = $this->sdk->management()->jobs();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Jobs::class);
});

test('logs() returns an instance of Auth0\SDK\API\Management\Logs', function(): void {
    $class = $this->sdk->management()->logs();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Logs::class);
});

test('logStreams() returns an instance of Auth0\SDK\API\Management\LogStreams', function(): void {
    $class = $this->sdk->management()->logStreams();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\LogStreams::class);
});

test('organizations() returns an instance of Auth0\SDK\API\Management\Organizations', function(): void {
    $class = $this->sdk->management()->organizations();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Organizations::class);
});

test('roles() returns an instance of Auth0\SDK\API\Management\Roles', function(): void {
    $class = $this->sdk->management()->roles();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Roles::class);
});

test('rules() returns an instance of Auth0\SDK\API\Management\Rules', function(): void {
    $class = $this->sdk->management()->rules();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Rules::class);
});

test('resourceServers() returns an instance of Auth0\SDK\API\Management\ResourceServers', function(): void {
    $class = $this->sdk->management()->resourceServers();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\ResourceServers::class);
});

test('stats() returns an instance of Auth0\SDK\API\Management\Stats', function(): void {
    $class = $this->sdk->management()->stats();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Stats::class);
});

test('tenants() returns an instance of Auth0\SDK\API\Management\Tenants', function(): void {
    $class = $this->sdk->management()->tenants();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Tenants::class);
});

test('tickets() returns an instance of Auth0\SDK\API\Management\Tickets', function(): void {
    $class = $this->sdk->management()->tickets();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Tickets::class);
});

test('userBlocks() returns an instance of Auth0\SDK\API\Management\UserBlocks', function(): void {
    $class = $this->sdk->management()->userBlocks();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\UserBlocks::class);
});

test('users() returns an instance of Auth0\SDK\API\Management\Users', function(): void {
    $class = $this->sdk->management()->users();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Users::class);
});

test('usersByEmail() returns an instance of Auth0\SDK\API\Management\UsersByEmail', function(): void {
    $class = $this->sdk->management()->usersByEmail();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\UsersByEmail::class);
});

test('getLastRequest() returns an HttpRequest or null', function(): void {
    expect($this->sdk->management()->getLastRequest())->toBeNull();

    $this->sdk->management()->users()->getAll();

    expect($this->sdk->management()->getLastRequest())->toBeInstanceOf(HttpRequest::class);
});

test('Caching of management tokens works.', function(): void {
    $managementToken = uniqid();

    $cache = new ArrayAdapter();
    $token = $cache->getItem('managementAccessToken');
    $token->set($managementToken);
    $cache->save($token);

    $this->configuration->setManagementToken(null);
    $this->configuration->setManagementTokenCache($cache);

    $class = $this->sdk->management()->blacklists();

    expect($class)->toBeInstanceOf(\Auth0\SDK\API\Management\Blacklists::class);
});

test('A client credential exchange occurs if a managementToken is not configured, but a client id and secret are', function(): void {
    $cache = new ArrayAdapter();

    $this->configuration->setClientSecret(uniqid());
    $this->configuration->setManagementToken(null);
    $this->configuration->setManagementTokenCache($cache);

    $authentication = new Authentication($this->configuration);
    $token = (new TokenGenerator())->withHs256();

    $authentication->getHttpClient()->mockResponse(
        HttpResponseGenerator::create('{"access_token":"1.2.3","id_token":"' . $token . '","refresh_token":"4.5.6"}')
    );

    $this->sdk->management()->getHttpClient($authentication);

    expect($cache->getItem('managementAccessToken')->get())->toEqual('1.2.3');
});


text:
(function( global, $ ) {
  var plugins = {},
      MAX_IMAGE_WIDTH = 1280,
      MAX_IMAGE_HEIGHT = 740;

  var EditorHelper = function() {
    throw "Do not use EditorHelper in this manner. Use EditorHelper.init instead.";
  };

  // This fix is to ensure content-editable still updates correctly, and deals with ie9 not reading document.activeElement properly
  function blurActiveEl() {
   if ( document.activeElement && document.activeElement.blur ) {
      document.activeElement.blur();
    }
  }

  function calculateFinalPositions( event, ui, trackEvent, targetContainer, container, options ) {
    var target = targetContainer.getBoundingClientRect(),
        cont = container.getBoundingClientRect(),
        height = cont.height,
        width = cont.width,
        top = ui.position.top,
        left = ui.position.left,
        targetHeight = target.height,
        targetWidth = target.width,
        minHeightPix = targetHeight * ( ( options.minHeight || 0 ) / 100 ),
        minWidthPix = targetWidth * ( ( options.minWidth || 0 ) / 100 );

    top = Math.max( 0, top );
    left = Math.max( 0, left );
    height = Math.max( minHeightPix, height );
    width = Math.max( minWidthPix, width );

    if ( ( container.offsetTop + height ) > targetHeight ) {
      top = targetHeight - height;
    }

    if ( ( container.offsetLeft + width ) > targetWidth ) {
      left = targetWidth - width;
    }

    height = ( height / targetHeight ) * 100;
    width = ( width / targetWidth ) * 100;

    if ( options.end ) {
      options.end();
    }

    // Enforce container size here, instead of relying on the update.
    container.style.width = width + "%";
    container.style.height = height + "%";

    blurActiveEl();

    trackEvent.update({
      height: height,
      width: width,
      top: ( top / targetHeight ) * 100,
      left: ( left / targetWidth ) * 100
    });
  }

  EditorHelper.init = function( butter ) {

    /**
     * Member: draggable
     *
     * Makes a container draggable using jQueryUI
     *
     * @param {TrackEvent} trackEvent: The trackEvent to update when position changes
     * @param {DOMElement} dragContainer: the container which to apply draggable to
     * @param {media} The current media's target element in Butter ( parent container )
     * @param {Object} extra options to apply to the draggable call
     *                 Options are:
     *                    {DOMElement} handle: Restrict drag start event to this element
     *                    {Function} start: Function to execute on drag start event
     *                    {Function} end: Fucntion to execute on drag end event
     */
    global.EditorHelper.draggable = function( trackEvent, dragContainer, targetContainer, options ) {
      if ( $( dragContainer ).data( "draggable" ) ) {
        return;
      }

      var iframeCover = targetContainer.querySelector( ".butter-iframe-fix" );

      options = options || {};

      function createHelper( suffix ) {
        var el = document.createElement( "div" );
        el.classList.add( "ui-draggable-handle" );
        el.classList.add( "ui-draggable-" + suffix );
        return el;
      }

      dragContainer.appendChild( createHelper( "top" ) );
      dragContainer.appendChild( createHelper( "bottom" ) );
      dragContainer.appendChild( createHelper( "left" ) );
      dragContainer.appendChild( createHelper( "right" ) );
      dragContainer.appendChild( createHelper( "grip" ) );

      $( dragContainer ).draggable({
        handle: ".ui-draggable-handle",
        containment: "parent",
        start: function() {
          iframeCover.style.display = "block";

          // Open the editor
          butter.editor.editTrackEvent( trackEvent );

          if ( options.start ) {
            options.start();
          }
        },
        stop: function( event, ui ) {
          iframeCover.style.display = "none";

          calculateFinalPositions( event, ui, trackEvent, targetContainer, dragContainer, options );
        }
      });
    };

    /**
     * Member: resizable
     *
     * Makes a container resizable using jQueryUI
     *
     * @param {TrackEvent} trackEvent: The trackEvent to update when size changes
     * @param {DOMElement} resizeContainer: the container which to apply resizable to
     * @param {media} The current media's target element in Butter ( parent container )
     * @param {Object} extra options to apply to the resizeable call
     *                 Options are:
     *                    {String} handlePositions: describes where to position resize handles ( i.e. "n,s,e,w" )
     *                              - Recommended that this option is specified due to a bug in z-indexing with
     *                                jQueryUI Resizable.
     *                    {Function} start: Function to execute on resize start event
     *                    {Function} end: Fucntion to execute on resize end event
     *                    {Number} minWidth: Minimum width that the resizeContainer should be
     *                    {Number} minHeight: Minimum height that the resizeContainer should be
     */
    global.EditorHelper.resizable = function( trackEvent, resizeContainer, targetContainer, options ) {
      if ( $( resizeContainer ).data( "resizable" ) ) {
        return;
      }

      var iframeCover = targetContainer.querySelector( ".butter-iframe-fix" );

      options = options || {};

      $( resizeContainer ).resizable({
        handles: options.handlePositions,
        start: function() {
          iframeCover.style.display = "block";

          // Open the editor
          butter.editor.editTrackEvent( trackEvent );

          if ( options.start ) {
            options.start();
          }
        },
        containment: "parent",
        stop: function( event, ui ) {
          iframeCover.style.display = "none";

          calculateFinalPositions( event, ui, trackEvent, targetContainer, resizeContainer, options );
        }
      });
    };

    /**
     * Member: contentEditable
     *
     * Makes a container's content editable using contenteditable
     *
     * @param {TrackEvent} trackEvent: The trackEvent to update when content changes
     * @param {DOMElement} contentContainer: the container which to listen for changes and set as editable
     */
    global.EditorHelper.contentEditable = function( trackEvent, contentContainers ) {
      var newText = "",
          contentContainer,
          updateText,
          updateTrackEvent,
          onBlur,
          onKeyDown,
          onMouseDown;

      updateText = function() {
        newText = "";
        for ( var i = 0, l = contentContainers.length; i < l; i++ ) {
          contentContainer = contentContainers[ i ];
          contentContainer.innerHTML = contentContainer.innerHTML.replace( /<br>/g, "\n" );
          newText += contentContainer.textContent;
          if ( i < l - 1 ) {
            newText += "\n";
          }
        }
      };
      updateTrackEvent = function() {
        blurActiveEl();
        trackEvent.update({
          text: newText
        });
      };
      onBlur = function() {
        // store the new text.
        updateText();
        // update the text after any existing events are done.
        // this way we do not revert any other event's changes.
        setTimeout( updateTrackEvent, 0 );
      };
      onKeyDown = function( e ) {
        // enter key for an update.
        // shift + enter for newline.
        if ( !e.shiftKey && e.keyCode === 13 ) {
          updateText();
          updateTrackEvent();
        }
      };
      onMouseDown = function( e ) {
        e.stopPropagation();

        // Open the editor
        butter.editor.editTrackEvent( trackEvent );

        $( contentContainer ).draggable( "destroy" );
      };

      for ( var i = 0, l = contentContainers.length; i < l; i++ ) {
        contentContainer = contentContainers[ i ];
        if ( contentContainer ) {
          contentContainer.addEventListener( "blur", onBlur, false );
          contentContainer.addEventListener( "keydown", onKeyDown, false );
          contentContainer.addEventListener( "mousedown", onMouseDown, false );
          contentContainer.setAttribute( "contenteditable", "true" );
        }
      }
    };

    var mimeTypeMapping = {
      "image/gif": "image/png",
      "image/jpeg": "image/jpeg",
      "image/png": "image/png"
    };

    /**
     * Member: droppable
     *
     * Make a container listen for drop events for loading images from a local machine
     *
     * @param {TrackEvent} trackEvent: The trackEvent to update when content changes
     * @param {DOMElement} dropContainer: The container that listens for the drop events
     */

    global.EditorHelper.droppable = function( trackEvent, dropContainer ) {
      dropContainer.addEventListener( "dragover", function( e ) {
        e.preventDefault();
        dropContainer.classList.add( "butter-dragover" );
      }, false );

      dropContainer.addEventListener( "dragleave", function( e ) {
        e.preventDefault();
        dropContainer.classList.remove( "butter-dragover" );
      }, false );

      dropContainer.addEventListener( "mousedown", function( e ) {
        // Prevent being able to drag the images inside and re drop them
        e.preventDefault();
      }, false );

      dropContainer.addEventListener( "drop", function( e ) {
        var file, imgSrc, imgURI, image, div;

        e.preventDefault();
        e.stopPropagation();

        dropContainer.classList.remove( "butter-dragover" );

        if ( !e.dataTransfer || !e.dataTransfer.files || !e.dataTransfer.files[ 0 ] ) {
          butter.dispatch( "droppable-unsupported" );
          return;
        }

        file = e.dataTransfer.files[ 0 ];

        // If we can't reasonably convert whatever they're dropping on us then bail
        var exportAs = mimeTypeMapping[ file.type ];
        if ( !exportAs ) {
          butter.dispatch( "filetype-unsupported" );
          return;
        }

        if ( window.URL && window.URL.createObjectURL ) {
          imgSrc = window.URL.createObjectURL( file );
        } else if ( window.webkitURL && window.webkitURL.createObjectURL ) {
          imgSrc = window.webkitURL.createObjectURL( file );
        } else {
          butter.dispatch( "droppable-unsupported" );
        }

        // So yeah, Opera has the functionality namespaced but all it currently does is:
        // window.URL.createObjectURL = function(obj) {
        //   return obj;
        // };
        if ( imgSrc === file ) {
          butter.dispatch( "droppable-unsupported" );
          return;
        } else {

          image = document.createElement( "img" );
          image.onload = function() {
            var width = this.width,
                height = this.height,
                wRatio, hRatio, resizeRatio,
                scaledWidth, scaledHeight,
                canvas = document.createElement( "canvas" ),
                context;

            // Fit image nicely into our largest embed size, using
            // the longest side and aspect ratio. Inspired by:
            // http://stackoverflow.com/questions/7863653/algorithm-to-resize-image-and-maintain-aspect-ratio-to-fit-iphone
            if ( width >= height ) {
              if ( width <= MAX_IMAGE_WIDTH && height <= MAX_IMAGE_HEIGHT ) {
                scaledWidth = width;
                scaledHeight = height;
              } else {
                wRatio = MAX_IMAGE_WIDTH / width;
                hRatio = MAX_IMAGE_HEIGHT / height;
                resizeRatio = Math.min( wRatio, hRatio );
                scaledHeight = height * resizeRatio;
                scaledWidth = width * resizeRatio;
              }
            } else {
              if ( height <= MAX_IMAGE_WIDTH && width <= MAX_IMAGE_HEIGHT ) {
                scaledWidth = width;
                scaledHeight = height;
              } else {
                wRatio = MAX_IMAGE_HEIGHT / width;
                hRatio = MAX_IMAGE_WIDTH / height;
                resizeRatio = Math.min( wRatio, hRatio );
                scaledHeight = height * resizeRatio;
                scaledWidth = width * resizeRatio;
              }
            }

            canvas.width = scaledWidth;
            canvas.height = scaledHeight;
            context = canvas.getContext( "2d" );
            context.drawImage( this, 0, 0, scaledWidth, scaledHeight );

            imgURI = canvas.toDataURL( exportAs );

            // If the browser's canvas impl. doesn't support whatever we requested then bail
            if ( imgURI.indexOf( exportAs ) === -1 ) {
              butter.dispatch( "droppable-unsupported" );
              return;
            }

            trackEvent.update( { src: imgURI } );

            if ( window.URL && window.URL.revokeObjectURL ) {
              window.URL.revokeObjectURL( imgSrc );
            } else if ( window.webkitURL && window.webkitURL.revokeObjectURL ) {
              window.webkitURL.revokeObjectURL( imgSrc );
            }
          };
          image.src = imgSrc;

          butter.editor.editTrackEvent( trackEvent );

          // Force image to download, esp. Opera. We can't use
          // "display: none", since that makes it invisible, and
          // thus not load.  Opera also requires the image be
          // in the DOM before it will load.
          div = document.createElement( "div" );
          div.setAttribute( "data-butter-exclude", "true" );
          div.className = "butter-image-preload";
          div.appendChild( image );
          document.body.appendChild( div );
        }
      }, false );
    };

    function _updateFunction( e ) {

      var trackEvent = e.target;

      if ( trackEvent.popcornTrackEvent && plugins[ trackEvent.type ] ) {
        plugins[ trackEvent.type ]( trackEvent, butter.currentMedia.popcorn.popcorn );
      }
    } //updateFunction

    butter.listen( "trackeventupdated", _updateFunction );
  };

  EditorHelper.addPlugin = function( plugin, callback ) {
    plugins[ plugin ] = callback;
  };

  global.EditorHelper = EditorHelper;

}( window, window.jQuery ));


text:
package org.ldp4j.application.kernel.impl;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

import org.junit.Before;
import org.junit.Test;
import org.ldp4j.application.data.Name;
import org.ldp4j.application.data.NamingScheme;
import org.ldp4j.application.kernel.impl.InMemoryContainer;
import org.ldp4j.application.kernel.impl.InMemorySlug;
import org.ldp4j.application.kernel.resource.Container;
import org.ldp4j.application.kernel.resource.ResourceId;

public class InMemorySlugTest {

	private static final Name<Integer> CONTAINER_NAME = NamingScheme.getDefault().name(1);

	private static final ResourceId CONTAINER_ID = ResourceId.createId(CONTAINER_NAME, "template");

	private Container container;

	@Before
	public void setUp() {
		this.container = new InMemoryContainer(CONTAINER_ID);
	}

	@Test
	public void testNextPath$default() throws Exception {
		InMemorySlug slug=InMemorySlug.create("slug", container);
		assertThat(slug.nextPath(),equalTo("slug"));
	}

	@Test
	public void testNextSlugPath$regular() throws Exception {
		InMemorySlug slug=InMemorySlug.create("slug", container);
		slug.setVersion(23);
		assertThat(slug.nextPath(),equalTo("slug_23"));
		assertThat(slug.nextPath(),equalTo("slug_24"));
	}

	@Test
	public void testNextSlugPath$reset() throws Exception {
		InMemorySlug slug=InMemorySlug.create("slug", container);
		slug.setVersion(23);
		assertThat(slug.nextPath(),equalTo("slug_23"));
		slug.setVersion(23);
		assertThat(slug.nextPath(),equalTo("slug_23"));
	}

	@Test
	public void testCreate$regular() throws Exception {
		InMemorySlug slug=InMemorySlug.create("slug", container);
		System.out.println(slug);
		assertThat(slug.preferredPath(),equalTo("slug"));
		assertThat(slug.version(),equalTo(0L));
		assertThat(slug.containerId(),equalTo(this.container.id()));
	}

	@Test
	public void testCreate$simpleCornerCase() throws Exception {
		InMemorySlug slug=InMemorySlug.create("_", container);
		System.out.println(slug);
		assertThat(slug.preferredPath(),equalTo("_"));
		assertThat(slug.version(),equalTo(0L));
		assertThat(slug.containerId(),equalTo(this.container.id()));
	}

	@Test
	public void testCreate$simpleCornerCaseSimpleClash() throws Exception {
		InMemorySlug slug=InMemorySlug.create("_23", container);
		System.out.println(slug);
		assertThat(slug.preferredPath(),equalTo("_23"));
		assertThat(slug.version(),equalTo(0L));
		assertThat(slug.containerId(),equalTo(this.container.id()));
	}

	@Test
	public void testCreate$simpleCornerCaseComplexClash() throws Exception {
		InMemorySlug slug=InMemorySlug.create("_23_24", container);
		System.out.println(slug);
		assertThat(slug.preferredPath(),equalTo("_23"));
		assertThat(slug.version(),equalTo(24L));
		assertThat(slug.containerId(),equalTo(this.container.id()));
	}

	@Test
	public void testCreate$compositeCornerCase() throws Exception {
		InMemorySlug slug=InMemorySlug.create("__", container);
		System.out.println(slug);
		assertThat(slug.preferredPath(),equalTo("__"));
		assertThat(slug.version(),equalTo(0L));
		assertThat(slug.containerId(),equalTo(this.container.id()));
	}

	@Test
	public void testCreate$compositeCornerCaseSimpleClash() throws Exception {
		InMemorySlug slug=InMemorySlug.create("__23", container);
		System.out.println(slug);
		assertThat(slug.preferredPath(),equalTo("_"));
		assertThat(slug.version(),equalTo(23L));
		assertThat(slug.containerId(),equalTo(this.container.id()));
	}

	@Test
	public void testCreate$compositeCornerCaseComplexClash() throws Exception {
		InMemorySlug slug=InMemorySlug.create("__23_24", container);
		System.out.println(slug);
		assertThat(slug.preferredPath(),equalTo("__23"));
		assertThat(slug.version(),equalTo(24L));
		assertThat(slug.containerId(),equalTo(this.container.id()));
	}

	@Test
	public void testCreate$simpleClash() throws Exception {
		InMemorySlug slug=InMemorySlug.create("slug_23", container);
		System.out.println(slug);
		assertThat(slug.preferredPath(),equalTo("slug"));
		assertThat(slug.version(),equalTo(23L));
		assertThat(slug.containerId(),equalTo(this.container.id()));
	}

	@Test
	public void testCreate$compositeClash() throws Exception {
		InMemorySlug slug=InMemorySlug.create("slug_23_24", container);
		System.out.println(slug);
		assertThat(slug.preferredPath(),equalTo("slug_23"));
		assertThat(slug.version(),equalTo(24L));
		assertThat(slug.containerId(),equalTo(this.container.id()));
	}

}


text:
<?xml version='1.0' encoding='UTF-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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.
-->

<!-- START SNIPPET: jar-with-dependencies -->
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/${mdoVersion}"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/${mdoVersion} http://maven.apache.org/xsd/assembly-${mdoVersion}.xsd">
  <!-- TODO: a jarjar format would be better -->
  <id>jar-with-dependencies</id>
  <formats>
    <format>jar</format>
  </formats>
  <includeBaseDirectory>false</includeBaseDirectory>
  <dependencySets>
    <dependencySet>
      <outputDirectory>/</outputDirectory>
      <useProjectArtifact>true</useProjectArtifact>
      <unpack>true</unpack>
      <scope>runtime</scope>
    </dependencySet>
  </dependencySets>
</assembly>
<!-- END SNIPPET: jar-with-dependencies -->